ehsanulhaque92/multimodal-prescriptive-pdm
0
1from flask import request, jsonify, render_template2from app import app3from app.utils import (4 get_rul_prediction, 5 get_fault_prediction, 6 simulate_drift_detection, 7 get_dashboard_data,8 get_rag_chain_instance9)10import pandas as pd11import app_config as config12import logging13 14# Load Data on App Start (only data, not models)15try:16 rul_df_processed = pd.read_csv(config.PROCESSED_DATA_DIR / "rul_processed_data.csv")17except FileNotFoundError:18 rul_df_processed = None19 logging.warning("RUL processed data not found. Dashboard for RUL assets will be affected.")20 21# --- Main Application Routes ---22 23@app.route('/healthz')24def healthz():25 """Simple health check endpoint for Render."""26 return "OK", 20027 28@app.route('/')29@app.route('/dashboard')30def dashboard():31 dashboard_data = get_dashboard_data(rul_df_processed)32 return render_template('dashboard.html', title='Dashboard', assets=dashboard_data.get('assets', []), topics=dashboard_data.get('topics', []))33 34@app.route('/asset/<asset_id>')35def asset_detail(asset_id):36 if 'Turbofan' in asset_id:37 asset_type = 'rul'38 try: unit_number = int(asset_id.split('#')[-1])39 except (ValueError, IndexError): return "Invalid Turbofan ID format", 40440 if rul_df_processed is not None:41 asset_history_df = rul_df_processed[rul_df_processed['unit_number'] == unit_number].copy()42 historical_data_json = asset_history_df.to_dict(orient='list')43 else: historical_data_json = {}44 elif 'Machine' in asset_id or 'Conveyor' in asset_id:45 asset_type, historical_data_json = 'classification', {}46 else: return "Unknown Asset Type", 40447 return render_template('asset_detail.html', title=f"Asset: {asset_id}", asset_id=asset_id, asset_type=asset_type, historical_data=historical_data_json)48 49@app.route('/model-monitor')50def model_monitor():51 monitoring_data = simulate_drift_detection()52 return render_template('model_monitor.html', title="Model Monitor", monitoring_data=monitoring_data)53 54@app.route('/about')55def about():56 return render_template('about.html', title="About")57 58# --- API Endpoints ---59 60@app.route('/api/predict', methods=['POST'])61def api_predict():62 data = request.get_json()63 prediction_type, payload = data.get('type'), data.get('data')64 df = pd.DataFrame(payload)65 if prediction_type == 'rul':66 result = get_rul_prediction(df, with_shap=True)67 elif prediction_type == 'classification':68 result = get_fault_prediction(df)69 else: return jsonify({"error": "Invalid prediction type"}), 40070 if "error" in result: return jsonify(result), 50071 return jsonify(result)72 73@app.route('/api/ask', methods=['POST'])74def ask_question():75 data = request.get_json()76 question = data.get("question")77 rag_chain = get_rag_chain_instance()78 if rag_chain is None:79 return jsonify({"error": "RAG chain is not available."}), 50080 try:81 answer = rag_chain.invoke(question)82 return jsonify({"answer": answer})83 except Exception as e:84 logging.error(f"Error in RAG chain: {e}", exc_info=True)85 return jsonify({"error": "Failed to process question."}), 50086 87@app.route('/api/feedback', methods=['POST'])88def handle_feedback():89 data = request.get_json()90 logging.info(f"--- FEEDBACK RECEIVED ---: {data}")91 return jsonify({"status": "success"}), 200