Skip to main content

PerSent (Persian Sentiment Analyzer)

PyPI Python CI License: MIT Persian

PerSent Logo

PerSent is a lightweight Python library and command-line tool for sentiment and emotion analysis of Persian (Farsi) text.

  • PolarityClassifier labels product/service reviews as recommended, not_recommended or no_idea, with probabilities.
  • EmotionAnalyzer scores seven emotions with a weighted lexicon: شادی (happiness), غم (sadness), ترس (fear), عصبانیت (anger), تنفر (disgust), شگفتی (surprise), آرامش (calmness).
  • Pre-trained models included (no download at runtime), CSV in/out, train and evaluate your own models.

Installation

pip install PerSent

Requires Python 3.10–3.13.

Quick start

Review polarity

from PerSent import PolarityClassifier

clf = PolarityClassifier.pretrained()

clf.predict("کیفیت عالی داشت")                 # 'recommended'
clf.predict_proba("کیفیت عالی داشت")           # {'not_recommended': 0.13, 'recommended': 0.74, 'no_idea': 0.13}

result = clf.analyze("افتضاح بود")
result.label, result.confidence                # ('not_recommended', 0.9998)

clf.predict_many(["خوب بود", "پولم هدر رفت"])    # batch

Emotions

from PerSent import EmotionAnalyzer

emo = EmotionAnalyzer.pretrained()
result = emo.analyze("امتحانم رو خراب کردم. احساس می‌کنم یک شکست خورده‌ی تمام عیارم.")

result.scores          # {'شادی': 0.0, 'غم': 36.0, 'ترس': 28.0, 'عصبانیت': 36.0, ...}
result.dominant        # 'غم'
result.matched_words   # lexicon words that produced the scores
result.scores_en()     # {'happiness': 0.0, 'sadness': 36.0, 'fear': 28.0, 'anger': 36.0, ...}
result.to_dict(lang="en")

CSV files

clf.analyze_csv("comments.csv", "results.csv", text_column="نظرات",   # name or 0-based / negative index
                include_scores=True, summary_csv="summary.csv")

emo.analyze_csv("texts.csv", "emotions.csv", text_column="text", lang="en")  # one column per emotion

Both methods also accept a pandas.DataFrame and return the resulting DataFrame. Output files are UTF-8 with BOM, so they open correctly in Excel.

Command line

persent polarity "کیفیت عالی داشت" "افتضاح بود" --proba
echo "خیلی خوشحالم" | persent emotion --lang en
persent emotion --file texts.txt --json                    # one JSON object per line
persent csv comments.csv -o results.csv -c نظرات --scores --summary summary.csv
persent csv texts.csv -o emotions.csv --task emotion -c text
persent train polarity train.csv -o my_model/ --seed 42
persent evaluate test.csv -m my_model/

python -m PerSent ... works as well. Run persent <command> --help for all options.

Training, evaluating and saving models

from PerSent import PolarityClassifier, EmotionAnalyzer

clf = PolarityClassifier()
report = clf.fit_csv("dataset/train.csv", random_state=42)   # columns: body, recommendation_status
print(report)                  # Trained on ... texts, tested on ...: accuracy=..., macro-F1=...
clf.save("my_model/")          # -> my_model/comment_model.npz
clf = PolarityClassifier.load("my_model/")
print(clf.evaluate_csv("test.csv"))

emo = EmotionAnalyzer.pretrained()          # or EmotionAnalyzer() to start empty
emo.fit_csv("dataset/emotion_dataset.csv")  # columns: text, sentiment, weight
emo.add_lexicon("my_words.csv")             # word, emotion, weight
emo.add_word("سرمست", "happiness", weight=1.5)   # single words only
emo.save("my_emotions.json")
emo = EmotionAnalyzer.load("my_emotions.json")

Models are stored as plain .npz / .json files — loading them never executes code.

API reference

PolarityClassifier

Member Description
PolarityClassifier.pretrained() Bundled model.
PolarityClassifier.load(path) / save(path) Directory (comment_model.npz) or .npz file. 1.x pickle folders load with a warning.
predict(text) / predict_many(texts) Label(s). Texts without letters return no_idea.
predict_proba(text) {label: probability}.
analyze(text) / analyze_many(texts) PolarityResult(text, label, scores) with .confidence, .label_fa, .to_dict().
fit(texts, labels, *, vector_size=100, window=5, min_count=1, epochs=5, test_size=0.2, random_state=None, C=1.0, ...) Train Word2Vec + logistic regression. Returns a TrainingReport (accuracy, macro-F1, per-label metrics on a stratified hold-out split).
fit_csv(data, text_column="body", label_column="recommendation_status", **fit_kwargs) fit on a CSV path or DataFrame.
evaluate(texts, labels) / evaluate_csv(data, ...) EvaluationReport with accuracy, macro-F1, per-label metrics and confusion matrix.
analyze_csv(input, output=None, *, text_column=0, output_column="sentiment", include_scores=False, summary_csv=None) Analyze a column; returns a DataFrame.

