File size: 2,785 Bytes
bd14d9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3efedb0
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
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()