DevNumb commited on
Commit
d9f9a30
·
verified ·
1 Parent(s): 2061b93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -15
app.py CHANGED
@@ -1,39 +1,53 @@
1
  import gradio as gr
2
  import joblib
3
  import pandas as pd
 
4
 
5
- # Load models
6
  model = joblib.load("isolation_forest_model.joblib")
7
  scaler = joblib.load("standard_scaler.joblib")
8
  features = joblib.load("features_to_scale.joblib")
9
 
10
- def predict(*inputs):
 
11
  try:
 
 
 
12
  # Create dataframe
13
- data = pd.DataFrame([inputs], columns=features)
 
 
 
14
 
15
  # Scale
16
- scaled = scaler.transform(data)
17
 
18
  # Predict
19
  prediction = model.predict(scaled)
 
20
 
21
- if prediction[0] == -1:
22
- return "Anomaly Detected"
23
- else:
24
- return "Normal"
25
 
26
- except Exception as e:
27
- return str(e)
 
 
28
 
29
- # Create input fields dynamically
30
- inputs = [gr.Number(label=f) for f in features]
31
 
32
  demo = gr.Interface(
33
  fn=predict,
34
- inputs=inputs,
35
- outputs="text",
36
- title="Anomaly Detection API"
 
 
 
37
  )
38
 
39
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
  import joblib
3
  import pandas as pd
4
+ import json
5
 
6
+ # Load files
7
  model = joblib.load("isolation_forest_model.joblib")
8
  scaler = joblib.load("standard_scaler.joblib")
9
  features = joblib.load("features_to_scale.joblib")
10
 
11
+ def predict(json_input):
12
+
13
  try:
14
+ # Convert JSON string to dict
15
+ data_dict = json.loads(json_input)
16
+
17
  # Create dataframe
18
+ df = pd.DataFrame([data_dict])
19
+
20
+ # Ensure feature order
21
+ df = df[features]
22
 
23
  # Scale
24
+ scaled = scaler.transform(df)
25
 
26
  # Predict
27
  prediction = model.predict(scaled)
28
+ score = model.decision_function(scaled)
29
 
30
+ result = {
31
+ "prediction": "Anomaly"
32
+ if prediction[0] == -1
33
+ else "Normal",
34
 
35
+ "anomaly_score": float(score[0])
36
+ }
37
+
38
+ return result
39
 
40
+ except Exception as e:
41
+ return {"error": str(e)}
42
 
43
  demo = gr.Interface(
44
  fn=predict,
45
+ inputs=gr.Textbox(
46
+ lines=20,
47
+ label="JSON Input"
48
+ ),
49
+ outputs="json",
50
+ title="HVAC Anomaly Detection"
51
  )
52
 
53
  demo.launch(server_name="0.0.0.0", server_port=7860)