🔤 Parstoken
High-Performance Persian Text Preprocessing & Token Optimization for Large Language Models
A production-grade, zero-dependency Python toolkit designed to normalize, clean, and optimize Persian (Farsi) text for modern LLM APIs (OpenAI, Anthropic Claude, Google Gemini, Llama 3) — reducing token counts by up to 30–50% while preserving semantic meaning.
Key Features · Ecosystem Importance · Installation · Quick Start · LLM Integrations · Benchmarks · Governance & Maintenance
🌍 Ecosystem Importance
Right-to-Left (RTL) languages like Persian (Farsi), spoken by over 110 million people worldwide, face systemic inefficiencies in modern AI infrastructure:
- Token Inefficiency & Disproportionate API Costs: Generic BPE/WordPiece tokenizers (cl100k_base, Tiktoken, Llama) are heavily English-skewed. Persian text often requires 3× to 5× more tokens per word than English, placing higher financial and latency burdens on Persian-speaking developers.
- Character & Unicode Fragmentation: Widespread Arabic/Persian letter confusion (
يvsی,كvsک), inconsistent Zero-Width Non-Joiner (ZWNJ / نیمفاصله) usage, and unnecessary diacritics fragment vocabulary embeddings and degrade LLM comprehension. - The Open-Source Tooling Void: Legacy libraries (Hazm, Parsivar) were built for classical statistical NLP and are not designed for LLM context windows, prompt compression, or modern async pipelines.
Parstoken bridges this critical gap by delivering a modern, high-throughput, zero-dependency preprocessor engineered specifically for LLM workflows and retrieval-augmented generation (RAG).
✨ Key Features
| Capability | Technical Mechanism | Impact on LLMs |
|---|---|---|
| 🔄 Unicode & Script Normalization | Converts Arabic variants (ك, ي, ة, ۀ) to standard Persian glyphs; applies canonical NFC normalization. |
Prevents split subword tokens and ensures consistent embeddings. |
| 📏 Smart ZWNJ Management | Standardizes Zero-Width Non-Joiner (\u200c) around affixes (می, ها, تر) while removing orphaned ZWNJs. |
Preserves compound word semantics without wasting tokens. |
| ⚡ Repetition & Redundancy Compression | Compresses elongated characters (e.g., سلاااام → سلام) and redundant punctuation (؟؟؟ → ؟). |
Cuts token usage by 15–50% on informal and user-generated text. |
| ✂️ Diacritics & Noise Stripping | Removes Arabic short vowels (tashkeel/harakat) and unnecessary control characters. | Eliminates unnecessary tokens that carry zero prompt utility. |
| 🧹 Production-Ready Sanitizer | Configurable stripping of HTML/XML, URLs, emails, phone numbers, and social media artifacts. | Clean prompts for fine-tuning, RAG ingestion, and safety filters. |
| 🔢 Bidirectional Digit Conversion | Normalizes between Eastern Arabic (١٢٣), Persian (۱۲۳), and ASCII (123) digits. |
Consistent numeric representation for function calling and extraction. |
| 📊 Token Estimation & Metrics | Real-time token savings calculations calibrated for GPT-4, Claude, and Gemini models. | Instant observability of cost and latency improvements. |
| ⚡ Extreme Throughput | Pure Python implementation with zero third-party dependencies processing >24M chars/sec. | Negligible overhead in high-throughput production pipelines. |
📦 Installation
pip install parstoken
For development and running tests locally:
git clone https://github.com/ilifield/parstoken.git
cd parstoken
pip install -e ".[dev]"
🚀 Quick Start
1. One-Line Preprocessing Pipeline
from parstoken import pipeline
# Raw text with Arabic letters, elongation, diacritics, and redundant spacing
raw_text = "سلاااام دوست من! اين يك تَستِ عاااالی است... چطورییی؟؟؟"
result = pipeline(raw_text)
print(result.text)
# Output: سلام دوست من! این یک تست عالی است. چطوری؟
print(result.savings_summary)
# Output: Saved 12 tokens (38.7%) -- 31 -> 19
2. Unicode & Script Normalization
from parstoken import PersianNormalizer
normalizer = PersianNormalizer(
fix_arabic_chars=True, # ك -> ک, ي -> ی, ة -> ه
remove_diacritics=True, # Remove tashkeel (َ ُ ِ ّ ْ)
normalize_halfspace=True, # Standardize ZWNJ (نیمفاصله)
digit_target="fa" # Convert English digits to Persian (123 -> ۱۲۳)
)
text = normalizer.normalize("كتاب هاي آموزشي شماره 123 با تخفيف ويژه")
print(text)
# Output: کتابهای آموزشی شماره ۱۲۳ با تخفیف ویژه
3. Token-Saving Compression
from parstoken import TokenOptimizer
optimizer = TokenOptimizer(
compress_repeated_chars=True,
compress_repeated_punctuation=True,
remove_redundant_spaces=True
)
result = optimizer.optimize("واقعاااااا دستت درد نکنهههه!!!!! خیلییی خوب بوددددد")
print(result.text)
# Output: واقعا دستت درد نکنه! خیلی خوب بود
print(f"Characters saved: {result.chars_saved}")
print(f"Token reduction: {result.savings_percentage:.1f}%")
🔗 LLM Pipeline Integrations
OpenAI & LangChain Integration
from langchain_core.documents import Document
from parstoken import PersianNormalizer, TokenOptimizer
import openai
normalizer = PersianNormalizer()
optimizer = TokenOptimizer()
def preprocess_persian_prompt(user_query: str) -> str:
"""Normalize and compress Persian text before sending to OpenAI."""
normalized = normalizer.normalize(user_query)
optimized = optimizer.optimize(normalized).text
return optimized
# Example prompt
query = "لطفاااا درباره تاريخچه هوش مصنوعي توضيح بدهههه!"
optimized_query = preprocess_persian_prompt(query)
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant responding in Persian."},
{"role": "user", "content": optimized_query}
]
)
RAG & Hugging Face Dataset Ingestion
from parstoken import pipeline
def clean_dataset_record(record: dict) -> dict:
"""Prepare Persian corpus for embedding or fine-tuning."""
processed = pipeline(
record["text"],
normalize=True,
clean=True,
optimize=True
)
return {"text": processed.text, "tokens_saved": processed.tokens_saved}
💻 CLI Usage
Parstoken includes a comprehensive CLI suitable for batch processing, CI/CD data pipelines, and shell scripting:
# Normalize a file
parstoken normalize dataset.txt -o cleaned.txt
# Run full pipeline with token statistics
parstoken pipeline input.txt --normalize --clean --optimize --stats
# Filter social media noise
parstoken clean comments.txt --remove-emojis --remove-hashtags --remove-mentions
# Count and estimate tokens across models
parstoken count document.txt --model gpt-4o
# Pipe via standard input / Unix pipelines
cat corpus.txt | parstoken optimize --stats > optimized.txt
📈 Benchmarks
Tested on standard hardware across varying text structures:
| Module | Processing Throughput | Efficiency |
|---|---|---|
| Text Normalizer | 24.6M+ chars/sec | Sub-millisecond on 100K-word files |
| Noise Cleaner | 28.6M+ chars/sec | Regex-compiled single pass |
| Token Optimizer | 3.1M+ chars/sec | 15–50% token reduction on chat data |
| Full Pipeline | 2.8M+ chars/sec | Comprehensive end-to-end cleaning |
🛡️ Governance & Active Maintenance
Parstoken is an actively maintained open-source project adhering to strict community and engineering standards:
- 100% Test Coverage Strategy: Comprehensive suite of 76 unit tests validating Unicode mappings, boundary rules, diacritics stripping, and CLI operations across Python 3.8–3.13.
- Cross-Platform Continuous Integration: Automated GitHub Actions matrix testing on Ubuntu, macOS, and Windows.
- Semantic Versioning & Release Cycles: Stable releases following SemVer with thorough CHANGELOG documentation.
- Strict Issue Triage & PR Review SLA:
- Issue response within 48 hours.
- Standardized templates for bug reports and feature requests.
- Required CI validation and code review before PR merge.
Core Maintainer
- Iliya Sharifi (@ilifield) — Primary Maintainer
🤝 Contributing
Contributions from the open-source community are warmly welcomed! Please read our CONTRIBUTING.md guide before submitting a pull request.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/awesome-addition) - Commit your Changes (
git commit -m 'feat: add enhanced affix normalization') - Verify Tests Pass (
pytest) - Push to the Branch (
git push origin feature/awesome-addition) - Open a Pull Request
📜 License
Distributed under the MIT License. See LICENSE for more information.
Metadata
Release files for parstoken 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| parstoken-0.3.0.tar.gz | 28.8 kB | Without provenance | Details for parstoken-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| parstoken-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for parstoken-0.3.0-py3-none-any.whl |
Total release size: 50.4 kB
Release files / parstoken-0.3.0.tar.gz
| Download URL | parstoken-0.3.0.tar.gz |
|---|---|
| Size | 28.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e1d1f80750329a05cad2fe8831c94901270d8e1027b624d0efdb738d348ac91a
|
|
BLAKE2b-256 checksum How to use checksums |
ac639f55b27f0ef779efbddacbc96d2f3395fb6c8e8e8e6d6499bf570ad6905f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.3
|
Release files / parstoken-0.3.0-py3-none-any.whl
| Download URL | parstoken-0.3.0-py3-none-any.whl |
|---|---|
| Size | 21.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a4d9fd679a6a01639775d68ba23887e9aa727090f3a37701f1002272d0685e0b
|
|
BLAKE2b-256 checksum How to use checksums |
43a10738274f8fb3dcba358f9921630ed7c43c31b53d3f6351818eca69008654
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.3
|
Security for parstoken 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.