Spaces:
Sleeping
Sleeping
| import os | |
| import joblib | |
| import numpy as np | |
| from flask import Flask, request, jsonify | |
| from supabase import create_client | |
| SUPABASE_URL = os.getenv("SUPABASE_URL") | |
| SUPABASE_KEY = os.getenv("SUPABASE_KEY") | |
| supabase = create_client(SUPABASE_URL, SUPABASE_KEY) | |
| # ----------------------------- | |
| # Load Model | |
| # ----------------------------- | |
| model = joblib.load("predictive_model.pkl") | |
| # ----------------------------- | |
| # Flask App | |
| # ----------------------------- | |
| app = Flask(__name__) | |
| # ----------------------------- | |
| # Health Check | |
| # ----------------------------- | |
| def home(): | |
| return jsonify({ | |
| "status": "API is running", | |
| "message": "Predictive Maintenance Backend Active" | |
| }) | |
| # ----------------------------- | |
| # Prediction Endpoint | |
| # ----------------------------- | |
| def predict(): | |
| try: | |
| data = request.get_json() | |
| # Extract features (must match training order) | |
| features = [ | |
| data["Air_temperature"], | |
| data["Process_temperature"], | |
| data["Rotational_speed"], | |
| data["Torque"], | |
| data["Tool_wear"], | |
| data["Type_L"], | |
| data["Type_M"] | |
| ] | |
| features_array = np.array([features]) | |
| prediction = model.predict(features_array) | |
| probability = model.predict_proba(features_array)[0][1] | |
| status_text = "Failure" if prediction[0] == 1 else "No Failure" | |
| # ----------------------------- | |
| # Insert into Supabase | |
| # ----------------------------- | |
| supabase.table("machine_logs").insert({ | |
| "air_temperature": data["Air_temperature"], | |
| "process_temperature": data["Process_temperature"], | |
| "rotational_speed": data["Rotational_speed"], | |
| "torque": data["Torque"], | |
| "tool_wear": data["Tool_wear"], | |
| "type_l": data["Type_L"], | |
| "type_m": data["Type_M"], | |
| "prediction": int(prediction[0]) | |
| }).execute() | |
| return jsonify({ | |
| "prediction": int(prediction[0]), | |
| "status": status_text, | |
| "failure_probability": float(round(probability, 4)) | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # ----------------------------- | |
| # Get Latest Logs (Dashboard) | |
| # ----------------------------- | |
| def get_logs(): | |
| try: | |
| response = supabase.table("machine_logs") \ | |
| .select("*") \ | |
| .order("created_at", desc=True) \ | |
| .limit(10) \ | |
| .execute() | |
| return jsonify(response.data) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # ----------------------------- | |
| # Run App (for local testing) | |
| # ----------------------------- | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) |