mtoft20 commited on
Commit
10d26d3
·
verified ·
1 Parent(s): a58bdc0

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +33 -28
src/streamlit_app.py CHANGED
@@ -8,29 +8,37 @@ import json
8
  # =============================================================================
9
  # CONFIGURATION - Using Secrets Management
10
  # =============================================================================
11
- NOCODB_URL = "https://mtoft20-potm.hf.space/api/v1/db/data/noco/p9pozkcw81t9aee/mvtt3arw5ni7uqp" # Updated with table ID
12
 
13
- # Get sensitive data from Streamlit secrets or environment variables
14
  def get_api_credentials():
15
- """Get API credentials from secrets or environment"""
16
  try:
17
  # Try Streamlit secrets first (for Hugging Face Spaces)
18
  api_token = st.secrets.get("NOCODB_API_TOKEN", os.environ.get("NOCODB_API_TOKEN", ""))
19
  together_key = st.secrets.get("TOGETHER_API_KEY", os.environ.get("TOGETHER_API_KEY", ""))
20
 
21
- return api_token, together_key
22
- except:
23
- # Fallback to environment variables
24
- api_token = os.environ.get("NOCODB_API_TOKEN", "")
25
- together_key = os.environ.get("TOGETHER_API_KEY", "")
26
 
27
- return api_token, together_key
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  # Initialize Together AI client
30
  @st.cache_resource
31
  def get_ai_client():
32
  """Initialize Together AI client"""
33
- _, together_key = get_api_credentials()
34
  if not together_key:
35
  st.error("Together AI API key not found. Please configure it in the secrets.")
36
  return None
@@ -42,9 +50,9 @@ def get_ai_client():
42
  @st.cache_data(ttl=300) # Cache for 5 minutes
43
  def get_streaming_content():
44
  """Fetch streaming content from NocoDB with pagination"""
45
- api_token, _ = get_api_credentials()
46
 
47
- if not api_token:
48
  st.error("NocoDB credentials not configured. Please set up your secrets.")
49
  return []
50
 
@@ -60,7 +68,7 @@ def get_streaming_content():
60
  try:
61
  while True:
62
  offset = (page - 1) * page_size
63
- url = f"{NOCODB_URL}?limit={page_size}&offset={offset}"
64
 
65
  response = requests.get(url, headers=headers)
66
 
@@ -251,8 +259,13 @@ def extract_unique_names(content_list, field):
251
  def get_similar_content(content, n_recommendations=5):
252
  """Get pre-computed similar content from database"""
253
  try:
254
- # Get database credentials
255
- api_token, _ = get_api_credentials()
 
 
 
 
 
