banao-tech commited on
Commit
3eddd77
Β·
verified Β·
1 Parent(s): 3927523

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -112
app.py CHANGED
@@ -6,6 +6,7 @@ import requests
6
  import boto3
7
  import uuid
8
  import os
 
9
 
10
  # Load configuration from environment variables (Hugging Face Spaces)
11
  API_ENDPOINT = os.getenv("API_ENDPOINT", "https://oau6sljd4l.execute-api.ap-south-1.amazonaws.com/production/process")
@@ -20,7 +21,6 @@ AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
20
  AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "ap-south-1")
21
 
22
  # Default values
23
- DEFAULT_COURSE_ID = int(os.getenv("DEFAULT_COURSE_ID", "47"))
24
  DEFAULT_USER_ID = int(os.getenv("DEFAULT_USER_ID", "30"))
25
  DEFAULT_PERSONALIZATION_ID = int(os.getenv("DEFAULT_PERSONALIZATION_ID", "100"))
26
  API_TIMEOUT = int(os.getenv("API_TIMEOUT", "30"))
@@ -29,6 +29,16 @@ API_TIMEOUT = int(os.getenv("API_TIMEOUT", "30"))
29
  VALID_USERNAME = os.getenv("APP_USERNAME")
30
  VALID_PASSWORD = os.getenv("APP_PASSWORD")
31
 
 
 
 
 
 
 
 
 
 
 
32
  # Set page configuration
