A lightweight text processing library for pattern matching, similarity, classification and clustering
Project description
# PatternMind
[](https://opensource.org/licenses/Apache-2.0)
[](https://www.python.org/downloads/)
[](https://pypi.org/project/patternmind/)
**PatternMind** is a lightweight, dependency-free Python library for text processing and pattern learning. It provides powerful tools for similarity calculation, pattern recognition, text classification, clustering, and segmentation — all without requiring external NLP libraries.
## Features
- **Pattern Learning**: Train models to recognize patterns and generate responses (`train_pattern`, `predict_pattern`)
- **Similarity Calculation**: Measure semantic similarity between texts (`predict_similarity`, `train_similarity`)
- **Text Classification**: Train classifiers and predict labels for new texts (`train_class`, `predict_class`)
- **Clustering**: Automatically group similar sentences (`predict_cluster`)
- **Segmentation**: Split sentences into all possible n-grams (`predict_segment`)
## Installation
```bash
pip install patternmind
Quick Start
Similarity Calculation
import patternmind as pm
# Calculate similarity with default model
result = pm.predict_similarity("I love programming", "I enjoy coding")
print(result["result"]) # 85.5
# Train a custom similarity model
model = pm.train_similarity(
terms1=["I love Python", "I like Python"],
terms2=["I enjoy Python", "I adore Python"],
marks=[0.9, 0.8]
)
print(model["alpha"], model["beta"]) # 0.7, 0.3
# Use trained model
score = pm.predict_similarity("I love Python", "I enjoy Python", model)
print(score["result"]) # 87.3
Pattern Learning
import patternmind as pm
# Train a pattern model
model = pm.train_pattern(
inputs=["What is the capital of France?", "Capital of Germany?"],
outputs=["Paris", "Berlin"]
)
# Predict response
result = pm.predict_pattern("What is the capital of Italy?", model)
print(result["result"]) # Rome
# Find best matching pattern
best = pm.find_pattern("Capital of Spain?", [model])
print(best["result"]) # 0 (index of matched model)
Text Classification
import patternmind as pm
# Train classifier
model = pm.train_class(
inputs=["I love this product", "Terrible service"],
outputs=["positive", "negative"]
)
# Predict
result = pm.predict_class("Great experience!", model)
print(result["result"]) # positive
Clustering
import patternmind as pm
sentences = [
"I love programming",
"Coding is fun",
"Python is great",
"I hate bugs"
]
clusters = pm.predict_cluster(sentences, least=0.5)
print(clusters["result"])
# [['I love programming', 'Coding is fun', 'Python is great'], ['I hate bugs']]
Segmentation
import patternmind as pm
segments = pm.predict_segment("I love Python")
print(segments["result"])
# ['I', 'I love', 'I love Python', 'love', 'love Python', 'Python']
API Reference
Core Functions
predict_segment(sentence)
Generates all possible n-gram segments of a sentence.
Parameters:
· sentence (str): Input sentence
Returns:
· dict: {"result": list_of_segments}
predict_similarity(term1, term2, model)
Calculates similarity between two texts using a trained model.
Parameters:
· term1 (str): First text · term2 (str): Second text · model (dict): Model with alpha, beta, and synonyms
Returns:
· dict: {"result": similarity_score}
train_similarity(terms1, terms2, marks)
Trains a similarity model by finding optimal alpha and beta weights.
Parameters:
· terms1 (list): List of first texts · terms2 (list): List of second texts · marks (list): List of similarity scores (0-100)
Returns:
· dict: Model with alpha, beta, synonyms, and loss
train_pattern(inputs, outputs)
Trains a pattern recognition model.
Parameters:
· inputs (list): List of input patterns · outputs (list): List of corresponding outputs
Returns:
· dict: Model with pattern, sames, and loss
predict_pattern(text, model)
Predicts output for new text using a trained pattern model.
Parameters:
· text (str): Input text · model (dict): Trained pattern model
Returns:
· dict: {"result": predicted_output}
find_pattern(query, content, least)
Finds the best matching pattern model for a query.
Parameters:
· query (str): Text to match · content (list): List of pattern models · least (int): Minimum score threshold
Returns:
· dict: {"result": best_model_index}
train_class(inputs, outputs)
Trains a text classifier.
Parameters:
· inputs (list): List of texts · outputs (list): List of corresponding labels
Returns:
· dict: Model with tags, words, and loss
predict_class(query, model)
Predicts label for new text using a trained classifier.
Parameters:
· query (str): Text to classify · model (dict): Trained classifier model
Returns:
· dict: {"result": predicted_label}
predict_cluster(sentences, least, model)
Clusters similar sentences together.
Parameters:
· sentences (list): List of texts to cluster · least (float): Similarity threshold (0-1) · model (dict): Similarity model (optional)
Returns:
· dict: {"result": list_of_clusters}
Advanced Usage
Custom Similarity Training
import patternmind as pm
# Train with custom data
model = pm.train_similarity(
terms1=[
"I love programming",
"Python is awesome",
"Coding makes me happy"
],
terms2=[
"I enjoy coding",
"Python is great",
"Programming brings joy"
],
marks=[0.9, 0.85, 0.8]
)
# Use trained model
score = pm.predict_similarity(
"I love coding",
"Programming is fun",
model
)
print(score["result"])
Building a Chatbot with Pattern Recognition
import patternmind as pm
# Train patterns
patterns = [
{"input": "What is your name?", "output": "My name is PatternMind"},
{"input": "How are you?", "output": "I'm doing great, thanks!"},
{"input": "What can you do?", "output": "I can process text and learn patterns"}
]
inputs = [p["input"] for p in patterns]
outputs = [p["output"] for p in patterns]
# Train model
model = pm.train_pattern(inputs, outputs)
# Chat loop
while True:
user_input = input("You: ")
response = pm.predict_pattern(user_input, model)
print(f"Bot: {response['result']}")
Text Classification with Custom Data
import patternmind as pm
# Training data
texts = [
"I love this movie", "Great film", "Amazing acting",
"Terrible movie", "Waste of time", "Boring film"
]
labels = [
"positive", "positive", "positive",
"negative", "negative", "negative"
]
# Train classifier
model = pm.train_class(texts, labels)
# Test
test_texts = ["Fantastic movie!", "Horrible experience"]
for text in test_texts:
result = pm.predict_class(text, model)
print(f"{text} -> {result['result']}")
Model Persistence
Models can be saved and loaded using JSON serialization:
import json
# Save model
with open("model.json", "w") as f:
json.dump(model, f)
# Load model
with open("model.json", "r") as f:
loaded_model = json.load(f)
License
Apache License 2.0. See LICENSE and NOTICE for details.
Links
· Website: patternmind.ir · GitHub: github.com/patternmind/patternmind · Telegram: @patternmind
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests on GitHub.
Made with ❤️ by Ehsan Saeedi
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file patternmind-1.1.2.tar.gz.
File metadata
- Download URL: patternmind-1.1.2.tar.gz
- Upload date:
- Size: 18.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3b27ecf5af1ec594f2a045812009f4863944d4124fd2059f37465285fa4fc369
|
|
| MD5 |
147572f511723c6b9d7ec0b0d03bf12c
|
|
| BLAKE2b-256 |
f5cf8e1adeb37ed35597d24cbed1a78f39c4e27155b3bd8d0869c6fd77761108
|