Barisha commited on
Commit
a9a8ff2
ยท
verified ยท
1 Parent(s): 1c11fbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -34
app.py CHANGED
@@ -1,50 +1,87 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
3
  import torch
4
 
5
- MODEL_NAME = "nvidia/OpenGPT-OSS-20B"
6
-
7
- print("Loading model... this may take some time.")
8
 
9
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
10
  model = AutoModelForCausalLM.from_pretrained(
11
  MODEL_NAME,
12
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
13
- device_map="auto"
14
  )
15
 
16
- def chat(prompt, history):
17
- messages = ""
18
- for user, bot in history:
19
- messages += f"User: {user}\nAssistant: {bot}\n"
20
- messages += f"User: {prompt}\nAssistant:"
21
-
22
- inputs = tokenizer(messages, return_tensors="pt").to(model.device)
23
- outputs = model.generate(
24
- **inputs,
25
- max_new_tokens=300,
26
- temperature=0.7,
27
- do_sample=True,
28
- top_p=0.9,
29
- )
30
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
31
- # Remove the previous conversation from output
32
- reply = response.split("Assistant:")[-1].strip()
33
- history.append((prompt, reply))
34
- return reply, history
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
 
 
 
 
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  with gr.Blocks() as demo:
38
- gr.Markdown("# ๐Ÿง  GPT-OSS-20B Chat (HuggingFace Space)")
39
- chatbot = gr.Chatbot()
40
- message = gr.Textbox(label="Type your message")
41
- clear = gr.Button("Clear Chat")
 
42
 
43
- def user_submit(msg, history):
44
- reply, history = chat(msg, history)
45
- return "", history
46
 
47
- message.submit(user_submit, [message, chatbot], [message, chatbot])
48
- clear.click(lambda: None, None, chatbot)
49
 
50
  demo.launch()
 
1
  import gradio as gr
2
+ import numpy as np
3
+ import pandas as pd
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
  import torch
6
 
7
+ MODEL_NAME = "microsoft/phi-2"
 
 
8
 
9
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
10
  model = AutoModelForCausalLM.from_pretrained(
11
  MODEL_NAME,
12
+ torch_dtype=torch.float32,
13
+ device_map="cpu"
14
  )
15
 
16
+ # ----- Trend detection (math-based, NOT LLM) -----
17
+ def detect_trend(values):
18
+ diffs = np.diff(values)
19
+
20
+ if all(d > 0 for d in diffs):
21
+ return "INCREASING"
22
+ elif all(d < 0 for d in diffs):
23
+ return "DECREASING"
24
+ else:
25
+ return "MIXED"
26
+
27
+ # ----- Simple anomaly detection -----
28
+ def detect_anomaly(values):
29
+ mean = np.mean(values)
30
+ std = np.std(values)
31
+
32
+ anomalies = []
33
+ for i, v in enumerate(values):
34
+ if abs(v - mean) > 2 * std:
35
+ anomalies.append((i, v))
36
+
37
+ if len(anomalies) == 0:
38
+ return "No anomalies detected"
39
+ return str(anomalies)
40
+
41
+ # ----- LLM explanation -----
42
+ def explanation(entity, values, trend):
43
+ prompt = f"""
44
+ You are a KPI analysis expert.
45
+ The entity is: {entity}
46
+ The values are: {values}
47
+ The detected trend is: {trend}
48
 
49
+ Explain in simple words why the trend is {trend}.
50
+ """
51
+ inputs = tokenizer(prompt, return_tensors="pt")
52
+ outputs = model.generate(**inputs, max_new_tokens=150)
53
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
54
 
55
+ # ----- Main function -----
56
+ def analyze(entity, value_string):
57
+ try:
58
+ values = [float(x.strip()) for x in value_string.split(",")]
59
+ except:
60
+ return "โŒ Error: Please enter numbers separated by commas"
61
+
62
+ trend = detect_trend(values)
63
+ anomaly = detect_anomaly(values)
64
+ exp = explanation(entity, values, trend)
65
+
66
+ return f"""
67
+ ๐Ÿ“Œ **Entity:** {entity}
68
+ ๐Ÿ“‰ **Trend:** {trend}
69
+ โš ๏ธ **Anomalies:** {anomaly}
70
+
71
+ ๐Ÿง  **Explanation:**
72
+ {exp}
73
+ """
74
+
75
+ # ----- UI -----
76
  with gr.Blocks() as demo:
77
+ gr.Markdown("# ๐Ÿ“ˆ KPI Trend + Anomaly Analyzer (CPU-Friendly)")
78
+
79
+ entity = gr.Textbox(label="KPI Name (example: volte_rate)")
80
+ values = gr.Textbox(label="Values (comma separated, example: 10,11,13,14,15)")
81
+ output = gr.Markdown()
82
 
83
+ run_btn = gr.Button("Analyze")
 
 
84
 
85
+ run_btn.click(fn=analyze, inputs=[entity, values], outputs=output)
 
86
 
87
  demo.launch()