File size: 3,177 Bytes
ed0b977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import os
import logging
from flask import Flask, render_template, redirect, url_for, session, request
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# FIX: Force dnspython to use Google DNS to avoid local SRV timeout issues on Windows
import dns.resolver
dns.resolver.default_resolver = dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers = ['8.8.8.8']

from utils.db.db import init_db
from utils.blueprints.patient import patient_bp
from utils.blueprints.admin import admin_bp
from utils.blueprints.assistant import assistant_bp
from utils.blueprints.auth import auth_bp
from utils.blueprints.chat import chat_bp
from utils.blueprints.doctor import doctor_bp
from utils.blueprints.history import history_bp
from utils.blueprints.enhancer import enhancer_bp # Import the new enhancer blueprint
from ai_agents.patient_rag import rag_pipeline # Corrected import

app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "dev_secret_key_fallback")
mongo_uri = os.environ.get("MONGO_URI")
if mongo_uri and "mongodb.net/?" in mongo_uri:
    mongo_uri = mongo_uri.replace("mongodb.net/?", "mongodb.net/swiftquery?")
app.config['MONGO_URI'] = mongo_uri

init_db(app)

# Register Blueprints
app.register_blueprint(patient_bp)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(assistant_bp, url_prefix='/assistant')
app.register_blueprint(auth_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(doctor_bp, url_prefix='/doctor')
app.register_blueprint(history_bp)
app.register_blueprint(enhancer_bp) # Register the new enhancer blueprint

@app.before_request
def cleanup_session():
    # Fix for KeyError: 1 in get_flashed_messages
    # This happens if _flashes contains invalid data (not tuples)
    flashes = session.get('_flashes')
    if flashes:
        # Check if it looks malformed (e.g. list of dicts instead of list of tuples)
        is_malformed = False
        if not isinstance(flashes, list):
            is_malformed = True
        else:
            for item in flashes:
                if not isinstance(item, (tuple, list)) or len(item) < 2:
                    is_malformed = True
                    break
        
        if is_malformed:
            session.pop('_flashes', None)

@app.route("/")
def index():
    return render_template('index.html')

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # Pass through HTTP errors (like 404) so Flask handles them naturally
    if isinstance(e, HTTPException):
        return e

    # Log unexpected errors
    import traceback
    error_details = f"URL: {request.url}\n\n{traceback.format_exc()}"
    with open("global_error.txt", "w") as f:
        f.write(error_details)
    return "An error occurred. Check global_error.txt", 500

if __name__ == "__main__":
    try:
        port = int(os.environ.get('PORT', 8080))
        logging.info(f"Starting generic assistant server on port {port}...")
        app.run(port=port, debug=True)
    except Exception as ie:
        logging.critical(f"Critical error starting server: {ie}")
        raise ie