import os from flask import Flask, jsonify, request, render_template import config # <--- Imported configuration module from extensions import mongo, mail # We need to import urllib for proper URL escaping in case the MONGO_URI needs to be manually cleaned. from urllib.parse import quote_plus # --- END IMPORTS --- # --- START DATABASE CONNECTION FIX --- # Reads the MONGO_URI from the environment/secrets (set via Hugging Face Secrets). MONGO_URI_SECRET = os.environ.get('MONGO_URI') # Define the database name to be used (ensure this name exists in your Atlas cluster) DB_NAME = "assessment_db" # FIXED: Using the confirmed database name from Atlas if MONGO_URI_SECRET: # Use the MONGO_URI from the environment (Hugging Face Secret) for deployment class Config: MONGO_URI = MONGO_URI_SECRET # CRITICAL FIX: Explicitly set the database name for the connection object MONGO_DBNAME = DB_NAME app = Flask(__name__) app.config.from_object(Config) else: # Fallback to local configuration for development (as defined in your original app.py) app = Flask(__name__) app.config.from_object(config) print("WARNING: MONGO_URI secret not found. Using local config/localhost.") # --- END DATABASE CONNECTION FIX --- # Initialize extensions # We move the mongo initialization here to ensure it uses the final app config mongo.init_app(app) mail.init_app(app) # Import blueprints after extensions (assuming they are in separate files) from routes.auth import auth_bp from routes.test_routes import test_bp app.register_blueprint(auth_bp) app.register_blueprint(test_bp) from services.feedback_agent import build_feedback_agent app.feedback_agent = build_feedback_agent() # Import the evaluation logic (models load here, all NLTK/HF caching fixed) from services.evaluation import evaluate_answer # Imported, models loaded here @app.route("/") def home(): # This line uses the explicit client connection (mongo.cx) and database name (DB_NAME) # to avoid the 'AttributeError: NoneType' object has no attribute 'tests' crash. global DB_NAME # Use mongo.cx[DB_NAME] for reliable database access in Flask-PyMongo setups. tests = list(mongo.cx[DB_NAME].tests.find({}, {"_id": 0})) return render_template("home.html", tests=tests) if __name__ == "__main__": app.run(debug=True)