Spaces:
Sleeping
Sleeping
Uploaded dependencies
Browse files- Dockerfile +23 -0
- app.py +95 -0
- requirements.txt +5 -0
- rf_model.pkl +3 -0
Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use a lightweight Python image
|
| 2 |
+
FROM python:3.9-slim
|
| 3 |
+
|
| 4 |
+
# Create a non-root user for security (required by Hugging Face)
|
| 5 |
+
RUN useradd -m -u 1000 user
|
| 6 |
+
USER user
|
| 7 |
+
ENV PATH="/home/user/.local/bin:${PATH}"
|
| 8 |
+
|
| 9 |
+
# Set the working directory
|
| 10 |
+
WORKDIR /app
|
| 11 |
+
|
| 12 |
+
# Copy requirements first to leverage Docker cache
|
| 13 |
+
COPY --chown=user requirements.txt .
|
| 14 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 15 |
+
|
| 16 |
+
# Copy the rest of your files (app.py and model.joblib)
|
| 17 |
+
COPY --chown=user . .
|
| 18 |
+
|
| 19 |
+
# Expose the port Hugging Face expects
|
| 20 |
+
EXPOSE 7860
|
| 21 |
+
|
| 22 |
+
# Start the script
|
| 23 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import queue
|
| 4 |
+
import threading
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import joblib
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from flask import Flask
|
| 9 |
+
import paho.mqtt.client as mqtt
|
| 10 |
+
|
| 11 |
+
# ================= Configuration =================
|
| 12 |
+
# Use environment variables for flexibility, or keep your defaults
|
| 13 |
+
MQTT_BROKER = "broker.hivemq.com"
|
| 14 |
+
TOPIC_SENSOR = "sic7/stage4/DI-Binary/sensor"
|
| 15 |
+
TOPIC_PRED = "sic7/stage4/DI-Binary/prediction"
|
| 16 |
+
MQTT_PORT = 1883
|
| 17 |
+
|
| 18 |
+
# Load your pre-trained model (Ensure this filename matches your upload)
|
| 19 |
+
MODEL_PATH = "rf_model.pkl"
|
| 20 |
+
model = joblib.load(MODEL_PATH)
|
| 21 |
+
|
| 22 |
+
# ================= Web Server (Health Check) =================
|
| 23 |
+
# Hugging Face needs this to stay "Green"
|
| 24 |
+
server = Flask(__name__)
|
| 25 |
+
|
| 26 |
+
@server.route('/')
|
| 27 |
+
def home():
|
| 28 |
+
return f"Random Forest MQTT Server is running. Last sync: {datetime.now()}"
|
| 29 |
+
|
| 30 |
+
def run_flask():
|
| 31 |
+
# Hugging Face uses port 7860 by default
|
| 32 |
+
server.run(host='0.0.0.0', port=7860)
|
| 33 |
+
|
| 34 |
+
# ================= MQTT Logic =================
|
| 35 |
+
message_queue = queue.Queue()
|
| 36 |
+
|
| 37 |
+
def on_connect(client, userdata, flags, rc):
|
| 38 |
+
print(f"Connected to Broker with result code {rc}")
|
| 39 |
+
client.subscribe(TOPIC_SENSOR)
|
| 40 |
+
|
| 41 |
+
def on_message(client, userdata, msg):
|
| 42 |
+
try:
|
| 43 |
+
data = json.loads(msg.payload.decode())
|
| 44 |
+
message_queue.put(data)
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Error parsing message: {e}")
|
| 47 |
+
|
| 48 |
+
def process_loop(mqtt_client):
|
| 49 |
+
print("Inference loop started...")
|
| 50 |
+
while True:
|
| 51 |
+
# This blocks until a message is available
|
| 52 |
+
latest_msg = message_queue.get()
|
| 53 |
+
|
| 54 |
+
try:
|
| 55 |
+
# Extract data
|
| 56 |
+
temp = float(latest_msg["temp"])
|
| 57 |
+
hum = float(latest_msg["hum"])
|
| 58 |
+
soil = float(latest_msg["soil"])
|
| 59 |
+
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 60 |
+
|
| 61 |
+
# ML Prediction (Matching your DataFrame structure)
|
| 62 |
+
X = pd.DataFrame([{"temp": temp, "hum": hum, "soil": soil}])
|
| 63 |
+
X = X[["temp", "hum", "soil"]] # Ensure column order
|
| 64 |
+
pred = int(model.predict(X)[0]) # Convert to int for JSON/String serializing
|
| 65 |
+
|
| 66 |
+
# Log to console
|
| 67 |
+
print(f"[{ts}] Temp={temp}, Hum={hum}, Soil={soil} → Pred={pred}")
|
| 68 |
+
|
| 69 |
+
# Publish back to MQTT
|
| 70 |
+
mqtt_client.publish(TOPIC_PRED, f"CLASS:{pred}")
|
| 71 |
+
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error during prediction: {e}")
|
| 74 |
+
|
| 75 |
+
# Signal queue task completion
|
| 76 |
+
message_queue.task_done()
|
| 77 |
+
|
| 78 |
+
# ================= Main Execution =================
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
# 1. Setup MQTT Client
|
| 81 |
+
client = mqtt.Client()
|
| 82 |
+
client.on_connect = on_connect
|
| 83 |
+
client.on_message = on_message
|
| 84 |
+
|
| 85 |
+
client.connect(MQTT_BROKER, MQTT_PORT, 60)
|
| 86 |
+
|
| 87 |
+
# 2. Start Flask in a background thread
|
| 88 |
+
threading.Thread(target=run_flask, daemon=True).start()
|
| 89 |
+
|
| 90 |
+
# 3. Start the ML Processor in a background thread
|
| 91 |
+
threading.Thread(target=process_loop, args=(client,), daemon=True).start()
|
| 92 |
+
|
| 93 |
+
# 4. Start the MQTT Loop (Main Thread)
|
| 94 |
+
print("SERVER STARTED!")
|
| 95 |
+
client.loop_forever()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
pandas
|
| 3 |
+
joblib
|
| 4 |
+
scikit-learn==1.6.1
|
| 5 |
+
paho-mqtt
|
rf_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:555134a8c769edea443d1e409761404e8b86b847838f00707e31296a8c3739d2
|
| 3 |
+
size 270085
|