Update app.py
Browse files
app.py
CHANGED
|
@@ -1,39 +1,53 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import joblib
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
|
| 5 |
-
# Load
|
| 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(
|
|
|
|
| 11 |
try:
|
|
|
|
|
|
|
|
|
|
| 12 |
# Create dataframe
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Scale
|
| 16 |
-
scaled = scaler.transform(
|
| 17 |
|
| 18 |
# Predict
|
| 19 |
prediction = model.predict(scaled)
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
|
| 32 |
demo = gr.Interface(
|
| 33 |
fn=predict,
|
| 34 |
-
inputs=
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 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)
|