Spaces:
Sleeping
Sleeping
Download app.py from DI-Binary/FINALSICVII: direct link, hf CLI and curl.
- Browser
- Download file 2.91 kB
-
https://huggingface.co/spaces/DI-Binary/FINALSICVII/resolve/main/app.py
- Command line
-
hf download hf://spaces/DI-Binary/FINALSICVII/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DI-Binary/FINALSICVII/resolve/main/app.py
2.91 kB
| from flask import Flask | |
| import threading | |
| import json | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| from datetime import datetime | |
| import paho.mqtt.client as mqtt | |
| import queue | |
| # ================= HF Health Check ================= | |
| server = Flask(__name__) | |
| def health_check(): return "OK" | |
| def run_flask(): | |
| # Must listen on 0.0.0.0 and port 7860 | |
| server.run(host='0.0.0.0', port=7860) | |
| # ================= MQTT Configuration ================= | |
| MQTT_BROKER = "broker.hivemq.com" | |
| TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor" | |
| TOPIC_PRED = "sic7/stage4/DI-Binary/prediction" | |
| MQTT_PORT = 1883 | |
| # Define the client globally so process_loop can use it | |
| client = mqtt.Client() | |
| model = joblib.load("rf_model.pkl") | |
| print("Model loaded!") | |
| logs = [] | |
| message_queue = queue.Queue() | |
| # ================= MQTT Callbacks ================= | |
| def on_connect(client, userdata, flags, rc): | |
| print("Connected →", rc) | |
| client.subscribe(TOPIC_SENSOR) | |
| def on_message(client, userdata, msg): | |
| try: | |
| data = json.loads(msg.payload.decode()) | |
| # FIX THE DELAY: Clear the queue so we only process the latest sensor reading | |
| while not message_queue.empty(): | |
| try: | |
| message_queue.get_nowait() | |
| except queue.Empty: | |
| break | |
| message_queue.put(data) | |
| except Exception as e: | |
| print("Error parsing message:", e) | |
| # ================= Processor Thread ================= | |
| def process_loop(): | |
| global logs | |
| while True: | |
| # This blocks until a message is available | |
| latest_msg = message_queue.get() | |
| if latest_msg: | |
| try: | |
| temp = float(latest_msg["temp"]) | |
| hum = float(latest_msg["hum"]) | |
| soil = float(latest_msg["soil"]) | |
| ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| # ML Prediction | |
| X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}])[["temp","hum","soil"]] | |
| pred = model.predict(X)[0] | |
| # Logging | |
| logs.append([ts, temp, hum, soil, pred]) | |
| print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Prediction={pred}") | |
| # Kirim balik ke ESP32 | |
| client.publish(TOPIC_PRED, f"CLASS:{int(pred)}") | |
| except Exception as e: | |
| print("Processing error:", e) | |
| # ================= Main ================= | |
| if __name__ == "__main__": | |
| client.on_connect = on_connect | |
| client.on_message = on_message | |
| client.connect(MQTT_BROKER, MQTT_PORT, 60) | |
| # 1. Start web server (HF requirement) | |
| threading.Thread(target=run_flask, daemon=True).start() | |
| # 2. Start ML processing | |
| threading.Thread(target=process_loop, daemon=True).start() | |
| print("SERVER STARTED!") | |
| # 3. Start MQTT loop in main thread | |
| client.loop_forever() |