<jupyter_start><jupyter_text>Tolkien Elvish TranslatorThe Keras blog has a post that implements a simple Encoder and Decoder to tranlate English-French PhrasesAll Data scraped from: http://eldamo.org/<jupyter_code>import numpy as np
import pandas as pd
import keras

def raw_data_reader(raw_file_path,out_path):
    dat=open(raw_file_path,"r",encoding="utf-8")
    out=open(out_path,"w",encoding="utf-8")
    for i in dat:
        try:
            tmp=i.split("“")
        except:
            print ("****BAD***LINE***********")
        tmp[0]=tmp[0].strip(",”*[]†²\n\t{}><·’;")
        tmp[1]=tmp[1].strip(",”*[]†²\n\t{}><·’;")
        out.write(tmp[1]+",\t"+tmp[0]+"\n")
    out.close()

def encodeData(csvFilePath):
    inSeq=[]#Input phrases/sequences
    outSeq=[]
    inChars=set()#Characters used in input
    outChars=set()
    
    csvFile=open(csvFilePath,"r",encoding="utf-8")
    for i in csvFile:
        tmp=(i.split(","))
        inSeq.append(tmp[0])#Append sentences to list
        outSeq.append(tmp[1])#Elvish phrases list
        #Add to the list of English Characters
        for j in tmp[0]:
            for tmpChar in j:
                if tmpChar not in inChars:
                    inChars.add(tmpChar)
        #...significantly more elvish Characters            
        for j in tmp[1]:
            for tmpChar in j:
                if tmpChar not in outChars:
                    outChars.add(tmpChar)
                    
    return inSeq,outSeq,sorted(list(inChars)),sorted(list(outChars))
process_raw=True
if process_raw:
    inPath,outPath="raw_data/","processed_data/"
    raw_data_reader(inPath+"Sindarin_Phrases.dat",outPath+"Sindarin_Phrases.csv")
    raw_data_reader(inPath+"Quenya_Phrases.dat",outPath+"Quenya_Phrases.csv")

quenya=True
if quenya:
    print ("Loading the Quenya Phrase dataset")
    input_seq,out_seq,input_chars,out_chars=encodeData(outPath+"Quenya_Phrases.csv")
    modelPath="models/Quenya_LSTM.h5"
else:
    input_seq,out_seq,input_chars,out_chars=encodeData(outPath+"Sindarin_Phrases.csv") 
    modelPath="models/Sindarin_LSTM.h5"
num_encoder_tokens = len(input_chars)
num_decoder_tokens = len(out_chars)
max_encoder_seq_length = max([len(txt) for txt in input_seq])
max_decoder_seq_length = max([len(txt) for txt in out_seq])

print('Number of samples:', len(input_seq))
print('Number of unique input tokens:', num_encoder_tokens)
print('Number of unique output tokens:', num_decoder_tokens)
print('Max sequence length for inputs:', max_encoder_seq_length)
print('Max sequence length for outputs:', max_decoder_seq_length)
input_token_index = dict([(char, i) for i, char in enumerate(input_chars)])
target_token_index = dict([(char, i) for i, char in enumerate(out_chars)])

encodedInArray=np.zeros((len(input_seq), max_encoder_seq_length,\
                         num_encoder_tokens),dtype='float32')
decodedInArray=np.zeros((len(input_seq), max_decoder_seq_length,\
                         num_decoder_tokens),dtype='float32')
decodedOutArray=np.zeros((len(input_seq), max_decoder_seq_length,\
                          num_decoder_tokens),dtype='float32')
print ("Input Token Index")
print (input_token_index)

print ("")
print ("Target Token Index")
print (target_token_index)
for i, (input_text, target_text) in enumerate(zip(input_seq, out_seq)):
    print (input_text,"|",target_text.strip("\n"))
    for t, char in enumerate(input_text):
        encodedInArray[i, t, input_token_index[char]] = 1.
    for t, char in enumerate(target_text):
        decodedInArray[i, t, target_token_index[char]] = 1.  # Target data is offset by one
        if t > 0:
            decodedOutArray[i, t - 1, target_token_index[char]] = 1.
print ("What do the encodings look like?")
print (encodedInArray[0])
print("")
from keras.models import Model,load_model
from keras.layers import Input, LSTM, Dense

print ("Building the model:")
print ("Copied directly from Keras Blog")
batch_size = 64  # Batch size for training.
epochs = 30 # Number of epochs to train for.
latent_dim = 1024  # Latent dimensionality of the encoding space.

# Define an input sequence and process it.
encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
                                     initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)


train=True
if not train:
    model = load_model(modelPath)
else:
    # Run training
    model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
    model.fit([encodedInArray, decodedInArray], decodedOutArray,
              batch_size=batch_size,
              epochs=epochs,
              validation_split=0.1)

    # Save model
    model.save(modelPath)
# 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())
print ("Reverse input token lookup:")
print (reverse_input_char_index)
print ("")
print ("Reverse target token lookup:")
print (reverse_target_char_index)
#Build encoder and decoder system

encoder_model = Model(encoder_inputs, encoder_states)

decoder_state_input_h = Input(shape=(latent_dim,))
decoder_state_input_c = Input(shape=(latent_dim,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(
    decoder_inputs, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs] + decoder_states)
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.

    # 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.

        # Update states
        states_value = [h, c]

    return decoded_sentence
#Investigate the performance.
for seq_index in range(100):
    # Take one sequence (part of the training set)
    # for trying out decoding.
    inputSeq = encodedInArray[seq_index: seq_index + 1]
    #print (inputSeq)
    decoded_sentence = decode_sequence(inputSeq)
    print('-')
    print('Input sentence:', input_seq[seq_index])
    print('Decoded sentence:', decoded_sentence.strip("\n"))
    print("Target sentence: ",out_seq[seq_index])<jupyter_output>-
Input sentence: upon the shining shore
Decoded sentence: man kiluva nar 
Target sentence:  	ailinisse alkarain 

-
Input sentence: upon the shining shore
Decoded sentence: man kiluva nar 
Target sentence:  	ailinissen alkarain 

-
Input sentence: on the last shores
Decoded sentence: man kiluva nar 
Target sentence:  	ailinissen oilimaisen 

-
Input sentence: upon the last beaches
Decoded sentence: man kiluva nar 
Target sentence:  	ailissen oilimaisen 

-
Input sentence: the old darkness beyond the stars
Decoded sentence: man kiluva nar 
Target sentence:  	aire móre ala tinwi 

-
Input sentence: it shone like gold
Decoded sentence: man kiluva nar 
Target sentence:  	a kálie kulundon 

-
Input sentence: after the last night
Decoded sentence: man kiluva nar 
Target sentence:  	ala fuin oilimaite 

-
Input sentence: after the last night
Decoded sentence: man kiluva nar 
Target sentence:  	ala fuin oilimaite² 

-
Input sentence: before the last night
Decoded sentence: man kiluva nar 
Tar[...]
{'fraction_non_alphanumeric': 0.10102315562735595, 'fraction_numerical': 0.006031233171782445, 'mean_word_length': 3.98443370907139, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '65706', 'license': 'MIT', 'n_tokens_mistral': 3067, 'n_tokens_neox': 2909, 'n_words': 794, 'path': 'ElvishTranslator/ElvenLSTM.ipynb', 'repo_name': 'franckjay/TolkienElvishLSTM', 'size': '9285'}