raajeshkannan's picture
Upload app.py
10489f8 verified
Raw History Blame Contribute Delete
100 kB
# app.py - Hugging Face Space version of your full Quality Test Optimizer # Ported from your uploaded file (keeps all functions & UI; local file loaders replaced with placeholders). import os import io import psutil import heapq import random import textwrap import matplotlib.pyplot as plt # quality_test_optimizer_streamlit.py import streamlit as st import pandas as pd import numpy as np import json import io import math import re st.set_page_config(layout="wide", page_title="Quality Test Plan Optimizer") # --------------------------- # Helpers: rounding & thresholds # --------------------------- def roundup(x): """Round down to a 'nice' bucket as per your logic.""" if x is None or pd.isna(x): return 0 x = int(x) if x < 0: return 0 if x > 0 and x <= 10: return x if x > 10 and x < 99: return x if x % 10 == 0 else x - (x % 10) if x > 99 and x < 999: return x if x % 100 == 0 else x - (x % 100) if x > 999 and x < 9999: return x if x % 1000 == 0 else x - (x % 1000) if x > 9999 and x < 99999: return x if x % 10000 == 0 else x - (x % 10000) if x > 99999 and x < 999999: return x if x % 100000 == 0 else x - (x % 100000) if x > 999999 and x < 9999999: return x if x % 100000 == 0 else x - (x % 1000000) return x if x % 1000000 == 0 else x - (x % 10000000) def safe_percentile(series, percentile): """ Safely calculate percentile after converting to numeric with coercion. Returns 0.0 if no valid numeric data. """ clean_series = pd.to_numeric(series, errors="coerce").dropna() if clean_series.size == 0: return 0.0 #return float(np.percentile(clean_series, percentile)) return int(np.percentile(clean_series, percentile)) def make_sales_thresholds_from_sales(series): tmp_val = [0] i = 1 sales_std = {} # stepping down percentiles from 100 to 3 by 3 -> up to ~33 entries, we cap at 25 for percentiles in range(100, 0, -3): try: percentile_val = int(safe_percentile(series, percentiles)) except Exception: continue if percentile_val in tmp_val: continue percentile_val = int(roundup(percentile_val)) if percentile_val in tmp_val: continue tmp_val.append(percentile_val) sales_std[f"sales_std_{i}"] = percentile_val i += 1 #vars()["sales_std_"+str(i)]=percentile_val #print ("sales_std_"+str(i)+" = " +str(vars()["sales_std_"+str(i)])) if i > 25: break #vars()["sales_std_"+str(i)]=0 # Fill missing keys up to 25 with zeros #for j in range(1, 26): # key = f"sales_std_{j}" # if key not in sales_std: # sales_std[key] = 0 # Force last bucket to 1 and 0 as requested (overrides) #sales_std["sales_std_24"] = sales_std.get("sales_std_24", 1) #sales_std["sales_std_25"] = sales_std.get("sales_std_25", 0) # Ensure we have some sensible defaults for last few indexes if they weren't set #sales_std["sales_std_22"] = sales_std.get("sales_std_22", 4) #sales_std["sales_std_23"] = sales_std.get("sales_std_23", 3) #sales_std["sales_std_24"] = sales_std.get("sales_std_24", 1) #sales_std["sales_std_25"] = sales_std.get("sales_std_25", 0) #sales_std["sales_std_22"] = 4 sales_std["sales_std_23"] = 3 sales_std["sales_std_24"] = 1 sales_std["sales_std_25"] = 0 # Build thresholds list for bucketization (descending order pairs) sales_thresholds = [] for j in range(1, 25): min_v = sales_std[f"sales_std_{j}"] max_v = sales_std[f"sales_std_{j+1}"] sales_thresholds.append((min_v, max_v)) #st.write(f"sales_threshold: '{sales_thresholds}'") #st.write(f"sales_std: '{sales_std}'") return sales_std, sales_thresholds # --------------------------- # Matching logic helpers # --------------------------- def is_empty(value): if value is None: return True if isinstance(value, float) and math.isnan(value): return True if isinstance(value, (str, bytes)) and str(value).strip().upper() in ["", "EMPTY", "NONE", "NAN"]: return True return False def parse_redev_json(val): """Try to parse redev-like JSON string to list; return [] on parse fail.""" if is_empty(val): return [] try: parsed = json.loads(val) if isinstance(parsed, list): return parsed return [parsed] except Exception: try: s = str(val).strip() if s.startswith('[') and s.endswith(']'): inner = s[1:-1].replace('"', '').replace("'", "") tokens = [x.strip() for x in inner.split(',') if x.strip()] return tokens except Exception: pass return [] def check_field_conditions(value, conditions, thresholds, field_name=None, debug=False): """ Helper wrapper - retained for compatibility (not used everywhere). """ if not isinstance(conditions, list): res, _ = check_condition(value, conditions, thresholds, field_name, debug) return res conds_upper = [str(c).upper() for c in conditions] if "EMPTY" in conds_upper: # OR logic: pass if any condition True for cond in conditions: res, _ = check_condition(value, cond, thresholds, field_name, debug) if debug: print(f"[OR] field={field_name}, value={value}, cond={cond} -> {res}") if res: return True return False elif "NOTEMPTY" in conds_upper: # AND logic: pass only if all conditions True for cond in conditions: res, _ = check_condition(value, cond, thresholds, field_name, debug) if debug: print(f"[AND] field={field_name}, value={value}, cond={cond} -> {res}") if not res: return False return True else: # Default AND logic for cond in conditions: res, _ = check_condition(value, cond, thresholds, field_name, debug) if debug: print(f"[AND-DEFAULT] field={field_name}, value={value}, cond={cond} -> {res}") if not res: return False return True def check_condition(value, cond, thresholds, field_name=None, debug=False): """ Evaluate a single condition for a field value. Returns: (result: bool, resolved_values: dict) """ #resolved_values = {} empty_flag = is_empty(value) cond_str = str(cond).strip() if cond_str.upper() == "EMPTY": return empty_flag elif cond_str.upper() == "!=EMPTY": return not empty_flag if empty_flag: return False if debug: print(f"check_condition called with field='{field_name}', value='{value}', cond='{cond}'") #if cond is True or cond is False: # result = (bool(value) == bool(cond)) # if debug: # print(f" Boolean cond={cond}, result={result}") # return result, resolved_values #cs = str(cond).strip() #cs_upper = cs.upper() #if cs_upper in ("EMPTY", "NOTEMPTY", "!=EMPTY"): # if cs_upper == "EMPTY": # if debug: # print(f" Checking EMPTY: empty_flag={empty_flag}") # return empty_flag, resolved_values # else: # if debug: # print(f" Checking NOTEMPTY or !=EMPTY: empty_flag={empty_flag}") # return (not empty_flag), resolved_values #if empty_flag: # if debug: # print(" Value is empty but condition is not EMPTY, returning False") # return False, resolved_values # Accept forms like '>=complaints_P75' or '>=P75' (metric optional) #m = re.match(r'([<>]=?|!=)\s*([a-zA-Z_]+)?_?P(\d+)', cs) #if m: # op, metric, perc = m.groups() # if not metric: # if not field_name: # if debug: # print(" No metric and no field_name, returning False") # return False, resolved_values # fmap = { # "reviews_count": "reviews", # "reviews": "reviews", # "complaints": "complaints", # "average_rating": "ratings", # "ratings": "ratings" # } # metric = fmap.get(field_name.lower(), field_name.lower()) # perc_key = f"P{perc}" # metric_dict = thresholds.get(metric) # if isinstance(metric_dict, dict): # thr = metric_dict.get(perc_key) # if thr is None and debug: # print(f" WARNING: Threshold key '{perc_key}' not found in thresholds['{metric}']") # else: # thr = metric_dict # try: # val_f = float(value) # thr_f = float(thr) # except Exception as e: # if debug: # print(f" ERROR converting value or threshold to float: {e}") # return False, resolved_values # resolved_values[f"{metric}_P{perc}"] = thr_f # if debug: # print(f" Comparing: {val_f} {op} {thr_f}") # if op == ">=": # return val_f >= thr_f, resolved_values # elif op == "<=": # return val_f <= thr_f, resolved_values # elif op == ">": # return val_f > thr_f, resolved_values # elif op == "<": # return val_f < thr_f, resolved_values # elif op == "!=": # return val_f != thr_f, resolved_values # else: # if debug: # print(f" Unknown operator '{op}'") # return False, resolved_values # Numeric direct comparisons without percentile, e.g. >=3, <=5 # try: # if cs.startswith(">="): # val_comp = float(cs[2:].strip()) # result = float(value) >= val_comp # if debug: # print(f" Direct numeric comparison >= {val_comp}: {result}") # return result, resolved_values # elif cs.startswith("<="): # val_comp = float(cs[2:].strip()) # result = float(value) <= val_comp # if debug: # print(f" Direct numeric comparison <= {val_comp}: {result}") # return result, resolved_values # elif cs.startswith(">"): # val_comp = float(cs[1:].strip()) # result = float(value) > val_comp # if debug: # print(f" Direct numeric comparison > {val_comp}: {result}") # return result, resolved_values # elif cs.startswith("<"): # val_comp = float(cs[1:].strip()) # result = float(value) < val_comp # if debug: # print(f" Direct numeric comparison < {val_comp}: {result}") # return result, resolved_values # elif cs.startswith("!="): # val_comp = cs[2:].strip() # result = str(value) != val_comp # if debug: # print(f" Direct string comparison != {val_comp}: {result}") # return result, resolved_values # except Exception as e: # if debug: # print(f" Exception in direct numeric comparison: {e}") # pass # Direct equality fallback # result = str(value) == cs # if debug: # print(f" Direct equality comparison '{value}' == '{cs}': {result}") # return result, resolved_values threshold_match = re.match(r'([<>]=?|!=)([a-zA-Z_]+)?_?P(\d+)', cond_str) if threshold_match: op, metric, perc = threshold_match.groups() if metric is None and field_name is not None: key = field_name.lower() field_to_metric_map = { "complaints": "complaints", "reviews_count": "reviews", "reviews": "reviews", "average_rating": "ratings", "ratings": "ratings" } metric = field_to_metric_map.get(key, key) perc_key = f"P{perc}" if metric not in thresholds: print(f"Metric '{metric}' not found in thresholds.") return False threshold_value = thresholds.get(metric, {}).get(perc_key) if threshold_value is None: print(f"Threshold value for {metric} {perc_key} not found.") return False try: val_float = float(value) thresh_float = float(threshold_value) if op == ">=": return val_float >= thresh_float elif op == "<=": return val_float <= thresh_float elif op == ">": return val_float > thresh_float elif op == "<": return val_float < thresh_float elif op == "!=": return val_float != thresh_float except Exception as e: print(f"Error in threshold comparison: {e}") return False # fallback numeric comparisons try: if cond_str.startswith(">="): return float(value) >= float(cond_str[2:]) elif cond_str.startswith("<="): return float(value) <= float(cond_str[2:]) elif cond_str.startswith(">"): return float(value) > float(cond_str[1:]) elif cond_str.startswith("<"): return float(value) < float(cond_str[1:]) elif cond_str.startswith("!="): return str(value) != cond_str[2:] except Exception as e: print(f"Exception in numeric check: {e}") return False return str(value) == cond_str def field_matches(val, cond, thresholds, field_name=None, debug=False): """ Simpler wrapper - used by orig code; keeps same semantics as check_field_conditions. """ return check_field_conditions(val, cond, thresholds, field_name, debug) def redev_status_matches(val, conditions): """ Matches Redev_Status JSON list values with conditions list. Supports 'EMPTY' condition, direct string matches, and JSON list matches. """ #conds = conditions if isinstance(conditions, list) else [conditions] #conds_upper = [str(c).upper() for c in conds] if is_empty(val): # val empty, match if any condition is 'EMPTY' #return "EMPTY" in conds_upper return "EMPTY" in [c.upper() for c in conditions] try: val_list = json.loads(val) if not isinstance(val_list, list): return False except Exception: return False # If val_list empty, consider 'EMPTY' condition again #if not val_list: # return "EMPTY" in conds_upper #for cond in conds: # cond_upper = str(cond).upper() # if cond_upper == "EMPTY" and not val_list: # return True # try: # cond_list = json.loads(cond) # if isinstance(cond_list, list) and all(x in val_list for x in cond_list): # return True # except Exception: # # fallback: direct string inclusion (case sensitive) # if cond in val_list: # return True for cond in conditions: cond_upper = str(cond).upper() if cond_upper == "EMPTY" and not val_list: return True try: cond_list = json.loads(cond) if isinstance(cond_list, list) and all(x in val_list for x in cond_list): return True except Exception: # fallback: check if condition string is in val_list if cond in val_list: return True return False def is_metric_condition_for_field(cond, field): """ Returns True if cond is a metric percentile condition relevant to the given field. Example: '<complaints_P75', '>=reviews_P90' """ if not isinstance(cond, str): return False # Regex to capture operator + optional whitespace + metric + '_P' + digits pattern = r'^[<>!]=?\s*([a-zA-Z]+)_P\d+$' m = re.match(pattern, cond.strip()) if not m: return False metric = m.group(1) if metric is None: return False # compare metric vs field name lower return metric.lower() == str(field).lower() def record_matches_config(record, filters, thresholds, debug=False, rule_idx=None, record_idx=None, debug_fn=None): """Return True if record satisfies all filters in config. Debug prints optionally, with expanded percentile threshold values in debug output.""" import ast # Convert any stringified list conditions to actual lists #for field, cond in filters.items(): # if isinstance(cond, str): # try: # parsed = ast.literal_eval(cond) # if isinstance(parsed, list): # filters[field] = parsed # except Exception: # pass # Not a list, keep as is def log(msg): if debug_fn: debug_fn(msg) elif debug: print(msg) def expand_condition_display(cond_str, resolved_values): cond_str = str(cond_str) for token, val in resolved_values.items(): cond_str = cond_str.replace(token, f"{token}(={val:.2f})") return cond_str log(f"Checking record idx={record_idx} against rule {rule_idx}") for field, cond in filters.items(): if str(field).strip() == "": continue val = record.get(field) #if isinstance(record, (pd.Series, dict)) else None # Special case: Redev_Status if field == "Redev_Status": cond_list = cond if isinstance(cond, list) else [cond] if not redev_status_matches(val, cond_list): log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond_list}") return False log(f"Field '{field}' val={val} condition={cond_list} => True") continue # Handle list conditions if isinstance(cond, list): cond_upper = [str(c).upper() for c in cond] empty_flag = is_empty(val) if "EMPTY" in cond_upper and "NOTEMPTY" in cond_upper: raise ValueError(f"Filter for field '{field}' cannot contain both 'EMPTY' and 'NOTEMPTY'.") if "EMPTY" in cond_upper: # OR logic: if value empty then pass, else any of other metric conditions passing will pass if empty_flag: log(f" Field '{field}' val={val} condition=EMPTY => True") continue else: #other_conds = [ # c for c in cond # if str(c).upper() != "EMPTY" and is_metric_condition_for_field(c, field) #] other_conds = [c for c in cond if str(c).upper() != "EMPTY"] if not other_conds: log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") return False passed_any = False #if not any(check_condition(val, c, thresholds, field)[0] for c in other_conds): # log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") # return False for c in other_conds: if check_condition(val, c, thresholds, field): passed_any = True if debug: log(f" Field '{field}' val={val} condition=EMPTY => True") break if not passed_any: if debug: log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") return False continue if "NOTEMPTY" in cond_upper: # AND logic: value must be not empty, and all other metric conditions (if present) must hold if empty_flag: log(f"❌ Field '{field}' failed. Value={val} is empty but condition includes NOTEMPTY") return False #other_conds = [ # c for c in cond # if str(c).upper() != "NOTEMPTY" and is_metric_condition_for_field(c, field) #] other_conds = [c for c in cond if str(c).upper() != "NOTEMPTY"] if not other_conds: log(f" Field '{field}' val={val} condition=NOTEMPTY => True") continue #if not all(check_condition(val, c, thresholds, field)[0] for c in other_conds): # log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") # return False passed_any = False for c in other_conds: if check_condition(val, c, thresholds, field): passed_any = True if debug: log(f" Field '{field}' val={val} condition=EMPTY => True") break if not passed_any: if debug: log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") return False continue # No EMPTY/NOTEMPTY in list: default to AND of metric conditions #filtered_conds = [c for c in cond if is_metric_condition_for_field(c, field)] #if not all(check_condition(val, c, thresholds, field)[0] for c in filtered_conds): # log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") # return False passed_any = False for c in cond: if check_condition(val, c, thresholds, field): passed_any = True if debug: log(f" Field '{field}' val={val} condition=EMPTY => True") break if not passed_any: if debug: log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") return False #else: # if it's not a metric condition reference to this field, we skip (keeps behavior friendly) # if not is_metric_condition_for_field(cond, field): continue # res, resolved_values = check_condition(val, cond, thresholds, field) # log(f" Field '{field}' val={val} condition={expand_condition_display(cond, resolved_values)} => {res}") # if not res: # log(f"❌ Field '{field}' failed. Value={val}, Condition={expand_condition_display(cond, resolved_values)}") # return False else: res = check_condition(val, cond, thresholds, field) if debug: log(f" Field '{field}' val={val} condition=EMPTY => True") if not res: if debug: log(f"❌ Field '{field}' failed. Value={val}, Conditions={cond}") return False return True # --------------------------- # Two-phase scoring function # --------------------------- def assign_priority_score_two_phase( df, priority_config, fallback_config, thresholds, sales_thresholds, debug_rows=0, debug_tpnb=None, max_debug_lines=200 ): """ Two-phase scoring with automatic percentile computation before scoring. Returns: (scored_dataframe, debug_logs) """ df = df.copy() df["priority_score"] = None df["matched_rule"] = None debug_logs = [] # Ensure numeric columns are numeric df['Reviews_Count'] = pd.to_numeric(df['Reviews_Count'], errors='coerce') df['Average_Rating'] = pd.to_numeric(df['Average_Rating'], errors='coerce') df['complaints'] = pd.to_numeric(df['complaints'], errors='coerce') def normalize_val_str(x): if pd.isna(x) or (isinstance(x, str) and x.strip() == ""): return "" return x for col in ['actionplan_status', 'Redev_Status']: if col in df.columns: df[col] = df[col].map(normalize_val_str) def add_debug(msg, row=None): """Append debug message if matches filter and under max limit.""" if debug_tpnb: if row is None or str(row.get("tpnb")) != str(debug_tpnb): return # strict filtering if len(debug_logs) < max_debug_lines: debug_logs.append(msg) # ---- NEW: Precompute percentiles before scoring ---- #numeric_cols_for_thresholds = { # "reviews_P75": ("Reviews_Count", 75), # "reviews_P25": ("Reviews_Count", 25), # "complaints_P75": ("complaints", 75), # "complaints_P25": ("complaints", 25), # "rating_P75": ("Average_Rating", 75), # "rating_P25": ("Average_Rating", 25) #} #for thresh_key, (col_name, perc) in numeric_cols_for_thresholds.items(): # if col_name in df.columns: # Convert to numeric safely # numeric_series = pd.to_numeric(df[col_name], errors='coerce').dropna() # Compute percentile safely # value = float(np.nanpercentile(numeric_series, perc)) if numeric_series.size > 0 else 0.0 # Split the metric name and percentile from thresh_key # if "_P" in thresh_key: # metric, perc_str = thresh_key.split("_P") # perc_label = f"P{perc_str}" # else: # metric = thresh_key # perc_label = f"P{perc}" # Ensure nested dict exists # if metric not in thresholds or not isinstance(thresholds.get(metric), dict): # thresholds[metric] = {} # Store both nested and flat for backward compatibility # thresholds[metric][perc_label] = value # thresholds[thresh_key] = value # add_debug(f"[Percentiles] {metric}_{perc_label} = {value}", None) # Debug prints for unique values in key columns fields_to_debug = ['complaints', 'Average_Rating', 'Reviews_Count', 'actionplan_status', 'Redev_Status'] if debug_rows > 0: #print(df[['complaints', 'Average_Rating', 'Reviews_Count', 'actionplan_status', 'Redev_Status']].head(debug_rows)) pass # ---- PHASE 1 ---- for idx, row in df.iterrows(): sales_val = row.get('sales') if pd.isna(sales_val): continue sales_val = int(sales_val) best_score = None best_rule = None debug_this_row = ( (debug_tpnb is not None and str(row.get("tpnb")) == str(debug_tpnb)) or (debug_tpnb is None and idx < debug_rows) ) if debug_tpnb and not debug_this_row: continue for rule_idx, config in enumerate(priority_config): match = record_matches_config( row, config["filters"], thresholds, debug=debug_this_row, rule_idx=rule_idx, record_idx=idx, debug_fn=(lambda msg, r=row: add_debug(f"TPNB={r.get('tpnb')} | {msg}", r)) ) if match: #score = config["base_score"] # start from base score (usually 1) #for idx, threshold in enumerate(sales_std_vars, start=1): # sales_std_vars is descending #if sales_val >= threshold: #score = config["base_score"] + idx #break #else: # If sales below all thresholds, assign lowest bucket #score = config["base_score"] + len(sales_std_vars) # assign score to df #df.at[row_index, "Priority_Score"] = score # if best_score is None or score > best_score: # best_score = score # best_rule = f"rule_{rule_idx}" # add_debug(f"[Phase1] Row {idx} ({row.get('tpnb')}) matched rule {rule_idx} bucket {index} → score {score}", row) for index, (min_val, max_val) in enumerate(sales_thresholds): # First bucket special case if index == 0 and sales_val > sales_thresholds[0][0]: score = config["base_score"] + index # Last bucket special case elif index == len(sales_thresholds) - 1 and sales_val <= sales_thresholds[-1][1]: score = config["base_score"] + len(sales_thresholds) elif max_val < sales_val <= min_val: score = config["base_score"] + index + 1 elif sales_val <= 0: score = 2000 else: continue if best_score is None or score > best_score: best_score = score best_rule = f"rule_{rule_idx}" df.at[idx, "priority_score"] = best_score df.at[idx, "matched_rule"] = best_rule # ---- PHASE 2 (Fallback) ---- mask_unscored = df["priority_score"].isna() for idx, row in df[mask_unscored].iterrows(): sales_val = row.get('sales') best_score = None best_rule = None # Preserve legacy Priority_Score if present if "Priority_Score" in df.columns: legacy_score = row.get("Priority_Score") if pd.notna(legacy_score): df.at[idx, "priority_score"] = legacy_score df.at[idx, "matched_rule"] = "legacy_preserve" continue debug_this_row = ( (debug_tpnb is not None and str(row.get("tpnb")) == str(debug_tpnb)) or (debug_tpnb is None and idx < debug_rows) ) if debug_tpnb and not debug_this_row: continue for fb_idx, config in enumerate(fallback_config): match = record_matches_config( row, config["filters"], thresholds, debug=debug_this_row, rule_idx=fb_idx, record_idx=idx, debug_fn=(lambda msg, r=row: add_debug(f"TPNB={r.get('tpnb')} | {msg}", r)) ) add_debug(f"[Fallback] Row {idx} ({row.get('tpnb')}) Rule {fb_idx} match={match}", row) if not match: continue base = config["base_score"] if fb_idx in (0, 1): if pd.isna(sales_val) or sales_val <= 0: score = base else: sales_val_int = int(sales_val) score = base for index, (min_val, max_val) in enumerate(sales_thresholds): bucket_name = f"{max_val} ≤ sales ≤ {min_val}" if index == 0 and sales_val_int > min_val: # Top bucket: sales_val > max_val score = base + 1 break elif index == len(sales_thresholds) - 1 and sales_val_int <= max_val: score = base + len(sales_thresholds) break elif max_val < sales_val_int <= min_val: score = base + index + 1 break else: # Rules 2 & 3 fixed score 2000 score = 2000 #print(f" Rule {fb_idx} fixed score {score}") best_score = score best_rule = f"fallback_{fb_idx}" break df.at[idx, "priority_score"] = best_score df.at[idx, "matched_rule"] = best_rule return df, debug_logs # --------------------------- # Default priority_config (if JSON not provided) # --------------------------- DEFAULT_PRIORITY_CONFIG = [ { "filters": {"Redev_Status": "EMPTY", "complaints": ["EMPTY",">=P75"], "Average_Rating": ["EMPTY","<=3"], "Reviews_Count": ["EMPTY",">=P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 1 }, { "filters": {"Redev_Status": "EMPTY", "complaints":["EMPTY",">=P75"], "Average_Rating": ["EMPTY","<=3"], "Reviews_Count": ["NOTEMPTY","<P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 26 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["EMPTY",">=P75"], "Average_Rating": ["NOTEMPTY",">3"], "Reviews_Count": ["EMPTY",">=P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 51 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["EMPTY",">=P75"], "Average_Rating": ["NOTEMPTY",">3"], "Reviews_Count": ["NOTEMPTY","<P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 76 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["NOTEMPTY","<P75"], "Average_Rating": ["EMPTY","<=3"], "Reviews_Count": ["EMPTY",">=P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 101 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["NOTEMPTY","<P75"], "Average_Rating": ["EMPTY","<=3"], "Reviews_Count": ["NOTEMPTY","<P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 126 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["NOTEMPTY","<P75"], "Average_Rating": ["NOTEMPTY",">3"], "Reviews_Count": ["EMPTY",">=P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 151 }, { "filters": {"Redev_Status": "EMPTY", "complaints": ["NOTEMPTY","<P75"], "Average_Rating": ["NOTEMPTY",">3"], "Reviews_Count": ["NOTEMPTY","<P75"], "actionplan_status": ["EMPTY","NO_ACTION_REQUIRED"]}, "base_score": 176 } ] # default fallback config DEFAULT_FALLBACK_CONFIG = [ {"filters": { "actionplan_status": ["EMPTY"], "Redev_Status": ['["Complete"]']}, "base_score": 1001}, {"filters": { "actionplan_status": ["NO_ACTION_REQUIRED"], "Redev_Status": ['["Complete"]']}, "base_score": 1501}, {"filters": { "actionplan_status": ["NOTEMPTY",'!="NO_ACTION_REQUIRED"']}, "base_score": 2000}, {"filters": { "actionplan_status": ["EMPTY"], "Redev_Status": ["NOTEMPTY",'!=[\“Complete\”]']}, "base_score": 2000}, {"filters": { "Redev_Status": ['["Complete"]']}, "base_score": 2000} ] # --------------------------- # Streamlit UI # --------------------------- st.title("📅 Quality Test Plan Optimizer") st.markdown( """ <style> div.stButton > button:first-child { background-color: green; color: white; font-weight: bold; } div.stButton > button:first-child:hover { background-color: darkgreen; color: white; } </style> """, unsafe_allow_html=True ) # Clear caches on start of site #if 'scored' in st.session_state: # del st.session_state['scored'] #if 'debug_info' in st.session_state: # del st.session_state['debug_info'] #if 'result' in st.session_state: # del st.session_state['result'] # Sidebar: file uploads + controls st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) st.sidebar.header("Input files & settings") uploaded_sales = st.sidebar.file_uploader("Sales file (CSV)", type=["csv"], key="sales") uploaded_tests = st.sidebar.file_uploader("Tests file (CSV) - last_test_date column", type=["csv"], key="tests") uploaded_ratings = st.sidebar.file_uploader("Ratings file (CSV)", type=["csv"], key="ratings") uploaded_redev = st.sidebar.file_uploader("Redev file (CSV)", type=["csv"], key="redev") uploaded_kqi = st.sidebar.file_uploader("KQI file (CSV)", type=["csv"], key="kqi") uploaded_complaints = st.sidebar.file_uploader("Complaints file (CSV)", type=["csv"], key="complaints") uploaded_tier = st.sidebar.file_uploader("Tier file (CSV)", type=["csv"], key="tier") uploaded_actplan = st.sidebar.file_uploader("Action Plan file (CSV)", type=["csv"], key="actplan") st.sidebar.markdown("---") st.sidebar.header("Debug & Run") # Debug TPNB input - ONLY ONCE, with a unique key debug_tpnb_input = st.sidebar.text_input("Debug TPNB (optional)", value="", key="debug_tpnb_input") # Convert to int if valid, else None debug_tpnb = int(debug_tpnb_input) if debug_tpnb_input.strip().isdigit() else None # Debug rows input - ONLY ONCE, with unique key debug_rows = st.sidebar.number_input("How many rows to debug (0 disables)", min_value=0, max_value=50, value=5, step=1, key="debug_rows_input") # Checkbox for debug mode if you want use_debug = st.sidebar.checkbox("Debug mode (prints first N rows trace)", value=False, key="use_debug_checkbox") use_debug = debug_rows > 0 or (debug_tpnb_input.strip() != "") st.sidebar.header("Percentile & rating controls") reviews_pct = st.sidebar.selectbox("Reviews percentile (for Pnn)", [0.25, 0.50, 0.75, 0.95, 0.98, 0.99], index=2) complaints_pct = st.sidebar.selectbox("Complaints percentile (for Pnn)", [0.25, 0.50, 0.75, 0.95, 0.98, 0.99], index=2) ratings_cutoff = st.sidebar.selectbox("Ratings cutoff (ratings_std)", [1, 2, 3, 4, 5], index=2) #st.write("reviews cnt percentile chosen % is:", reviews_pct) #st.write("complaints cnt percentile chosen % is:", complaints_pct) #st.write("ratings cnt percentile chosen % is:", ratings_cutoff) st.sidebar.markdown("---") st.sidebar.header("Priority config and fallback config") uploaded_config = st.sidebar.file_uploader("Optional: priority_config.json", type=["json"], key="pconfig") uploaded_fallback = st.sidebar.file_uploader("Optional: fallback_config.json", type=["json"], key="fconfig") # in-memory threshold object will be displayed show_thresholds = st.sidebar.expander("View generated thresholds (in-memory)") def read_csv_from_upload(uploaded): if uploaded is None: return None try: return pd.read_csv(uploaded) except Exception: uploaded.seek(0) return pd.read_csv(io.TextIOWrapper(uploaded)) # --------------------------- # Load priority_config JSON (or default) # --------------------------- if uploaded_config: try: priority_config = json.load(uploaded_config) except Exception: uploaded_config.seek(0) priority_config = json.load(io.TextIOWrapper(uploaded_config)) else: priority_config = DEFAULT_PRIORITY_CONFIG if uploaded_fallback: try: fallback_config = json.load(uploaded_fallback) except Exception: uploaded_fallback.seek(0) fallback_config = json.load(io.TextIOWrapper(uploaded_fallback)) else: fallback_config = DEFAULT_FALLBACK_CONFIG # Define a function to be cached @st.cache_data def expensive_computation(data): st.write(f"Executing expensive_computation with: {data}") time.sleep(2) # Simulate a time-consuming operation return f"Processed: {data}" # Callback function to clear the cache def clear_cache_callback(): expensive_computation.clear() st.success("Cache cleared!") # --------------------------- # Preprocessing - read uploaded files or sample placeholder # --------------------------- @st.cache_data def load_default_sales(): return pd.read_csv("sales_data_7Aug.csv") @st.cache_data def load_default_tests(): return pd.read_csv("tests_data_7Aug.csv") @st.cache_data def load_default_ratings(): return pd.read_csv("ratings_data_7Aug.csv") @st.cache_data def load_default_redev(): return pd.read_csv("redevelopment_data_26Jun.csv") @st.cache_data def load_default_kqi(): return pd.read_csv("kqi_data.csv") @st.cache_data def load_default_complaints(): return pd.read_csv("complaints_data_7Aug.csv") @st.cache_data def load_default_tier(): return pd.read_csv("tier_data_7Aug.csv") @st.cache_data def load_default_actplan(): return pd.read_csv("action_plan_data_7Aug.csv") # load or upload files (uses read_csv_from_upload defined above) sales_df = read_csv_from_upload(uploaded_sales) if uploaded_sales else load_default_sales() tests_df = read_csv_from_upload(uploaded_tests) if uploaded_tests else load_default_tests() ratings_df = read_csv_from_upload(uploaded_ratings) if uploaded_ratings else load_default_ratings() redev_df = read_csv_from_upload(uploaded_redev) if uploaded_redev else load_default_redev() kqi_df = read_csv_from_upload(uploaded_kqi) if uploaded_kqi else load_default_kqi() complaints_df = read_csv_from_upload(uploaded_complaints) if uploaded_complaints else load_default_complaints() tier_df = read_csv_from_upload(uploaded_tier) if uploaded_tier else load_default_tier() actplan_df = read_csv_from_upload(uploaded_actplan) if uploaded_actplan else load_default_actplan() if uploaded_sales: st.sidebar.success("Sales file uploaded by user") else: st.sidebar.info("Using default Sales file") # If some are missing, let user know input_files_ok = True required = {"sales": sales_df, "tests": tests_df, "ratings": ratings_df, "redev": redev_df, "kqi": kqi_df, "complaints": complaints_df, "tier": tier_df, "action_plan": actplan_df} missing = [k for k, v in required.items() if v is None] if missing: st.sidebar.warning(f"Upload these files to run end-to-end: {', '.join(missing)}") input_files_ok = False # If user uploaded everything, do preprocessing if input_files_ok: st.sidebar.success("All input files uploaded.") # Copy & normalize columns as required names X_sales_data = sales_df.copy() X_test_data = tests_df.copy() X_rate_data = ratings_df.copy() X_redev_data = redev_df.copy() X_kqi_data = kqi_df.copy() X_complaints_data = complaints_df.copy() X_tier_data = tier_df.copy() X_actplan_data = actplan_df.copy() # Ratings/complaints: keep only period number if column exists 'period' if "period" in X_rate_data.columns: X_rate_data['period'] = X_rate_data['period'].astype(str).str.split(r'[_/]').str[0] if "period" in X_complaints_data.columns: X_complaints_data['period'] = X_complaints_data['period'].astype(str).str.split(r'[_/]').str[0] # Tests: ensure last_test_date parsed if exists if "last_test_date" in X_test_data.columns: try: X_test_data['last_test_date'] = pd.to_datetime(X_test_data['last_test_date']).dt.date except Exception: X_test_data['last_test_date'] = pd.to_datetime(X_test_data['last_test_date'], errors='coerce') # Merge sales sums by category/tpnb/description if all(c in X_sales_data.columns for c in ["category", "tpnb", "description", "sales", "returns"]): X_new_sales_data = X_sales_data.groupby(['category', 'tpnb', 'description'], as_index=False)[['sales', 'returns']].sum() else: st.error("Sales file doesn't have required columns: category,tpnb,description,sales,returns") st.stop() # Pivot tests: convert rows (test_type) to columns using last_test_date if "tpnb" in X_test_data.columns and "test_type" in X_test_data.columns and "last_test_date" in X_test_data.columns: X_new_test_data = X_test_data.pivot(index='tpnb', columns='test_type', values='last_test_date').reset_index() else: X_new_test_data = X_test_data.copy() # Merge sales & test date X_new_quality_data = pd.merge(X_new_sales_data, X_new_test_data, on=['tpnb'], how='left') # Fill NaNs with empty string (we will treat empty consistently) X_new_quality_data = X_new_quality_data.fillna('') # Merge ratings (average and count) aggregated if all(c in X_rate_data.columns for c in ["tpnb", "totalReviewCount", "averageReviewRating"]): X_new_rate_data = X_rate_data.groupby('tpnb', as_index=False)[['totalReviewCount', 'averageReviewRating']].mean() X_new_quality_data = pd.merge(X_new_quality_data, X_new_rate_data, on='tpnb', how='left') else: if 'totalReviewCount' not in X_new_quality_data.columns: X_new_quality_data['totalReviewCount'] = '' if 'averageReviewRating' not in X_new_quality_data.columns: X_new_quality_data['averageReviewRating'] = '' X_new_quality_data = X_new_quality_data.fillna('') # Merge redev status if 'status' in X_redev_data.columns and 'tpnb' in X_redev_data.columns: X_new_quality_data = pd.merge(X_new_quality_data, X_redev_data[['tpnb', 'status']], on='tpnb', how='left') # Rename after merge X_new_quality_data.rename({'status': 'Redev_Status'}, axis=1, inplace=True) else: X_new_quality_data['Redev_Status'] = '' X_new_quality_data = X_new_quality_data.fillna('') # KQI merge (kqi_tpnb expected in KQI file) if 'kqi_tpnb' in X_kqi_data.columns: X_new_quality_data = pd.merge(X_new_quality_data, X_kqi_data, how='left', left_on='tpnb', right_on='kqi_tpnb', validate="many_to_one") else: X_new_quality_data['kqi_tpnb'] = X_new_quality_data.get('kqi_tpnb', '') # Reviews / ratings numeric conversions & renames #X_new_quality_data.rename({'averageReviewRating': 'Average_Rating', 'totalReviewCount': 'Reviews_Count', 'kqi_tpnb': 'kqi'}, axis=1, inplace=True) X_new_quality_data.rename({'averageReviewRating': 'Average_Rating', 'totalReviewCount': 'Reviews_Count'}, axis=1, inplace=True) if 'Reviews_Count' in X_new_quality_data.columns: X_new_quality_data['Reviews_Count'] = pd.to_numeric(X_new_quality_data['Reviews_Count'], errors='coerce') else: X_new_quality_data['Reviews_Count'] = np.nan if 'Average_Rating' in X_new_quality_data.columns: X_new_quality_data['Average_Rating'] = pd.to_numeric(X_new_quality_data['Average_Rating'], errors='coerce') else: X_new_quality_data['Average_Rating'] = np.nan # Complaints aggregation if 'tpnb' in X_complaints_data.columns and 'complaints' in X_complaints_data.columns: X_new_complaints_data = X_complaints_data.groupby('tpnb', as_index=False)[['complaints']].sum() X_new_quality_data = pd.merge(X_new_quality_data, X_new_complaints_data[['tpnb', 'complaints']], on='tpnb', how='left') else: if 'complaints' not in X_new_quality_data.columns: X_new_quality_data['complaints'] = np.nan X_new_quality_data = X_new_quality_data.fillna('') # Tier & action plan merges if 'tpnb' in X_tier_data.columns: merge_cols = [c for c in ['brand', 'tier'] if c in X_tier_data.columns] if merge_cols: X_new_quality_data = pd.merge(X_new_quality_data, X_tier_data[['tpnb'] + merge_cols], on='tpnb', how='left') if 'tpnb' in X_actplan_data.columns and 'status' in X_actplan_data.columns: X_new_quality_data = pd.merge(X_new_quality_data, X_actplan_data[['tpnb', 'status']], on='tpnb', how='left') X_new_quality_data.rename({'status': 'actionplan_status'}, axis=1, inplace=True) else: if 'actionplan_status' not in X_new_quality_data.columns: X_new_quality_data['actionplan_status'] = '' # final fillna & sorts X_new_quality_data = X_new_quality_data.fillna('') # Keep exact columns in requested order where possible, add missing columns as '' required_cols = ['category', 'tpnb', 'description', 'sales', 'returns', 'MQR', 'PAC', 'QUALITY_PANEL', 'SPEC_CHECK', 'Reviews_Count', 'Average_Rating', 'Redev_Status', 'kqi_tpnb', 'KQI_ind', 'complaints', 'brand', 'tier', 'actionplan_status'] for c in required_cols: if c not in X_new_quality_data.columns: X_new_quality_data[c] = '' # Create KQI_ind column mapping def set_kqi_ind(v): if is_empty(v): return "No" return "Yes" X_new_quality_data['KQI_ind'] = X_new_quality_data['kqi_tpnb'].map(set_kqi_ind) # Convert sales & complaints to numeric where possible for thresholds X_new_quality_data['sales'] = pd.to_numeric(X_new_quality_data['sales'], errors='coerce').fillna(0).astype(float) X_new_quality_data['complaints'] = pd.to_numeric(X_new_quality_data['complaints'], errors='coerce') # Ensure numeric columns are clean before thresholds for col in ['complaints', 'Reviews_Count', 'Average_Rating', 'sales']: if col in X_new_quality_data.columns: X_new_quality_data[col] = pd.to_numeric(X_new_quality_data[col], downcast='integer', errors='coerce') X_new_quality_data[col] = X_new_quality_data[col].round(1) #complaints_clean = pd.to_numeric(X_new_quality_data['complaints'], errors='coerce').dropna() #reviews_clean = pd.to_numeric(X_new_quality_data['Reviews_Count'], errors='coerce').dropna() X_new_quality_data = X_new_quality_data.fillna('') # Prepare dynamic sales thresholds sales_std_vars, sales_thresholds = make_sales_thresholds_from_sales(X_new_quality_data['sales']) def round_half_up(n: float) -> int: """ Round a number to the nearest integer using 'round half up' rule. (0.5 always rounds UP to the next integer) """ return math.floor(n + 0.5) if n >= 0 else math.ceil(n - 0.5) # Take the nth percentile of reviews chosen by user reviews_pct_cnt=pd.to_numeric(X_new_quality_data["Reviews_Count"]).quantile(reviews_pct) reviews_pct_cnt=round_half_up(reviews_pct_cnt) # Take the nth percentile of complaints chosen by user complaints_pct_cnt=pd.to_numeric(X_new_quality_data["complaints"]).quantile(complaints_pct) complaints_pct_cnt=round_half_up(complaints_pct_cnt) st.write("Reviews percentile chosen % is:", reviews_pct, " and associated count is:", reviews_pct_cnt) st.write("complaints percentile chosen % is:", complaints_pct, " and associated count is:", complaints_pct_cnt) st.write("Ratings cutoff chosen % is:", ratings_cutoff) # Build thresholds dict in-memory (you can replace with computed percentiles if you want) thresholds = { # values below are placeholders; the assign_priority_score_two_phase function will precompute more percentiles #"complaints_P75": float(np.nanpercentile(X_new_quality_data['complaints'].dropna().astype(float), 75)) if X_new_quality_data['complaints'].dropna().size>0 else 0.0, #"complaints_P75": float(np.nanpercentile(complaints_clean, 75)) if complaints_clean.size > 0 else 0.0, #"reviews_P75": float(np.nanpercentile(pd.to_numeric(X_new_quality_data['Reviews_Count'], errors='coerce').dropna(), 75)) if X_new_quality_data['Reviews_Count'].dropna().size>0 else 0.0, #"reviews_P75": float(np.nanpercentile(reviews_clean, 75)) if reviews_clean.size > 0 else 0.0, #"ratings_std": float(ratings_cutoff), #"sales_std": sales_std_vars "complaints": { #"P75": complaints_cnt_P75 #"P75": 18 "P75": complaints_pct_cnt }, "reviews": { #"P75": review_counts_P75 #"P75": 3 "P75": reviews_pct_cnt }, #"ratings": 3, "ratings": ratings_cutoff, "sales_std": sales_thresholds } # Show thresholds in sidebar expand with show_thresholds: st.json(thresholds) # how many rows to display first_rows=10 st.markdown(f"### Preview: Merged Source files & Pre-processed Data (First {first_rows} rows)") st.dataframe(X_new_quality_data[required_cols].sort_values(by=['category', 'sales','returns', 'complaints','Average_Rating','Reviews_Count','Redev_Status','actionplan_status'], ascending=False).head(first_rows)) X_new_quality_data = X_new_quality_data.fillna('') # BUTTON to run scoring st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) if st.sidebar.button("Generate Priority Score"): st.info("Running two-phase scoring... this may take a bit for large files.") # Prepare debug_tpnb variable from input debug_tpnb = int(debug_tpnb_input.strip()) if debug_tpnb_input.strip().isdigit() else None # Call scoring function scored, debug_info = assign_priority_score_two_phase( X_new_quality_data, priority_config=priority_config, fallback_config=fallback_config, thresholds=thresholds, sales_thresholds=sales_thresholds, debug_rows=debug_rows if debug_tpnb is None else 0, debug_tpnb=debug_tpnb, max_debug_lines=200 # limit logs from source ) # Save scored dataframe in session state st.session_state['scored'] = scored st.session_state['debug_info'] = debug_info # Show debug info in collapsible expander if (debug_tpnb is not None or debug_rows > 0) and debug_info: with st.expander(f"Debug output ({len(debug_info)} lines, showing last 50)"): limited_debug_info = debug_info[-50:] if len(debug_info) > 50 else debug_info st.text("\n".join(limited_debug_info)) st.success("Scoring finished.") # Display results if scored data exists in session state if 'scored' in st.session_state: scored = st.session_state['scored'] # fill the empty scores with 2000 if scored['priority_score'].isnull().any(): scored['priority_score'] = scored['priority_score'].fillna(2000) # fill NaN with -1 numeric else: #st.write('no null values') scored.replace({'NULL': np.nan, 'N/A': np.nan, '': np.nan, ' ': np.nan}, inplace=True) scored['priority_score'] = scored['priority_score'].fillna(2000) # fill NaN with -1 numeric priority_scores = scored['priority_score'] display_scores = priority_scores.fillna(2000) # fill NaN with -1 numeric ps_counts = display_scores.value_counts(dropna=False).sort_index(ascending=True) #ps_counts = priority_scores.value_counts(dropna=False).sort_index(ascending=True) st.divider() st.markdown("### Priority Score distribution") st.dataframe(ps_counts.rename_axis('priority_score').reset_index(name='count').head(200)) matched_rules = scored['matched_rule'].fillna('fallback_?') mr_counts = matched_rules.value_counts() #st.markdown("### Matched rule counts") #st.dataframe(mr_counts.rename_axis('matched_rule').reset_index(name='count').head(200)) st.divider() # Filter widget for priority_score with Select All checkbox st.markdown("### View and filter data by Priority Score") unique_scores = sorted(scored["priority_score"].dropna().unique()) #unique_scores = sorted(scored["priority_score"].unique()) select_all = st.checkbox("Select All priority scores", value=True, key="select_all_scores") if select_all: default_selection = unique_scores else: default_selection = [] selected_scores = st.multiselect( "Select priority_score(s) to display", options=unique_scores, default=default_selection, key="filter_priority_scores" ) if selected_scores: filtered_scored = scored[scored["priority_score"].isin(selected_scores)] else: filtered_scored = scored.copy() # Filter the top n rows top_rows = 100 st.markdown(f"### Filtered Priority Score (Displaying first {top_rows} rows) - Total rows: {len(filtered_scored)}") display_cols = required_cols + ['priority_score', 'matched_rule'] st.dataframe(filtered_scored[display_cols].sort_values(by=['priority_score', 'category', 'sales', 'returns', 'complaints', 'Average_Rating', 'Reviews_Count', 'Redev_Status', 'actionplan_status'],ascending=True).head(top_rows)) # Chart: Top n scores - Set value to number of top priority scores to display top_n = 25 st.markdown(f"### Filtered Priority Score (Chart): Top {top_n}") top_scores = ps_counts.reset_index() top_scores.columns = ['priority_score', 'count'] top_scores = top_scores.head(top_n) if not top_scores.empty: st.bar_chart(top_scores.set_index('priority_score')['count']) # CSV Download button csv_buf = io.StringIO() scored.to_csv(csv_buf, index=False) csv_bytes = csv_buf.getvalue().encode('utf-8') st.download_button("Download Initial Scored CSV", data=csv_bytes, file_name="initial_scored_priority.csv", mime="text/csv") # Inject CSS st.markdown(""" <style> /* General styling for all download buttons */ div[data-testid="stDownloadButton"] > button { border-radius: 8px; font-weight: bold; color: white; } /* First download button */ div[data-testid="stDownloadButton"]:nth-child(1) > button { background-color: #ff4b4b; /* Red */ } /* Second download button */ div[data-testid="stDownloadButton"]:nth-child(2) > button { background-color: #4bb543; /* Green */ } /* Third download button */ div[data-testid="stDownloadButton"]:nth-child(3) > button { background-color: #1e90ff; /* Blue */ } </style> """, unsafe_allow_html=True) # Show debug info area if available if 'debug_info' in st.session_state and st.session_state['debug_info']: pass # already displayed after scoring #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # coding for assigning QP test dates based on priority scores # Take a copy of scored dataframe with priorities above to a new df test_propose_df = scored.copy() from datetime import datetime, timedelta # capture current date today_date = datetime.now().strftime("%Y-%m-%d") #print('today date is:', today_date) # Set configurable Test date duration as 15, 30, 60, 90, 120, 150, 180, 210, 240, 270 days accordingly pre_set_test_date = 7 set_test_date_1 = 30 set_test_date_2 = 45 set_test_date_3 = 60 set_test_date_4 = 75 set_test_date_5 = 90 set_test_date_6 = 105 set_test_date_7 = 120 set_test_date_8 = 135 set_test_date_9 = 150 set_test_date_10 = 165 set_test_date_11 = 180 set_test_date_12 = 195 set_test_date_13 = 210 set_test_date_14 = 225 set_test_date_15 = 240 # Var to check testing done or proposed duration cur_elapsed_test_duration = 180 qp_proposed_test_duration = 60 # Define a new function for QP testing types and calculate proposed test dates based on priority range & duration def propose_QP_test_dates(test_type, prio, cur_test_date): #print('entered function:-', prio, '-', qp_date, '-', str(pd.to_datetime(today_date) - pd.to_datetime(qp_date)).split("days")[0]) #st.write(f"prio score is: {prio}, {type(prio)}") if prio: prio = int(prio) # Quality Panel Proposal/calclations if test_type == 'QP': if (prio == 2000): return '' # If redev status is complete and priority score is 1000+, propose from next 90 days if (prio > 1000 and prio <= 1010): ## 90 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_5)).strftime("%Y-%m-%d")) elif (prio > 1010 and prio <= 1020): ## 105 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_6)).strftime("%Y-%m-%d")) elif (prio > 1020 and prio <= 1026): ## 120 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_7)).strftime("%Y-%m-%d")) # If action plan is NOT REQUIRED, give preference elif (prio > 1500 and prio <= 1515): ## 90 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_5)).strftime("%Y-%m-%d")) elif (prio > 1515 and prio <= 1526): ## 105 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_6)).strftime("%Y-%m-%d")) # For prio 1 to 50, propose QP dates within next 45 days (or if redev is complete) elif (prio <= 15): ## 30 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_1)).strftime("%Y-%m-%d")) elif (prio > 15 and prio <= 30): ## 45 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_2)).strftime("%Y-%m-%d")) elif (prio > 30 and prio <= 50): ## 60 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_3)).strftime("%Y-%m-%d")) # For all other priorities, check for current QP Test (if not done in last 1 year) and propose elif cur_test_date == '': if (prio > 50 and prio <= 75): ## 60 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_3)).strftime("%Y-%m-%d")) elif (prio > 75 and prio <= 100): ## 75 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_4)).strftime("%Y-%m-%d")) elif (prio > 100 and prio <= 125): ## 90 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_5)).strftime("%Y-%m-%d")) elif (prio > 125 and prio <= 150): ## 105 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_6)).strftime("%Y-%m-%d")) elif (prio > 150 and prio <= 200): ## 120 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_7)).strftime("%Y-%m-%d")) elif (prio > 200 and prio <= 250): ## 135 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_8)).strftime("%Y-%m-%d")) elif (prio > 250 and prio <= 300): ## 150 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_9)).strftime("%Y-%m-%d")) # For all other priorities, check for current QP Test (if not done in last 6 months) and propose elif cur_test_date != '' and int(str(pd.to_datetime(today_date) - pd.to_datetime(cur_test_date)).split("days")[0]) >= cur_elapsed_test_duration: if (prio > 50 and prio <= 100): ## 90 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_5)).strftime("%Y-%m-%d")) elif (prio > 100 and prio <= 150): ## 105 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_6)).strftime("%Y-%m-%d")) elif (prio > 150 and prio <= 200): ## 120 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_7)).strftime("%Y-%m-%d")) elif (prio > 200 and prio <= 250): ## 135 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_8)).strftime("%Y-%m-%d")) elif (prio > 250 and prio <= 300): ## 150 days from today return ((pd.Timestamp.today() + timedelta(set_test_date_9)).strftime("%Y-%m-%d")) # For all other priorities, check for current QP Test (if done in last 6 months) and donot propose any elif cur_test_date != '' and int(str(pd.to_datetime(today_date) - pd.to_datetime(cur_test_date)).split("days")[0]) < cur_elapsed_test_duration: return '' else: return '' # Set the SPEC CHECK DATE to 7 days before Proposed QP Dates as per the mandate/business pre-requisites def set_spec_dates_for_QP(test_type, qp_date): # Set the SPEC CHECK DATE to 7 days before Proposed QP Dates as per the mandate/business pre-requisites #print('test_type=', test_type, ' ;qp_date=', qp_date, ' ;pre_set_test_date=',pre_set_test_date) if qp_date is not None: if test_type == 'SPEC' and qp_date != '': #print(qp_date, type(qp_date)) return (pd.to_datetime(qp_date) - timedelta(pre_set_test_date)).strftime("%Y-%m-%d") else: return '' else: return '' # Apply the QP test dates for each of QP records by calling function test_propose_df['priority_score'] = pd.to_numeric(test_propose_df['priority_score'], errors='coerce') test_propose_df = test_propose_df.fillna('') #test_propose_df["Proposed_QUALITY_PANEL"] = test_propose_df.apply(lambda x : propose_QP_test_dates('QP',int(x["priority_score"]), x["QUALITY_PANEL"]), axis=1) test_propose_df["Proposed_QUALITY_PANEL"] = test_propose_df.apply( lambda x: propose_QP_test_dates('QP', int(x["priority_score"]), x["QUALITY_PANEL"]) if pd.notna(x["priority_score"]) and str(x["priority_score"]).strip() != "" else x["QUALITY_PANEL"], axis=1 ) test_propose_df = test_propose_df.fillna('') test_propose_df["Proposed_SPEC_CHECK"] = test_propose_df.apply(lambda x : set_spec_dates_for_QP('SPEC',x["Proposed_QUALITY_PANEL"]), axis=1) test_propose_df = test_propose_df.fillna('') #test_propose_counts = test_propose_df.value_counts(dropna=False) test_propose_counts = test_propose_df["Proposed_QUALITY_PANEL"].value_counts(dropna=False) # display non opt first n rows non_opt_rows=100 st.markdown(f"### Non-Optimized QP Test Schedule (Displaying first {non_opt_rows} rows) ") st.dataframe(test_propose_counts.rename_axis('Proposed_QUALITY_PANEL').reset_index(name='count').head(non_opt_rows)) #st.dataframe(test_propose_counts.rename_axis('Proposed_QUALITY_PANEL').reset_index(name='count').head(100)) test_propose_df['Adj_Proposed_QUALITY_PANEL']=test_propose_df['Proposed_QUALITY_PANEL'] test_propose_df = test_propose_df.fillna('') #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ################################################################################################################################################################################# # coding for product category-wise per week test plan adjustments starts here import heapq import plotly.express as px import plotly.graph_objects as go def cascade_schedule_percent_autofix( df_in, date_col='Adj_Proposed_QUALITY_PANEL', category_col='category', max_test_per_week=100, category_percent_split=None, max_months_ahead=12 ): df = df_in.copy() df = df.dropna(subset=[date_col]).reset_index(drop=True) df[date_col] = pd.to_datetime(df[date_col]) df['overflow_dump_flag'] = 0 if 'priority_rank' in df.columns: df['_priority'] = df['priority_rank'] else: df['_priority'] = range(len(df)) df['New_PROPOSED_QUALITY_PANEL'] = df[date_col] - pd.to_timedelta(df[date_col].dt.weekday, unit='d') df['New_PROPOSED_QUALITY_PANEL'] = df['New_PROPOSED_QUALITY_PANEL'].dt.normalize() if category_percent_split is None: category_percent_split = {} caps = {cat: int(round(max_test_per_week * pct / 100)) for cat, pct in category_percent_split.items()} last_week_start = df['New_PROPOSED_QUALITY_PANEL'].max() + pd.DateOffset(months=max_months_ahead) last_week_start = last_week_start - pd.to_timedelta(last_week_start.weekday(), unit='d') unique_weeks = sorted(df['New_PROPOSED_QUALITY_PANEL'].unique()) heap = list(unique_weeks) heapq.heapify(heap) in_heap = set(unique_weeks) while heap: ws = heapq.heappop(heap) in_heap.remove(ws) mask = df['New_PROPOSED_QUALITY_PANEL'] == ws if mask.sum() == 0: continue week_df = df.loc[mask].sort_values('_priority') keep_candidates_idx = [] for cat in week_df[category_col].unique(): cap = caps.get(cat, max_test_per_week) cat_idx = week_df[week_df[category_col] == cat].index keep_candidates_idx.extend(list(cat_idx[:cap])) keep_candidates = df.loc[keep_candidates_idx].sort_values('_priority') keep_final_idx = list(keep_candidates.index[:max_test_per_week]) week_idx = list(week_df.index) overflow_idx = [i for i in week_idx if i not in keep_final_idx] if overflow_idx: next_week_start = ws + pd.Timedelta(weeks=1) if next_week_start <= last_week_start: new_dates = df.loc[overflow_idx, date_col] + pd.Timedelta(weeks=1) df.loc[overflow_idx, date_col] = new_dates new_week_starts = new_dates - pd.to_timedelta(new_dates.dt.weekday, unit='d') new_week_starts = new_week_starts.dt.normalize() df.loc[overflow_idx, 'New_PROPOSED_QUALITY_PANEL'] = new_week_starts for nws in new_week_starts.unique(): if nws not in in_heap: heapq.heappush(heap, nws) in_heap.add(nws) else: df.loc[overflow_idx, 'New_PROPOSED_QUALITY_PANEL'] = last_week_start df.loc[overflow_idx, date_col] = last_week_start df.loc[overflow_idx, 'overflow_dump_flag'] = 1 df = df.sort_values(['New_PROPOSED_QUALITY_PANEL', '_priority']).drop(columns=['_priority']).reset_index(drop=True) return df # ---------------- Streamlit UI ---------------- st.set_page_config(page_title="Test Optimization Scheduler", layout="wide") st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) # Sidebar controls st.sidebar.title("⚙️ Category Configurations") #uploaded_file = st.sidebar.file_uploader("Upload CSV file", type=["csv"]) # Take a copy of scored dataframe with priorities above to a new df prioritized_df = test_propose_df.copy() date_col = st.sidebar.selectbox("Date Column", prioritized_df.columns, index=22) category_col = st.sidebar.selectbox("Category Column", prioritized_df.columns, index=0) max_test_per_week = st.sidebar.number_input("Max Tests per Week", min_value=1, max_value=500, value=100) max_months_ahead = st.sidebar.number_input("Max Months Ahead", min_value=1, max_value=36, value=12) st.sidebar.markdown("### Category Percentage Caps") categories = prioritized_df[category_col].unique() category_percent_split = {} for cat in categories: pct = st.sidebar.number_input(f"{cat} %", min_value=0, max_value=100, value=10) category_percent_split[cat] = pct # Inject CSS st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) #run_scheduler = st.sidebar.button("Run Test Schedule Optimizer") st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) #run_scheduler = st.sidebar.write("Run Scheduler") if (run_scheduler := st.sidebar.button("Run Test Schedule Optimizer")): #st.sidebar.button("Run Test Schedule Optimizer"): if 'result' in st.session_state: del st.session_state['result'] st.info("Running Test Optimizer... this may take a bit for large files.") # Right side output st.title("📅 Test Optimization Scheduling Simulator") if run_scheduler: result_df = cascade_schedule_percent_autofix( prioritized_df, date_col=date_col, category_col=category_col, max_test_per_week=max_test_per_week, category_percent_split=category_percent_split, max_months_ahead=max_months_ahead ) st.success("✅ Optimize completed") # fill the empty scores with 2000 if result_df['priority_score'].isnull().any(): result_df['priority_score'] = result_df['priority_score'].fillna(2000) else: #st.write('no null values') result_df.replace({'NULL': np.nan, 'N/A': np.nan, '': np.nan, ' ': np.nan}, inplace=True) result_df['priority_score'] = result_df['priority_score'].fillna(2000) #st.write(result_df['priority_score'].value_counts(dropna=False).sort_values(ascending=True)) # Display only key fields in the UI cols_to_display = ['category', 'brand', 'tier', 'tpnb', 'description', 'sales', 'returns', 'Average_Rating', 'Reviews_Count', 'complaints', 'Redev_Status', 'actionplan_status', 'KQI_ind', 'QUALITY_PANEL', 'SPEC_CHECK', 'priority_score', 'Adj_Proposed_QUALITY_PANEL', 'New_PROPOSED_QUALITY_PANEL' ] #result_df['QUALITY_PANEL'] = result_df['QUALITY_PANEL'].dt.strftime("%Y-%m-%d") #result_df['QUALITY_PANEL'] = pd.to_datetime(result_df['QUALITY_PANEL'], errors='coerce').dt.strftime("%Y-%m-%d") #result_df['Adj_Proposed_QUALITY_PANEL'] = result_df['Adj_Proposed_QUALITY_PANEL'].strftime("%Y-%m-%d") result_df['Adj_Proposed_QUALITY_PANEL'] = pd.to_datetime(result_df['Adj_Proposed_QUALITY_PANEL'], errors='coerce').dt.strftime("%Y-%m-%d") #result_df['New_PROPOSED_QUALITY_PANEL'] = result_df['New_PROPOSED_QUALITY_PANEL'].strftime("%d-%b-%Y") #result_df['New_PROPOSED_QUALITY_PANEL'] = pd.to_datetime(result_df['New_PROPOSED_QUALITY_PANEL'], errors='coerce').dt.strftime("%Y-%m-%d") #result_display_df = result_df[cols_to_display].sort_values(by=['category','priority_score', 'New_PROPOSED_QUALITY_PANEL']) result_display_df = result_df[cols_to_display].sort_values(by=['New_PROPOSED_QUALITY_PANEL','priority_score','category'], ascending=True) result_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime(result_df["New_PROPOSED_QUALITY_PANEL"], errors="coerce") # --------------------------- # Filter from current month onwards # --------------------------- today = pd.Timestamp.today() start_of_month = today.replace(day=1) upd_result_df = result_df[result_df["New_PROPOSED_QUALITY_PANEL"] >= start_of_month] upd_result_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime(upd_result_df['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d") # display the first n optimized rows opt_rows=100 st.write(f"### Optimized QP Test Schedule: (Displaying first {opt_rows} rows >= Current Month)") st.dataframe(upd_result_df[cols_to_display].sort_values(by=['New_PROPOSED_QUALITY_PANEL','priority_score','category'], ascending=True).head(opt_rows)) # CSV Download button optimized_csv_buf = io.StringIO() result_df.to_csv(optimized_csv_buf, index=False) csv_bytes = optimized_csv_buf.getvalue().encode('utf-8') st.download_button("Download Optimized QP Test Schedule CSV", data=csv_bytes, file_name="QP_optimized_test_schedule.csv", mime="text/csv") overflow_items = result_df[result_df['overflow_dump_flag'] == 1] total_overflow_count = overflow_items.shape[0] st.subheader("Test Overflow Summary") if total_overflow_count == 0: st.success("✅ No overflow items dumped into final week.") else: st.error(f"🚨 TOTAL OVERFLOW ITEMS DUMPED: {total_overflow_count}") overflow_summary = ( overflow_items .groupby([category_col, 'New_PROPOSED_QUALITY_PANEL']) .size() .reset_index(name='overflow_count') .sort_values('overflow_count', ascending=False) ) st.dataframe(overflow_summary) st.subheader("📊 Weekly Schedule Distribution") week_summary = ( result_df .groupby(['New_PROPOSED_QUALITY_PANEL', category_col]) .size() .reset_index(name='count') ) fig1 = px.bar( week_summary, x='New_PROPOSED_QUALITY_PANEL', y='count', color=category_col, title='Items per Week by Category', text='count' ) fig1.update_layout(xaxis_title="Week Start", yaxis_title="Count", barmode='stack') st.plotly_chart(fig1, use_container_width=True) st.subheader("📈 Total Weekly Count vs Max Cap") total_weekly = ( result_df .groupby('New_PROPOSED_QUALITY_PANEL') .size() .reset_index(name='total_count') ) fig2 = go.Figure() fig2.add_trace(go.Bar( x=total_weekly['New_PROPOSED_QUALITY_PANEL'], y=total_weekly['total_count'], name='Total Count', customdata=total_weekly['New_PROPOSED_QUALITY_PANEL'], hovertemplate='Week Start: %{customdata}<br>Total: %{y}<extra></extra>' )) fig2.add_trace(go.Scatter( x=total_weekly['New_PROPOSED_QUALITY_PANEL'], y=[max_test_per_week] * len(total_weekly), mode='lines', name='Max Cap', line=dict(color='red', dash='dash') )) fig2.update_layout( title='Total Items per Week vs Max Cap', xaxis_title='Week Start', yaxis_title='Total Count' ) st.plotly_chart(fig2, use_container_width=True) # Save result_df dataframe in session state st.session_state['result'] = result_df # if run scheduler is not clicked else: st.info("Run 'Run Test Schedule Optimizer' button to compute optimization and view results.") #st.write('Type of total weekly new proposed quality panel date is', type(total_weekly['New_PROPOSED_QUALITY_PANEL'])) #st.write('Type of result df new proposed quality panel date is', type(result_df['New_PROPOSED_QUALITY_PANEL'])) #week_to_inspect = st.selectbox( # "Select Week to Inspect Details", # options=pd.to_datetime(total_weekly['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d").dropna().unique() #) #st.write('Type of result df new proposed quality panel date is', type(result_df['New_PROPOSED_QUALITY_PANEL'])) #st.write('selected new weekdate is:', week_to_inspect, 'type is:', type(week_to_inspect)) #mask = result_df[pd.to_datetime(result_df['New_PROPOSED_QUALITY_PANEL']) == pd.to_datetime(week_to_inspect)] #st.write('result_df is:', pd.to_datetime(result_df['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d").dropna().unique()) #st.write('week to inspect is:', pd.to_datetime(week_to_inspect).strftime("%Y-%m-%d")) #if not result_df[mask].empty: #filtered_week = result_df[pd.to_datetime(result_df['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d") == pd.to_datetime(week_to_inspect).strftime("%Y-%m-%d")] #else: # week_to_inspect = st.selectbox( # "Select Week to Inspect Details", # options=total_weekly['New_PROPOSED_QUALITY_PANEL'].unique() # ) #st.write(f"### Details for Week Starting {week_to_inspect}") #if not filtered_week.empty: # st.dataframe(filtered_week) #else: # st.write(f"No records to display for the selected date - {week_to_inspect}") # DEBUG #st.write("DEBUG week_to_inspect:", week_to_inspect, "Type:", type(week_to_inspect)) # Display results if scored data exists in session state if 'result' in st.session_state: result_df = st.session_state['result'] st.divider() st.markdown(f"### Category-wise Optimized Test Schedule: (By Priority Score)") # Suppose your data is in `df` with columns: Row Labels + categories pivot_cols = ['category', 'tpnb', 'priority_score', 'New_PROPOSED_QUALITY_PANEL'] import pandas as pd from datetime import datetime import streamlit as st # --------------------------- # Ensure datetime # --------------------------- result_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime( result_df["New_PROPOSED_QUALITY_PANEL"], errors="coerce" ) # --------------------------- # Filter from current month onwards # --------------------------- today = pd.Timestamp.today() start_of_month = today.replace(day=1) filtered_df = result_df[result_df["New_PROPOSED_QUALITY_PANEL"] >= start_of_month] filtered_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime(filtered_df['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d") filtered_df['priority_score'] = pd.to_numeric(filtered_df['priority_score'], downcast='integer', errors='coerce') #st.write('filtered_df length is :', len(filtered_df)) pivot_unique_scores = sorted(filtered_df["priority_score"].dropna().unique()) #st.write('pivot_unique_scores length is :', len(pivot_unique_scores)) pivot_select_all = st.checkbox("Select All Priority Scores", value=True, key="pivot_select_all_scores") if pivot_select_all: pivot_default_selection = pivot_unique_scores #st.write('length of pivot_default_selection in if is :', len(pivot_default_selection)) else: pivot_default_selection = [] #st.write('length of pivot_default_selection in else is :', len(pivot_default_selection)) pivot_selected_scores = st.multiselect( "Select priority_score(s) to display", options=pivot_unique_scores, default=pivot_default_selection, key="pivot_filter_priority_scores" ) #st.write('pivot_selected_scores is :', pivot_selected_scores) if pivot_selected_scores: pivot_filtered_scored = filtered_df[filtered_df["priority_score"].isin(pivot_selected_scores)] #st.write('inside if - pivot_filtered_scored length is:', len(pivot_filtered_scored)) else: pivot_filtered_scored = filtered_df.copy() #st.write('inside else - pivot_filtered_scored length is:', len(pivot_filtered_scored)) # display first categorized n rows cat_top_rows = 100 st.markdown(f"### Displaying first {cat_top_rows} rows >= Current Month: [Total rows: {len(pivot_filtered_scored)}]") pivot_display_cols = pivot_cols #st.write('last- pivot_display_cols df length is:', len(pivot_filtered_scored)) #st.dataframe(pivot_filtered_scored[pivot_display_cols].head(200)) pivoted = pivot_filtered_scored.pivot_table( index=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score', ], values='tpnb', aggfunc='count' # or 'sum', 'max', etc. ).sort_values(by=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score'], ascending=True).reset_index() st.dataframe(pivoted.head(cat_top_rows)) import matplotlib.pyplot as plt # Plotting the pivot table as a bar chart pivoted.plot(kind='bar', figsize=(8, 6)) plt.title('Pivot Chart - Test Plan Optimized by Category') plt.ylabel('TPNB #') plt.show() # CSV Download button upd_optimized_csv_buf = io.StringIO() pivoted.to_csv(upd_optimized_csv_buf, index=False) upd_csv_bytes = upd_optimized_csv_buf.getvalue().encode('utf-8') st.download_button("Download Category-wise Optimized Test Schedule CSV(by score)", data=csv_bytes, file_name="QP_category-wise_optimized_test_schedule_by_score.csv", mime="text/csv") st.divider() st.markdown(f"### Category-wise Optimized Test Schedule: (By Week)") # Suppose your data is in `df` with columns: Row Labels + categories pivot_cols_wk = ['category', 'tpnb', 'priority_score', 'New_PROPOSED_QUALITY_PANEL'] import pandas as pd from datetime import datetime import streamlit as st # --------------------------- # Ensure datetime # --------------------------- result_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime( result_df["New_PROPOSED_QUALITY_PANEL"], errors="coerce" ) # --------------------------- # Filter from current month onwards # --------------------------- today = pd.Timestamp.today() start_of_month = today.replace(day=1) filtered_df_wk = result_df[result_df["New_PROPOSED_QUALITY_PANEL"] >= start_of_month] filtered_df_wk["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime(filtered_df_wk['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d") filtered_df_wk['priority_score'] = pd.to_numeric(filtered_df_wk['priority_score'], downcast='integer', errors='coerce') #st.write('filtered_df length is :', len(filtered_df_wk)) pivot_unique_scores_wk = sorted(filtered_df_wk["New_PROPOSED_QUALITY_PANEL"].dropna().unique()) #st.write('pivot_unique_scores length is :', len(pivot_unique_scores_wk)) pivot_select_all_wk = st.checkbox("Select All Weeks", value=True, key="pivot_select_all_weeks") if pivot_select_all_wk: pivot_default_selection_wk = pivot_unique_scores_wk #st.write('length of pivot_default_selection in if is :', len(pivot_default_selection_wk)) else: pivot_default_selection_wk = [] #st.write('length of pivot_default_selection in else is :', len(pivot_default_selection_wk)) pivot_selected_scores_wk = st.multiselect( "Select Week(s) to display", options=pivot_unique_scores_wk, default=pivot_default_selection_wk, key="pivot_filter_weeks" ) #st.write('pivot_selected_scores is :', pivot_selected_scores_wk) if pivot_selected_scores_wk: pivot_filtered_scored_wk = filtered_df_wk[filtered_df_wk["New_PROPOSED_QUALITY_PANEL"].isin(pivot_selected_scores_wk)] #st.write('inside if - pivot_filtered_scored length is:', len(pivot_filtered_scored_wk)) else: pivot_filtered_scored_wk = filtered_df_wk.copy() #st.write('inside else - pivot_filtered_scored length is:', len(pivot_filtered_scored_wk)) # display first categorized n rows cat_top_rows = 100 st.markdown(f"### Displaying first {cat_top_rows} rows >= Current Month: [Total rows: {len(pivot_filtered_scored_wk)}]") pivot_display_cols = pivot_cols #st.write('last- pivot_display_cols df length is:', len(pivot_filtered_scored_wk)) #st.dataframe(pivot_filtered_scored_wk[pivot_display_cols].head(200)) pivoted_wk = pivot_filtered_scored_wk.pivot_table( index=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score', ], values='tpnb', aggfunc='count' # or 'sum', 'max', etc. ).sort_values(by=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score'], ascending=True).reset_index() st.dataframe(pivoted_wk.head(cat_top_rows)) import matplotlib.pyplot as plt # Plotting the pivot table as a bar chart pivoted_wk.plot(kind='bar', figsize=(8, 6)) plt.title('Pivot Chart - Test Plan Optimized by Category') plt.ylabel('TPNB #') plt.show() # CSV Download button upd_optimized_csv_buf_wk = io.StringIO() pivoted_wk.to_csv(upd_optimized_csv_buf_wk, index=False) upd_csv_bytes_wk = upd_optimized_csv_buf_wk.getvalue().encode('utf-8') st.download_button("Download Category-wise Optimized Test Schedule CSV (by Weeks)", data=csv_bytes, file_name="QP_category-wise_optimized_test_schedule_by_weeks.csv", mime="text/csv") st.divider() st.markdown(f"### Category-wise Optimized Test Schedule: (By Category)") # Suppose your data is in `df` with columns: Row Labels + categories pivot_cols_wk = ['category', 'tpnb', 'priority_score', 'New_PROPOSED_QUALITY_PANEL'] import pandas as pd from datetime import datetime import streamlit as st # --------------------------- # Ensure datetime # --------------------------- result_df["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime( result_df["New_PROPOSED_QUALITY_PANEL"], errors="coerce" ) # --------------------------- # Filter from current month onwards # --------------------------- today = pd.Timestamp.today() start_of_month = today.replace(day=1) filtered_df_cat = result_df[result_df["New_PROPOSED_QUALITY_PANEL"] >= start_of_month] filtered_df_cat["New_PROPOSED_QUALITY_PANEL"] = pd.to_datetime(filtered_df_cat['New_PROPOSED_QUALITY_PANEL']).dt.strftime("%Y-%m-%d") filtered_df_cat['priority_score'] = pd.to_numeric(filtered_df_cat['priority_score'], downcast='integer', errors='coerce') #st.write('filtered_df length is :', len(filtered_df_cat)) pivot_unique_scores_cat = sorted(filtered_df_cat["category"].dropna().unique()) #st.write('pivot_unique_scores length is :', len(pivot_unique_scores_cat)) pivot_select_all_cat = st.checkbox("Select All Categories", value=True, key="pivot_select_all_categories") if pivot_select_all_cat: pivot_default_selection_cat = pivot_unique_scores_cat #st.write('length of pivot_default_selection in if is :', len(pivot_default_selection_cat)) else: pivot_default_selection_cat = [] #st.write('length of pivot_default_selection in else is :', len(pivot_default_selection_cat)) pivot_selected_scores_cat = st.multiselect( "Select Category(ies) to display", options=pivot_unique_scores_cat, default=pivot_default_selection_cat, key="pivot_filter_categories" ) #st.write('pivot_selected_scores is :', pivot_selected_scores_cat) if pivot_selected_scores_cat: pivot_filtered_scored_cat = filtered_df_cat[filtered_df_cat["category"].isin(pivot_selected_scores_cat)] #st.write('inside if - pivot_filtered_scored length is:', len(pivot_filtered_scored_cat)) else: pivot_filtered_scored_cat = filtered_df_cat.copy() #st.write('inside else - pivot_filtered_scored length is:', len(pivot_filtered_scored_cat)) # display first categorized n rows cat_top_rows = 100 st.markdown(f"### Displaying first {cat_top_rows} rows >= Current Month: [Total rows: {len(pivot_filtered_scored_cat)}]") pivot_display_cols = pivot_cols #st.write('last- pivot_display_cols df length is:', len(pivot_filtered_scored_cat)) #st.dataframe(pivot_filtered_scored_cat[pivot_display_cols].head(200)) pivoted_cat = pivot_filtered_scored_cat.pivot_table( index=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score', ], values='tpnb', aggfunc='count' # or 'sum', 'max', etc. ).sort_values(by=['New_PROPOSED_QUALITY_PANEL', 'category', 'priority_score'], ascending=True).reset_index() st.dataframe(pivoted_cat.head(cat_top_rows)) import matplotlib.pyplot as plt # Plotting the pivot table as a bar chart pivoted_cat.plot(kind='bar', figsize=(8, 6)) plt.title('Pivot Chart - Test Plan Optimized by Category') plt.ylabel('TPNB #') plt.show() # CSV Download button upd_optimized_csv_buf_cat = io.StringIO() pivoted_cat.to_csv(upd_optimized_csv_buf_cat, index=False) upd_csv_bytes_cat = upd_optimized_csv_buf_cat.getvalue().encode('utf-8') st.download_button("Download Category-wise Optimized Test Schedule CSV (by Categories)", data=csv_bytes, file_name="QP_category-wise_optimized_test_schedule_by_categories.csv", mime="text/csv") # if run optimizer was not run earlier else: st.info("Click 'Run Test Schedule Optimizer' button to compute optimization and view results.") ################################################################################################################################################################################# else: # Custom CSS for info box #st.markdown(""" # <style> # .custom-info { # background-color: darkblue; /* light yellow */ # color: white; /* black text */ # padding: 15px; # border-radius: 10px; # border: 1px solid #f0ad4e; # } # </style> #""", unsafe_allow_html=True) st.info("Click 'Generate Priority Score' button to compute and view results.") #st.markdown('<div class="custom-info">"Run \'Generate priority score\' to compute and view results." 🚀</div>', unsafe_allow_html=True) # Optional: Add a button to clear cached scored dataframe and rerun if st.sidebar.button("Clear Cached Data"): if 'scored' in st.session_state: del st.session_state['scored'] if 'debug_info' in st.session_state: del st.session_state['debug_info'] if 'result' in st.session_state: del st.session_state['result'] st.experimental_rerun() # Add a button in the sidebar to clear the cache st.sidebar.button("Clear Source File Cache", on_click=clear_cache_callback) # Small helper test capture (optional) import sys def run_test_with_capture(): thresholds_local = {"complaints": {"P75": 18}, "reviews": {"P75": 3}, "ratings": 3} val = 1.0 cond = "<complaints_P75" field = "complaints" buf = io.StringIO() sys_stdout = sys.stdout sys.stdout = buf result = check_condition(val, cond, thresholds_local, field, debug=True) sys.stdout = sys_stdout output = buf.getvalue() st.text(f"Captured debug output:\n{output}") st.write(f"Test condition: value={val}, cond='{cond}', field='{field}'") st.write(f"Result: {result}") st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) if st.sidebar.button('Debug "check_condition" function'): run_test_with_capture() st.sidebar.markdown("<hr style='border:1px solid #ccc;'>", unsafe_allow_html=True) else: st.info("Upload required input CSV files in the sidebar to run data Preprocessing and Scoring.") # --------------------------- # System Resource Tracker (app-level and full host) # --------------------------- def system_stats(): mem = psutil.virtual_memory() cpu = psutil.cpu_percent(interval=0.5) st.sidebar.subheader("⚙️ System Stats") st.sidebar.write(f"**Full Space CPU Usage:** {cpu:.1f}%") st.sidebar.write(f"**Full Space Memory Used:** {mem.used / (1024**3):.2f} GB / {mem.total / (1024**3):.2f} GB") # app-process-only memory try: import os as _os proc = psutil.Process(_os.getpid()) mem_mb = proc.memory_info().rss / (1024**2) st.sidebar.write(f"**Our App Memory Used:** {mem_mb:.2f} MB") except Exception: pass system_stats()
# app.py - Hugging Face Space version of your full Quality Test Optimizer
# Ported from your uploaded file (keeps all functions & UI; local file loaders replaced with placeholders).
import os
import io
import psutil
import heapq
import random
import textwrap
import matplotlib.pyplot as plt
# quality_test_optimizer_streamlit.py
import streamlit as st
import pandas as pd
import numpy as np
import json
import io
import math
import re
st.set_page_config(layout="wide", page_title="Quality Test Plan Optimizer")
# ---------------------------
# Helpers: rounding & thresholds
# ---------------------------
def roundup(x):
"""Round down to a 'nice' bucket as per your logic."""
if x is None or pd.isna(x):
return 0
x = int(x)
if x < 0:
return 0
if x > 0 and x <= 10:
return x
if x > 10 and x < 99:
return x if x % 10 == 0 else x - (x % 10)
if x > 99 and x < 999:
return x if x % 100 == 0 else x - (x % 100)
if x > 999 and x < 9999:
return x if x % 1000 == 0 else x - (x % 1000)
if x > 9999 and x < 99999:
return x if x % 10000 == 0 else x - (x % 10000)
if x > 99999 and x < 999999:
return x if x % 100000 == 0 else x - (x % 100000)
if x > 999999 and x < 9999999:
return x if x % 100000 == 0 else x - (x % 1000000)
return x if x % 1000000 == 0 else x - (x % 10000000)
def safe_percentile(series, percentile):
"""
Safely calculate percentile after converting to numeric with coercion.
Returns 0.0 if no valid numeric data.
"""
clean_series = pd.to_numeric(series, errors="coerce").dropna()
if clean_series.size == 0:
return 0.0
#return float(np.percentile(clean_series, percentile))
return int(np.percentile(clean_series, percentile))
def make_sales_thresholds_from_sales(series):
tmp_val = [0]
i = 1
sales_std = {}
# stepping down percentiles from 100 to 3 by 3 -> up to ~33 entries, we cap at 25
for percentiles in range(100, 0, -3):
try:
percentile_val = int(safe_percentile(series, percentiles))
except Exception:
continue
if percentile_val in tmp_val:
continue
percentile_val = int(roundup(percentile_val))
if percentile_val in tmp_val:
continue
tmp_val.append(percentile_val)
sales_std[f"sales_std_{i}"] = percentile_val
i += 1
#vars()["sales_std_"+str(i)]=percentile_val
#print ("sales_std_"+str(i)+" = " +str(vars()["sales_std_"+str(i)]))
if i > 25:
break
#vars()["sales_std_"+str(i)]=0
# Fill missing keys up to 25 with zeros
#for j in range(1, 26):
# key = f"sales_std_{j}"
# if key not in sales_std:
# sales_std[key] = 0
# Force last bucket to 1 and 0 as requested (overrides)
#sales_std["sales_std_24"] = sales_std.get("sales_std_24", 1)
#sales_std["sales_std_25"] = sales_std.get("sales_std_25", 0)
# Ensure we have some sensible defaults for last few indexes if they weren't set
#sales_std["sales_std_22"] = sales_std.get("sales_std_22", 4)
#sales_std["sales_std_23"] = sales_std.get("sales_std_23", 3)