import joblib import tensorflow as tf import numpy as np def fix_tokenizer_issue(): """ Script untuk memperbaiki masalah tokenizer OOV """ # Load tokenizer dan model try: tokenizer = joblib.load("tokenizer_raw.pkl") model = tf.keras.models.load_model("best_bilstm_model.h5") print("๐Ÿ“Š Tokenizer Info:") print(f"Vocabulary size: {len(tokenizer.word_index)}") print(f"Model input shape: {model.input_shape}") # Check embedding layer embedding_layer = model.layers[1] # Assuming embedding is second layer print(f"Embedding input dim: {embedding_layer.input_dim}") # Test dengan beberapa kata test_words = ["saya", "marah", "sekali", "anjing", "bahagia"] print("\n๐Ÿ” Testing words:") for word in test_words: seq = tokenizer.texts_to_sequences([word]) print(f"'{word}' -> {seq}") if seq[0]: # If sequence is not empty max_index = max(seq[0]) if max_index >= embedding_layer.input_dim: # Fix: compare with embedding layer print(f" โš ๏ธ Index {max_index} exceeds embedding vocab size ({embedding_layer.input_dim})!") else: print(f" โœ… Index {max_index} is valid") # Solution: Filter tokenizer print("\n๐Ÿ”ง Applying fix...") # Get model's actual vocabulary size from embedding layer actual_vocab_size = embedding_layer.input_dim # Create filtered word_index filtered_word_index = {} for word, idx in tokenizer.word_index.items(): if idx < actual_vocab_size: filtered_word_index[word] = idx # Update tokenizer tokenizer.word_index = filtered_word_index print(f"โœ… Fixed! New vocabulary size: {len(tokenizer.word_index)}") print(f"Model embedding vocab size: {actual_vocab_size}") # Save fixed tokenizer joblib.dump(tokenizer, "tokenizer_raw_fixed.pkl") print("๐Ÿ’พ Saved as tokenizer_raw_fixed.pkl") # Test the fix print("\n๐Ÿงช Testing fix:") for word in test_words: seq = tokenizer.texts_to_sequences([word]) print(f"'{word}' -> {seq}") if seq[0]: max_index = max(seq[0]) if max_index >= actual_vocab_size: print(f" โŒ Still has issue: {max_index} >= {actual_vocab_size}") else: print(f" โœ… Fixed: {max_index} < {actual_vocab_size}") return True except FileNotFoundError as e: print(f"โŒ File not found: {e}") print("Pastikan file 'tokenizer_raw.pkl' dan 'best_bilstm_model.h5' ada di directory yang sama") return False except Exception as e: print(f"โŒ Error: {e}") return False def create_safe_tokenizer_function(): """ Membuat fungsi helper untuk safe tokenization """ code = ''' def safe_texts_to_sequences(tokenizer, texts, max_vocab_size=None): """ Safe version of texts_to_sequences yang menghindari OOV error """ if max_vocab_size is None: max_vocab_size = len(tokenizer.word_index) + 1 sequences = tokenizer.texts_to_sequences(texts) # Filter out indices that exceed vocabulary filtered_sequences = [] for seq in sequences: filtered_seq = [idx for idx in seq if idx < max_vocab_size] filtered_sequences.append(filtered_seq) return filtered_sequences # Usage example: # sequences = safe_texts_to_sequences(tokenizer, [text], embedding_layer.input_dim) ''' with open("safe_tokenizer_helper.py", "w") as f: f.write(code) print("๐Ÿ’พ Created safe_tokenizer_helper.py") if __name__ == "__main__": print("๐Ÿš€ Starting tokenizer fix process...\n") success = fix_tokenizer_issue() if success: print("\nโœ… Tokenizer fix completed successfully!") print("๐Ÿ“ Files created:") print(" - tokenizer_raw_fixed.pkl") create_safe_tokenizer_function() print(" - safe_tokenizer_helper.py") print("\n๐Ÿ“‹ Next steps:") print("1. Replace 'tokenizer_raw.pkl' dengan 'tokenizer_raw_fixed.pkl' di app.py") print("2. Atau gunakan safe_texts_to_sequences() function untuk handling OOV") print("3. Deploy ulang Hugging Face Space") else: print("\nโŒ Fix process failed. Check the error messages above.")