Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -267,6 +267,119 @@ from contextlib import contextmanager
|
|
| 267 |
from collections import deque
|
| 268 |
from typing import Optional, Tuple, List, Dict, Any
|
| 269 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
from mis import seller_scorecard_df, render_customer_360, render_seller_scorecards, ensure_mis_indexes
|
| 271 |
|
| 272 |
|
|
@@ -3928,23 +4041,33 @@ def render_chat_output(out):
|
|
| 3928 |
if card.get("error"):
|
| 3929 |
st.error(card["error"])
|
| 3930 |
else:
|
| 3931 |
-
|
| 3932 |
-
|
| 3933 |
-
|
| 3934 |
-
|
| 3935 |
-
|
| 3936 |
-
|
| 3937 |
-
|
| 3938 |
-
|
| 3939 |
-
|
| 3940 |
-
|
| 3941 |
-
|
| 3942 |
-
|
| 3943 |
-
|
| 3944 |
-
|
| 3945 |
-
|
| 3946 |
-
|
| 3947 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3948 |
def render_df_with_pagination(df: pd.DataFrame, key_prefix: str, page_size: int = 10):
|
| 3949 |
total = len(df)
|
| 3950 |
if total <= page_size:
|
|
|
|
| 267 |
from collections import deque
|
| 268 |
from typing import Optional, Tuple, List, Dict, Any
|
| 269 |
import matplotlib.pyplot as plt
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# === Auto-Chart Helpers (Admin-only) ===
|
| 274 |
+
def _infer_columns_for_chart(df: pd.DataFrame):
|
| 275 |
+
"""
|
| 276 |
+
Return a dict describing the best chart config, or None.
|
| 277 |
+
Heuristics:
|
| 278 |
+
- scatter: 2 numeric columns
|
| 279 |
+
- bar/pie: 1 categorical + 1 numeric (≤ 8 categories -> pie, else bar)
|
| 280 |
+
- stacked_bar: 2 categoricals + 1 numeric
|
| 281 |
+
"""
|
| 282 |
+
try:
|
| 283 |
+
if df is None or df.empty:
|
| 284 |
+
return None
|
| 285 |
+
df2 = df.copy()
|
| 286 |
+
|
| 287 |
+
# Identify dtypes
|
| 288 |
+
num_cols = [c for c in df2.columns if pd.api.types.is_numeric_dtype(df2[c])]
|
| 289 |
+
cat_cols = [c for c in df2.columns if (not pd.api.types.is_numeric_dtype(df2[c])) and df2[c].nunique() > 0]
|
| 290 |
+
|
| 291 |
+
# Prefer explicit common naming if present
|
| 292 |
+
preferred_cats = [c for c in df2.columns if c.lower() in (
|
| 293 |
+
"category","categories","product_category","seller_id","product_id","state","city",
|
| 294 |
+
"payment_type","status","month","date","order_status","review_score"
|
| 295 |
+
)]
|
| 296 |
+
preferred_nums = [c for c in df2.columns if c.lower() in (
|
| 297 |
+
"count","cnt","total","sum","amount","revenue","value","score","quantity","qty","gmv"
|
| 298 |
+
)]
|
| 299 |
+
|
| 300 |
+
# 1) Scatter: at least 2 numeric columns
|
| 301 |
+
if len(num_cols) >= 2:
|
| 302 |
+
return {"kind":"scatter", "x": num_cols[0], "y": num_cols[1]}
|
| 303 |
+
|
| 304 |
+
# 2) 1 cat + 1 num → bar or pie
|
| 305 |
+
if cat_cols and num_cols:
|
| 306 |
+
cat = preferred_cats[0] if preferred_cats and preferred_cats[0] in cat_cols else cat_cols[0]
|
| 307 |
+
num = preferred_nums[0] if preferred_nums and preferred_nums[0] in num_cols else num_cols[0]
|
| 308 |
+
|
| 309 |
+
top = (df2[[cat, num]]
|
| 310 |
+
.groupby(cat, dropna=False, as_index=False)[num].sum()
|
| 311 |
+
.sort_values(num, ascending=False))
|
| 312 |
+
ncat = top[cat].nunique()
|
| 313 |
+
if ncat <= 8 and (top[num] >= 0).all():
|
| 314 |
+
return {"kind":"pie", "cat": cat, "val": num, "data": top.head(8)}
|
| 315 |
+
else:
|
| 316 |
+
return {"kind":"bar", "x": cat, "y": num, "data": top.head(25)}
|
| 317 |
+
|
| 318 |
+
# 3) 2 cats + 1 num → stacked bar
|
| 319 |
+
if len(cat_cols) >= 2 and num_cols:
|
| 320 |
+
cat1, cat2 = cat_cols[:2]
|
| 321 |
+
num = num_cols[0]
|
| 322 |
+
data = (df2[[cat1, cat2, num]]
|
| 323 |
+
.groupby([cat1, cat2], dropna=False, as_index=False)[num].sum())
|
| 324 |
+
return {"kind":"stacked_bar", "x": cat1, "hue": cat2, "y": num, "data": data}
|
| 325 |
+
|
| 326 |
+
return None
|
| 327 |
+
except Exception:
|
| 328 |
+
return None
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _render_chart_matplotlib(cfg: dict, df: pd.DataFrame):
|
| 332 |
+
import matplotlib.pyplot as plt
|
| 333 |
+
try:
|
| 334 |
+
kind = cfg.get("kind")
|
| 335 |
+
if kind == "scatter":
|
| 336 |
+
x, y = cfg["x"], cfg["y"]
|
| 337 |
+
fig, ax = plt.subplots()
|
| 338 |
+
ax.scatter(df[x], df[y])
|
| 339 |
+
ax.set_xlabel(x); ax.set_ylabel(y); ax.set_title(f"{y} vs {x}")
|
| 340 |
+
st.pyplot(fig, use_container_width=True)
|
| 341 |
+
|
| 342 |
+
elif kind == "bar":
|
| 343 |
+
data = cfg.get("data", df)
|
| 344 |
+
x, y = cfg["x"], cfg["y"]
|
| 345 |
+
fig, ax = plt.subplots()
|
| 346 |
+
ax.bar(data[x].astype(str), data[y])
|
| 347 |
+
ax.set_xlabel(x); ax.set_ylabel(y); ax.set_title(f"{y} by {x}")
|
| 348 |
+
ax.tick_params(axis='x', rotation=45)
|
| 349 |
+
st.pyplot(fig, use_container_width=True)
|
| 350 |
+
|
| 351 |
+
elif kind == "pie":
|
| 352 |
+
data = cfg.get("data", df)
|
| 353 |
+
cat, val = cfg["cat"], cfg["val"]
|
| 354 |
+
fig, ax = plt.subplots()
|
| 355 |
+
vals = data[val].clip(lower=0)
|
| 356 |
+
ax.pie(vals, labels=data[cat].astype(str), autopct=lambda p: f"{p:.0f}%")
|
| 357 |
+
ax.set_title(f"{val} share by {cat}")
|
| 358 |
+
st.pyplot(fig, use_container_width=True)
|
| 359 |
+
|
| 360 |
+
elif kind == "stacked_bar":
|
| 361 |
+
data = cfg.get("data", df)
|
| 362 |
+
x, hue, y = cfg["x"], cfg["hue"], cfg["y"]
|
| 363 |
+
pivot = data.pivot_table(index=x, columns=hue, values=y, aggfunc="sum", fill_value=0)
|
| 364 |
+
fig, ax = plt.subplots()
|
| 365 |
+
bottom = None
|
| 366 |
+
for col in pivot.columns:
|
| 367 |
+
vals = pivot[col].values
|
| 368 |
+
if bottom is None:
|
| 369 |
+
ax.bar(pivot.index.astype(str), vals, label=str(col))
|
| 370 |
+
bottom = vals
|
| 371 |
+
else:
|
| 372 |
+
ax.bar(pivot.index.astype(str), vals, bottom=bottom, label=str(col))
|
| 373 |
+
bottom = bottom + vals
|
| 374 |
+
ax.set_xlabel(x); ax.set_ylabel(y); ax.set_title(f"{y} by {x} and {hue}")
|
| 375 |
+
ax.legend(loc="best", fontsize="small")
|
| 376 |
+
ax.tick_params(axis='x', rotation=45)
|
| 377 |
+
st.pyplot(fig, use_container_width=True)
|
| 378 |
+
else:
|
| 379 |
+
st.info("No suitable chart found.")
|
| 380 |
+
except Exception as e:
|
| 381 |
+
st.warning(f"Could not render chart: {e}")
|
| 382 |
+
|
| 383 |
from mis import seller_scorecard_df, render_customer_360, render_seller_scorecards, ensure_mis_indexes
|
| 384 |
|
| 385 |
|
|
|
|
| 4041 |
if card.get("error"):
|
| 4042 |
st.error(card["error"])
|
| 4043 |
else:
|
| 4044 |
+
|
| 4045 |
+
df_to_show = card.get("df", None)
|
| 4046 |
+
if isinstance(df_to_show, pd.DataFrame):
|
| 4047 |
+
if card.get("limit_enforced"):
|
| 4048 |
+
st.markdown(
|
| 4049 |
+
'<div class="oa-note">For performance, results are limited to <b>50</b> rows. '
|
| 4050 |
+
'Include the word <b>“All”</b> in your question to bypass this cap (may be slower).</div>',
|
| 4051 |
+
unsafe_allow_html=True
|
| 4052 |
+
)
|
| 4053 |
+
if df_to_show.empty:
|
| 4054 |
+
st.info("No rows returned.")
|
| 4055 |
+
else:
|
| 4056 |
+
_role = (st.session_state.get("auth") or {}).get("role", "").lower()
|
| 4057 |
+
if _role == "admin":
|
| 4058 |
+
cfg = _infer_columns_for_chart(df_to_show)
|
| 4059 |
+
if cfg:
|
| 4060 |
+
c_tbl, c_plt = st.columns(2, gap="large")
|
| 4061 |
+
with c_tbl:
|
| 4062 |
+
render_df_with_pagination(df_to_show, key_prefix=f"q{i}", page_size=10)
|
| 4063 |
+
with c_plt:
|
| 4064 |
+
_render_chart_matplotlib(cfg, df_to_show)
|
| 4065 |
+
else:
|
| 4066 |
+
render_df_with_pagination(df_to_show, key_prefix=f"q{i}", page_size=10)
|
| 4067 |
+
else:
|
| 4068 |
+
render_df_with_pagination(df_to_show, key_prefix=f"q{i}", page_size=10)
|
| 4069 |
+
else:
|
| 4070 |
+
st.info("No tabular result to display.")
|
| 4071 |
def render_df_with_pagination(df: pd.DataFrame, key_prefix: str, page_size: int = 10):
|
| 4072 |
total = len(df)
|
| 4073 |
if total <= page_size:
|