import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Embedding, Dense
# Step 1: Load and preprocess the data
# Load the English and Arabic sentences from file
with open('data.txt', 'r') as file:
data = file.readlines()
# Split the data into train, validate, and test sets
train_data = data[:8000]
val_data = data[8000:9000]
test_data = data[9000:]
# Tokenize the sentences and convert them into numerical representations
tokenizer = Tokenizer()
tokenizer.fit_on_texts(train_data)
input_sentences = tokenizer.texts_to_sequences([sentence.split('\t')[0] for sentence in train_data])
target_sentences = tokenizer.texts_to_sequences([sentence.split('\t')[1] for sentence in train_data])
input_sentences_val = tokenizer.texts_to_sequences([sentence.split('\t')[0] for sentence in val_data])
target_sentences_val = tokenizer.texts_to_sequences([sentence.split('\t')[1] for sentence in val_data])
input_sentences_test = tokenizer.texts_to_sequences([sentence.split('\t')[0] for sentence in test_data])
target_sentences_test = tokenizer.texts_to_sequences([sentence.split('\t')[1] for sentence in test_data])
# Determine the maximum sentence length
max_sentence_length = max(
len(sentence) for sentence in input_sentences + target_sentences
)
# Pad or truncate the sentences to a fixed length
input_sequences = pad_sequences(input_sentences, maxlen=max_sentence_length, padding='post')
target_sequences = pad_sequences(target_sentences, maxlen=max_sentence_length, padding='post')
input_sequences_val = pad_sequences(input_sentences_val, maxlen=max_sentence_length, padding='post')
target_sequences_val = pad_sequences(target_sentences_val, maxlen=max_sentence_length, padding='post')
input_sequences_test = pad_sequences(input_sentences_test, maxlen=max_sentence_length, padding='post')
# Step 2: Build the model
vocab_size = len(tokenizer.word_index) + 1
embedding_dim = 256
hidden_units = 512
# Encoder
encoder_inputs = Input(shape=(max_sentence_length,))
encoder_embeddings = Embedding(vocab_size, embedding_dim)(encoder_inputs)
encoder_outputs, forward_h, forward_c, backward_h, backward_c = LSTM(hidden_units, return_sequences=True, return_state=True)(encoder_embeddings)
state_h = tf.keras.layers.Concatenate()([forward_h, backward_h])
state_c = tf.keras.layers.Concatenate()([forward_c, backward_c])
encoder_states = [state_h, state_c]
# Decoder
decoder_inputs = Input(shape=(max_sentence_length,))
decoder_embeddings = Embedding(vocab_size, embedding_dim)(decoder_inputs)
decoder_lstm = LSTM(hidden_units*2, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_embeddings, initial_state=encoder_states)
decoder_dense = Dense(vocab_size, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
# Step 3: Train the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit([input_sequences, target_sequences[:, :-1]], target_sequences[:, 1:], batch_size=64, epochs=10, validation_data=([input_sequences_val, target_sequences_val[:, :-1]], target_sequences_val[:, 1:]))
# Step 4: Evaluate the model
# Generate predictions for test set
predictions = model.predict([input_sequences_test, np.zeros((len(input_sequences_test), max_sentence_length))])
# Convert numerical representations back to sentences
predicted_sentences = []
for prediction in predictions:
predicted_sentence = ' '.join([tokenizer.index_word[index] for index in np.argmax(prediction, axis=1)])
predicted_sentences.append(predicted_sentence)
# Print an example translation from the test set
input_sentence_test = test_data[0].split('\t')[0]
target_sentence_test = test_data[0].split('\t')[1]
predicted_sentence_test = predicted_sentences[0]
print('Input Sentence:', input_sentence_test)
print('Target Sentence:', target_sentence_test)
print('Predicted Sentence:', predicted_sentence_test)