256
  headers = {
257
  "xc-token": api_token,
258
  "accept": "application/json"
@@ -261,20 +274,13 @@ def get_similar_content(content, n_recommendations=5):
261
  title = content.get('title', '')
262
  show_id = content.get('show_id', '')
263
 
264
- # URLs for similarity tables using table IDs
265
- similarity_table_urls = [
266
- "https://mtoft20-potm.hf.space/api/v1/db/data/noco/p9pozkcw81t9aee/mp7bnn9tzhojh7k", # Part 1 similarities
267
- "https://mtoft20-potm.hf.space/api/v1/db/data/noco/p9pozkcw81t9aee/m8e5rglns4acmef", # Part 2 similarities
268
- "https://mtoft20-potm.hf.space/api/v1/db/data/noco/p9pozkcw81t9aee/m2driodimid10k6" # Part 3 similarities
269
- ]
270
-
271
  # Try finding by both show_id and title
272
  query = f'where=(show_id,eq,{show_id})~and(title,eq,{title})'
273
  params = {
274
  "where": query
275
  }
276
 
277
- for table_url in similarity_table_urls:
278
  try:
279
  response = requests.get(table_url, headers=headers, params=params)
280
 
@@ -288,14 +294,13 @@ def get_similar_content(content, n_recommendations=5):
288
 
289
  # Get full content details for each similar item
290
  similar_content = []
291
- for item in similar_items[:n_recommendations]: # Only process top N items
292
- # Query main content table for full details using show_id
293
  show_id = item.get('show_id', '')
294
  query = f'where=(show_id,eq,{show_id})'
295
  content_params = {
296
  "where": query
297
  }
298
- content_response = requests.get(NOCODB_URL, headers=headers, params=content_params)
299
 
300
  if content_response.status_code == 200:
301
  content_data = content_response.json()
@@ -304,7 +309,7 @@ def get_similar_content(content, n_recommendations=5):
304
  content_dict['similarity'] = f"{item['similarity']:.2%}"
305
  similar_content.append(content_dict)
306
 
307
- return similar_content[:n_recommendations] # Return top N items
308
  except Exception as parse_error:
309
  continue
310
  except Exception as e:
@@ -330,7 +335,7 @@ def main():
330
  st.write("*At your service! Allow me to curate the perfect streaming entertainment for you.*")
331
 
332
  # Check API credentials
333
- api_token, together_key = get_api_credentials()
334
 
335
  if not together_key:
336
  st.error("⚠️ Together AI API key not configured!")
 
8
  # =============================================================================
9
  # CONFIGURATION - Using Secrets Management
10
  # =============================================================================
 
11
 
 
12
  def get_api_credentials():
13
+ """Get API credentials and URLs from secrets or environment"""
14
  try:
15
  # Try Streamlit secrets first (for Hugging Face Spaces)
16
  api_token = st.secrets.get("NOCODB_API_TOKEN", os.environ.get("NOCODB_API_TOKEN", ""))
17
  together_key = st.secrets.get("TOGETHER_API_KEY", os.environ.get("TOGETHER_API_KEY", ""))
18
 
19
+ # Get NocoDB URLs from secrets or environment
20
+ base_url = st.secrets.get("NOCODB_BASE_URL", os.environ.get("NOCODB_BASE_URL", ""))
21
+ content_table_id = st.secrets.get("NOCODB_CONTENT_TABLE_ID", os.environ.get("NOCODB_CONTENT_TABLE_ID", ""))
22
+ similarity_table_ids = st.secrets.get("NOCODB_SIMILARITY_TABLE_IDS", os.environ.get("NOCODB_SIMILARITY_TABLE_IDS", "")).split(",")
 
23
 
24
+ if not base_url or not content_table_id:
25
+ st.error("NocoDB URLs not configured properly in secrets.")
26
+ return None, None, None, None, None
27
+
28
+ # Construct full URLs
29
+ content_url = f"{base_url}/{content_table_id}"
30
+ similarity_urls = [f"{base_url}/{table_id}" for table_id in similarity_table_ids if table_id]
31
+
32
+ return api_token, together_key, content_url, similarity_urls
33
+ except Exception as e:
34
+ st.error(f"Error loading credentials: {str(e)}")
35
+ return None, None, None, None
36
 
37
  # Initialize Together AI client
38
  @st.cache_resource
39
  def get_ai_client():
40
  """Initialize Together AI client"""
41
+ _, together_key, _, _ = get_api_credentials()
42
  if not together_key:
43
  st.error("Together AI API key not found. Please configure it in the secrets.")
44
  return None
 
50
  @st.cache_data(ttl=300) # Cache for 5 minutes
51
  def get_streaming_content():
52
  """Fetch streaming content from NocoDB with pagination"""
53
+ api_token, _, content_url, _ = get_api_credentials()
54
 
55
+ if not api_token or not content_url:
56
  st.error("NocoDB credentials not configured. Please set up your secrets.")
57
  return []
58
 
 
68
  try:
69
  while True:
70
  offset = (page - 1) * page_size
71
+ url = f"{content_url}?limit={page_size}&offset={offset}"
72
 
73
  response = requests.get(url, headers=headers)
74
 
 
259
  def get_similar_content(content, n_recommendations=5):
260
  """Get pre-computed similar content from database"""
261
  try:
262
+ # Get database credentials and URLs
263
+ api_token, _, content_url, similarity_urls = get_api_credentials()
264
+
265
+ if not api_token or not similarity_urls:
266
+ st.error("NocoDB credentials or URLs not configured properly.")
267
+ return []
268
+
269
  headers = {
270
  "xc-token": api_token,
271
  "accept": "application/json"
 
274
  title = content.get('title', '')
275
  show_id = content.get('show_id', '')
276
 
 
 
 
 
 
 
 
277
  # Try finding by both show_id and title
278
  query = f'where=(show_id,eq,{show_id})~and(title,eq,{title})'
279
  params = {
280
  "where": query
281
  }
282
 
283
+ for table_url in similarity_urls:
284
  try:
285
  response = requests.get(table_url, headers=headers, params=params)
286
 
 
294
 
295
  # Get full content details for each similar item
296
  similar_content = []
297
+ for item in similar_items[:n_recommendations]:
 
298
  show_id = item.get('show_id', '')
299
  query = f'where=(show_id,eq,{show_id})'
300
  content_params = {
301
  "where": query
302
  }
303
+ content_response = requests.get(content_url, headers=headers, params=content_params)
304
 
305
  if content_response.status_code == 200:
306
  content_data = content_response.json()
 
309
  content_dict['similarity'] = f"{item['similarity']:.2%}"
310
  similar_content.append(content_dict)
311
 
312
+ return similar_content[:n_recommendations]
313
  except Exception as parse_error:
314
  continue
315
  except Exception as e:
 
335
  st.write("*At your service! Allow me to curate the perfect streaming entertainment for you.*")
336
 
337
  # Check API credentials
338
+ api_token, together_key, _, _ = get_api_credentials()
339
 
340
  if not together_key:
341
  st.error("⚠️ Together AI API key not configured!")