File size: 1,146 Bytes
af37519 57b6e56 af37519 e2101d5 57b6e56 5705bf5 e2101d5 af37519 57b6e56 af37519 57b6e56 83beff9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
import torch
import gradio as gr
import os
# Load the pre-trained model and tokenizer from the root directory
model_path = "." # Root directory
print(f"Checking files in {model_path}: {os.listdir(model_path)}") # Debug: List files in root
tokenizer = DistilBertTokenizer.from_pretrained(model_path)
model = DistilBertForSequenceClassification.from_pretrained(model_path)
# Prediction function
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"
# Create Gradio interface
interface = gr.Interface(fn=predict_sentiment, inputs="text", outputs="text", title="Amazon Sentiment Analysis Demo")
interface.launch(share=True) |