arifa-batool's picture
Update app.py
edff6b4 verified
raw
history blame
6.56 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
# ====================== MODEL ======================
model_path = "./best_model"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForSequenceClassification.from_pretrained(model_path)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
def predict_sentiment(text):
if not text or text.strip() == "":
return "Please enter text", "0.00"
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=512
).to(device)
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=1)
pred_id = torch.argmax(probs, dim=1).item()
confidence = torch.max(probs).item()
label = model.config.id2label[pred_id]
return label, f"{confidence:.2%}"
# ====================== PROFESSIONAL CSS ======================
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
:root {
--bg: #070A12;
--panel: rgba(255, 255, 255, 0.04);
--panel-strong: rgba(255, 255, 255, 0.07);
--border: rgba(255, 255, 255, 0.08);
--primary: #7C3AED;
--secondary: #22D3EE;
--text: #E5E7EB;
--muted: #9CA3AF;
}
body {
background: radial-gradient(circle at top, #0B1020, #05060A);
font-family: 'Inter', sans-serif;
}
.gradio-container {
max-width: 100% !important;
margin: auto !important;
padding: 40px 20px;
}
/* Main Card */
.block {
background: var(--panel) !important;
border: 1px solid var(--border) !important;
border-radius: 24px !important;
padding: 40px !important;
backdrop-filter: blur(12px);
box-shadow: 0 20px 60px rgba(0,0,0,0.6);
}
/* Title */
h1 {
font-size: 46px !important;
font-weight: 800 !important;
text-align: center;
color: white;
letter-spacing: -1px;
}
h1 span {
background: linear-gradient(90deg, #7C3AED, #22D3EE);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Subtitle */
.subtitle {
text-align: center;
color: var(--muted);
font-size: 17px;
margin-bottom: 30px;
}
/* Button */
button {
background: linear-gradient(135deg, var(--primary), var(--secondary)) !important;
color: white !important;
font-weight: 700 !important;
font-size: 17px !important;
padding: 16px 0 !important;
border-radius: 16px !important;
width: 100%;
margin: 15px 0 25px 0;
box-shadow: 0 10px 30px rgba(124, 58, 237, 0.3);
}
button:hover {
transform: translateY(-3px);
box-shadow: 0 15px 40px rgba(34, 211, 238, 0.3);
}
/* Input */
textarea {
background: rgba(0,0,0,0.35) !important;
border: 1px solid var(--border) !important;
border-radius: 16px !important;
color: var(--text) !important;
font-size: 16.5px !important;
padding: 18px !important;
min-height: 160px !important;
}
textarea:focus {
border-color: var(--secondary) !important;
}
/* Output Labels (Cyan) */
label {
color: var(--secondary) !important;
font-weight: 600 !important;
font-size: 15px !important;
}
/* Output Boxes - Subtle Dark */
.output-text {
background: rgba(0,0,0,0.35) !important;
border: 1px solid var(--border) !important;
border-radius: 16px !important;
padding: 20px !important;
font-size: 18px !important;
color: white !important;
font-weight: 600;
text-align: center;
}
"""
examples = [
["یہ بہت اچھا پروڈکٹ ہے"],
["مجھے یہ بالکل پسند نہیں آیا"],
["زبردست تجربہ تھا"],
["خدمات بہت خراب تھیں"],
["یہ ٹھیک تھا"]
]
with gr.Blocks(css=custom_css, title="Urdu Sentiment Analysis") as interface:
gr.Markdown("# 🇵🇰 Urdu Sentiment <span>Analyzer</span>")
gr.Markdown('<p class="subtitle">Fine-tuned mBERT for Accurate Urdu Sentiment Classification</p>')
with gr.Row():
with gr.Column(scale=7):
text_input = gr.Textbox(
label="Enter Urdu Text",
placeholder="یہاں اردو جملہ لکھیں...",
lines=9
)
analyze_btn = gr.Button("Analyze Sentiment")
gr.Examples(
examples=examples,
inputs=text_input,
label="Example Sentences"
)
with gr.Column(scale=5):
gr.Markdown("### Prediction Results")
sentiment = gr.Textbox(
label="Predicted Sentiment",
interactive=False,
elem_classes="output-text"
)
confidence = gr.Textbox(
label="Confidence Score",
interactive=False,
elem_classes="output-text"
)
# Footer
gr.Markdown("""
<div style="text-align:center; margin-top:50px; color:#6B7280; font-size:14px;">
Built with Transformers + Gradio • Production-ready Urdu NLP Demo
</div>
""")
analyze_btn.click(
fn=predict_sentiment,
inputs=text_input,
outputs=[sentiment, confidence]
)
interface.launch()
# from transformers import AutoTokenizer, AutoModelForSequenceClassification
# import gradio as gr
# import torch
# model_path = "./best_model"
# tokenizer = AutoTokenizer.from_pretrained(model_path)
# model = AutoModelForSequenceClassification.from_pretrained(model_path)
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# model.to(device)
# model.eval()
# def predict_sentiment(text):
# inputs = tokenizer(
# text,
# return_tensors="pt",
# truncation=True,
# padding=True
# ).to(device)
# with torch.no_grad():
# outputs = model(**inputs)
# probs = torch.softmax(outputs.logits, dim=1)
# pred_id = torch.argmax(probs, dim=1).item()
# confidence = torch.max(probs).item()
# label = model.config.id2label[pred_id]
# return label, confidence
# # Gradio UI
# interface = gr.Interface(
# fn=predict_sentiment,
# inputs=gr.Textbox(label="Enter Urdu Text"),
# outputs=[
# gr.Textbox(label="Sentiment"),
# gr.Textbox(label="Confidence")
# ],
# title="Urdu Sentiment Analysis (mBERT)",
# )
# interface.launch()