Akshayram1 commited on
Commit
4980e0d
·
verified ·
1 Parent(s): 8b5a437

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -100
app.py CHANGED
@@ -2,124 +2,108 @@ import os
2
  import streamlit as st
3
  import pandas as pd
4
  import google.generativeai as genai
 
5
 
6
  # Configuration
7
  os.environ['GOOGLE_API_KEY'] = os.getenv('GOOGLE_API_KEY', 'your_key_here')
 
8
 
9
- # Load scholarships data
10
  @st.cache_data
11
  def load_scholarships():
12
- scholarships = pd.read_csv("scholarships_data.csv")
13
- scholarships.rename(columns=lambda x: x.strip(), inplace=True) # Clean column names
14
- required_columns = ['Scholarship Name', 'Eligibility', 'Link']
15
- if not all(col in scholarships.columns for col in required_columns):
16
- st.error(f"Missing required columns in the CSV file: {required_columns}")
17
- st.stop()
18
- return scholarships
19
-
20
- # Initialize Generative AI
21
- def get_genai_client():
22
  try:
23
- genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
24
- return genai.GenerativeModel('gemini-pro')
 
 
25
  except Exception as e:
26
- st.error(f"AI Initialization Error: {str(e)}")
27
- return None
28
-
29
- # Recommendation engine
30
- def recommend_scholarships(user_data, scholarships):
31
- matches = []
32
- for _, row in scholarships.iterrows():
33
- eligibility = row['Eligibility'].lower()
34
- if (
35
- (user_data['citizenship'] in eligibility) and
36
- (user_data['age'] <= parse_age(eligibility)) and
37
- (user_data['income'] <= parse_income(eligibility)) and
38
- (user_data['education'] in eligibility) and
39
- (user_data['category'] in eligibility)
40
- ):
41
- matches.append(row)
42
- return pd.DataFrame(matches)
43
 
44
- # Helper functions for eligibility parsing
45
- def parse_age(eligibility):
46
- if 'below 35' in eligibility:
47
- return 35
48
- return 100 # Default if no age restriction
 
 
 
 
49
 
50
- def parse_income(eligibility):
51
- if '₹2,50,000' in eligibility:
52
- return 250000
53
- return float('inf') # Default if no income restriction
54
 
55
  # Streamlit app
56
  def main():
57
- st.title("AI-Powered Scholarship Advisor")
 
 
 
 
58
 
59
  # User input form
60
- with st.form("scholarship_form"):
61
  st.header("Student Profile")
62
- citizenship = st.selectbox("Citizenship", ["India", "Other"]).lower()
63
- age = st.number_input("Age", 1, 100, 25)
64
- income = st.number_input("Annual Family Income (₹)", 0, 10000000, 500000)
65
- education = st.selectbox(
66
- "Education Level",
67
- ["Class 10", "Class 12", "Undergraduate",
68
- "Postgraduate", "PhD"]
69
- ).lower()
70
- category = st.selectbox(
71
- "Category",
72
- ["General", "OBC", "SC", "ST", "EWS", "Minority"]
73
- ).lower()
74
 
75
- submitted = st.form_submit_button("Find Scholarships") # Form submission button
76
-
77
- # Process form submission
78
  if submitted:
79
- # Validate inputs
80
- if not os.environ.get('GOOGLE_API_KEY'):
81
- st.warning("Please set GOOGLE_API_KEY environment variable")
82
- return
83
-
84
- # Load data and generate recommendations
85
- scholarships = load_scholarships()
86
- user_data = {
87
- 'citizenship': citizenship,
88
- 'age': age,
89
- 'income': income,
90
- 'education': education,
91
- 'category': category
92
- }
93
- results = recommend_scholarships(user_data, scholarships)
94
-
95
- # Display results
96
- if not results.empty:
97
- st.subheader(f"Found {len(results)} Matching Scholarships")
98
- for _, row in results.iterrows():
99
- st.markdown(f"""
100
- **{row['Scholarship Name']}**
101
- **Eligibility:** {row['Eligibility']}
102
- [Apply Here]({row['Link']})
103
- """)
104
- st.divider()
105
- else:
106
- st.warning("No scholarships found matching your criteria.")
107
-
108
- # Generate AI-powered advice
109
- model = get_genai_client()
110
- if model:
111
- prompt = f"""
112
- Act as an experienced education counselor.
113
- For a {age}-year-old {citizenship} citizen with:
114
- - Annual income: ₹{income}
115
- - Education level: {education}
116
- - Category: {category}
117
- Provide personalized advice about these scholarships:
118
- {results['Scholarship Name'].tolist()}
119
- """
120
- response = model.generate_content(prompt)
121
- st.subheader("AI Advisor Recommendations")
122
- st.write(response.text)
 
 
 
 
123
 
