File size: 3,368 Bytes
9edad62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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()