Spaces:
Sleeping
Sleeping
Commit ·
cddf904
1
Parent(s): 320d35a
Refine merchant interface workflow
Browse files695 unmodified lines696697698699700701121 unmodified lines82382482582682782833 unmodified lines86286386486586686764 unmodified lines93293393493593693793893994094139 unmodified lines9819829839849859865 unmodified lines99299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310245 unmodified lines10301031103210331034103510361037103810391040695 unmodified linesreturn rows or [["No rows", "Try Refresh", metric, "-", 0.0, 0.0, 0.0]]def merchant_score_filter(aspect: str, prediction: str, category: str) -> List[List[Any]]:rows = []for product in PRODUCTS:121 unmodified lines)def external_review_predict(review: str, features: str, categories: str, price: Any, rating: Any, count: Any, selected_aspect: str) -> Tuple[str, str, List[List[Any]]]:try:result = _predict_custom(review, features, categories, price, rating, count)33 unmodified lines)def _status_html() -> str:missing = []if not CHECKPOINT_PATH.exists() or CHECKPOINT_PATH.stat().st_size < 1024 * 1024:64 unmodified lines.info-tip { position:relative; display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; border-radius:999px; border:1px solid #bfdbfe; background:#eff6ff; color:#1e40af; font-weight:800; cursor:help; }.info-tip .tip-content { display:none; position:absolute; right:0; top:30px; z-index:20; width:420px; max-width:80vw; background:white; border:1px solid var(--line); border-radius:8px; padding:10px; box-shadow:0 12px 30px rgba(15,23,42,.16); }.info-tip:hover .tip-content { display:block; }.negative-grid { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:10px; margin:8px 0 14px; }.negative-card { display:grid; grid-template-columns:64px 1fr; gap:10px; border:1px solid #fecaca; border-left:4px solid #ef4444; border-radius:8px; padding:10px; background:#fffafa; }.negative-card p { margin:5px 0 0; color:#334155; font-size:13px; }.mini-product-img { width:64px; height:76px; object-fit:cover; border-radius:6px; border:1px solid var(--line); background:#f8fafc; }@media (max-width:860px) { .aspect-grid, .metric-grid, .product-layout, .decision-layout, .negative-grid { grid-template-columns:1fr; } .product-img { width:100%; height:180px; } }"""39 unmodified linesgr.HTML('<div class="module-head"><h3>Product Score Monitor</h3><span class="info-tip">i<span class="tip-content">' + model_info_html() + '</span></span></div>')gr.HTML('<div class="small-label">Most negative products across the six aspects</div>')negative_spotlight = gr.HTML('<div class="note-card">Loading most negative products...</div>')with gr.Accordion("Score filters and export", open=True):with gr.Row():merchant_metric = gr.Dropdown(["Overall"] + ASPECTS, value="Overall", label="Aspect")5 unmodified linesexport_scores = gr.Button("Export Score List")merchant_scores_file = gr.File(label="Downloaded score CSV", interactive=False)with gr.Accordion("New Product Metadata Risk Screening", open=False):with gr.Row():with gr.Column(scale=1):new_import = gr.File(label="Import product metadata JSON/CSV")new_features = gr.Textbox("Cotton Polyester Blend, Slim Fit, Graphic Print, Machine Wash", label="New product features", lines=4)new_categories = gr.Textbox("Clothing > Women > Tops > T-Shirts", label="New product categories")new_price = gr.Number(29.99, label="Price")new_rating = gr.Number(4.1, label="Expected or early average rating")new_count = gr.Number(35, label="Expected or early rating count")new_focus = gr.Dropdown(["All"] + ASPECTS, value="All", label="Focus aspect")screen_btn = gr.Button("Predict Metadata Risk", variant="primary")with gr.Column(scale=1):risk_summary = gr.HTML()risk_table = gr.Dataframe(headers=["Aspect", "Risk Level", "Model Signal", "Confidence", "Reason"], value=[["Click Predict Metadata Risk", "", "", 0.0, ""]], datatype=["str", "str", "str", "number", "str"], interactive=False)export_risk = gr.Button("Export Risk Result")risk_file = gr.File(label="Downloaded risk CSV", interactive=False)with gr.Accordion("External Review Prediction", open=False):with gr.Row():with gr.Column(scale=1):ext_import = gr.File(label="Import review metadata JSON/CSV")external_review = gr.Textbox("The fabric is soft and the color looks good, but it runs small and the zipper feels weak.", label="External customer review", lines=5)ext_features = gr.Textbox("Cotton Blend, Slim Fit, Zipper Closure", label="Product features", lines=3)ext_categories = gr.Textbox("Clothing > Women > Jackets", label="Product categories")ext_price = gr.Number(39.99, label="Price")ext_rating = gr.Number(4.2, label="Average rating")ext_count = gr.Number(312, label="Rating count")ext_aspect = gr.Dropdown(["All"] + ASPECTS, value="All", label="Highlight aspect")external_btn = gr.Button("Analyze External Review", variant="primary")with gr.Column(scale=1):ext_overall = gr.HTML()ext_aspects = gr.HTML()5 unmodified linesmerchant_metric.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)merchant_prediction.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)merchant_category.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)new_import.change(import_new_product_payload, new_import, [new_features, new_categories, new_price, new_rating, new_count, new_focus])screen_btn.click(screen_new_product, [new_features, new_categories, new_price, new_rating, new_count, new_focus], [risk_summary, risk_table])export_risk.click(export_risk_rows, risk_table, risk_file)ext_import.change(import_external_review_payload, ext_import, [external_review, ext_features, ext_categories, ext_price, ext_rating, ext_count, ext_aspect])external_btn.click(external_review_predict, [external_review, ext_features, ext_categories, ext_price, ext_rating, ext_count, ext_aspect], [ext_overall, ext_aspects, ext_table])export_ext.click(export_external_rows, ext_table, ext_file)with gr.Tab("Research Metrics"):695 unmodified lines696697698699700701702703704705706707708709710711712713714715716717718719720721722723724121 unmodified lines84684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690733 unmodified lines94194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199264 unmodified lines1057105810591060106110621063106410651066106739 unmodified lines11071108110911101111111211135 unmodified lines11191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911705 unmodified lines117611771178117911801181118211831184118511861187118811891190695 unmodified linesreturn rows or [["No rows", "Try Refresh", metric, "-", 0.0, 0.0, 0.0]]def merchant_aspect_overview() -> List[List[Any]]:rows = []for aspect in ASPECTS:neg_count, top_name, top_conf, top_reason = 0, "-", 0.0, "-"for product in PRODUCTS:try:result = _predict_product(product["name"])except Exception:continued = result.get("aspect_details", {}).get(aspect, {})if d.get("label") != "Negative":continueneg_count += 1conf = _safe_float(d.get("confidence"))if conf >= top_conf:hits = _keyword_hits(product.get("review", ""), aspect)top_name = product["name"]top_conf = conftop_reason = ", ".join(hits) if hits else _short_text(product.get("review") or product.get("features"), 90)rows.append([aspect, neg_count, top_name, round(top_conf, 4), top_reason])return rowsdef merchant_score_filter(aspect: str, prediction: str, category: str) -> List[List[Any]]:rows = []for product in PRODUCTS:121 unmodified lines)def _read_uploaded_records(file_obj) -> List[Dict[str, Any]]:if not file_obj:return []path = Path(getattr(file_obj, "name", file_obj))try:if path.suffix.lower() == ".json":data = json.loads(path.read_text(encoding="utf-8"))if isinstance(data, dict):data = data.get("items") or data.get("data") or [data]return data if isinstance(data, list) else []with path.open("r", encoding="utf-8-sig", newline="") as fh:return list(csv.DictReader(fh))except Exception:return []def download_new_product_template():rows = [["Cotton Polyester Blend, Slim Fit, Graphic Print, Machine Wash","Clothing > Women > Tops > T-Shirts",29.99,4.1,35,"All",]]return _write_csv_download("new_product_metadata_template.csv",["features", "categories", "price", "average_rating", "rating_number", "focus_aspect"],rows,)def batch_screen_new_products(file_obj) -> Tuple[str, List[List[Any]]]:records = _read_uploaded_records(file_obj)if not records:return '<div class="note-card">Upload a CSV or JSON file first.</div>', []rows = []for i, data in enumerate(records, 1):features = data.get("features") or data.get("features_text") or ""categories = data.get("categories") or data.get("categories_text") or ""price = _safe_float(data.get("price"), 0.0)rating = _safe_float(data.get("average_rating") or data.get("rating"), 4.0)count = _safe_float(data.get("rating_number") or data.get("rating_count"), 0.0)focus = data.get("focus_aspect") or data.get("focus") or "All"_, detail_rows = screen_new_product(features, categories, price, rating, count, focus)high = [r[0] for r in detail_rows if r[1] == "High"]rows.append([f"Product {i}","High" if high else "Low",focus,len(high),f"{_short_text(categories, 55)} | high-risk aspects: {', '.join(high) or 'None'}",])return f'<div class="note-card"><b>Batch screening completed:</b> {len(rows)} products analyzed.</div>', rowsdef external_review_predict(review: str, features: str, categories: str, price: Any, rating: Any, count: Any, selected_aspect: str) -> Tuple[str, str, List[List[Any]]]:try:result = _predict_custom(review, features, categories, price, rating, count)33 unmodified lines)def download_external_review_template():rows = [["The fabric is soft and the color looks good, but it runs small.","Cotton Blend, Slim Fit, Zipper Closure","Clothing > Women > Jackets",39.99,4.2,312,"All",]]return _write_csv_download("external_review_template.csv",["review", "features", "categories", "price", "average_rating", "rating_number", "highlight_aspect"],rows,)def batch_external_review_predict(file_obj) -> Tuple[str, str, List[List[Any]]]:records = _read_uploaded_records(file_obj)if not records:return '<div class="note-card">Upload a CSV or JSON file first.</div>', "", []rows = []for i, data in enumerate(records, 1):review = data.get("review") or data.get("review_text") or ""features = data.get("features") or data.get("features_text") or ""categories = data.get("categories") or data.get("categories_text") or ""price = _safe_float(data.get("price"), 0.0)rating = _safe_float(data.get("average_rating") or data.get("rating"), 4.0)count = _safe_float(data.get("rating_number") or data.get("rating_count"), 0.0)aspect = data.get("highlight_aspect") or data.get("aspect") or "All"overall_html, _, detail_rows = external_review_predict(review, features, categories, price, rating, count, aspect)negative = [r[0] for r in detail_rows if r[1] == "Negative"]rows.append([f"Review {i}",f"Negative: {', '.join(negative)}" if negative else "No major negative",len(negative),f"{_short_text(review, 70)} | {_short_text(categories, 45)}",])return f'<div class="note-card"><b>Batch review prediction completed:</b> {len(rows)} reviews analyzed.</div>', "", rowsdef toggle_analysis_mode(mode: str):single = mode.startswith("Single")return gr.update(visible=single), gr.update(visible=not single)def _status_html() -> str:missing = []if not CHECKPOINT_PATH.exists() or CHECKPOINT_PATH.stat().st_size < 1024 * 1024:64 unmodified lines.info-tip { position:relative; display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; border-radius:999px; border:1px solid #bfdbfe; background:#eff6ff; color:#1e40af; font-weight:800; cursor:help; }.info-tip .tip-content { display:none; position:absolute; right:0; top:30px; z-index:20; width:420px; max-width:80vw; background:white; border:1px solid var(--line); border-radius:8px; padding:10px; box-shadow:0 12px 30px rgba(15,23,42,.16); }.info-tip:hover .tip-content { display:block; }.negative-grid { display:grid; grid-template-columns:repeat(6, minmax(0, 1fr)); gap:10px; margin:8px 0 14px; }.negative-card { display:grid; grid-template-columns:64px 1fr; gap:10px; border:1px solid #fecaca; border-left:4px solid #ef4444; border-radius:8px; padding:10px; background:#fffafa; }.negative-card p { margin:5px 0 0; color:#334155; font-size:13px; }.mini-product-img { width:64px; height:76px; object-fit:cover; border-radius:6px; border:1px solid var(--line); background:#f8fafc; }@media (max-width:1100px) { .negative-grid { grid-template-columns:repeat(3, minmax(0, 1fr)); } }@media (max-width:860px) { .aspect-grid, .metric-grid, .product-layout, .decision-layout, .negative-grid { grid-template-columns:1fr; } .product-img { width:100%; height:180px; } }"""39 unmodified linesgr.HTML('<div class="module-head"><h3>Product Score Monitor</h3><span class="info-tip">i<span class="tip-content">' + model_info_html() + '</span></span></div>')gr.HTML('<div class="small-label">Most negative products across the six aspects</div>')negative_spotlight = gr.HTML('<div class="note-card">Loading most negative products...</div>')aspect_overview = gr.Dataframe(headers=["Aspect", "Negative Count", "Most Negative Product", "Confidence", "Reason"], value=merchant_aspect_overview(), datatype=["str", "number", "str", "number", "str"], interactive=False, label="Six-aspect negative overview")with gr.Accordion("Score filters and export", open=True):with gr.Row():merchant_metric = gr.Dropdown(["Overall"] + ASPECTS, value="Overall", label="Aspect")5 unmodified linesexport_scores = gr.Button("Export Score List")merchant_scores_file = gr.File(label="Downloaded score CSV", interactive=False)with gr.Accordion("New Product Metadata Risk Screening", open=False):risk_mode = gr.Radio(["Single product analysis", "Batch import analysis"], value="Single product analysis", label="Analysis mode")with gr.Row():with gr.Column(scale=1):with gr.Group(visible=True) as risk_single_group:new_features = gr.Textbox("Cotton Polyester Blend, Slim Fit, Graphic Print, Machine Wash", label="New product features", lines=4)new_categories = gr.Textbox("Clothing > Women > Tops > T-Shirts", label="New product categories")with gr.Row():new_price = gr.Number(29.99, label="Price")new_rating = gr.Number(4.1, label="Expected or early average rating")with gr.Row():new_count = gr.Number(35, label="Expected or early rating count")new_focus = gr.Dropdown(["All"] + ASPECTS, value="All", label="Focus aspect")screen_btn = gr.Button("Predict Metadata Risk", variant="primary")with gr.Group(visible=False) as risk_batch_group:new_import = gr.File(label="Import product metadata JSON/CSV")with gr.Row():new_template = gr.Button("Download Import Template")batch_screen_btn = gr.Button("Batch Analyze Metadata", variant="primary")new_template_file = gr.File(label="Template CSV", interactive=False)with gr.Column(scale=1):risk_summary = gr.HTML()risk_table = gr.Dataframe(headers=["Aspect", "Risk Level", "Model Signal", "Confidence", "Reason"], value=[["Click Predict Metadata Risk", "", "", 0.0, ""]], datatype=["str", "str", "str", "number", "str"], interactive=False)export_risk = gr.Button("Export Risk Result")risk_file = gr.File(label="Downloaded risk CSV", interactive=False)with gr.Accordion("External Review Prediction", open=False):ext_mode = gr.Radio(["Single product analysis", "Batch import analysis"], value="Single product analysis", label="Analysis mode")with gr.Row():with gr.Column(scale=1):with gr.Group(visible=True) as ext_single_group:external_review = gr.Textbox("The fabric is soft and the color looks good, but it runs small and the zipper feels weak.", label="External customer review", lines=5)with gr.Row():ext_features = gr.Textbox("Cotton Blend, Slim Fit, Zipper Closure", label="Product features", lines=3)ext_categories = gr.Textbox("Clothing > Women > Jackets", label="Product categories", lines=3)with gr.Row():ext_price = gr.Number(39.99, label="Price")ext_rating = gr.Number(4.2, label="Average rating")with gr.Row():ext_count = gr.Number(312, label="Rating count")ext_aspect = gr.Dropdown(["All"] + ASPECTS, value="All", label="Highlight aspect")external_btn = gr.Button("Analyze External Review", variant="primary")with gr.Group(visible=False) as ext_batch_group:ext_import = gr.File(label="Import review metadata JSON/CSV")with gr.Row():ext_template = gr.Button("Download Import Template")batch_external_btn = gr.Button("Batch Analyze Reviews", variant="primary")ext_template_file = gr.File(label="Template CSV", interactive=False)with gr.Column(scale=1):ext_overall = gr.HTML()ext_aspects = gr.HTML()5 unmodified linesmerchant_metric.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)merchant_prediction.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)merchant_category.change(merchant_score_filter, [merchant_metric, merchant_prediction, merchant_category], merchant_scores)risk_mode.change(toggle_analysis_mode, risk_mode, [risk_single_group, risk_batch_group])screen_btn.click(screen_new_product, [new_features, new_categories, new_price, new_rating, new_count, new_focus], [risk_summary, risk_table])new_template.click(download_new_product_template, None, new_template_file)batch_screen_btn.click(batch_screen_new_products, new_import, [risk_summary, risk_table])export_risk.click(export_risk_rows, risk_table, risk_file)ext_mode.change(toggle_analysis_mode, ext_mode, [ext_single_group, ext_batch_group])external_btn.click(external_review_predict, [external_review, ext_features, ext_categories, ext_price, ext_rating, ext_count, ext_aspect], [ext_overall, ext_aspects, ext_table])ext_template.click(download_external_review_template, None, ext_template_file)batch_external_btn.click(batch_external_review_predict, ext_import, [ext_overall, ext_aspects, ext_table])export_ext.click(export_external_rows, ext_table, ext_file)with gr.Tab("Research Metrics"):
app.py+170-20