Bibek Mukherjee commited on
Commit
bd14d9e
·
verified ·
1 Parent(s): e59ec7d

Update src/data/database.py

Browse files
Files changed (1) hide show
  1. src/data/database.py +76 -50
src/data/database.py CHANGED
@@ -1,51 +1,77 @@
1
- from sqlalchemy import create_engine, Column, Integer, Float, String, Boolean, ForeignKey, Text
2
- from sqlalchemy.ext.declarative import declarative_base
3
- from sqlalchemy.orm import sessionmaker, relationship
4
-
5
- # Create SQLite database
6
- SQLALCHEMY_DATABASE_URL = "sqlite:///./loan_applications.db"
7
- engine = create_engine(SQLALCHEMY_DATABASE_URL)
8
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
9
- Base = declarative_base()
10
-
11
- # Define database models
12
- class Application(Base):
13
- __tablename__ = "applications"
14
-
15
- id = Column(Integer, primary_key=True, index=True)
16
- no_of_dependents = Column(Integer)
17
- education = Column(String)
18
- self_employed = Column(String)
19
- income_annum = Column(Float)
20
- loan_amount = Column(Float)
21
- loan_term = Column(Integer)
22
- cibil_score = Column(Integer)
23
- residential_assets_value = Column(Float)
24
- commercial_assets_value = Column(Float)
25
- luxury_assets_value = Column(Float)
26
- bank_asset_value = Column(Float)
27
-
28
- predictions = relationship("Prediction", back_populates="application")
29
-
30
- class Prediction(Base):
31
- __tablename__ = "predictions"
32
-
33
- id = Column(Integer, primary_key=True, index=True)
34
- application_id = Column(Integer, ForeignKey("applications.id"))
35
- prediction = Column(Boolean)
36
- probability = Column(Float)
37
- explanation = Column(Text)
38
- feature_importance = Column(Text) # Stored as JSON string
39
-
40
- application = relationship("Application", back_populates="predictions")
41
-
42
- # Create tables
43
- Base.metadata.create_all(bind=engine)
44
-
45
- # Dependency to get database session
46
- def get_db():
47
- db = SessionLocal()
48
- try:
49
- yield db
50
- finally:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  db.close()
 
1
+ import os
2
+ from sqlalchemy import create_engine, Column, Integer, Float, String, Boolean, ForeignKey, Text
3
+ from sqlalchemy.ext.declarative import declarative_base
4
+ from sqlalchemy.orm import sessionmaker, relationship
5
+
6
+ # Determine the appropriate database path
7
+ project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
+ db_dir = os.path.join(project_root, "data")
9
+ os.makedirs(db_dir, exist_ok=True)
10
+
11
+ # Create SQLite database with absolute path for better reliability
12
+ SQLALCHEMY_DATABASE_URL = f"sqlite:///{os.path.join(db_dir, 'loan_applications.db')}"
13
+
14
+ # Create engine with check_same_thread=False for Streamlit compatibility
15
+ engine = create_engine(
16
+ SQLALCHEMY_DATABASE_URL,
17
+ connect_args={"check_same_thread": False}
18
+ )
19
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
20
+ Base = declarative_base()
21
+
22
+ # Define database models
23
+ class Application(Base):
24
+ __tablename__ = "applications"
25
+
26
+ id = Column(Integer, primary_key=True, index=True)
27
+ no_of_dependents = Column(Integer)
28
+ education = Column(String)
29
+ self_employed = Column(String)
30
+ income_annum = Column(Float)
31
+ loan_amount = Column(Float)
32
+ loan_term = Column(Integer)
33
+ cibil_score = Column(Integer)
34
+ residential_assets_value = Column(Float)
35
+ commercial_assets_value = Column(Float)
36
+ luxury_assets_value = Column(Float)
37
+ bank_asset_value = Column(Float)
38
+
39
+ predictions = relationship("Prediction", back_populates="application")
40
+
41
+ class Prediction(Base):
42
+ __tablename__ = "predictions"
43
+
44
+ id = Column(Integer, primary_key=True, index=True)
45
+ application_id = Column(Integer, ForeignKey("applications.id"))
46
+ prediction = Column(Boolean)
47
+ probability = Column(Float)
48
+ explanation = Column(Text)
49
+ feature_importance = Column(Text) # Stored as JSON string
50
+
51
+ application = relationship("Application", back_populates="predictions")
52
+
53
+ # Create tables with error handling
54
+ try:
55
+ Base.metadata.create_all(bind=engine)
56
+ except Exception as e:
57
+ print(f"Error creating database tables: {e}")
58
+ # If there's an error with the database file, try to recreate it
59
+ if 'file is not a database' in str(e):
60
+ try:
61
+ # Remove the corrupted database file
62
+ db_path = SQLALCHEMY_DATABASE_URL.replace('sqlite:///', '')
63
+ if os.path.exists(db_path):
64
+ os.remove(db_path)
65
+ print(f"Removed corrupted database file. Creating a new one.")
66
+ # Create tables again
67
+ Base.metadata.create_all(bind=engine)
68
+ except Exception as inner_e:
69
+ print(f"Failed to recreate database: {inner_e}")
70
+
71
+ # Dependency to get database session
72
+ def get_db():
73
+ db = SessionLocal()
74
+ try:
75
+ yield db
76
+ finally:
77
  db.close()