A sophisticated predictive text system that combines rule-based NLP techniques with deep learning models to provide accurate, context-aware text predictions in real-time.
- Hybrid Prediction System: Combines ML models with rule-based fallbacks for robust predictions
- Real-time Predictions: Instant suggestions as you type with configurable debouncing
- Offline Support: Complete caching system for offline operation
- Multiple Models: Support for both formal (Wikipedia-trained) and conversational (chat-trained) models
- Smart Fallbacks: Automatically switches to rule-based predictions when ML confidence is low
- Enhanced BiLSTM Architecture: Bidirectional LSTM with attention mechanism for better context understanding
- N-gram Models: Unigram, bigram, and trigram models for rule-based predictions
- POS Tagging: Part-of-speech aware predictions for grammatically correct suggestions
- Intelligent Caching: Multi-level caching for instant responses
- Model Persistence: All models and data are cached locally for offline use
- Python 3.8 or higher
- 4GB+ RAM recommended
- 2GB+ free disk space for models and datasets
-
Clone or download the project files
-
Create a virtual environment (recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Download NLTK data (first time only):
python -c "import nltk; nltk.download('punkt'); nltk.download('averaged_perceptron_tagger'); nltk.download('brown'); nltk.download('stopwords')"- Start the server:
python app.py- Open your browser and navigate to:
http://localhost:5000
- The system will automatically initialize with rule-based predictions. You can start typing immediately!
- Train a formal (Wikipedia) model:
python model_train.py --mode wiki --limit 20000 --epochs 10- Train a conversational (chat) model:
python model_train.py --mode chat --limit 20000 --epochs 10- Start the server with trained models:
python app.py- Typing Area: Start typing in the text area to see real-time predictions
- Suggestions: Click on any suggestion chip to apply it to your text
- Modes:
- Hybrid: Combines ML and rule-based (recommended)
- ML Only: Uses only the neural network model
- Rule Only: Uses only linguistic rules
POST /predict
Content-Type: application/json
{
"text": "I want to",
"mode": "hybrid",
"ml_mode": "wiki",
"k": 5
}POST /train
Content-Type: application/json
{
"mode": "wiki",
"limit": 20000,
"epochs": 10,
"batch_size": 128
}POST /evaluate
Content-Type: application/json
{
"mode": "wiki",
"sample_size": 1000
}βββββββββββββββββββββββββββββββββββββββββββ
β Web Interface (HTML) β
βββββββββββββββββββ¬ββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββ
β Flask Application (app.py) β
ββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Request handling β
β β’ Prediction service β
β β’ Model management β
β β’ Caching layer β
ββββββββββββ¬βββββββββββββββββββ¬ββββββββββββ
β β
ββββββββββββΌβββββββ ββββββββββΌβββββββββββ
β Rule-Based β β ML Models β
β Predictor β β (BiLSTM) β
βββββββββββββββββββ€ βββββββββββββββββββββ€
β β’ N-grams β β β’ Wikipedia β
β β’ POS tagging β β β’ Chat/Dialog β
β β’ Patterns β β β’ Attention β
βββββββββββββββββββ βββββββββββββββββββββ
Input Text β Tokenization β Embedding (256d)
β
Bidirectional LSTM (256 units)
β
Bidirectional LSTM (128 units)
β
Dense Layer (512)
β
Dropout (0.4)
β
Dense Layer (256)
β
Dropout (0.3)
β
Output (Vocabulary Size)
- Phrase Completions: Common phrase patterns (e.g., "I want to" β ["go", "eat", "see"])
- N-gram Models: Statistical predictions based on word sequences
- POS Patterns: Grammar-aware predictions based on part-of-speech tags
- Word Associations: Context-aware word relationships
- Model Caching: All trained models are saved to disk
- Prediction Caching: Recent predictions are cached in memory
- Dataset Caching: Downloaded datasets are cached locally
- Tokenizer Caching: Preprocessed tokenizers are persisted
- Debouncing: Configurable delay (200ms default) to reduce API calls
- Batch Processing: Efficient batch inference for multiple predictions
- Memory Management: Automatic cache size limits and cleanup
Edit in model_train.py:
max_vocab = 20000 # Maximum vocabulary size
max_seq_len = 30 # Maximum sequence length
embedding_dim = 256 # Embedding dimensions
lstm_units = 256 # LSTM unit countEdit in app.py:
CACHE_MAX_SIZE = 1000 # Maximum prediction cache entries
debug = True # Debug mode
host = "127.0.0.1" # Server host
port = 5000 # Server port# Customize training
python model_train.py \
--mode wiki \
--limit 50000 \ # Number of sentences
--epochs 15 \ # Training epochs
--batch-size 256 # Batch sizeproject/
βββ app.py # Flask application
βββ model_train.py # ML model training
βββ rule_based_predictive_keyboard.py # Rule-based predictor
βββ index.html # Web interface
βββ requirements.txt # Python dependencies
βββ README.md # Documentation
βββ model_cache/ # Cached models (created automatically)
β βββ wiki_bilstm_final.h5 # Wikipedia model
β βββ chat_bilstm_final.h5 # Chat model
β βββ tokenizer_wiki.pkl # Wikipedia tokenizer
β βββ tokenizer_chat.pkl # Chat tokenizer
β βββ rule_based_model.pkl # Rule-based model
β βββ sentences_*.pkl # Cached datasets
βββ templates/ # HTML templates (if using)
βββ index.html
-
"Model not found" error:
- Solution: Train the model first using
python model_train.py
- Solution: Train the model first using
-
Slow predictions:
- Solution: Reduce
topKvalue or increase debounce delay
- Solution: Reduce
-
Out of memory:
- Solution: Reduce
limitparameter when training or use smaller batch size
- Solution: Reduce
-
Dataset download fails:
- Solution: Check internet connection; cached data will be used if available
-
NLTK data not found:
- Solution: Run the NLTK download command in the installation section
- For faster startup: Use pre-trained models from cache
- For better accuracy: Train with more data (increase
limit) - For faster predictions: Use rule-based mode or reduce suggestion count
- For offline use: Train models once and they'll be cached permanently
After training, you can evaluate your models:
- Top-1 Accuracy: Percentage of correct next-word predictions
- Top-5 Accuracy: Percentage where correct word is in top 5 predictions
- Perplexity: Lower is better (measures prediction uncertainty)
Expected performance:
- Rule-based: 15-25% Top-1 accuracy
- ML (trained on 20k sentences): 35-45% Top-1 accuracy
- ML (trained on 50k+ sentences): 45-55% Top-1 accuracy
To use your own dataset:
- Add your dataset loader in
model_train.py:
def load_custom_dataset():
# Your code here
return sentences- Train with custom data:
sentences = load_custom_dataset()
trainer = PredictiveKeyboardTrainer()
trainer.train(sentences)The system can be integrated into other applications:
import requests
# Get predictions
response = requests.post('http://localhost:5000/predict',
json={'text': 'Hello', 'mode': 'hybrid', 'k': 5})
predictions = response.json()['suggestions']This project is provided as-is for educational and development purposes.
Improvements are welcome! Consider:
- Adding more sophisticated language models (GPT, BERT)
- Implementing user personalization
- Adding multi-language support
- Improving the UI/UX
- Adding voice input support
| Mode | Response Time | Accuracy (Top-1) | Accuracy (Top-5) |
|---|---|---|---|
| Rule-based | <10ms | 20% | 35% |
| ML (cached) | 15-30ms | 40% | 65% |
| Hybrid | 20-40ms | 45% | 70% |
Benchmarks on Intel i5, 8GB RAM with 20k training sentences
Ready to start? Run python app.py and open http://localhost:5000 π