Upload folder using huggingface_hub
Browse filesFiles changed (3)
- app.pyAdded+118
- dashboard.htmlAdded+140
- train.pyAdded+68
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118from flask import Flask, jsonify, render_templateimport joblib, pandas as pd, numpy as npfrom datetime import datetimeimport psycopg2from psycopg2 import pool
app = Flask(_name_)
# ---------- Load model bundle ----------bundle = joblib.load('gas_danger_model.pkl')model = bundle['model']FEATURES = bundle['features'] # ['Hour', 'Weekday', 'Month', 'Afternoon']
# ---------- PostgreSQL connection pool ----------PG_POOL = pool.SimpleConnectionPool( 1, 5, user="postgres.czytuqnowdogaowfnfhe", password="235711", host="aws-0-eu-central-1.pooler.supabase.com", port="5432", dbname="postgres")
# ---------- Per‑gas safety limits ----------SAFETY_THRESHOLDS = { 'alcohol': 1000, 'NH3': 25, 'CO': 35, 'CO2': 5000, 'Toluene': 100, 'acetone': 750, 'lpg': 1000, 'smoke': 1.0}
# ---------- Helper to fetch latest row ----------def fetch_latest_reading(): """ Returns a dict with keys exactly matching the ones used elsewhere: CO2, NH3, alcohol, Toluene, acetone, lpg, CO, smoke, timestamp """ sql = """ SELECT co2, nh3, alcohol, toluene, acetone, lpg, co, smoke, "timestamp" FROM gas_data ORDER BY "timestamp" DESC LIMIT 1; """ conn = PG_POOL.getconn() try: with conn.cursor() as cur: cur.execute(sql) row = cur.fetchone() if row is None: return None raw_keys = ['co2','nh3','alcohol','toluene','acetone', 'lpg','co','smoke','timestamp'] raw = dict(zip(raw_keys, row)) # Map to mixed‑case keys expected elsewhere return { 'CO2': raw['co2'], 'NH3': raw['nh3'], 'alcohol': raw['alcohol'], 'Toluene': raw['toluene'], 'acetone': raw['acetone'], 'lpg': raw['lpg'], 'CO': raw['co'], 'smoke': raw['smoke'], 'timestamp':raw['timestamp'] } finally: PG_POOL.putconn(conn)
# ---------- Routes ----------@app.route('/api/predict', methods=['GET'])def predict(): current = fetch_latest_reading() if current is None: return jsonify({'error': 'No rows in gas_data table'}), 404
ts = current['timestamp'] now = ts if ts else datetime.now()
# Add time‑based features current.update({ 'Hour': now.hour, 'Weekday': now.weekday(), 'Month': now.month, 'Afternoon': int(12 <= now.hour <= 15) })
# Build feature vector in training order X = pd.DataFrame([[current.get(f, np.nan) for f in FEATURES]], columns=FEATURES) prob = float(model.predict_proba(X)[0, 1])
# Per‑gas alert block alerts = { g: { 'value': current[g], 'threshold': thr, 'status': 'danger' if current[g] > thr else 'safe' } for g, thr in SAFETY_THRESHOLDS.items() }
return jsonify({ 'prediction': prob, 'alerts': alerts, 'overall_status': 'danger' if prob > 0.4 else 'safe', 'timestamp': now.isoformat() })
@app.route('/')def dashboard(): return render_template('dashboard.html') # supply your own template
if _name_ == '_main_': app.run(debug=True, port=5000)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140<!DOCTYPE html><html><head> <title>Gas Danger Monitoring</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> body { font-family: Arial, sans-serif; margin: 20px; } .dashboard { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; } .card { background: #f5f5f5; padding: 15px; border-radius: 8px; margin-bottom: 15px; } .danger { background: #ffcccc; border-left: 5px solid red; } .safe { background: #ccffcc; border-left: 5px solid green; } .gauge { height: 20px; background: #ddd; border-radius: 10px; margin: 5px 0; } .gauge-fill { height: 100%; border-radius: 10px; } </style></head><body> <h1>Factory Gas Monitoring</h1> <div class="dashboard"> <div> <div class="card" id="status-card"> <h2>System Status: <span id="overall-status">Loading...</span></h2> <p>Danger Probability: <span id="danger-prob">-</span></p> <div class="gauge"> <div class="gauge-fill" id="danger-gauge"></div> </div> </div> <div class="card"> <h2>Gas Levels vs Safety Thresholds</h2> <canvas id="gasChart" height="300"></canvas> </div> </div> <div> <div class="card"> <h2>Alerts</h2> <div id="alerts-container"></div> </div> <div class="card"> <h2>Key Metrics</h2> <div id="metrics"> <p>Last Updated: <span id="timestamp">-</span></p> <p>Top Risk Factor: <span id="top-risk">CO_rolling_12h</span></p> </div> </div> </div> </div>
<script> let gasChart; // Fetch data every 5 seconds function updateData() { fetch('/api/predict') .then(response => response.json()) .then(data => { // Update overall status document.getElementById('overall-status').textContent = data.overall_status.toUpperCase(); document.getElementById('overall-status').className = data.overall_status; // Update danger probability const dangerPercent = (data.prediction * 100).toFixed(1); document.getElementById('danger-prob').textContent = ${dangerPercent}%; document.getElementById('danger-gauge').style.width = ${dangerPercent}%; document.getElementById('danger-gauge').style.backgroundColor = data.prediction > 0.4 ? 'red' : 'green'; // Update timestamp document.getElementById('timestamp').textContent = new Date(data.timestamp).toLocaleString(); // Update alerts const alertsContainer = document.getElementById('alerts-container'); alertsContainer.innerHTML = ''; for (const [gas, info] of Object.entries(data.alerts)) { const alertDiv = document.createElement('div'); alertDiv.className = card ${info.status}; alertDiv.innerHTML = ` <h3>${gas}</h3> <p>${info.value.toFixed(2)} ppm (Threshold: ${info.threshold} ppm)</p> <p>Status: <strong>${info.status.toUpperCase()}</strong></p> `; alertsContainer.appendChild(alertDiv); } // Update chart updateChart(data.alerts); }); } function updateChart(alerts) { const gases = Object.keys(alerts); const values = gases.map(gas => alerts[gas].value); const thresholds = gases.map(gas => alerts[gas].threshold); if (gasChart) { gasChart.data.datasets[0].data = values; gasChart.data.datasets[1].data = thresholds; gasChart.update(); } else { const ctx = document.getElementById('gasChart').getContext('2d'); gasChart = new Chart(ctx, { type: 'bar', data: { labels: gases, datasets: [ { label: 'Current Level (ppm)', data: values, backgroundColor: values.map((v, i) => v > thresholds[i] ? 'rgba(255, 99, 132, 0.7)' : 'rgba(54, 162, 235, 0.7)' ) }, { label: 'Safety Threshold', data: thresholds, type: 'line', borderColor: 'rgba(255, 159, 64, 1)', borderWidth: 2, fill: false } ] }, options: { scales: { y: { beginAtZero: true, title: { display: true, text: 'Concentration (ppm)' } } } } }); } } // Initial load updateData(); setInterval(updateData, 5000); // Refresh every 5 seconds </script></body></html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import pandas as pdimport numpy as npimport joblibfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom xgboost import XGBClassifierfrom sklearn.metrics import classification_report
# ---------------- Load & preprocess ----------------df = pd.read_csv('../city_day_clean_dated.csv', parse_dates=['Date']).sort_values('Date')
# Fill missing hoursfull = pd.DataFrame(pd.date_range(df['Date'].min(), df['Date'].max(), freq='h'), # 'H' → 'h' columns=['DateTime'])df = full.merge(df, left_on=full['DateTime'].dt.date, right_on=df['Date'].dt.date, how='left').ffill()df['Date'] = df['DateTime']
# Filter numeric gas columns only (avoid 'DateTime', etc.)gas_cols = ['alcohol', 'NH3', 'CO', 'CO2', 'Toluene', 'acetone', 'lpg', 'smoke']
# Create danger flagsdanger_thresholds = {col: np.percentile(df[col].dropna(), 95) for col in gas_cols}for col in gas_cols: df[f'{col}_danger'] = (df[col] > danger_thresholds[col]).astype(int)
df['Danger'] = df[[f'{col}_danger' for col in gas_cols]].max(axis=1)
# Time featuresdf['Hour'] = df['DateTime'].dt.hourdf['Weekday'] = df['DateTime'].dt.weekdaydf['Month'] = df['DateTime'].dt.monthdf['Afternoon'] = ((df['Hour'] >= 12) & (df['Hour'] <= 15)).astype(int)
# Simple demo featuresfeatures = ['Hour', 'Weekday', 'Month', 'Afternoon']target = 'Danger'
train = df[df['DateTime'] < '2020-01-01']test = df[df['DateTime'] >= '2020-01-01']
X_train, y_train = train[features], train[target]X_test, y_test = test[features], test[target]
# ---------------- Build model ----------------model = make_pipeline( StandardScaler(), XGBClassifier( n_estimators=200, max_depth=5, learning_rate=0.1, subsample=0.8, colsample_bytree=0.8, scale_pos_weight=10, random_state=42, eval_metric='logloss' ))model.fit(X_train, y_train)
print('Training report:')print(classification_report(y_train, model.predict(X_train)))print('\nTest report:')print(classification_report(y_test, model.predict(X_test)))
# ---------------- Save bundle ----------------joblib.dump({'model': model, 'features': features}, 'gas_danger_model.pkl')print('✔️ Model saved to gas_danger_model.pkl')app.pyAdded+118
dashboard.htmlAdded+140
train.pyAdded+68