Skip to main content

Basha

Basha is a lightweight, explainable and customizable Python library for sentiment and emotion analysis.

It analyses English text and returns:

  • Sentiment label: positive, negative or neutral
  • Continuous compound score from -1 to +1
  • Positive, negative and neutral proportions
  • Emotion information
  • Sarcasm information
  • Per-word explanations
  • Social-media normalization information

Features

Basha currently supports:

  • Weighted sentiment vocabulary
  • Positive, negative and neutral classification
  • Emotion detection
  • Negation handling
  • Intensifiers and diminishers
  • Capital-letter emphasis
  • Punctuation emphasis
  • Contrast words such as but
  • Emoji and emoticon sentiment
  • Spelling correction for sentiment words
  • Complete sentiment phrases
  • Context-dependent words
  • Basic sarcasm detection
  • Social-media slang
  • Hashtag conversion
  • Username and URL removal
  • Batch prediction
  • Custom sentiment words
  • Explainable output

Installation

After the package is published, install it using:

pip install basha-sentiment

For local development, open the terminal in the project folder and run:

python -m pip install --editable .

Basic usage

from basha import bashaanalyser


analyzer = bashaanalyser()

result = analyzer.predict(
    "This product is excellent"
)

print(result)

Get the sentiment label

from basha import bashaanalyser


analyzer = bashaanalyser()

result = analyzer.predict(
    "This product is excellent"
)

print(result["label"])

Output:

positive

Standard class-name usage

Python classes normally use capital letters. Basha also supports:

from basha import BashaAnalyser


analyzer = BashaAnalyser()

result = analyzer.predict(
    "This is amazing!"
)

print(result["label"])

Example output

{
    "text": "This product is very good!",
    "label": "positive",
    "emotion": {
        "label": "joy",
        "confidence": 0.75
    },
    "scores": {
        "compound": 0.72,
        "positive": 0.25,
        "negative": 0.0,
        "neutral": 0.75
    },
    "flags": {
        "sarcasm": False,
        "normalized_text": "This product is very good!",
        "social_normalizations": []
    },
    "explanation": [
        {
            "token": "good",
            "base_score": 2.0,
            "final_score": 3.0,
            "rules": [
                "intensifier: very"
            ]
        }
    ]
}

The exact numerical values can change when the vocabulary and rules are updated.

Negation

print(
    analyzer.predict(
        "This product is not good"
    )["label"]
)

Output:

negative

Basha also handles positive negation:

print(
    analyzer.predict(
        "This product is not bad"
    )["label"]
)

Output:

positive

Intensifiers and diminishers

normal = analyzer.predict("good")
strong = analyzer.predict("very good")
weak = analyzer.predict("slightly good")

print(normal["scores"]["compound"])
print(strong["scores"]["compound"])
print(weak["scores"]["compound"])

very good should have a stronger positive score than good, while slightly good should have a weaker positive score.

Contrast handling

result = analyzer.predict(
    "The camera is good, but the battery is terrible"
)

print(result["label"])

Output:

negative

The part appearing after but receives more importance.

Emoji and emoticon support

print(
    analyzer.predict(
        "I love this phone 😍"
    )["label"]
)

print(
    analyzer.predict(
        "This is bad :("
    )["label"]
)

Output:

positive
negative

Spelling correction

Basha can safely correct certain misspelled sentiment words:

result = analyzer.predict(
    "This product is graet"
)

print(result["label"])
print(result["explanation"])

The word graet can be interpreted as great.

Basha does not automatically correct every unknown word. It corrects only sufficiently clear spelling mistakes to reduce incorrect corrections.

Sarcasm detection

result = analyzer.predict(
    "Excellent service, yeah right."
)

print(result["label"])
print(result["flags"]["sarcasm"])
print(result["flags"]["sarcasm_reasons"])

Possible output:

negative
True
['sarcasm marker: yeah right']

Sarcasm detection is rule-based and cannot understand every form of sarcasm.

Social-media text

result = analyzer.predict(
    "@company this product is gr8! #AmazingProduct"
)

print(result["label"])
print(result["flags"]["normalized_text"])
print(result["flags"]["social_normalizations"])

Basha can:

  • Convert gr8 to great
  • Convert luv to love
  • Split #AmazingProduct into amazing product
  • Ignore usernames such as @company
  • Ignore URLs
  • Normalize repeated letters