124
  if __name__ == "__main__":
125
  main()
 
2
  import streamlit as st
3
  import pandas as pd
4
  import google.generativeai as genai
5
+ from google.generativeai.types import GenerationConfig
6
 
7
  # Configuration
8
  os.environ['GOOGLE_API_KEY'] = os.getenv('GOOGLE_API_KEY', 'your_key_here')
9
+ genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
10
 
11
+ # Load and prepare data
12
  @st.cache_data
13
  def load_scholarships():
 
 
 
 
 
 
 
 
 
 
14
  try:
15
+ df = pd.read_csv("scholarships_data.csv", quotechar='"', quoting=1)
16
+ df = df.map(lambda x: x.strip() if isinstance(x, str) else x)
17
+ df.rename(columns=lambda x: x.strip(), inplace=True)
18
+ return df
19
  except Exception as e:
20
+ st.error(f"Error loading data: {str(e)}")
21
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Convert CSV to RAG context
24
+ def create_rag_context(df):
25
+ context = "Scholarship Database:\n\n"
26
+ for _, row in df.iterrows():
27
+ context += f"""Scholarship Name: {row['Scholarship Name']}
28
+ Eligibility: {row['Eligibility']}
29
+ Deadline: {row['Deadline']}
30
+ Link: {row['Link']}\n\n"""
31
+ return context
32
 
33
+ # Initialize Gemini model
34
+ def get_rag_model():
35
+ return genai.GenerativeModel('gemini-pro')
 
36
 
37
  # Streamlit app
38
  def main():
39
+ st.title("AI Scholarship Advisor 🎓")
40
+
41
+ # Load data and create RAG context
42
+ df = load_scholarships()
43
+ rag_context = create_rag_context(df)
44
 
45
  # User input form
46
+ with st.form("profile_form"):
47
  st.header("Student Profile")
48
+ age = st.number_input("Age", 16, 50, 20)
49
+ citizenship = st.selectbox("Citizenship", ["India", "Other"])
50
+ income = st.number_input("Annual Family Income (₹)", 0, 10000000, 300000)
51
+ education = st.selectbox("Education Level",
52
+ ["High School", "Undergraduate", "Postgraduate", "PhD"])
53
+ category = st.selectbox("Category",
54
+ ["General", "OBC", "SC", "ST", "EWS", "Minority"])
55
+
56
+ submitted = st.form_submit_button("Get Recommendations")
 
 
 
57
 
 
 
 
58
  if submitted:
59
+ # Create user profile
60
+ user_profile = f"""
61
+ Student Profile:
62
+ - Age: {age}
63
+ - Citizenship: {citizenship}
64
+ - Annual Income: ₹{income}
65
+ - Education Level: {education}
66
+ - Category: {category}
67
+ """
68
+
69
+ # Generate response using RAG
70
+ model = get_rag_model()
71
+ prompt = f"""
72
+ {rag_context}
73
+
74
+ {user_profile}
75
+
76
+ Task:
77
+ 1. Analyze the student profile against all scholarships
78
+ 2. Identify top 5 most relevant scholarships with priority order
79
+ 3. For each scholarship:
80
+ - List matching eligibility criteria
81
+ - Explain why it's a good match
82
+ - Provide direct application link
83
+ 4. Format response with markdown headers and bullet points
84
+
85
+ Important:
86
+ - Be specific about eligibility matches
87
+ - Highlight deadlines if available
88
+ - Never invent scholarships not in the database
89
+ """
90
+
91
+ with st.spinner("Analyzing 50+ scholarships..."):
92
+ response = model.generate_content(
93
+ prompt,
94
+ generation_config=GenerationConfig(
95
+ temperature=0.3,
96
+ top_p=0.95,
97
+ max_output_tokens=2000
98
+ )
99
+ )
100
+
101
+ st.subheader("Personalized Recommendations")
102
+ st.markdown(response.text)
103
+
104
+ # Show raw data for transparency
105
+ with st.expander("View Full Scholarship Database"):
106
+ st.dataframe(df)
107
 
108
  if __name__ == "__main__":
109
  main()