hyvfyjf's picture
Update Main.py
db0be53
import gradio as gr
import numpy as np
import tensorflow as tf
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
# Function to load the model
def load_model():
model_path = "/home/user/app/political_ideology_model"
return tf.keras.models.load_model(model_path)
# Function to load the tokenizer
def load_tokenizer():
tokenizer_path = "/home/user/app/political_ideology_tokenizer"
return AutoTokenizer.from_pretrained(tokenizer_path)
# Load model and tokenizer
model = load_model()
tokenizer = load_tokenizer()
# Mapping from numeric labels to text labels
id2label = {0: "Conservative", 1: "Liberal", 2: "Socialist", 3: "Libertarian"}
def predict_political_ideology(file_obj):
try:
# Decode the bytes object to get text
text = file_obj.decode("utf-8")
# Prepare input for the model
inputs = tokenizer(text, truncation=True, padding=True, return_tensors="tf")
model_output = model.predict({'input_ids': inputs["input_ids"], 'attention_mask': inputs["attention_mask"]})
# Extract logits from the model's output
logits = model_output['logits'] if isinstance(model_output, dict) else model_output
# Convert logits to probabilities
probabilities = tf.nn.softmax(logits, axis=-1)
# Get the predicted class ID and its corresponding probability
predicted_class_id = np.argmax(probabilities, axis=-1)[0]
predicted_probability = float(probabilities[0, predicted_class_id])
predicted_label = id2label[predicted_class_id]
return f"{predicted_label} (Confidence: {predicted_probability:.2f})"
except Exception as e:
return str(e) # Return the error for debugging
# Gradio Interface with file input
iface = gr.Interface(
fn=predict_political_ideology,
inputs=gr.File(type="binary", label="Upload Text File"),
outputs="text",
title="Political Ideology Predictor",
description="Upload a text file to predict its political ideology."
)
# Launch the app
if __name__ == "__main__":
iface.launch(inbrowser=True, share=True, auth=('User', 'Password'))