EmotionAnalyzer

Member Description
EmotionAnalyzer.pretrained() Bundled lexicon.
EmotionAnalyzer.load(path) / save(path) .json file or directory.
analyze(text) / analyze_many(texts) EmotionResult(text, scores, matched_words) with .dominant, .dominant_en, .scores_en(), .to_dict(lang).
scores(text) / dominant(text) Shortcuts.
fit_csv(data, text_column="text", emotion_column=None, weight_column="weight", *, reset=False) Learn emotion words from labelled texts (merged into the current lexicon unless reset=True).
add_lexicon(data, word_column=0, emotion_column=1, weight_column=2) Add a word/emotion/weight table. Emotions may be Persian or English names.
add_word(word, emotion, weight=1.0) Add a single word.
analyze_csv(input, output=None, *, text_column="text", expand=True, lang="fa") One column per emotion plus dominant_emotion.

Errors derive from PerSent.PerSentError: ModelNotLoadedError, ModelFileError, DataValidationError (which is also a ValueError). Messages are logged with the standard logging module (logger "PerSent").

Model quality and limitations

  • The bundled polarity 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 opinion words such as "خوب", "بد" and "عالی", which are removed before classification; short reviews made only of such words are therefore unreliable.

A larger training set is available here.

Upgrading from 1.x

CommentAnalyzer and SentimentAnalyzer still work exactly as before but emit a DeprecationWarning; they will be removed in PerSent 2.0.

1.x 1.5+
a = CommentAnalyzer(); a.loadModel() clf = PolarityClassifier.pretrained()
a.analyzeText(t) clf.predict(t) (or clf.analyze(t) for probabilities)
a.analyzeTexts(ts) clf.predict_many(ts)
a.train(csv) → accuracy clf.fit_csv(csv) → TrainingReport
a.saveModel() / a.loadModel() with model_dir clf.save(dir) / PolarityClassifier.load(dir)
a.analyzeCSV(i, o, s, col) → DataFrame or None clf.analyze_csv(i, o, text_column=col, summary_csv=s) (raises on error)
s = SentimentAnalyzer(); s.loadModel() emo = EmotionAnalyzer.pretrained()
s.analyzeText(t) emo.analyze(t).scores
s.train(csv) → {"status": ...} emo.fit_csv(csv) (raises on error)
s.loadLex(csv) emo.add_lexicon(csv)
s.saveModel(name) / s.loadModel(name) emo.save(path) / EmotionAnalyzer.load(path)
s.analyzeCSV(i, o) → True / False emo.analyze_csv(i, o)

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.

The project grew out of Sentiment-Survey-Analyzer.

License

MIT

Metadata

Release files for PerSent 1.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for PerSent 1.5.0
File Size Uploaded Provenance Actions
persent-1.5.0.tar.gz 13.8 MB With provenance Details for persent-1.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for PerSent 1.5.0
File Interpreter ABI Platform Actions
persent-1.5.0-py3-none-any.whl Python 3 none any Details for persent-1.5.0-py3-none-any.whl

Total release size: 27.6 MB

Release files / persent-1.5.0.tar.gz

Download URL persent-1.5.0.tar.gz
Size 13.8 MB
Tags Source
SHA-256 checksum
How to use checksums
3f26b2cd955a36bbb95c943ad01529da8d82b220b896e9a4fcc73ad261e0e89d
BLAKE2b-256 checksum
How to use checksums
2ac752410b16f03b833495869e745c8b241a87ed7dddec8e4784d1e42320e0f0
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 11, 2026.

Transparency log

Release files / persent-1.5.0-py3-none-any.whl

Download URL persent-1.5.0-py3-none-any.whl
Size 13.8 MB
Tags Python 3
SHA-256 checksum
How to use checksums
5503449f380a840ac30a4ab560b72a9acc77408c3576ae40e90c23241542e712
BLAKE2b-256 checksum
How to use checksums
d9a872bc483d0ebd8e54742686b84b27dec74ad019d6fb7f8bf34c94d843521c
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 11, 2026.

Transparency log

Security for PerSent 1.5.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.

Select from 2 files

Attestation for persent-1.5.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 11, 2026.

Transparency log

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page