33
  st.set_page_config(
34
  page_title="Base Course Personalization",
@@ -272,105 +282,11 @@ if 'session_ids' not in st.session_state:
272
  if 'authenticated' not in st.session_state:
273
  st.session_state.authenticated = False
274
  if 'current_page' not in st.session_state:
275
- st.session_state.current_page = "Course Personalization"
276
-
277
- # Admin Dashboard Functions
278
- def fetch_sessions():
279
- """Fetch all sessions from DynamoDB"""
280
- try:
281
- dynamodb = boto3.client(
282
- "dynamodb",
283
- region_name=DYNAMODB_REGION,
284
- aws_access_key_id=AWS_ACCESS_KEY_ID,
285
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
286
- )
287
-
288
- response = dynamodb.scan(TableName=SESSION_TABLE)
289
- items = response.get("Items", [])
290
- sessions = []
291
- for item in items:
292
- sessions.append({
293
- "session_id": item.get("session_id", {}).get("S"),
294
- "status": item.get("status", {}).get("S", "unknown"),
295
- "node": item.get("node", {}).get("S", "-"),
296
- "updated_at": item.get("updated_at", {}).get("S", "-"),
297
- "video_url": item.get("video_url", {}).get("S", None),
298
- })
299
- return sessions
300
- except Exception as e:
301
- st.error(f"⚠️ Error fetching sessions: {e}")
302
- return []
303
-
304
- def render_admin_dashboard():
305
- """Render the admin dashboard page"""
306
- st.markdown("<h1 style='color:#4F97FF;text-align:center;'>πŸ“Š Base Video Generation Dashboard</h1>", unsafe_allow_html=True)
307
-
308
- # Auto-refresh controls
309
- col1, col2, col3 = st.columns([1, 1, 2])
310
- with col1:
311
- if st.button("πŸ”„ Refresh Now", key="manual_refresh"):
312
- st.rerun()
313
-
314
- with col2:
315
- auto_refresh = st.toggle("Auto Refresh (15s)", value=False)
316
-
317
- # Fetch sessions
318
- sessions = fetch_sessions()
319
-
320
- if not sessions:
321
- st.warning("No sessions found yet.")
322
- st.info("Sessions will appear here once you start generating courses from the Course Personalization page.")
323
- else:
324
- # Display session count
325
- st.markdown(f"### πŸ“ˆ Found {len(sessions)} session(s)")
326
-
327
- # Sort sessions by updated_at (newest first)
328
- try:
329
- sessions.sort(key=lambda x: x['updated_at'] if x['updated_at'] != '-' else '1970-01-01', reverse=True)
330
- except:
331
- pass
332
-
333
- # Display sessions
334
- for i, session in enumerate(sessions):
335
- status_color = {
336
- 'completed': 'lime',
337
- 'processing': 'orange',
338
- 'in_progress': 'orange',
339
- 'running': 'orange',
340
- 'failed': 'red',
341
- 'error': 'red'
342
- }.get(session['status'].lower(), 'yellow')
343
-
344
- with st.container():
345
- st.markdown(f"""
346
- <div style="background:#2D2D2D;padding:1.5rem;border-radius:12px;margin-bottom:1rem;border:1px solid #444;">
347
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
348
- <h4 style="color:#4F97FF;margin:0;">πŸ†” Session {i+1}</h4>
349
- <span style="background:{status_color};color:black;padding:0.3rem 0.8rem;border-radius:15px;font-size:0.8rem;font-weight:bold;">{session['status'].upper()}</span>
350
- </div>
351
- <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
352
- <div>
353
- <b>Session ID:</b><br><code style="background:#1A1A1A;padding:0.3rem;border-radius:4px;">{session['session_id']}</code>
354
- </div>
355
- <div>
356
- <b>Current Node:</b><br><span style="color:#E0E0E0;">{session['node']}</span>
357
- </div>
358
- </div>
359
- <div style="margin-top:1rem;">
360
- <b>⏱️ Last Update:</b> <span style="color:#888;">{session['updated_at']}</span>
361
- </div>
362
- {f"<div style='margin-top:1rem;'><b>πŸŽ₯ Final Video:</b> <a href='{session['video_url']}' target='_blank' style='color:#4F97FF;'>πŸ“Ί Watch Video</a></div>" if session['video_url'] else ""}
363
- </div>
364
- """, unsafe_allow_html=True)
365
-
366
- # Auto-refresh mechanism
367
- if auto_refresh:
368
- time.sleep(15)
369
- st.rerun()
370
 
371
  # Authentication check
372
  if not st.session_state.authenticated:
373
- st.markdown('<h1 class="main-header">πŸ” Login to Course Personalization</h1>', unsafe_allow_html=True)
374
 
375
  # Check if credentials are configured
376
  if not VALID_USERNAME or not VALID_PASSWORD:
@@ -412,13 +328,13 @@ if not st.session_state.authenticated:
412
  # Navigation and Header (after login)
413
  col1, col2, col3, col4 = st.columns([3, 2, 2, 1])
414
  with col1:
415
- st.markdown('<h1 class="main-header">πŸ“š Base Course Management</h1>', unsafe_allow_html=True)
416
 
417
  with col2:
418
  page = st.selectbox(
419
  "πŸ“‹ Navigate to:",
420
- ["Course Personalization", "Admin Dashboard"],
421
- index=0 if st.session_state.current_page == "Course Personalization" else 1,
422
  key="page_selector"
423
  )
424
  st.session_state.current_page = page
@@ -428,15 +344,30 @@ with col4:
428
  st.session_state.authenticated = False
429
  st.session_state.topics_list = [{"topic_title": "What is Flask", "chapter_title": "Introduction to Flask"}]
430
  st.session_state.session_ids = []
431
- st.session_state.current_page = "Course Personalization"
432
  st.rerun()
433
 
434
  # Page routing
435
  if st.session_state.current_page == "Admin Dashboard":
436
  render_admin_dashboard()
437
  else:
438
- # Course Personalization Page (Original Content)
 
 
 
439
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  # Topics Section (Outside form for dynamic interaction)
441
  st.markdown('<div class="section-header">πŸ“‹ Topics Configuration</div>', unsafe_allow_html=True)
442
 
@@ -598,13 +529,18 @@ else:
598
  st.markdown("<br>", unsafe_allow_html=True)
599
  col1, col2, col3 = st.columns([1, 2, 1])
600
  with col2:
601
- submitted = st.form_submit_button("πŸš€ Generate Base Course", use_container_width=True)
602
 
603
  # Handle submission
604
  if submitted:
605
  # Use the topics from session state directly
606
  topics_to_process = st.session_state.topics_list
607
 
 
 
 
 
 
608
  # Validate inputs
609
  valid_topics = []
610
  for topic in topics_to_process:
@@ -615,14 +551,13 @@ else:
615
  st.error("❌ Please enter at least one topic with both topic title and chapter title")
616
  else:
617
  # Show loading state with better animation
618
- with st.spinner("🎬 Generating your personalized course... This may take a few moments."):
619
  progress_bar = st.progress(0)
620
  for i in range(100):
621
  time.sleep(0.02) # Simulating progress
622
  progress_bar.progress(i + 1)
623
 
624
  # Hardcoded values
625
- course_id = DEFAULT_COURSE_ID
626
  user_id = DEFAULT_USER_ID
627
  personalization_id = DEFAULT_PERSONALIZATION_ID
628
 
@@ -659,16 +594,16 @@ else:
659
  "video_type": "base_video"
660
  }
661
 
662
- # Generate topics data with user input for titles and hardcoded values for others
663
  topics_data = []
664
  for i, topic in enumerate(valid_topics):
