import gradio as gr from transformers import AutoModelForSequenceClassification, AutoTokenizer import torch # Load model and tokenizer model_name = "Kyudan/distilbert-base-uncased-finetuned-cola" model = AutoModelForSequenceClassification.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) def classify_text(text): # Tokenize the input text inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) # Perform inference with torch.no_grad(): outputs = model(**inputs) # Get the predicted class and its probability probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1) predicted_class = torch.argmax(probabilities, dim=-1).item() confidence = probabilities[0][predicted_class].item() # Map the predicted class to a label (assuming binary classification) label = "Positive" if predicted_class == 1 else "Negative" return f"Classification: {label}\nConfidence: {confidence:.2f}" # Gradio interface setup demo = gr.Interface( fn=classify_text, inputs="text", outputs="text", title="Text Classification Demo", description="Enter a sentence to classify its sentiment (positive/negative)." ) if __name__ == "__main__": demo.launch(share=True)