import json
import numpy as np
import tensorflow as tf
from tensorflow import keras
from huggingface_hub import from_pretrained_keras
import gradio as gr
latent_dim = 256
num_encoder_tokens = 71
max_encoder_seq_length = 15
num_decoder_tokens = 92
max_decoder_seq_length = 59
with open("input_vocab.json", "r", encoding="utf-8") as f:
input_token_index = json.load(f)
with open("target_vocab.json", "r", encoding="utf-8") as f:
target_token_index = json.load(f)
model = from_pretrained_keras("keras-io/char-lstm-seq2seq")
# Define sampling models
# Restore the model and construct the encoder and decoder.
encoder_inputs = model.input[0] # input_1
encoder_outputs, state_h_enc, state_c_enc = model.layers[2].output # lstm_1
encoder_states = [state_h_enc, state_c_enc]
encoder_model = keras.Model(encoder_inputs, encoder_states)
decoder_inputs = model.input[1] # input_2
decoder_state_input_h = keras.Input(shape=(latent_dim,), name="input_3")
decoder_state_input_c = keras.Input(shape=(latent_dim,), name="input_4")
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_lstm = model.layers[3]
decoder_outputs, state_h_dec, state_c_dec = decoder_lstm(
decoder_inputs, initial_state=decoder_states_inputs
)
decoder_states = [state_h_dec, state_c_dec]
decoder_dense = model.layers[4]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = keras.Model(
[decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states
)
# Reverse-lookup token index to decode sequences back to
# something readable.
reverse_input_char_index = dict((i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict((i, char) for char, i in target_token_index.items())
def decode_sequence(input_seq):
# Encode the input as state vectors.
states_value = encoder_model.predict(input_seq)
# Generate empty target sequence of length 1.
target_seq = np.zeros((1, 1, num_decoder_tokens))
# Populate the first character of target sequence with the start character.
target_seq[0, 0, target_token_index["\t"]] = 1.0
# Sampling loop for a batch of sequences
# (to simplify, here we assume a batch of size 1).
stop_condition = False
decoded_sentence = ""
while not stop_condition:
output_tokens, h, c = decoder_model.predict([target_seq] + states_value)
# Sample a token
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence += sampled_char
# Exit condition: either hit max length
# or find stop character.
if sampled_char == "\n" or len(decoded_sentence) > max_decoder_seq_length:
stop_condition = True
# Update the target sequence (of length 1).
target_seq = np.zeros((1, 1, num_decoder_tokens))
target_seq[0, 0, sampled_token_index] = 1.0
# Update states
states_value = [h, c]
return decoded_sentence
def translate(input_text):
if len(input_text) > max_encoder_seq_length:
input_text = input_text[:max_encoder_seq_length]
encoder_input_data = np.zeros(
(1, max_encoder_seq_length, num_encoder_tokens), dtype="float32"
)
for t, char in enumerate(input_text):
encoder_input_data[0, t, input_token_index[char]] = 1.0
encoder_input_data[0, t + 1 :, input_token_index[" "]] = 1.0
target_text = decode_sequence(encoder_input_data)
return target_text
input_box = gr.inputs.Textbox(type="str", label="Input Text")
target = gr.outputs.Textbox()
iface = gr.Interface(
translate,
input_box,
target,
title="Character-level recurrent sequence-to-sequence model",
description="Model for Translating English to French using a Character-level recurrent sequence-to-sequence trained with small data.",
article='Author: Anurag Singh . Based on the keras example from fchollet',
examples=["Hi.", "Wait!", "Go on."],
)
iface.launch()