Emotion detection

result = analyzer.predict(
    "I am extremely happy today"
)

print(result["emotion"])

Basha can identify emotions supported by its emotion vocabulary, such as:

  • Joy
  • Sadness
  • Anger
  • Fear
  • Surprise
  • Disgust
  • Neutral or uncertain emotion

Context-dependent words

Some words have different meanings in different situations:

print(
    analyzer.predict(
        "The movie was sick"
    )["label"]
)

print(
    analyzer.predict(
        "I feel sick"
    )["label"]
)

Possible output:

positive
negative

Other context-dependent words include words such as sharp, hot, sweet, fire and killer.

Custom words

You can add a word to one analyzer:

from basha import bashaanalyser


analyzer = bashaanalyser()

analyzer.add_word(
    "supercalifragilistic",
    3.5
)

result = analyzer.predict(
    "This is supercalifragilistic"
)

print(result["label"])

The custom score must be between -4.0 and +4.0.

Batch prediction

from basha import bashaanalyser


analyzer = bashaanalyser()

results = analyzer.predict_batch([
    "This product is excellent",
    "This product is terrible",
    "The parcel arrived today"
])

for result in results:
    print(result["label"])

Output:

positive
negative
neutral

Running tests

Install development tools:

python -m pip install --editable ".[dev]"

Run all tests:

python -m pytest

Passing tests prove that the tested behaviours work correctly. They do not prove complete real-world accuracy.

Benchmarking

Optional benchmark dependencies can be installed using:

python -m pip install --editable ".[benchmark]"

A benchmark can compare Basha with VADER and TextBlob using:

  • Total execution time
  • Average time per sentence
  • Sentences processed per second

Do not claim that Basha is faster until benchmark results confirm it.

Project structure

basha/
├── src/
│   └── basha/
│       ├── __init__.py
│       ├── analyzer.py
│       ├── context.py
│       ├── emotions.py
│       ├── lexicon.py
│       ├── modifiers.py
│       ├── phrases.py
│       ├── sarcasm.py
│       ├── social.py
│       ├── spelling.py
│       ├── symbols.py
│       └── tokenizer.py
├── tests/
│   └── test_sentiment.py
├── example.py
├── LICENSE
├── pyproject.toml
└── README.md

Limitations

Basha is currently a rule-based English sentiment-analysis library.

Known limitations include:

  • It does not learn automatically from new data
  • Sarcasm detection is limited to recognized patterns
  • Context understanding is limited to defined rules
  • Spelling correction does not correct every unknown word
  • Emotion detection depends on its emotion vocabulary
  • Mixed sentiment may be simplified into one overall label
  • Multilingual text is not yet fully supported
  • Real-world accuracy must still be measured using labelled datasets

Development status

Basha is currently under active development. Its vocabulary, rules, output format and API may change before version 1.0.0.

Author

Bajil Mohammed E.P. Mohammed Shahbi

License

This project is licensed under the MIT License.

Metadata

Release files for basha-sentiment 0.3.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 basha-sentiment 0.3.0
File Size Uploaded Provenance
basha_sentiment-0.3.0.tar.gz 33.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for basha-sentiment 0.3.0
File Interpreter ABI Platform
basha_sentiment-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 63.2 kB

Release files / basha_sentiment-0.3.0.tar.gz

Download URL basha_sentiment-0.3.0.tar.gz
Size 33.1 kB
Tags Source
SHA-256 checksum
How to use checksums
c44323edb77f8c4f02cb66bc42c9f9b0de393f61c3ca7d7e3f5e2df3159fff64
BLAKE2b-256 checksum
How to use checksums
c1af34ddff6315ca9c5258858c403e587401baba9f531b268cf4bc40c9b3de9c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.2

Release files / basha_sentiment-0.3.0-py3-none-any.whl

Download URL basha_sentiment-0.3.0-py3-none-any.whl
Size 30.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2fdb9a579b55c3c0737099eca694628375b17fe67a06f51eeb62fe1ce165931d
BLAKE2b-256 checksum
How to use checksums
46e8c849a67209ea47abd2808ff83d40d856dc35e552b1815b05ed3005a84cad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.2

Security for basha-sentiment 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.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files No provenance

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