Views
No views yet
pages/04_Hamlet_Next_Word_LSTM.py)artifacts/next_word_lstm.h5 — trained Keras modelartifacts/tokenizer.pickle — fitted Keras Tokenizerartifacts/config.json — generation/config values (e.g., max_sequence_len, vocab cap)hamlet.txt — training text used in the notebookmax_sequence_len = 40 (from artifacts/config.json)1import pickle
2import numpy as np
3import tensorflow as tf
4from huggingface_hub import hf_hub_download
5from tensorflow.keras.preprocessing.sequence import pad_sequences
6
7REPO_ID = "ash001/hamlet-nextword-lstm"
8
9# Download artifacts
10model_path = hf_hub_download(REPO_ID, "artifacts/next_word_lstm.h5")
11tok_path = hf_hub_download(REPO_ID, "artifacts/tokenizer.pickle")
12cfg_path = hf_hub_download(REPO_ID, "artifacts/config.json")
13
14model = tf.keras.models.load_model(model_path, compile=False)
15with open(tok_path, "rb") as f:
16 tokenizer = pickle.load(f)
17
18import json
19cfg = json.load(open(cfg_path, "r"))
20max_sequence_len = int(cfg["max_sequence_len"])
21
22def next_word_topk(seed_text: str, k: int = 10):
23 token_list = tokenizer.texts_to_sequences([seed_text])[0]
24 token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding="pre")
25 probs = model.predict(token_list, verbose=0)[0]
26 top_idx = np.argsort(probs)[-k:][::-1]
27 return [(tokenizer.index_word.get(int(i), ""), float(probs[i])) for i in top_idx]
28
29print(next_word_topk("what a piece of work", k=10))