================================================================================
# Architecture 6: Recurrent Neural Networks (LSTM) for IMDB Sentiment Classification
# Library: keres | Framework: TensorFlow / Keras | Total Cells: 6
================================================================================


# --------------------------------------------------------------------------------
# [CELL 1 / 6] : Imports (TensorFlow, Keras, LSTM, Embedding, IMDB)
# --------------------------------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.layers import LSTM, Dense, Embedding
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing import sequence

# Verify TensorFlow version
print("Using TensorFlow version:", tf.__version__)


# --------------------------------------------------------------------------------
# [CELL 2 / 6] : Hyperparameters & Dataset Loading (Padding & Truncation)
# --------------------------------------------------------------------------------
# Hyperparameters
max_features = 10000  # Top words to use
maxlen = 200  # Maximum sequence length
batch_size = 64
embedding_dim = 128

print("Loading IMDB data...")
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)

print(f"{len(x_train)} training sequences")
print(f"{len(x_test)} test sequences")

# Pad sequences to ensure uniform input length
print("\nPad sequences (samples x time)...")
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)

print("x_train shape:", x_train.shape)
print("x_test shape:", x_test.shape)


# --------------------------------------------------------------------------------
# [CELL 3 / 6] : Sequential LSTM Architecture Construction & Compilation
# --------------------------------------------------------------------------------
print("Building LSTM model...")
model = Sequential([
    Embedding(
        input_dim=max_features,
        output_dim=embedding_dim,
        input_length=maxlen,  # Can also use input_shape=(maxlen,)
    ),
    LSTM(units=64, dropout=0.2, recurrent_dropout=0.2),
    Dense(units=1, activation="sigmoid"),  # Binary classification output
])

model.compile(
    loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
)

# Display model architecture summary
model.summary()


# --------------------------------------------------------------------------------
# [CELL 4 / 6] : Model Training with Validation Split
# --------------------------------------------------------------------------------
epochs = 5

print("Training model...")
history = model.fit(
    x_train,
    y_train,
    batch_size=batch_size,
    epochs=epochs,
    validation_data=(x_test, y_test),
)


# --------------------------------------------------------------------------------
# [CELL 5 / 6] : Training & Validation Accuracy/Loss Curves Plotting
# --------------------------------------------------------------------------------
plt.figure(figsize=(12, 4))

# Accuracy Plot
plt.subplot(1, 2, 1)
plt.plot(history.history["accuracy"], label="Train Accuracy", linewidth=2)
plt.plot(
    history.history["val_accuracy"], label="Validation Accuracy", linewidth=2
)
plt.title("Model Accuracy Over Epochs")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.grid(True)

# Loss Plot
plt.subplot(1, 2, 2)
plt.plot(history.history["loss"], label="Train Loss", linewidth=2)
plt.plot(history.history["val_loss"], label="Validation Loss", linewidth=2)
plt.title("Model Loss Over Epochs")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()


# --------------------------------------------------------------------------------
# [CELL 6 / 6] : Inference on Sample Reviews & Word Index Decoding
# --------------------------------------------------------------------------------
# Setup word index mapping to decode reviews back to text
word_index = imdb.get_word_index()
word_index = {k: (v + 3) for k, v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2
word_index["<UNUSED>"] = 3
reverse_word_index = {v: k for k, v in word_index.items()}


def decode_review(text_indices):
  return " ".join([reverse_word_index.get(i, "?") for i in text_indices])


# Pick random samples from the test set
num_samples = 5
sample_indices = np.random.choice(len(x_test), num_samples, replace=False)

sample_texts = x_test[sample_indices]
sample_labels = y_test[sample_indices]

# Run predictions
predictions = model.predict(sample_texts)

print("--- Example Predictions Visualization ---")
for i in range(num_samples):
  raw_text = decode_review(sample_texts[i])
  actual_label = "Positive" if sample_labels[i] == 1 else "Negative"
  pred_prob = float(predictions[i][0])
  pred_label = "Positive" if pred_prob >= 0.5 else "Negative"

  print(f"\nSample {i+1}:")
  print(f"Review Snippet: {raw_text[:150]}...")
  print(f"Actual Sentiment   : {actual_label}")
  print(f"Predicted Sentiment: {pred_label} (Confidence: {pred_prob:.4f})")

================================================================================
💡 CUSTOMIZATION & ADAPTATION RECIPES FOR ARCHITECTURE 6 (LSTM for IMDB Sentiment in Keras):
================================================================================
1. SWITCH TO LOCAL CSV TEXT DATA VIA PANDAS:
   import pandas as pd
   from tensorflow.keras.preprocessing.text import Tokenizer
   from tensorflow.keras.preprocessing.sequence import pad_sequences
   df = pd.read_csv('customer_reviews.csv')  # columns: 'text', 'sentiment'
   tokenizer = Tokenizer(num_words=10000, oov_token='<OOV>')
   tokenizer.fit_on_texts(df['text'])
   seqs = tokenizer.texts_to_sequences(df['text'])
   x_train = pad_sequences(seqs, maxlen=200, padding='post', truncating='post')
   y_train = df['sentiment'].values

2. SWITCH TO BIDIRECTIONAL LSTM (Reads forward and backward):
   # Replace: LSTM(units=64, dropout=0.2, recurrent_dropout=0.2)
   # With:
   layers.Bidirectional(layers.LSTM(units=64, dropout=0.2, recurrent_dropout=0.2))

3. SWITCH TO GRU (Faster training, fewer parameters than LSTM):
   # Replace: LSTM(...)
   # With:
   layers.GRU(units=64, dropout=0.2, recurrent_dropout=0.2)

4. SWITCH OPTIMIZERS:
   # Replace: optimizer='adam'
   # With:
   optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0005)
================================================================================
