Akshayram1 commited on
Commit
f70d963
·
verified ·
1 Parent(s): 643cea0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -84
app.py CHANGED
@@ -1,106 +1,111 @@
1
  import os
2
  import streamlit as st
3
  import pandas as pd
4
- import requests
5
 
6
- # Load the scholarships data
 
 
 
7
  @st.cache_data
8
- def load_scholarships_data():
9
  return pd.read_csv("scholarships_data.csv")
10
 
11
- # Function to filter scholarships based on user input
12
- def recommend_scholarships(data, user_details):
13
- filtered_scholarships = []
14
- for _, row in data.iterrows():
15
- eligibility = row["Eligibility"].lower()
 
 
 
 
 
 
 
 
 
16
  if (
17
- (user_details["citizenship"] == "india" and "indian" in eligibility) or
18
- (user_details["age"] <= 35 and "below 35" in eligibility) or
19
- (user_details["income"] <= 250000 and "₹2,50,000" in eligibility) or
20
- (user_details["education_level"] in eligibility) or
21
- (user_details["category"] in eligibility)
22
  ):
23
- filtered_scholarships.append(row)
24
- return pd.DataFrame(filtered_scholarships)
25
 
26
- # Function to call Gemini API
27
- def query_gemini(prompt):
28
- gemini_api_key = os.getenv("GEMINI_API_KEY")
29
- if not gemini_api_key:
30
- st.error("Gemini API Key not found in environment variables.")
31
- return None
32
 
33
- url = "https://api.gemini.com/v1/query"
34
- headers = {
35
- "Authorization": f"Bearer {gemini_api_key}",
36
- "Content-Type": "application/json",
37
- }
38
- payload = {"prompt": prompt}
39
- response = requests.post(url, headers=headers, json=payload)
40
- if response.status_code == 200:
41
- return response.json().get("response", "")
42
- else:
43
- return "Error: Unable to fetch response from Gemini API."
44
 
45
- # Streamlit App
46
  def main():
47
- st.title("Scholarship Recommendation System")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- # User Input Form
50
- st.header("Student Scholarship Application Form")
51
- with st.form("student_form"):
52
- st.subheader("Personal Details")
53
- citizenship = st.selectbox("Citizenship", ["India", "Other"])
54
- age = st.number_input("Age", min_value=1, max_value=100)
55
- income = st.number_input("Annual Family Income (in ₹)", min_value=0, max_value=10000000)
56
- education_level = st.selectbox(
57
- "Education Level",
58
- ["Class 10", "Class 12", "Undergraduate", "Postgraduate", "PhD"]
59
- )
60
- category = st.selectbox(
61
- "Category",
62
- ["General", "OBC", "SC", "ST", "EWS", "Minority"]
63
- )
64
 
65
- submit_button = st.form_submit_button("Find Scholarships")
66
-
67
- # Process form submission
68
- if submit_button:
69
- # Load scholarships data
70
- scholarships_data = load_scholarships_data()
71
-
72
- # Prepare user details
73
- user_details = {
74
- "citizenship": citizenship.lower(),
75
- "age": age,
76
- "income": income,
77
- "education_level": education_level.lower(),
78
- "category": category.lower(),
79
  }
80
-
81
- # Filter scholarships
82
- recommended_scholarships = recommend_scholarships(scholarships_data, user_details)
83
 
84
  # Display results
85
- st.subheader("Recommended Scholarships")
86
- if not recommended_scholarships.empty:
87
- for _, scholarship in recommended_scholarships.iterrows():
88
- st.markdown(f"**{scholarship['Scholarship Name']}**")
89
- st.write(f"**Eligibility:** {scholarship['Eligibility']}")
90
- st.write(f"**Link:** {scholarship['Link']}")
91
- st.write("---")
92
- else:
93
- st.warning("No scholarships found matching your criteria.")
94
 
95
- # Ask Gemini for additional advice
96
- prompt = (
97
- f"Provide advice for a {age}-year-old {citizenship} citizen with an annual family income of ₹{income}, "
98
- f"pursuing {education_level}, belonging to the {category} category, to find suitable scholarships."
99
- )
100
- gemini_response = query_gemini(prompt)
101
- if gemini_response:
102
- st.subheader("Additional Advice from Gemini")
103
- st.write(gemini_response)
 
 
 
 
 
 
104
 
