JnS123456's picture
Update app.py
f7745b3 verified
Raw History Blame Contribute Delete
1.78 kB
import os
import shutil
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import gradio as gr
# Check if model is extracted; if not, extract it
if not os.path.exists("best_model"):
shutil.unpack_archive("best_model.zip", "best_model")
# Load the saved model and tokenizer
model = AutoModelForSequenceClassification.from_pretrained("best_model")
tokenizer = AutoTokenizer.from_pretrained("best_model")
# Ensure the model is in evaluation mode
model.eval()
# Define the prediction function
def predict(Text):
# Tokenize the input text
inputs = tokenizer(Text, return_tensors="pt", max_length=512, truncation=True, padding=True)
# Perform inference
with torch.no_grad():
logits = model(**inputs).logits
# Get predicted label and confidence scores
probs = torch.nn.functional.softmax(logits, dim=1)
_, predicted_label = torch.max(logits, dim=1)
# Map the predicted label to a human-readable class name
class_names = ["Class a", "Class b", "Class c", "Class d", "Class e"]
predicted_class = class_names[predicted_label.item()]
# Convert confidence scores to percentage with 2 decimal places
probs_percentage = [f"{p * 100:.2f}%" for p in probs.tolist()[0]]
# Return the predicted class and formatted confidence scores
return predicted_class, str(probs_percentage)
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=gr.Textbox(lines=2, placeholder="Enter your text"),
outputs=[
gr.Textbox(label="Predicted Class"),
gr.Textbox(label="Confidence")
],
title="Chronological Classification",
description="Classify poem into predefined categories."
)
# Launch the interface
iface.launch()