|
|
|
import gradio as gr |
|
import tensorflow as tf |
|
import json |
|
import numpy as np |
|
|
|
from tensorflow.keras.preprocessing.sequence import pad_sequences |
|
from tensorflow.keras.preprocessing.text import tokenizer_from_json |
|
|
|
|
|
def load_model(): |
|
model = tf.keras.models.load_model('polarisatie_model.h5') |
|
return model |
|
|
|
model = load_model() |
|
|
|
|
|
def load_tokenizer(tokenizer_path='tokenizer.json'): |
|
with open(tokenizer_path, 'r', encoding='utf-8') as f: |
|
tokenizer_json = f.read() |
|
tokenizer = tokenizer_from_json(tokenizer_json) |
|
return tokenizer |
|
|
|
tokenizer = load_tokenizer() |
|
|
|
|
|
def load_max_length(max_length_path='max_length.txt'): |
|
with open(max_length_path, 'r') as f: |
|
max_length = int(f.read().strip()) |
|
return max_length |
|
|
|
max_length = load_max_length() |
|
|
|
|
|
def preprocess(text): |
|
|
|
sequences = tokenizer.texts_to_sequences([text]) |
|
|
|
padded = pad_sequences(sequences, maxlen=max_length, padding='post', truncating='post') |
|
return padded |
|
|
|
|
|
def predict_polarization(text): |
|
if not text.strip(): |
|
return "Voer alstublieft een geldige zin in." |
|
|
|
|
|
processed_text = preprocess(text) |
|
|
|
|
|
prediction = model.predict(processed_text) |
|
|
|
|
|
is_polarizing = bool(prediction[0] > 0.5) |
|
|
|
return "Ja" if is_polarizing else "Nee" |
|
|
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("# Polarisatie Thermometer") |
|
gr.Markdown("Voer een zin in om te beoordelen of deze polariserend is.") |
|
|
|
with gr.Row(): |
|
input_text = gr.Textbox(label="Zin", placeholder="Schrijf hier een zin...", lines=2) |
|
|
|
evaluate_button = gr.Button("Evalueren") |
|
|
|
result = gr.Textbox(label="Is polariserend?", interactive=False) |
|
|
|
evaluate_button.click(fn=predict_polarization, inputs=input_text, outputs=result) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|