|
import gradio as gr |
|
import numpy as np |
|
import tensorflow as tf |
|
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification |
|
|
|
|
|
def load_model(): |
|
model_path = "/home/user/app/political_ideology_model" |
|
return tf.keras.models.load_model(model_path) |
|
|
|
|
|
def load_tokenizer(): |
|
tokenizer_path = "/home/user/app/political_ideology_tokenizer" |
|
return AutoTokenizer.from_pretrained(tokenizer_path) |
|
|
|
|
|
model = load_model() |
|
tokenizer = load_tokenizer() |
|
|
|
|
|
id2label = {0: "Conservative", 1: "Liberal", 2: "Socialist", 3: "Libertarian"} |
|
|
|
def predict_political_ideology(file_obj): |
|
try: |
|
|
|
text = file_obj.decode("utf-8") |
|
|
|
|
|
inputs = tokenizer(text, truncation=True, padding=True, return_tensors="tf") |
|
model_output = model.predict({'input_ids': inputs["input_ids"], 'attention_mask': inputs["attention_mask"]}) |
|
|
|
|
|
logits = model_output['logits'] if isinstance(model_output, dict) else model_output |
|
|
|
|
|
probabilities = tf.nn.softmax(logits, axis=-1) |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
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." |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch(inbrowser=True, share=True, auth=('User', 'Password')) |
|
|