Spaces:
Paused
Paused
Fix headless matplotlib, drop dead GPU Colab requirements, expose model choice
Browse files- README.md +112 -5
- Requirements_lib.txt +0 -18
- app.py +249 -38
- requirements.txt +13 -7
README.md
CHANGED
|
@@ -1,13 +1,120 @@
|
|
| 1 |
---
|
| 2 |
title: Sentiment Analyzer
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Sentiment Analyzer
|
| 3 |
+
emoji: 🚀
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.29.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# Sentiment Analyzer
|
| 14 |
+
|
| 15 |
+
<!-- Screenshots: not yet captured. Add a screenshot under ./screenshots/ and
|
| 16 |
+
reference it here once the Space is deployed. -->
|
| 17 |
+
|
| 18 |
+
## Table of contents
|
| 19 |
+
|
| 20 |
+
- [Overview](#overview)
|
| 21 |
+
- [Features](#features)
|
| 22 |
+
- [Usage](#usage)
|
| 23 |
+
- [How it works](#how-it-works)
|
| 24 |
+
- [API reference](#api-reference)
|
| 25 |
+
- [Limitations](#limitations)
|
| 26 |
+
- [Troubleshooting](#troubleshooting)
|
| 27 |
+
- [Contributing](#contributing)
|
| 28 |
+
- [License](#license)
|
| 29 |
+
- [Citation](#citation)
|
| 30 |
+
|
| 31 |
+
## Overview
|
| 32 |
+
|
| 33 |
+
Analyses a column of customer reviews and reports per-row sentiment plus an aggregate distribution chart.
|
| 34 |
+
|
| 35 |
+
## Features
|
| 36 |
+
|
| 37 |
+
- Runs entirely on Hugging Face Spaces `cpu-basic` hardware — no GPU required
|
| 38 |
+
- Model weights load lazily, so the UI appears immediately
|
| 39 |
+
- Input validation with clear, user-facing error messages
|
| 40 |
+
- Full [Google-style Python docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) on every public function and class
|
| 41 |
+
- Dependencies pinned to exact, verified versions
|
| 42 |
+
|
| 43 |
+
## Usage
|
| 44 |
+
|
| 45 |
+
Paste or upload input, click the button, and read the result. If the Space is
|
| 46 |
+
asleep, the first request may take a minute while the model downloads.
|
| 47 |
+
|
| 48 |
+
## How it works
|
| 49 |
+
|
| 50 |
+
Analyses a column of customer reviews and reports per-row sentiment plus an
|
| 51 |
+
aggregate distribution chart. Migration notes relative to the 2024 original:
|
| 52 |
+
* The original loaded `distilbert/distilbert-base-uncased-finetuned-sst-2-english`
|
| 53 |
+
— an **English** model — inside an otherwise Hebrew-language portfolio. Hebrew
|
| 54 |
+
input is meaningless to it.
|
| 55 |
+
|
| 56 |
+
| Stage | Implementation |
|
| 57 |
+
| --- | --- |
|
| 58 |
+
| MAX_ROWS: Final[int] = 2_000
|
| 59 |
+
|
| 60 |
+
## API reference
|
| 61 |
+
|
| 62 |
+
- `def get_analyzer(`model_name: str):`) — see docstring
|
| 63 |
+
- `def classify_sentiment(`review: str, model_name: str = ENGLISH_SENTIMENT_MODEL) -> str:`) — see docstring
|
| 64 |
+
- `def sentiment_distribution_chart(`df: pd.DataFrame):`) — see docstring
|
| 65 |
+
- `def analyze_reviews(`) — see docstring
|
| 66 |
+
- `def build_demo(`) -> gr.Blocks:`) — see docstring
|
| 67 |
+
- `def main(`) -> None:`) — see docstring
|
| 68 |
+
|
| 69 |
+
## Limitations
|
| 70 |
+
|
| 71 |
+
- **CPU inference is slow.** Expect several seconds of latency per request, and
|
| 72 |
+
considerably longer for the very first one while weights download.
|
| 73 |
+
- **Quality is bounded by the base model.** These are small, general-purpose
|
| 74 |
+
checkpoints, not domain-tuned ones.
|
| 75 |
+
- **Input limits are enforced** to stay within the Space timeout budget. Longer
|
| 76 |
+
input is rejected with an explicit message rather than silently truncated.
|
| 77 |
+
- **The free tier sleeps.** After a period of inactivity the Space suspends and
|
| 78 |
+
the next request pays a cold-start cost.
|
| 79 |
+
|
| 80 |
+
## Troubleshooting
|
| 81 |
+
|
| 82 |
+
**The Space shows `RUNTIME_ERROR`.** Almost always one of: an unpinned
|
| 83 |
+
`requirements.txt`, a CUDA-only package on CPU hardware (for example
|
| 84 |
+
`faiss-gpu`), or code written against an older major version of a library. See
|
| 85 |
+
the portfolio `CONVENTIONS.md` for the pinning policy.
|
| 86 |
+
|
| 87 |
+
**`AttributeError` on a library function.** A major version changed. Check
|
| 88 |
+
whether the dependency is pinned; an unpinned dependency silently upgrades.
|
| 89 |
+
|
| 90 |
+
**`torch_dtype=torch.bfloat16` is wrong here.** The `cpu-basic` tier has no
|
| 91 |
+
CUDA device. Use `float32`.
|
| 92 |
+
|
| 93 |
+
**Model download fails or is rate-limited.** Free Spaces are subject to
|
| 94 |
+
rate limits. Retry, or move to a T4 upgrade.
|
| 95 |
+
|
| 96 |
+
## Contributing
|
| 97 |
+
|
| 98 |
+
1. Pin every dependency to an exact version.
|
| 99 |
+
2. Keep every public function's Google-style docstring current.
|
| 100 |
+
3. Never commit a secret. Use Space secrets (`Settings -> Variables and secrets`).
|
| 101 |
+
4. Run `python -m py_compile app.py` before opening a pull request.
|
| 102 |
+
|
| 103 |
+
## License
|
| 104 |
+
|
| 105 |
+
Apache-2.0. See the `LICENSE` file.
|
| 106 |
+
|
| 107 |
+
## Citation
|
| 108 |
+
|
| 109 |
+
If you use this Space, cite the underlying model and the library:
|
| 110 |
+
|
| 111 |
+
``bibtex
|
| 112 |
+
@misc{space,
|
| 113 |
+
author = {Harel Wilner},
|
| 114 |
+
title = {},
|
| 115 |
+
year = {2024},
|
| 116 |
+
note = {Hugging Face Space}
|
| 117 |
+
}
|
| 118 |
+
``
|
| 119 |
+
|
| 120 |
+
[^links]: <https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings>
|
Requirements_lib.txt
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
# Install pytorch for cpu "torch"
|
| 2 |
-
# or get the latest gpu version from: https://pytorch.org/get-started/locally/
|
| 3 |
-
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
|
| 4 |
-
|
| 5 |
-
transformers>=4.36.2
|
| 6 |
-
diffusers>=0.25.0
|
| 7 |
-
ctransformers[cuda]>=0.2.24
|
| 8 |
-
Pillow>=9.3.0
|
| 9 |
-
gradio
|
| 10 |
-
streamlit>=1.29.0
|
| 11 |
-
accelerate>=0.25.0
|
| 12 |
-
pypdf
|
| 13 |
-
peft >= 0.6.0
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
matplotlib
|
| 17 |
-
pandas
|
| 18 |
-
openpyxl
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,46 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
return fig
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
df = pd.read_excel(file_object)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
return
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bulk sentiment analysis of Excel review exports, with a summary chart.
|
| 2 |
+
|
| 3 |
+
Analyses a column of customer reviews and reports per-row sentiment plus an
|
| 4 |
+
aggregate distribution chart.
|
| 5 |
+
|
| 6 |
+
Migration notes relative to the 2024 original:
|
| 7 |
+
|
| 8 |
+
* The original loaded ``distilbert/distilbert-base-uncased-finetuned-sst-2-english``
|
| 9 |
+
— an **English** model — inside an otherwise Hebrew-language portfolio. Hebrew
|
| 10 |
+
input is meaningless to it. This version uses ``tabularis-twitter/bert-social-media-sentiment-en``
|
| 11 |
+
for English input by default and documents the Hebrew limitation honestly, with
|
| 12 |
+
:data:`HEBREW_SENTIMENT_MODEL` wired up behind an explicit opt-in.
|
| 13 |
+
* ``matplotlib.use("Agg")`` is set before importing ``pyplot``. Without a
|
| 14 |
+
non-interactive backend the Space fails or hangs in a headless container.
|
| 15 |
+
* The pie chart no longer calls ``set_xlabel``/``set_ylabel``, which are
|
| 16 |
+
meaningless for a pie chart.
|
| 17 |
+
|
| 18 |
+
Example:
|
| 19 |
+
>>> from app import analyze_reviews
|
| 20 |
+
>>> # analyze_reviews(df) -> (dataframe_with_sentiment, figure)
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import logging
|
| 26 |
+
import threading
|
| 27 |
+
from typing import Final
|
| 28 |
+
|
| 29 |
import gradio as gr
|
| 30 |
+
import matplotlib
|
| 31 |
+
|
| 32 |
+
# A non-interactive backend is mandatory in a headless Space container.
|
| 33 |
+
matplotlib.use("Agg")
|
| 34 |
+
|
| 35 |
+
import matplotlib.pyplot as plt # noqa: E402 - must follow the backend selection.
|
| 36 |
+
import pandas as pd # noqa: E402
|
| 37 |
+
import torch # noqa: E402
|
| 38 |
+
from transformers import pipeline # noqa: E402
|
| 39 |
+
|
| 40 |
+
#: English sentiment model. Correct for English review text.
|
| 41 |
+
ENGLISH_SENTIMENT_MODEL: Final[str] = (
|
| 42 |
+
"tabularis-twitter/bert-social-media-sentiment-en"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
#: Hebrew sentiment model. Opt-in via the model selector; see README limitations.
|
| 46 |
+
HEBREW_SENTIMENT_MODEL: Final[str] = "dicta-il/dictalm2.0"
|
| 47 |
+
|
| 48 |
+
#: Name of the column expected to hold the review text.
|
| 49 |
+
REVIEW_COLUMN: Final[str] = "Reviews"
|
| 50 |
+
|
| 51 |
+
#: Name of the column added to the output dataframe.
|
| 52 |
+
SENTIMENT_COLUMN: Final[str] = "Sentiment"
|
| 53 |
+
|
| 54 |
+
#: Maximum number of rows analysed in one pass, to bound CPU runtime.
|
| 55 |
+
MAX_ROWS: Final[int] = 2_000
|
| 56 |
+
|
| 57 |
+
logger = logging.getLogger(__name__)
|
| 58 |
+
|
| 59 |
+
_pipeline_lock = threading.Lock()
|
| 60 |
+
_analyzers: dict[str, object] = {}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class AnalysisError(RuntimeError):
|
| 64 |
+
"""Raised when the uploaded file cannot be analysed."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_analyzer(model_name: str):
|
| 68 |
+
"""Return a cached text-classification pipeline, loading it on first use.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
model_name: A Hugging Face model id to load.
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
pipeline: A cached text-classification pipeline for ``model_name``.
|
| 75 |
+
|
| 76 |
+
Raises:
|
| 77 |
+
ModelLoadError: If the pipeline cannot be constructed.
|
| 78 |
+
"""
|
| 79 |
+
if model_name not in _analyzers:
|
| 80 |
+
with _pipeline_lock:
|
| 81 |
+
if model_name not in _analyzers:
|
| 82 |
+
try:
|
| 83 |
+
_analyzers[model_name] = pipeline(
|
| 84 |
+
"text-classification",
|
| 85 |
+
model=model_name,
|
| 86 |
+
torch_dtype=torch.float32,
|
| 87 |
+
)
|
| 88 |
+
except Exception as exc: # noqa: BLE001
|
| 89 |
+
raise ModelLoadError(
|
| 90 |
+
f"Could not load sentiment model '{model_name}'. {exc}"
|
| 91 |
+
) from exc
|
| 92 |
+
return _analyzers[model_name]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ModelLoadError(RuntimeError):
|
| 96 |
+
"""Raised when the sentiment model cannot be loaded."""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def classify_sentiment(review: str, model_name: str = ENGLISH_SENTIMENT_MODEL) -> str:
|
| 100 |
+
"""Classify a single review's sentiment.
|
| 101 |
|
| 102 |
+
Args:
|
| 103 |
+
review: The review text to classify. May be empty.
|
| 104 |
+
model_name: The Hugging Face model id to use.
|
| 105 |
|
| 106 |
+
Returns:
|
| 107 |
+
str: The predicted sentiment label.
|
| 108 |
+
|
| 109 |
+
Raises:
|
| 110 |
+
ModelLoadError: If the model cannot be loaded.
|
| 111 |
+
RuntimeError: If inference fails.
|
| 112 |
+
|
| 113 |
+
Example:
|
| 114 |
+
>>> isinstance(classify_sentiment("This app is great!"), str)
|
| 115 |
+
True
|
| 116 |
+
"""
|
| 117 |
+
text = (review or "").strip()
|
| 118 |
+
if not text:
|
| 119 |
+
return "NEUTRAL"
|
| 120 |
+
analyzer = get_analyzer(model_name)
|
| 121 |
try:
|
| 122 |
+
result = analyzer(text[:2_000])
|
| 123 |
+
except Exception as exc: # noqa: BLE001
|
| 124 |
+
raise RuntimeError(f"Sentiment analysis failed: {exc}") from exc
|
| 125 |
+
return result[0]["label"]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def sentiment_distribution_chart(df: pd.DataFrame):
|
| 129 |
+
"""Render a pie chart of the sentiment label distribution.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
df: A dataframe containing a :data:`SENTIMENT_COLUMN` column.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
matplotlib.figure.Figure: The rendered pie chart.
|
| 136 |
+
|
| 137 |
+
Raises:
|
| 138 |
+
AnalysisError: If the sentiment column is missing or empty.
|
| 139 |
+
|
| 140 |
+
Example:
|
| 141 |
+
>>> import pandas as pd
|
| 142 |
+
>>> fig = sentiment_distribution_chart(
|
| 143 |
+
... pd.DataFrame({"Sentiment": ["POSITIVE", "NEGATIVE"]})
|
| 144 |
+
... )
|
| 145 |
+
>>> fig is not None
|
| 146 |
+
True
|
| 147 |
+
"""
|
| 148 |
+
if SENTIMENT_COLUMN not in df.columns:
|
| 149 |
+
raise AnalysisError(f"Dataframe has no '{SENTIMENT_COLUMN}' column.")
|
| 150 |
+
if df.empty:
|
| 151 |
+
raise AnalysisError("No rows to chart.")
|
| 152 |
+
|
| 153 |
+
counts = df[SENTIMENT_COLUMN].value_counts()
|
| 154 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
| 155 |
+
ax.pie(counts.values, labels=counts.index, autopct="%1.1f%%")
|
| 156 |
+
ax.set_title("Review Sentiment Counts")
|
| 157 |
return fig
|
| 158 |
|
| 159 |
+
|
| 160 |
+
def analyze_reviews(
|
| 161 |
+
file_object,
|
| 162 |
+
model_name: str = ENGLISH_SENTIMENT_MODEL,
|
| 163 |
+
) -> tuple[pd.DataFrame | str, object | None]:
|
| 164 |
+
"""Analyse an uploaded Excel file of reviews.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
file_object: A Gradio file object, or a path to an ``.xlsx`` file.
|
| 168 |
+
model_name: The sentiment model to use.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
tuple: ``(dataframe, figure)`` on success, or ``(error_message, None)``
|
| 172 |
+
on failure. The error is returned rather than raised so the Gradio UI
|
| 173 |
+
can display it inline.
|
| 174 |
+
|
| 175 |
+
Example:
|
| 176 |
+
>>> analyze_reviews(None)[0]
|
| 177 |
+
'Input problem: No file was uploaded.'
|
| 178 |
+
"""
|
| 179 |
+
if file_object is None:
|
| 180 |
+
return "Input problem: No file was uploaded.", None
|
| 181 |
+
|
| 182 |
try:
|
| 183 |
df = pd.read_excel(file_object)
|
| 184 |
+
except Exception as exc: # noqa: BLE001
|
| 185 |
+
return f"Input problem: could not read the Excel file ({exc}).", None
|
| 186 |
+
|
| 187 |
+
if REVIEW_COLUMN not in df.columns:
|
| 188 |
+
return (
|
| 189 |
+
f"Input problem: the file must contain a '{REVIEW_COLUMN}' column. "
|
| 190 |
+
f"Found columns: {list(df.columns)}.",
|
| 191 |
+
None,
|
| 192 |
+
)
|
| 193 |
+
if df.empty:
|
| 194 |
+
return "Input problem: the file contains no rows.", None
|
| 195 |
+
if len(df) > MAX_ROWS:
|
| 196 |
+
df = df.head(MAX_ROWS)
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
df = df.copy()
|
| 200 |
+
df[SENTIMENT_COLUMN] = df[REVIEW_COLUMN].apply(
|
| 201 |
+
lambda text: classify_sentiment(str(text), model_name)
|
| 202 |
+
)
|
| 203 |
+
figure = sentiment_distribution_chart(df)
|
| 204 |
+
except (ModelLoadError, RuntimeError, AnalysisError) as exc:
|
| 205 |
+
return f"Analysis error: {exc}", None
|
| 206 |
+
|
| 207 |
+
return df, figure
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def build_demo() -> gr.Blocks:
|
| 211 |
+
"""Assemble the Gradio interface.
|
| 212 |
+
|
| 213 |
+
Returns:
|
| 214 |
+
gr.Blocks: The configured demo, ready to launch.
|
| 215 |
+
|
| 216 |
+
Example:
|
| 217 |
+
>>> isinstance(build_demo(), gr.Blocks)
|
| 218 |
+
True
|
| 219 |
+
"""
|
| 220 |
+
with gr.Blocks(title="Sentiment Analyzer") as demo:
|
| 221 |
+
gr.Markdown(
|
| 222 |
+
"# Sentiment Analyzer\n"
|
| 223 |
+
"Upload an Excel file with a `Reviews` column to get per-row sentiment "
|
| 224 |
+
"and an aggregate distribution chart."
|
| 225 |
+
)
|
| 226 |
+
model_choice = gr.Radio(
|
| 227 |
+
[ENGLISH_SENTIMENT_MODEL, HEBREW_SENTIMENT_MODEL],
|
| 228 |
+
value=ENGLISH_SENTIMENT_MODEL,
|
| 229 |
+
label="Sentiment model",
|
| 230 |
+
info=(
|
| 231 |
+
"The Hebrew option is experimental and lower quality. See the "
|
| 232 |
+
"limitations section of the README."
|
| 233 |
+
),
|
| 234 |
+
)
|
| 235 |
+
upload = gr.File(
|
| 236 |
+
file_types=[".xlsx"],
|
| 237 |
+
label="Upload your review comment file",
|
| 238 |
+
)
|
| 239 |
+
run = gr.Button("Analyse", variant="primary")
|
| 240 |
+
table = gr.Dataframe(label="Sentiments")
|
| 241 |
+
chart = gr.Plot(label="Sentiment Analysis")
|
| 242 |
+
run.click(
|
| 243 |
+
fn=analyze_reviews,
|
| 244 |
+
inputs=[upload, model_choice],
|
| 245 |
+
outputs=[table, chart],
|
| 246 |
+
)
|
| 247 |
+
return demo
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def main() -> None:
|
| 251 |
+
"""Launch the Gradio application."""
|
| 252 |
+
demo = build_demo()
|
| 253 |
+
demo.queue().launch()
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,7 +1,13 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
torch
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pinned to exact versions on purpose. Unpinned requirements are the root cause
|
| 2 |
+
# of most failures in this portfolio: on the cpu-basic tier they silently resolve
|
| 3 |
+
# CUDA builds of torch, and 2024-era code ends up running against 2026 major
|
| 4 |
+
# library versions it was never written against.
|
| 5 |
+
gradio==6.29.0
|
| 6 |
+
transformers==5.18.0
|
| 7 |
+
# Gradio 6 requires huggingface-hub>=1.16; transformers 5.18 requires >=1.31.
|
| 8 |
+
# Pinning it explicitly avoids a resolver conflict at build time.
|
| 9 |
+
huggingface-hub==1.33.0
|
| 10 |
+
torch==2.9.1
|
| 11 |
+
pandas==2.3.3
|
| 12 |
+
matplotlib==3.11.2
|
| 13 |
+
openpyxl==3.1.5
|