Spaces:
Sleeping
Sleeping
Download reviewguard/analytics.py from Emirinth/ReviewGuard: direct link, hf CLI and curl.
- Browser
- Download file 3.96 kB
-
https://huggingface.co/spaces/Emirinth/ReviewGuard/resolve/main/reviewguard/analytics.py
- Command line
-
hf download hf://spaces/Emirinth/ReviewGuard/reviewguard/analytics.py
-
curl -L -o analytics.py https://huggingface.co/spaces/Emirinth/ReviewGuard/resolve/main/reviewguard/analytics.py
3.96 kB
| """Business insights computed from a batch of analysed reviews. | |
| Each function looks at the batch from a different angle: time, ratings, money and wording. | |
| """ | |
| import pandas as pd | |
| from sklearn.feature_extraction.text import CountVectorizer | |
| from reviewguard import config | |
| def monthly_trend(results: pd.DataFrame, min_reviews: int = 30) -> pd.DataFrame: | |
| """Count reviews per month and flag months where negativity spikes. | |
| A spike is a month whose negative share is two standard deviations above the running average. | |
| Months with fewer than min_reviews reviews are never flagged because they are too noisy. | |
| """ | |
| monthly = ( | |
| results.dropna(subset=["date"]) | |
| .assign( | |
| month=lambda t: pd.to_datetime(t["date"]).dt.to_period("M").dt.to_timestamp(), | |
| negative=lambda t: t["sentiment"] == "negative", | |
| ) | |
| .groupby("month") | |
| .agg(reviews=("text", "size"), negative_share=("negative", "mean")) | |
| .reset_index() | |
| ) | |
| # The running baseline only uses busy months, so tiny early months cannot distort it. | |
| busy = monthly["reviews"] >= min_reviews | |
| shares = monthly["negative_share"].where(busy) | |
| baseline = shares.expanding().mean().shift(1) | |
| spread = shares.expanding().std().shift(1) | |
| monthly["spike"] = busy & (monthly["negative_share"] > baseline + 2 * spread) | |
| return monthly | |
| def negativity_change( | |
| monthly: pd.DataFrame, min_reviews: int = 30, window: int = 6 | |
| ) -> tuple[float, float] | None: | |
| """Compare the negative share of the first and last busy months. | |
| Returns the average share over the first window months and over the last window months. | |
| """ | |
| busy = monthly[monthly["reviews"] >= min_reviews] | |
| if len(busy) < 2 * window: | |
| return None | |
| return busy["negative_share"].head(window).mean(), busy["negative_share"].tail(window).mean() | |
| def rating_versus_text(results: pd.DataFrame) -> pd.DataFrame: | |
| """Cross-tabulate star ratings against the sentiment the model read in the text. | |
| Cells far from the diagonal are reviews whose rating and words disagree. | |
| """ | |
| rated = results.dropna(subset=["stars"]) | |
| return pd.crosstab(rated["stars"].astype(int), rated["sentiment"]).reindex( | |
| columns=config.LABELS, fill_value=0 | |
| ) | |
| def exposure_by_team(results: pd.DataFrame) -> pd.Series: | |
| """Add up refund exposure of Urgent and Review cases for each responsible team.""" | |
| flagged = results[results["flag"].isin(["Urgent", "Review"])] | |
| return flagged.groupby("team")["refund_exposure"].sum().sort_values() | |
| def complaint_phrases(results: pd.DataFrame, top_k: int = 10, min_reviews: int = 5) -> pd.DataFrame: | |
| """Find the phrases that set negative reviews apart from the rest. | |
| Each phrase is scored by how much more often negative reviews use it than other reviews. | |
| This skips phrases such as product names that every review mentions. | |
| """ | |
| is_negative = (results["sentiment"] == "negative").to_numpy() | |
| if is_negative.sum() < min_reviews: | |
| return pd.DataFrame(columns=["phrase", "reviews", "times_more_likely"]) | |
| vectorizer = CountVectorizer(ngram_range=(2, 3), stop_words="english", binary=True, min_df=3) | |
| matrix = vectorizer.fit_transform(results["text"]) | |
| negative_count = matrix[is_negative].sum(axis=0).A1 | |
| other_count = matrix[~is_negative].sum(axis=0).A1 | |
| # Add-one smoothing keeps phrases that never appear in other reviews from dividing by zero. | |
| lift = ((negative_count + 1) / (is_negative.sum() + 1)) / ( | |
| (other_count + 1) / ((~is_negative).sum() + 1) | |
| ) | |
| phrases = pd.DataFrame( | |
| { | |
| "phrase": vectorizer.get_feature_names_out(), | |
| "reviews": negative_count, | |
| "times_more_likely": lift.round(1), | |
| } | |
| ) | |
| phrases = phrases[phrases["reviews"] >= min_reviews] | |
| return ( | |
| phrases.sort_values("times_more_likely", ascending=False).head(top_k).reset_index(drop=True) | |
| ) | |