Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import torch | |
| from transformers import BertTokenizer, BertForSequenceClassification | |
| model_path = "my_model" | |
| tokenizer = BertTokenizer.from_pretrained(model_path) | |
| model = BertForSequenceClassification.from_pretrained(model_path) | |
| device = torch.device("cpu") | |
| model.to(device) | |
| model.eval() | |
| def predict(text): | |
| inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| logits = outputs.logits | |
| probs = torch.softmax(logits, dim=1) | |
| predicted_class = torch.argmax(probs, dim=1).item() | |
| confidence = probs[0][predicted_class].item() | |
| label = "π’ Positive" if predicted_class == 1 else "π΄ Negative" | |
| return label, f"{confidence:.2f}" | |
| # π¨ CUSTOM UI | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(""" | |
| # π¬ AI Sentiment Analyzer | |
| ### Analyze emotions in text using BERT π€ | |
| """) | |
| with gr.Row(): | |
| text_input = gr.Textbox( | |
| placeholder="Type your sentence here...", | |
| lines=3, | |
| label="Input Text" | |
| ) | |
| analyze_btn = gr.Button("Analyze Sentiment π") | |
| with gr.Row(): | |
| result_label = gr.Textbox(label="Prediction") | |
| confidence_score = gr.Textbox(label="Confidence") | |
| analyze_btn.click( | |
| fn=predict, | |
| inputs=text_input, | |
| outputs=[result_label, confidence_score] | |
| ) | |
| demo.launch() |