# app.py import os import subprocess import logging import traceback from flask import Flask, render_template, request, jsonify from dotenv import load_dotenv # <--- Make sure python-dotenv is in requirements.txt # Load environment variables load_dotenv() from crew.agents.loan_officer_agent import LoanOfficerSupervisor logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) # --- CONFIGURATION --- REQUIRED_CODE = os.getenv("CODE") @app.route('/') def home(): return render_template('index.html') @app.route('/ask', methods=['POST']) def ask(): try: data = request.json user_query = data.get('query') user_code = data.get('code') # <--- Get the password from the frontend # --- SECURITY CHECK --- if user_code != REQUIRED_CODE: logger.warning(f"⛔ Access Denied. Wrong code: {user_code}") return jsonify({ "status": "error", "message": "⛔ Access Denied: Incorrect Access Code." }), 401 # ---------------------- if not user_query: return jsonify({"error": "Query cannot be empty"}), 400 # Initialize and run the supervisor supervisor = LoanOfficerSupervisor() result = supervisor.run(user_query) # Return the result directly because it already contains {"status": "success", "data": {...}} return jsonify(result) except Exception as e: logger.error(f"Server Error: {str(e)}") traceback.print_exc() return jsonify({ "status": "error", "message": str(e) }), 500 if __name__ == '__main__': # Auto-ingestion logic for Docker if not os.path.exists("rag/vectorstore"): logger.info("⚠️ Vectorstore not found. Attempting to ingest policies...") if os.getenv("MISTRAL_API_KEY"): try: subprocess.run(["python", "rag/ingest_policies.py"], check=True) logger.info("✅ Ingestion complete.") except Exception as e: logger.error(f"❌ Ingestion failed: {e}") else: logger.error("❌ Error: MISTRAL_API_KEY is missing.") app.run(debug=True, host='0.0.0.0', port=7860)