AnApp / app.py
Zhbzhb2333's picture
Update app.py
468e96d verified
import pandas as pd
import numpy as np
import gradio as gr
# ---------- Load data ----------
df_reviews = pd.read_csv("synthetic_book_reviews.csv")
df_sales = pd.read_csv("synthetic_sales_data.csv")
# ---------- Build decision table ----------
avg_sales = df_sales.groupby("title")["units_sold"].mean().reset_index()
avg_sales.columns = ["title", "avg_units_sold"]
sentiment_counts = df_reviews.groupby(["title", "sentiment_label"]).size().unstack(fill_value=0)
sentiment_counts["total"] = sentiment_counts.sum(axis=1)
# 避免没有某类情绪时报错
for col in ["positive", "negative", "neutral"]:
if col not in sentiment_counts.columns:
sentiment_counts[col] = 0
sentiment_counts["positive_ratio"] = sentiment_counts["positive"] / sentiment_counts["total"].replace(0, np.nan)
sentiment_counts["negative_ratio"] = sentiment_counts["negative"] / sentiment_counts["total"].replace(0, np.nan)
df_decision = avg_sales.merge(sentiment_counts.reset_index(), on="title", how="left")
def pricing_decision(row):
if row["avg_units_sold"] >= 120 and row["positive_ratio"] >= 0.6:
return "increase price"
elif row["avg_units_sold"] <= 60 and row["negative_ratio"] >= 0.4:
return "decrease price"
else:
return "keep price"
df_decision["pricing_decision"] = df_decision.apply(pricing_decision, axis=1)
# ---------- Gradio UI function ----------
titles = sorted(df_decision["title"].dropna().unique().tolist())
def query_book(title):
row = df_decision[df_decision["title"] == title].iloc[0]
return {
"title": title,
"avg_units_sold": float(row["avg_units_sold"]),
"positive_ratio": float(row["positive_ratio"]) if pd.notna(row["positive_ratio"]) else None,
"negative_ratio": float(row["negative_ratio"]) if pd.notna(row["negative_ratio"]) else None,
"pricing_decision": row["pricing_decision"]
}
demo = gr.Interface(
fn=query_book,
inputs=gr.Dropdown(choices=titles, label="Select a book title"),
outputs=gr.JSON(label="Pricing Decision Result"),
title="Book Pricing Decision Demo",
description="Rule-based pricing decision based on average sales and sentiment ratios."
)
if __name__ == "__main__":
demo.launch()