File size: 4,813 Bytes
a7a8f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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.")