|
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 |
|
|
|
|
|
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) |
|
|
|
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{os.path.join(db_dir, 'loan_applications.db')}" |
|
|
|
|
|
engine = create_engine( |
|
SQLALCHEMY_DATABASE_URL, |
|
connect_args={"check_same_thread": False} |
|
) |
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) |
|
Base = declarative_base() |
|
|
|
|
|
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) |
|
|
|
application = relationship("Application", back_populates="predictions") |
|
|
|
|
|
try: |
|
Base.metadata.create_all(bind=engine) |
|
except Exception as e: |
|
print(f"Error creating database tables: {e}") |
|
|
|
if 'file is not a database' in str(e): |
|
try: |
|
|
|
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.") |
|
|
|
Base.metadata.create_all(bind=engine) |
|
except Exception as inner_e: |
|
print(f"Failed to recreate database: {inner_e}") |
|
|
|
|
|
def get_db(): |
|
db = SessionLocal() |
|
try: |
|
yield db |
|
finally: |
|
db.close() |