import streamlit as st import google.generativeai as genai import json from typing import List, Dict # Load courses from JSON file def load_courses(): try: with open('all_courses.json', 'r', encoding='utf-8') as f: return json.load(f) except Exception as e: st.error(f"Error loading courses: {str(e)}") return [] def setup_gemini(): """Configure and return Gemini model using API key from Streamlit secrets""" try: # Access API key from Streamlit secrets API_KEY = st.secrets["GEMINI_API_KEY"] genai.configure(api_key=API_KEY) return genai.GenerativeModel('gemini-pro') except Exception as e: st.error(f"Error setting up Gemini: {str(e)}") return None def search_courses(query: str, model, courses: List[Dict]) -> str: """Search courses using Gemini model""" if not model: return "Error: Gemini model not initialized properly" prompt = f""" Given these Analytics Vidhya courses: {json.dumps(courses, indent=2)} Find the most relevant courses for this search query: "{query}" Respond in this format: 1. Brief explanation of why these courses match (2-3 sentences) 2. List of matching courses in order of relevance, with short explanation for each Only include relevant courses. Focus on the title, description, and topics. Keep the response concise and practical. """ try: response = model.generate_content(prompt) return response.text except Exception as e: return f"Error performing search: {str(e)}" def main(): st.set_page_config( page_title="Analytics Vidhya Course Search", page_icon="📚", layout="centered" ) st.title("📚 Analytics Vidhya Course Search Assistant") # Load courses data courses = load_courses() if not courses: st.error("No courses data available. Please ensure all_courses.json exists.") return # Display total number of courses st.info(f"📊 Total available courses: {len(courses)}") # Initialize Gemini model once at startup model = setup_gemini() if not model: st.error("Failed to initialize Gemini model. Please check your API key.") return # Main search interface query = st.text_input( "What would you like to learn?", placeholder="e.g., machine learning for beginners" ) search_button = st.button("🔍 Search", type="primary", use_container_width=True) # Sample queries suggestions st.markdown(""" ### Sample Queries: - "machine learning courses" - "python for data science" - "deep learning and neural networks" - "data visualization techniques" """) if search_button: if not query: st.warning("⚠️ Please enter a search query") return try: with st.spinner("🔎 Searching for relevant courses..."): results = search_courses(query, model, courses) st.markdown("### 🎯 Search Results") st.markdown(results) except Exception as e: st.error(f"❌ An error occurred: {str(e)}") st.info("Please try again with a different query") if __name__ == "__main__": main()