Barisha commited on
Commit
de8a99d
Β·
verified Β·
1 Parent(s): b817834

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -33
app.py CHANGED
@@ -27,38 +27,52 @@ def change_score(values):
27
  return float(np.std(values))
28
 
29
  def explain(kpi, values, trend):
30
- values = values[:50] # prevent token overflow
 
31
  prompt = f"""
32
- Explain KPI trend.
33
- KPI: {kpi}
 
 
 
 
 
 
 
 
34
  Trend: {trend}
35
- Values: {values}
36
- Explain shortly.
 
37
  """
38
- out = llm(prompt, max_new_tokens=80)
39
- return out[0]["generated_text"]
40
 
41
- # ---- MAIN FUNCTION ----
42
- def analyze(file, progress=gr.Progress()):
43
- start_time = time.time()
44
- print("βœ… Analyze function triggered")
45
 
 
 
 
46
  if file is None:
47
- return "❌ Upload a CSV file"
48
 
49
  df = pd.read_csv(file.name)
 
 
 
50
 
51
- # Auto-detect numeric KPIs
52
- kpis = df.select_dtypes(include=np.number).columns.tolist()
 
53
 
54
- if not kpis:
55
- return "❌ No numeric KPI columns found"
 
 
56
 
57
  results = []
58
- total = len(kpis)
59
 
60
- # ---- Spinner + Progress ----
61
- for i, kpi in enumerate(kpis):
62
  progress((i+1)/total, desc=f"Analyzing {kpi}...")
63
 
64
  vals = df[kpi].dropna().tolist()
@@ -67,10 +81,8 @@ def analyze(file, progress=gr.Progress()):
67
 
68
  results.append((kpi, trend, score, vals))
69
 
70
- # Rank KPIs
71
  ranked = sorted(results, key=lambda x: x[2], reverse=True)
72
 
73
- # ---- LLM explanations ----
74
  progress(0.9, desc="Generating LLM explanations...")
75
 
76
  explanations = []
@@ -83,26 +95,31 @@ def analyze(file, progress=gr.Progress()):
83
 
84
  elapsed = round(time.time() - start_time, 2)
85
 
86
- # ---- Final Output ----
87
- output = f"⏱ Time taken: {elapsed} sec\n\n"
88
- output += "πŸ”₯ Top 5 KPIs with most change:\n\n"
89
- for kpi, trend, score, _ in ranked[:5]:
90
- output += f"- {kpi}: {trend} (Οƒ={round(score,2)})\n"
91
 
92
- output += "\n🧠 LLM Insights:\n\n"
93
  for e in explanations:
94
- output += e + "\n\n"
95
 
96
- return output
97
 
98
  # ---- UI ----
99
  with gr.Blocks() as app:
100
- gr.Markdown("## πŸ“Š KPI Trend Analyzer (LLM Powered)")
101
 
102
  file_input = gr.File(label="Upload CSV")
103
- analyze_btn = gr.Button("Analyze KPIs")
 
 
 
 
 
 
104
  output_box = gr.Markdown()
105
 
106
- analyze_btn.click(fn=analyze, inputs=[file_input], outputs=[output_box])
107
 
108
- app.launch() # ⚠️ no share=True
 
27
  return float(np.std(values))
28
 
29
  def explain(kpi, values, trend):
30
+ values = values[:20] # keep input small
31
+
32
  prompt = f"""
33
+ You are a business data analyst.
34
+ Based on this KPI trend, write ONE short human sentence like a manager insight.
35
+
36
+ Examples:
37
+ - "Call drops are rising sharply, which may impact customer satisfaction."
38
+ - "Network latency is gradually improving over time."
39
+
40
+ Now generate a similar sentence:
41
+
42
+ KPI Name: {kpi}
43
  Trend: {trend}
44
+ Recent values: {values}
45
+
46
+ Output only ONE sentence.
47
  """
 
 
48
 
49
+ out = llm(prompt, max_new_tokens=40)
50
+ return out[0]["generated_text"].strip()
 
 
51
 
52
+
53
+ # ---- CSV LOAD ----
54
+ def load_csv(file):
55
  if file is None:
56
+ return gr.update(choices=[]), None
57
 
58
  df = pd.read_csv(file.name)
59
+ numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
60
+
61
+ return gr.update(choices=numeric_cols, value=numeric_cols), df
62
 
63
+ # ---- MAIN ANALYSIS ----
64
+ def analyze(df, selected_kpis, progress=gr.Progress()):
65
+ start_time = time.time()
66
 
67
+ if df is None:
68
+ return "❌ Upload a CSV first"
69
+ if not selected_kpis:
70
+ return "❌ Select at least one KPI"
71
 
72
  results = []
73
+ total = len(selected_kpis)
74
 
75
+ for i, kpi in enumerate(selected_kpis):
 
76
  progress((i+1)/total, desc=f"Analyzing {kpi}...")
77
 
78
  vals = df[kpi].dropna().tolist()
 
81
 
82
  results.append((kpi, trend, score, vals))
83
 
 
84
  ranked = sorted(results, key=lambda x: x[2], reverse=True)
85
 
 
86
  progress(0.9, desc="Generating LLM explanations...")
87
 
88
  explanations = []
 
95
 
96
  elapsed = round(time.time() - start_time, 2)
97
 
98
+ out = f"⏱ Time taken: {elapsed} sec\n\n"
99
+ out += "πŸ”₯ KPI Trend Results\n\n"
100
+ for kpi, trend, score, _ in ranked:
101
+ out += f"- {kpi}: {trend} (Οƒ={round(score,2)})\n"
 
102
 
103
+ out += "\n🧠 LLM Insights:\n\n"
104
  for e in explanations:
105
+ out += e + "\n\n"
106
 
107
+ return out
108
 
109
  # ---- UI ----
110
  with gr.Blocks() as app:
111
+ gr.Markdown("## πŸ“Š KPI Trend Analyzer (LLM Controlled)")
112
 
113
  file_input = gr.File(label="Upload CSV")
114
+ kpi_selector = gr.CheckboxGroup(label="Select KPIs", choices=[])
115
+
116
+ df_state = gr.State()
117
+
118
+ file_input.upload(fn=load_csv, inputs=file_input, outputs=[kpi_selector, df_state])
119
+
120
+ analyze_btn = gr.Button("Analyze Selected KPIs")
121
  output_box = gr.Markdown()
122
 
123
+ analyze_btn.click(fn=analyze, inputs=[df_state, kpi_selector], outputs=output_box)
124
 
125
+ app.launch()