import os from sqlalchemy import create_engine, Column, Integer, Float, String, Boolean, ForeignKey, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship # Determine the appropriate database path project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) db_dir = os.path.join(project_root, "data") os.makedirs(db_dir, exist_ok=True) # Create SQLite database with absolute path for better reliability SQLALCHEMY_DATABASE_URL = f"sqlite:///{os.path.join(db_dir, 'loan_applications.db')}" # Create engine with check_same_thread=False for Streamlit compatibility engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() # Define database models class Application(Base): __tablename__ = "applications" id = Column(Integer, primary_key=True, index=True) no_of_dependents = Column(Integer) education = Column(String) self_employed = Column(String) income_annum = Column(Float) loan_amount = Column(Float) loan_term = Column(Integer) cibil_score = Column(Integer) residential_assets_value = Column(Float) commercial_assets_value = Column(Float) luxury_assets_value = Column(Float) bank_asset_value = Column(Float) predictions = relationship("Prediction", back_populates="application") class Prediction(Base): __tablename__ = "predictions" id = Column(Integer, primary_key=True, index=True) application_id = Column(Integer, ForeignKey("applications.id")) prediction = Column(Boolean) probability = Column(Float) explanation = Column(Text) feature_importance = Column(Text) # Stored as JSON string application = relationship("Application", back_populates="predictions") # Create tables with error handling try: Base.metadata.create_all(bind=engine) except Exception as e: print(f"Error creating database tables: {e}") # If there's an error with the database file, try to recreate it if 'file is not a database' in str(e): try: # Remove the corrupted database file db_path = SQLALCHEMY_DATABASE_URL.replace('sqlite:///', '') if os.path.exists(db_path): os.remove(db_path) print(f"Removed corrupted database file. Creating a new one.") # Create tables again Base.metadata.create_all(bind=engine) except Exception as inner_e: print(f"Failed to recreate database: {inner_e}") # Dependency to get database session def get_db(): db = SessionLocal() try: yield db finally: db.close()