Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ import gradio as gr
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
import torch
|
|
|
|
| 5 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
|
| 7 |
# ---------- Model ----------
|
|
@@ -17,6 +18,8 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 17 |
# ---------- Trend Logic ----------
|
| 18 |
def detect_trend(values):
|
| 19 |
diffs = np.diff(values)
|
|
|
|
|
|
|
| 20 |
if all(d > 0 for d in diffs):
|
| 21 |
return "INCREASING"
|
| 22 |
elif all(d < 0 for d in diffs):
|
|
@@ -24,6 +27,7 @@ def detect_trend(values):
|
|
| 24 |
else:
|
| 25 |
return "MIXED"
|
| 26 |
|
|
|
|
| 27 |
def change_score(values):
|
| 28 |
values = np.array(values, dtype=float)
|
| 29 |
if len(values) < 2:
|
|
@@ -34,15 +38,18 @@ def change_score(values):
|
|
| 34 |
|
| 35 |
# ---------- LLM Explanation ----------
|
| 36 |
def explain(kpi, values, trend):
|
|
|
|
|
|
|
|
|
|
| 37 |
prompt = f"""
|
| 38 |
-
You are a telecom KPI expert.
|
| 39 |
-
KPI name: {kpi}
|
| 40 |
-
Values: {
|
| 41 |
-
Detected trend: {trend}
|
| 42 |
-
|
| 43 |
-
In 2 short sentences explain what this trend might mean.
|
| 44 |
-
"""
|
| 45 |
-
inputs = tokenizer(prompt, return_tensors="pt")
|
| 46 |
output = model.generate(**inputs, max_new_tokens=120)
|
| 47 |
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 48 |
|
|
@@ -57,30 +64,51 @@ def load_csv(file):
|
|
| 57 |
return df, gr.update(choices=numeric_cols, value=numeric_cols[:5])
|
| 58 |
|
| 59 |
# ---------- Main Analysis ----------
|
| 60 |
-
def analyze(df, selected_kpis):
|
|
|
|
| 61 |
print("β
Analyze function triggered")
|
| 62 |
|
| 63 |
if df is None or not selected_kpis:
|
| 64 |
return "β Upload CSV and select KPI columns"
|
| 65 |
|
|
|
|
|
|
|
| 66 |
results = []
|
| 67 |
explanations = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
for kpi in selected_kpis:
|
| 70 |
vals = df[kpi].dropna().values.tolist()
|
| 71 |
trend = detect_trend(vals)
|
| 72 |
score = change_score(vals)
|
|
|
|
| 73 |
results.append((kpi, trend, score, vals))
|
| 74 |
|
|
|
|
| 75 |
ranked = sorted(results, key=lambda x: x[2], reverse=True)
|
| 76 |
|
| 77 |
-
# LLM
|
|
|
|
|
|
|
| 78 |
for kpi, trend, score, vals in ranked[:5]:
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
explanations.append(f"**{kpi}** β {exp}")
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
for kpi, trend, score, _ in ranked[:5]:
|
| 85 |
text += f"**{kpi}** β {trend} (Score: {score})\n\n"
|
| 86 |
|
|
@@ -109,11 +137,11 @@ with gr.Blocks() as demo:
|
|
| 109 |
output = gr.Markdown()
|
| 110 |
|
| 111 |
analyze_btn.click(
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
)
|
| 117 |
|
| 118 |
-
|
| 119 |
demo.launch(share=True)
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
import torch
|
| 5 |
+
import time
|
| 6 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 7 |
|
| 8 |
# ---------- Model ----------
|
|
|
|
| 18 |
# ---------- Trend Logic ----------
|
| 19 |
def detect_trend(values):
|
| 20 |
diffs = np.diff(values)
|
| 21 |
+
if len(diffs) == 0:
|
| 22 |
+
return "FLAT"
|
| 23 |
if all(d > 0 for d in diffs):
|
| 24 |
return "INCREASING"
|
| 25 |
elif all(d < 0 for d in diffs):
|
|
|
|
| 27 |
else:
|
| 28 |
return "MIXED"
|
| 29 |
|
| 30 |
+
|
| 31 |
def change_score(values):
|
| 32 |
values = np.array(values, dtype=float)
|
| 33 |
if len(values) < 2:
|
|
|
|
| 38 |
|
| 39 |
# ---------- LLM Explanation ----------
|
| 40 |
def explain(kpi, values, trend):
|
| 41 |
+
# β
limit values to max 50 numbers
|
| 42 |
+
short_values = values[:50]
|
| 43 |
+
|
| 44 |
prompt = f"""
|
| 45 |
+
You are a telecom KPI expert.
|
| 46 |
+
KPI name: {kpi}
|
| 47 |
+
Values (sample): {short_values}
|
| 48 |
+
Detected trend: {trend}
|
| 49 |
+
|
| 50 |
+
In 2 short sentences explain what this trend might mean.
|
| 51 |
+
"""
|
| 52 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
|
| 53 |
output = model.generate(**inputs, max_new_tokens=120)
|
| 54 |
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 55 |
|
|
|
|
| 64 |
return df, gr.update(choices=numeric_cols, value=numeric_cols[:5])
|
| 65 |
|
| 66 |
# ---------- Main Analysis ----------
|
| 67 |
+
def analyze(df, selected_kpis, progress=gr.Progress(track_tqdm=False)):
|
| 68 |
+
start_time = time.time()
|
| 69 |
print("β
Analyze function triggered")
|
| 70 |
|
| 71 |
if df is None or not selected_kpis:
|
| 72 |
return "β Upload CSV and select KPI columns"
|
| 73 |
|
| 74 |
+
progress(0, desc="Starting analysis...")
|
| 75 |
+
|
| 76 |
results = []
|
| 77 |
explanations = []
|
| 78 |
+
total = len(selected_kpis)
|
| 79 |
+
|
| 80 |
+
# ---- KPI Analysis ----
|
| 81 |
+
for i, kpi in enumerate(selected_kpis):
|
| 82 |
+
progress((i + 1) / total, desc=f"Analyzing {kpi}...")
|
| 83 |
|
|
|
|
| 84 |
vals = df[kpi].dropna().values.tolist()
|
| 85 |
trend = detect_trend(vals)
|
| 86 |
score = change_score(vals)
|
| 87 |
+
|
| 88 |
results.append((kpi, trend, score, vals))
|
| 89 |
|
| 90 |
+
# ---- Sort by score ----
|
| 91 |
ranked = sorted(results, key=lambda x: x[2], reverse=True)
|
| 92 |
|
| 93 |
+
# ---- LLM Explanations for Top 5 ----
|
| 94 |
+
progress(0.9, desc="Generating LLM explanations...")
|
| 95 |
+
|
| 96 |
for kpi, trend, score, vals in ranked[:5]:
|
| 97 |
+
try:
|
| 98 |
+
exp = explain(kpi, vals, trend)
|
| 99 |
+
except Exception as e:
|
| 100 |
+
exp = f"β οΈ LLM Error: {str(e)}"
|
| 101 |
explanations.append(f"**{kpi}** β {exp}")
|
| 102 |
|
| 103 |
+
progress(1.0, desc="Done β
")
|
| 104 |
+
|
| 105 |
+
# ---- Time Taken ----
|
| 106 |
+
elapsed = round(time.time() - start_time, 2)
|
| 107 |
+
|
| 108 |
+
# ---- Output ----
|
| 109 |
+
text = f"β±οΈ Time taken: {elapsed} seconds\n\n"
|
| 110 |
+
text += "## π₯ Top 5 KPIs with Biggest Change\n"
|
| 111 |
+
|
| 112 |
for kpi, trend, score, _ in ranked[:5]:
|
| 113 |
text += f"**{kpi}** β {trend} (Score: {score})\n\n"
|
| 114 |
|
|
|
|
| 137 |
output = gr.Markdown()
|
| 138 |
|
| 139 |
analyze_btn.click(
|
| 140 |
+
fn=analyze,
|
| 141 |
+
inputs=[df_state, kpi_select],
|
| 142 |
+
outputs=output,
|
| 143 |
+
show_progress=True
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# β
Share link required in HF Spaces
|
| 147 |
demo.launch(share=True)
|