Akshay Ukey commited on
Commit
3604ee1
Β·
1 Parent(s): 8ef62a4

Fix database connection handling for Docker build

Browse files
Files changed (3) hide show
  1. add_secrets.py +63 -0
  2. app.py +1 -2
  3. database.py +17 -1
add_secrets.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Add database credentials as secrets to Hugging Face Space
4
+ """
5
+
6
+ from huggingface_hub import HfApi
7
+ import os
8
+
9
+ # Initialize HF API
10
+ api = HfApi()
11
+
12
+ # Database credentials from Supabase
13
+ secrets = {
14
+ "DB_HOST": "fwwnrulrrlgtfzbfusno.supabase.co",
15
+ "DB_NAME": "postgres",
16
+ "DB_USER": "postgres",
17
+ "DB_PASSWORD": "SentimentDB2024!@#",
18
+ "DB_PORT": "5432"
19
+ }
20
+
21
+ # Add secrets to the Space
22
+ try:
23
+ api.add_space_secret(
24
+ repo_id="wintersoldier91/Antisentiment",
25
+ key="DB_HOST",
26
+ value=secrets["DB_HOST"]
27
+ )
28
+ print("βœ… Added DB_HOST secret")
29
+
30
+ api.add_space_secret(
31
+ repo_id="wintersoldier91/Antisentiment",
32
+ key="DB_NAME",
33
+ value=secrets["DB_NAME"]
34
+ )
35
+ print("βœ… Added DB_NAME secret")
36
+
37
+ api.add_space_secret(
38
+ repo_id="wintersoldier91/Antisentiment",
39
+ key="DB_USER",
40
+ value=secrets["DB_USER"]
41
+ )
42
+ print("βœ… Added DB_USER secret")
43
+
44
+ api.add_space_secret(
45
+ repo_id="wintersoldier91/Antisentiment",
46
+ key="DB_PASSWORD",
47
+ value=secrets["DB_PASSWORD"]
48
+ )
49
+ print("βœ… Added DB_PASSWORD secret")
50
+
51
+ api.add_space_secret(
52
+ repo_id="wintersoldier91/Antisentiment",
53
+ key="DB_PORT",
54
+ value=secrets["DB_PORT"]
55
+ )
56
+ print("βœ… Added DB_PORT secret")
57
+
58
+ print("\nπŸŽ‰ All database secrets added successfully!")
59
+ print("Your Hugging Face Space now has access to the Supabase database.")
60
+
61
+ except Exception as e:
62
+ print(f"❌ Error adding secrets: {e}")
63
+ print("Please check your token permissions and try again.")
app.py CHANGED
@@ -74,8 +74,7 @@ st.markdown(premium_cdn, unsafe_allow_html=True)
74
  # Database setup
75
  CACHE_MINUTES = 15 # Cache data for 15 minutes
76
 
77
- # Initialize database (tables created in Supabase)
78
- init_database()
79
 
80
  # FinViz news fetching functions
81
  finviz_url = 'https://finviz.com/quote.ashx?t='
 
74
  # Database setup
75
  CACHE_MINUTES = 15 # Cache data for 15 minutes
76
 
77
+ # Database initialization will be done lazily when needed
 
78
 
79
  # FinViz news fetching functions
80
  finviz_url = 'https://finviz.com/quote.ashx?t='
database.py CHANGED
@@ -18,7 +18,11 @@ def get_db_connection():
18
  )
19
  except psycopg2.Error as e:
20
  print(f"Database connection error: {e}")
21
- raise
 
 
 
 
22
 
23
  def init_database():
24
  """Initialize database tables (already done in Supabase)"""
@@ -27,6 +31,9 @@ def init_database():
27
  def get_historical_data(ticker, days=30):
28
  """Retrieve historical data from database"""
29
  conn = get_db_connection()
 
 
 
30
  cursor = conn.cursor()
31
 
32
  ist = pytz.timezone('Asia/Kolkata')
@@ -59,6 +66,9 @@ def get_historical_data(ticker, days=30):
59
  def can_fetch_new_data(ticker):
60
  """Check if we can fetch new data based on rate limiting"""
61
  conn = get_db_connection()
 
 
 
62
  cursor = conn.cursor()
63
 
64
  cursor.execute('''
@@ -94,6 +104,9 @@ def can_fetch_new_data(ticker):
94
  def update_cache_metadata(ticker, article_count):
95
  """Update cache metadata after fetching"""
96
  conn = get_db_connection()
 
 
 
97
  cursor = conn.cursor()
98
  ist = pytz.timezone('Asia/Kolkata')
99
  now = datetime.now(ist).isoformat()
@@ -114,6 +127,9 @@ def update_cache_metadata(ticker, article_count):
114
  def store_sentiment_data(ticker, parsed_and_scored_news):
115
  """Store sentiment data in PostgreSQL"""
116
  conn = get_db_connection()
 
 
 
117
  cursor = conn.cursor()
118
  ist = pytz.timezone('Asia/Kolkata')
119
  fetched_at = datetime.now(ist).isoformat()
 
18
  )
19
  except psycopg2.Error as e:
20
  print(f"Database connection error: {e}")
21
+ # Return None instead of raising to allow graceful fallback
22
+ return None
23
+ except Exception as e:
24
+ print(f"Unexpected database error: {e}")
25
+ return None
26
 
27
  def init_database():
28
  """Initialize database tables (already done in Supabase)"""
 
31
  def get_historical_data(ticker, days=30):
32
  """Retrieve historical data from database"""
33
  conn = get_db_connection()
34
+ if conn is None:
35
+ return pd.DataFrame()
36
+
37
  cursor = conn.cursor()
38
 
39
  ist = pytz.timezone('Asia/Kolkata')
 
66
  def can_fetch_new_data(ticker):
67
  """Check if we can fetch new data based on rate limiting"""
68
  conn = get_db_connection()
69
+ if conn is None:
70
+ return True, "Database not available - fetching fresh data"
71
+
72
  cursor = conn.cursor()
73
 
74
  cursor.execute('''
 
104
  def update_cache_metadata(ticker, article_count):
105
  """Update cache metadata after fetching"""
106
  conn = get_db_connection()
107
+ if conn is None:
108
+ return # Skip if database not available
109
+
110
  cursor = conn.cursor()
111
  ist = pytz.timezone('Asia/Kolkata')
112
  now = datetime.now(ist).isoformat()
 
127
  def store_sentiment_data(ticker, parsed_and_scored_news):
128
  """Store sentiment data in PostgreSQL"""
129
  conn = get_db_connection()
130
+ if conn is None:
131
+ return # Skip if database not available
132
+
133
  cursor = conn.cursor()
134
  ist = pytz.timezone('Asia/Kolkata')
135
  fetched_at = datetime.now(ist).isoformat()