Download app.py from DI-Binary/FINALSIC7: direct link, hf CLI and curl.
- Browser
- Download file 3.04 kB
-
https://huggingface.co/DI-Binary/FINALSIC7/resolve/main/app.py
- Command line
-
hf download hf://DI-Binary/FINALSIC7/app.py
-
curl -L -o app.py https://huggingface.co/DI-Binary/FINALSIC7/resolve/main/app.py
3.04 kB
| import os | |
| import json | |
| import queue | |
| import threading | |
| import pandas as pd | |
| import joblib | |
| from datetime import datetime | |
| from flask import Flask | |
| import paho.mqtt.client as mqtt | |
| # ================= Configuration ================= | |
| # Use environment variables for flexibility, or keep your defaults | |
| MQTT_BROKER = "broker.hivemq.com" | |
| TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor" | |
| TOPIC_PRED = "sic7/stage4/DI-Binary/prediction" | |
| MQTT_PORT = 1883 | |
| # Load your pre-trained model (Ensure this filename matches your upload) | |
| MODEL_PATH = "rf_model.pkl" | |
| model = joblib.load(MODEL_PATH) | |
| # ================= Web Server (Health Check) ================= | |
| # Hugging Face needs this to stay "Green" | |
| server = Flask(__name__) | |
| def home(): | |
| return f"Random Forest MQTT Server is running. Last sync: {datetime.now()}" | |
| def run_flask(): | |
| # Hugging Face uses port 7860 by default | |
| server.run(host='0.0.0.0', port=7860) | |
| # ================= MQTT Logic ================= | |
| message_queue = queue.Queue() | |
| def on_connect(client, userdata, flags, rc): | |
| print(f"Connected to Broker with result code {rc}") | |
| client.subscribe(TOPIC_SENSOR) | |
| def on_message(client, userdata, msg): | |
| try: | |
| data = json.loads(msg.payload.decode()) | |
| message_queue.put(data) | |
| except Exception as e: | |
| print(f"Error parsing message: {e}") | |
| def process_loop(mqtt_client): | |
| print("Inference loop started...") | |
| while True: | |
| # This blocks until a message is available | |
| latest_msg = message_queue.get() | |
| try: | |
| # Extract data | |
| 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 (Matching your DataFrame structure) | |
| X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}]) | |
| X = X[["temp", "hum", "soil"]] # Ensure column order | |
| pred = int(model.predict(X)[0]) # Convert to int for JSON/String serializing | |
| # Log to console | |
| print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Pred={pred}") | |
| # Publish back to MQTT | |
| mqtt_client.publish(TOPIC_PRED, f"CLASS:{pred}") | |
| except Exception as e: | |
| print(f"Error during prediction: {e}") | |
| # Signal queue task completion | |
| message_queue.task_done() | |
| # ================= Main Execution ================= | |
| if __name__ == "__main__": | |
| # 1. Setup MQTT Client | |
| client = mqtt.Client() | |
| client.on_connect = on_connect | |
| client.on_message = on_message | |
| client.connect(MQTT_BROKER, MQTT_PORT, 60) | |
| # 2. Start Flask in a background thread | |
| threading.Thread(target=run_flask, daemon=True).start() | |
| # 3. Start the ML Processor in a background thread | |
| threading.Thread(target=process_loop, args=(client,), daemon=True).start() | |
| # 4. Start the MQTT Loop (Main Thread) | |
| print("SERVER STARTED!") | |
| client.loop_forever() |