PerSent (Persian Sentiment Analyzer)
PerSent is a lightweight Python library for sentiment and emotion analysis of Persian (Farsi) text.
CommentAnalyzerclassifies product/service reviews asrecommended,not_recommendedorno_idea(Word2Vec sentence embeddings + logistic regression).SentimentAnalyzerscores seven emotions with a weighted lexicon: شادی (happiness), غم (sadness), ترس (fear), عصبانیت (anger), تنفر (disgust), شگفتی (surprise), آرامش (calmness).- Single texts or whole CSV files, pre-trained models included, train your own models from CSV.
Installation
pip install PerSent
Requires Python 3.10–3.13. Pre-trained models are bundled with the package, so no download is needed at runtime.
Quick start
Review / comment polarity
from PerSent import CommentAnalyzer
analyzer = CommentAnalyzer()
analyzer.loadModel() # bundled pre-trained model
analyzer.analyzeText("کیفیت عالی داشت") # 'recommended'
analyzer.analyzeText("افتضاح بود") # 'not_recommended'
analyzer.analyzeTexts(["خوب بود", "بد بود"]) # list of labels
Batch-process a CSV file (adds a sentiment column):
analyzer.analyzeCSV("comments.csv", "results.csv") # first column
analyzer.analyzeCSV("comments.csv", "results.csv", None, -1) # last column
analyzer.analyzeCSV("comments.csv", "results.csv", None, "نظرات") # column by name
analyzer.analyzeCSV("comments.csv", "results.csv", "summary.csv") # + summary report
Emotions
from PerSent import SentimentAnalyzer
analyzer = SentimentAnalyzer()
analyzer.loadModel()
result = analyzer.analyzeText("امتحانم رو خراب کردم. احساس میکنم یک شکست خوردهی تمام عیارم.")
for emotion, score in sorted(result.items(), key=lambda x: x[1], reverse=True):
print(f"{emotion}: {score:.2f}%")
غم: 36.00%
عصبانیت: 36.00%
ترس: 28.00%
شادی: 0.00%
...
analyzer.analyzeCSV("input.csv", "output.csv") # text column 'text' -> 'sentiment_analysis'
Training and saving your own models
Pass a model_dir to keep your own models. Without it, loadModel() always loads the bundled
pre-trained model and train() keeps the result in memory only.
from PerSent import CommentAnalyzer, SentimentAnalyzer
comments = CommentAnalyzer(model_dir="my_models")
accuracy = comments.train("train.csv", random_state=42) # saved to my_models/comment_model.npz
comments.loadModel() # later: loads from my_models/
emotions = SentimentAnalyzer(model_dir="my_models")
emotions.train("dataset/emotion_dataset.csv") # saved to my_models/weighted_sentiment_model.json
emotions.saveModel("custom") # my_models/custom.json
emotions.loadModel("custom")
API reference
CommentAnalyzer(model_dir=None)
| Method | Description |
|---|---|
train(train_csv, test_size=0.2, vector_size=100, window=5, random_state=None, text_column="body", label_column="recommendation_status", workers=4) |
Train from a CSV. Labels must be recommended, not_recommended or no_idea; empty labels count as no_idea. Returns held-out accuracy. Saves to model_dir if set. |
analyzeText(text) |
Label for one text. Texts without letters (empty, digits only, …) return no_idea. |
analyzeTexts(texts, show_progress=False) |
Labels for many texts. |
analyzeCSV(input_csv, output_path, summary_path=None, text_column=0) |
Analyze a CSV column (name or 0-based / negative index). Returns a DataFrame, or None on error. |
saveModel(model_dir=None) / loadModel(model_dir=None) |
Save / load comment_model.npz. loadModel falls back to the bundled model. |
SentimentAnalyzer(model_dir=None)
| Method | Description |
|---|---|
train(train_csv, text_col="text", emotion_col=None, weight_col="weight", reset=False) |
Learn weighted emotion words from a CSV. emotion_col defaults to sentiment (or emotion). Merges into the current model unless reset=True. Returns {"status", "message"}. |
loadLex(csv_file, word_col=0, emotion_col=1, weight_col=2) |
Add a word/emotion/weight lexicon. Columns by index, or by name for CSVs with a header. Invalid weights default to 1.0. |
analyzeText(text) |
{emotion: percentage} for the seven emotions (all 0.0 if no lexicon word is found). |
analyzeCSV(input_csv, output_csv, text_col="text", output_col="sentiment_analysis") |
Analyze a CSV. Returns True / False. |
saveModel(model_name="weighted_sentiment_model", model_dir=None) / loadModel(...) |
Save / load <model_name>.json. |
Errors derive from PerSent.PerSentError (ModelNotLoadedError, ModelFileError, DataValidationError).
Progress and status messages use the standard logging module (logger name "PerSent").
Model quality and limitations
- The bundled comment model reaches about 65 % accuracy (macro-F1 ≈ 0.64) on a 10 000-review sample of
dataset/train.csv(three balanced classes, so chance level is 33 %). Better models are planned. - The emotion analyzer is lexicon-based and does not handle negation yet ("خوشحال نیستم" is scored as happiness).
- hazm's stop-word list contains common opinion words such as "خوب" and "عالی", which are removed before classification.
A larger training set is available here.
Upgrading from 1.3.x
- Models are stored in safe, pickle-free formats (
.npz/.json). Models you saved with 1.3.x can still be loaded withCommentAnalyzer(model_dir=...)/SentimentAnalyzer(model_dir=...)(aDeprecationWarningis shown); callsaveModel()once to convert them.scripts/convert_legacy_models.pyconverts a folder in one go. - PerSent no longer creates or reads a
PerSent/modelfolder in the current working directory. Passmodel_direxplicitly to save and load your own models.
See CHANGELOG.md for all changes.
Development
git clone https://github.com/RezaGooner/PerSent.git
cd PerSent
pip install -e ".[dev]"
pytest
ruff check . && ruff format --check .
Contributing
Bug reports, ideas and pull requests are welcome — see CONTRIBUTING.
- Open an issue
- Fork and send a pull request
- Email:
RezaAsadiProgrammer@gmail.com· Telegram:@RezaGooner
The project grew out of Sentiment-Survey-Analyzer.
License
Metadata
Release files for PerSent 1.4.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 |
|---|---|---|---|---|
| persent-1.4.0.tar.gz | 13.8 MB | With provenance | Details for persent-1.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| persent-1.4.0-py3-none-any.whl | Python 3 | none | any | Details for persent-1.4.0-py3-none-any.whl |
Total release size: 27.5 MB
Release files / persent-1.4.0.tar.gz
| Download URL | persent-1.4.0.tar.gz |
|---|---|
| Size | 13.8 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2010bc34d0029aa043efb026a8fe985630001e5ddf95181f46f106ddbd0cacf6
|
|
BLAKE2b-256 checksum How to use checksums |
1062d68d9a8efcae576ec5fa0503cf1d801bf7b045210feb536d6d35bcd75a7f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logRelease files / persent-1.4.0-py3-none-any.whl
| Download URL | persent-1.4.0-py3-none-any.whl |
|---|---|
| Size | 13.8 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d1d8a125f70576453a54638e57e6381e213d168ec5291debbae103d8d66e2854
|
|
BLAKE2b-256 checksum How to use checksums |
4504160717786647c9e55c88e1866332f5f722e95bc9fe2170a308ae4b4a195a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logSecurity for PerSent 1.4.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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for persent-1.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logA 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.