665
  topics_data.append({
666
  "topic_id": 10834 + i, # Hardcoded with increment
667
  "topic_title": topic["topic_title"].strip(),
668
- "chapter_id": 647, # Hardcoded
669
  "chapter_title": topic["chapter_title"].strip(), # User input
670
- "course_id": course_id,
671
- "video_url": f"https://techlearn-dev.s3.ap-south-1.amazonaws.com/course_videos/47/647/172906{4365+i*50}.mp4", # Hardcoded with variation
672
  "video_duration": 462 + i*20, # Hardcoded with variation
673
  "sequence_number": i + 1,
674
  })
@@ -697,7 +632,7 @@ else:
697
  response_data = response.json()
698
  session_ids = response_data.get("session_ids", [])
699
 
700
- st.success("πŸŽ‰ Base Course started successfully!")
701
 
702
  # Store session IDs in session state
703
  st.session_state.session_ids.extend(session_ids)
@@ -708,6 +643,7 @@ else:
708
  col1, col2 = st.columns(2)
709
  with col1:
710
  st.markdown(f"""
 
711
  **Course ID**: {course_id}
712
  **Programming Language**: {programming_language.capitalize()}
713
  **Target Language**: {target_language.capitalize()}
@@ -716,7 +652,8 @@ else:
716
  st.markdown(f"""
717
  **Voice**: {tts_voice.capitalize()} ({tts_gender.capitalize()})
718
  **Topics Count**: {len(valid_topics)}
719
- **Hinglish**: {"Enabled" if toggle_hinglish else "Disabled"}
 
720
  """)
721
 
722
  # Display session IDs
@@ -734,7 +671,7 @@ else:
734
  # Information about tracking
735
  st.info(f"""
736
  πŸ’‘ **Tracking Information**
737
- You can track the progress of your video generation using the session IDs above.
738
  The processing status will be updated in DynamoDB table: {SESSION_TABLE}
739
  Region: {DYNAMODB_REGION}
740
 
 
6
  import boto3
7
  import uuid
8
  import os
9
+ from AdminDashboard import render_admin_dashboard
10
 
11
  # Load configuration from environment variables (Hugging Face Spaces)
12
  API_ENDPOINT = os.getenv("API_ENDPOINT", "https://oau6sljd4l.execute-api.ap-south-1.amazonaws.com/production/process")
 
21
  AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "ap-south-1")
22
 
23
  # Default values
 
24
  DEFAULT_USER_ID = int(os.getenv("DEFAULT_USER_ID", "30"))
25
  DEFAULT_PERSONALIZATION_ID = int(os.getenv("DEFAULT_PERSONALIZATION_ID", "100"))
26
  API_TIMEOUT = int(os.getenv("API_TIMEOUT", "30"))
 
29
  VALID_USERNAME = os.getenv("APP_USERNAME")
30
  VALID_PASSWORD = os.getenv("APP_PASSWORD")
31
 
32
+ # Course configurations
33
+ COURSE_CONFIGS = {
34
+ "AI Ready Course": {"course_id": 47, "chapter_id": 647},
35
+ "MERN": {"course_id": 48, "chapter_id": 648},
36
+ "Machine Learning": {"course_id": 49, "chapter_id": 649},
37
+ "Data Science": {"course_id": 50, "chapter_id": 650},
38
+ "Flask": {"course_id": 51, "chapter_id": 651},
39
+ "Django": {"course_id": 52, "chapter_id": 652}
40
+ }
41
+
42
  # Set page configuration