105
  if __name__ == "__main__":
106
  main()
 
1
  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
  return pd.read_csv("scholarships_data.csv")
13
 
14
+ # Initialize Generative AI
15
+ def get_genai_client():
16
+ try:
17
+ genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
18
+ return genai.GenerativeModel('gemini-pro')
19
+ except Exception as e:
20
+ st.error(f"AI Initialization Error: {str(e)}")
21
+ return None
22
+
23
+ # Recommendation engine
24
+ def recommend_scholarships(user_data, scholarships):
25
+ matches = []
26
+ for _, row in scholarships.iterrows():
27
+ eligibility = row['Eligibility'].lower()
28
  if (
29
+ (user_data['citizenship'] in eligibility) and
30
+ (user_data['age'] <= parse_age(eligibility)) and
31
+ (user_data['income'] <= parse_income(eligibility)) and
32
+ (user_data['education'] in eligibility) and
33
+ (user_data['category'] in eligibility)
34
  ):
35
+ matches.append(row)
36
+ return pd.DataFrame(matches)
37
 
38
+ # Helper functions for eligibility parsing
39
+ def parse_age(eligibility):
40
+ if 'below 35' in eligibility:
41
+ return 35
42
+ return 100 # Default if no age restriction
 
43
 
44
+ def parse_income(eligibility):
45
+ if '₹2,50,000' in eligibility:
46
+ return 250000
47
+ return float('inf') # Default if no income restriction
 
 
 
 
 
 
 
48
 
49
+ # Streamlit app
50
  def main():
51
+ st.title("AI-Powered Scholarship Advisor")
52
+
53
+ # User input form
54
+ with st.form("scholarship_form"):
55
+ st.header("Student Profile")
56
+ citizenship = st.selectbox("Citizenship", ["India", "Other"]).lower()
57
+ age = st.number_input("Age", 1, 100, 25)
58
+ income = st.number_input("Annual Family Income (₹)", 0, 10000000, 500000)
59
+ education = st.selectbox("Education Level",
60
+ ["Class 10", "Class 12", "Undergraduate",
61
+ "Postgraduate", "PhD"]).lower()
62
+ category = st.selectbox("Category",
63
+ ["General", "OBC", "SC", "ST", "EWS", "Minority"]).lower()
64
+
65
+ submitted = st.form_submit_button("Find Scholarships")
66
 
67
+ if submitted:
68
+ # Validate inputs
69
+ if not os.environ.get('GOOGLE_API_KEY'):
70
+ st.warning("Please set GOOGLE_API_KEY environment variable")
71
+ return
 
 
 
 
 
 
 
 
 
 
72
 
73
+ # Load data and generate recommendations
74
+ scholarships = load_scholarships()
75
+ user_data = {
76
+ 'citizenship': citizenship,
77
+ 'age': age,
78
+ 'income': income,
79
+ 'education': education,
80
+ 'category': category
 
 
 
 
 
 
81
  }
82
+ results = recommend_scholarships(user_data, scholarships)
 
 
83
 
84
  # Display results
85
+ st.subheader(f"Found {len(results)} Matching Scholarships")
86
+ for _, row in results.iterrows():
87
+ st.markdown(f"""
88
+ **{row['Scholarship Name']}**
89
+ **Eligibility:** {row['Eligibility']}
90
+ [Apply Here]({row['Link']})
91
+ """)
92
+ st.divider()
 
93
 
94
+ # Generate AI-powered advice
95
+ model = get_genai_client()
96
+ if model:
97
+ prompt = f"""
98
+ Act as an experienced education counselor.
99
+ For a {age}-year-old {citizenship} citizen with:
100
+ - Annual income: ₹{income}
101
+ - Education level: {education}
102
+ - Category: {category}
103
+ Provide personalized advice about these scholarships:
104
+ {results['Scholarship Name'].tolist()}
105
+ """
106
+ response = model.generate_content(prompt)
107
+ st.subheader("AI Advisor Recommendations")
108
+ st.write(response.text)
109
 
110
  if __name__ == "__main__":
111
  main()