43
  st.set_page_config(
44
  page_title="Base Course Personalization",
 
282
  if 'authenticated' not in st.session_state:
283
  st.session_state.authenticated = False
284
  if 'current_page' not in st.session_state:
285
+ st.session_state.current_page = "Course Generation"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  # Authentication check
288
  if not st.session_state.authenticated:
289
+ st.markdown('<h1 class="main-header">πŸ” Login to Course Management</h1>', unsafe_allow_html=True)
290
 
291
  # Check if credentials are configured
292
  if not VALID_USERNAME or not VALID_PASSWORD:
 
328
  # Navigation and Header (after login)
329
  col1, col2, col3, col4 = st.columns([3, 2, 2, 1])
330
  with col1:
331
+ st.markdown('<h1 class="main-header">πŸ“š Course Management System</h1>', unsafe_allow_html=True)
332
 
333
  with col2:
334
  page = st.selectbox(
335
  "πŸ“‹ Navigate to:",
336
+ ["Course Generation", "Admin Dashboard"],
337
+ index=0 if st.session_state.current_page == "Course Generation" else 1,
338
  key="page_selector"
339
  )
340
  st.session_state.current_page = page
 
344
  st.session_state.authenticated = False
345
  st.session_state.topics_list = [{"topic_title": "What is Flask", "chapter_title": "Introduction to Flask"}]
346
  st.session_state.session_ids = []
347
+ st.session_state.current_page = "Course Generation"
348
  st.rerun()
349
 
350
  # Page routing
351
  if st.session_state.current_page == "Admin Dashboard":
352
  render_admin_dashboard()
353
  else:
354
+ # Course Generation Page (Original Content)
355
+
356
+ # Course Selection Section
357
+ st.markdown('<div class="section-header">πŸ“š Course Selection</div>', unsafe_allow_html=True)
358
 
359
+ col1, col2 = st.columns([2, 3])
360
+ with col1:
361
+ selected_course = st.selectbox(
362
+ "Select Course Type",
363
+ options=list(COURSE_CONFIGS.keys()),
364
+ index=0,
365
+ help="Choose the course you want to generate content for"
366
+ )
367
+
368
+ with col2:
369
+ st.info(f"**Selected:** {selected_course} (Course ID: {COURSE_CONFIGS[selected_course]['course_id']})")
370
+
371
  # Topics Section (Outside form for dynamic interaction)
372
  st.markdown('<div class="section-header">πŸ“‹ Topics Configuration</div>', unsafe_allow_html=True)
373
 
 
529
  st.markdown("<br>", unsafe_allow_html=True)
530
  col1, col2, col3 = st.columns([1, 2, 1])
531
  with col2:
532
+ submitted = st.form_submit_button("πŸš€ Generate Course", use_container_width=True)
533
 
534
  # Handle submission
535
  if submitted:
536
  # Use the topics from session state directly
537
  topics_to_process = st.session_state.topics_list
538
 
539
+ # Get course configuration
540
+ course_config = COURSE_CONFIGS[selected_course]
541
+ course_id = course_config["course_id"]
542
+ chapter_id = course_config["chapter_id"]
543
+
544
  # Validate inputs
545
  valid_topics = []
546
  for topic in topics_to_process:
 
551
  st.error("❌ Please enter at least one topic with both topic title and chapter title")
552
  else:
553
  # Show loading state with better animation
554
+ with st.spinner(f"🎬 Generating your {selected_course} course... This may take a few moments."):
555
  progress_bar = st.progress(0)
556
  for i in range(100):
557
  time.sleep(0.02) # Simulating progress
558
  progress_bar.progress(i + 1)
559
 
560
  # Hardcoded values
 
561
  user_id = DEFAULT_USER_ID
562
  personalization_id = DEFAULT_PERSONALIZATION_ID
563
 
 
594
  "video_type": "base_video"
595
  }
596
 
597
+ # Generate topics data with user input for titles and course-specific values
598
  topics_data = []
599
  for i, topic in enumerate(valid_topics):
600
  topics_data.append({
601
  "topic_id": 10834 + i, # Hardcoded with increment
602
  "topic_title": topic["topic_title"].strip(),
603
+ "chapter_id": chapter_id, # From selected course
604
  "chapter_title": topic["chapter_title"].strip(), # User input
605
+ "course_id": course_id, # From selected course
606
+ "video_url": f"https://techlearn-dev.s3.ap-south-1.amazonaws.com/course_videos/{course_id}/{chapter_id}/172906{4365+i*50}.mp4", # Course-specific
607
  "video_duration": 462 + i*20, # Hardcoded with variation
608
  "sequence_number": i + 1,
609
  })
 
632
  response_data = response.json()
633
  session_ids = response_data.get("session_ids", [])
634
 
635
+ st.success(f"πŸŽ‰ {selected_course} generation started successfully!")
636
 
637
  # Store session IDs in session state
638
  st.session_state.session_ids.extend(session_ids)
 
643
  col1, col2 = st.columns(2)
644
  with col1:
645
  st.markdown(f"""
646
+ **Course**: {selected_course}
647
  **Course ID**: {course_id}
648
  **Programming Language**: {programming_language.capitalize()}
649
  **Target Language**: {target_language.capitalize()}
 
652
  st.markdown(f"""
653
  **Voice**: {tts_voice.capitalize()} ({tts_gender.capitalize()})
654
  **Topics Count**: {len(valid_topics)}
655
+ **Hinglish**: {"Enabled" if toggle_hinglish else "Disabled"}
656
+ **Chapter ID**: {chapter_id}
657
  """)
658
 
659
  # Display session IDs
 
671
  # Information about tracking
672
  st.info(f"""
673
  πŸ’‘ **Tracking Information**
674
+ You can track the progress of your {selected_course} course generation using the session IDs above.
675
  The processing status will be updated in DynamoDB table: {SESSION_TABLE}
676
  Region: {DYNAMODB_REGION}
677