Spaces:
Sleeping
Sleeping
File size: 10,823 Bytes
8098153 d7a89ba 8098153 d7a89ba 8098153 d7a89ba 8098153 d7a89ba 8098153 d7a89ba 8098153 d7a89ba 8098153 0583f91 8098153 |
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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
from flask import Flask, jsonify, request, render_template, redirect, url_for
import os
from github_scraper import get_github_profile
from codeforces_scraper import get_codeforces_profile
from leetcode_scraper import get_leetcode_profile
from ipu_scraper import StudentScraper # Updated to use the StudentScraper class
app = Flask(__name__,
static_folder='static', # Directory for CSS/JS files
template_folder='templates') # Directory for HTML files
# Ensure static and templates directories exist
os.makedirs('static', exist_ok=True)
os.makedirs('templates', exist_ok=True)
# Initialize the StudentScraper with the correct encryption key
ipu_scraper = StudentScraper(encryption_key="Qm9sRG9OYVphcmEK")
@app.route('/')
def home():
return redirect(url_for('test_frontend'))
@app.route('/test')
def test_frontend():
return render_template('indexx.html')
@app.route('/api/students', methods=['GET'])
def get_students_list():
import json
enrollment_no = request.args.get('enrollment_no')
json_path = os.path.join(os.path.dirname(__file__), 'final_cleaned_student_data.json')
if not os.path.exists(json_path):
return jsonify({'error': 'Student data file not found.'}), 404
try:
with open(json_path, 'r', encoding='utf-8') as f:
all_students = json.load(f)
if enrollment_no:
student = all_students.get(enrollment_no)
if not student:
return jsonify({'error': 'Student not found.'}), 404
return jsonify(student)
return jsonify(list(all_students.values()))
except Exception:
return jsonify({'error': 'Failed to load student data.'}), 500
@app.route('/favicon.ico')
def favicon():
return '', 204
@app.route('/api/leetcode/<username>', methods=['GET'])
def get_leetcode_profile_route(username: str):
# Validate username
if not username or username.strip() == "":
return jsonify({
'success': False,
'error': 'Username cannot be empty'
}), 400
result = get_leetcode_profile(username)
# Handle LeetCode-specific errors
if not result.get('success', True):
error_msg = result.get('error', 'Unknown error')
# Special handling for user not found
if "not found" in error_msg.lower() or "not exist" in error_msg.lower():
return jsonify({
'success': False,
'error': f'LeetCode user "{username}" not found'
}), 404
# Generic server error
return jsonify({
'success': False,
'error': f'LeetCode API error: {error_msg}'
}), 500
return jsonify(result)
@app.route('/api/github/<username>', methods=['GET'])
def get_github_profile_route(username: str):
if not username or username.strip() == "":
return jsonify({'success': False, 'error': 'Username cannot be empty'}), 400
result = get_github_profile(username)
return jsonify(result)
@app.route('/api/codeforces/<username>', methods=['GET'])
def get_codeforces_profile_route(username: str):
if not username or username.strip() == "":
return jsonify({'success': False, 'error': 'Username cannot be empty'}), 400
result = get_codeforces_profile(username)
return jsonify(result)
@app.route('/api/ipu/<enrollment_no>', methods=['GET'])
def get_ipu_student_route(enrollment_no: str):
"""New endpoint for IPU student data"""
if not enrollment_no or enrollment_no.strip() == "":
return jsonify({
'success': False,
'error': 'Enrollment number cannot be empty'
}), 400
try:
# Get student data using the StudentScraper
student_data = ipu_scraper.get_student_data(enrollment_no)
# Transform the data to match what the frontend expects
if student_data.get("status") == "success":
# Create the expected structure
transformed_data = {
'enrollment_no': student_data['student_info'].get('enroll_no', ''),
'name': student_data['student_info'].get('name', ''),
'img': student_data['student_info'].get('img', ''),
'results': student_data['academic_summary'].get('semester_results', []),
'programme': student_data['programme_info'].get('branch', {}),
'institute': student_data['programme_info'].get('institute', {}),
'subjects': [subject for result in student_data['academic_summary'].get('semester_results', [])
for subject in result.get('subject_results', [])],
'cgpa': student_data['academic_summary']['overall_performance'].get('cgpa', 0)
}
return jsonify({
'success': True,
'data': transformed_data
})
else:
# If preprocessing failed, try to extract data from raw response
raw_data = student_data
if "data" in raw_data and "metadata" in raw_data:
transformed_data = {
'enrollment_no': raw_data['data'].get('enroll_no', ''),
'name': raw_data['data'].get('name', ''),
'img': raw_data['data'].get('img', ''),
'results': raw_data['data'].get('results', []),
'programme': raw_data['metadata'].get('programmeData', {}).get('branch', {}),
'institute': raw_data['metadata'].get('instituteData', {}),
'subjects': [],
'cgpa': raw_data['data'].get('cgpa', 0)
}
return jsonify({
'success': True,
'data': transformed_data
})
else:
return jsonify({
'success': False,
'error': 'Failed to process student data'
}), 500
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/api/all', methods=['GET'])
def get_all_profiles():
leetcode_user = request.args.get('leetcode')
github_user = request.args.get('github')
codeforces_user = request.args.get('codeforces')
enrollment_no = request.args.get('enrollment') # New parameter for IPU
results = {
'success': True,
'data': {},
'errors': {}
}
# Validate at least one parameter is provided
if not any([leetcode_user, github_user, codeforces_user, enrollment_no]):
return jsonify({
'success': False,
'error': 'At least one parameter (leetcode/github/codeforces/enrollment) is required'
}), 400
# Fetch LeetCode profile
if leetcode_user:
leetcode_result = get_leetcode_profile(leetcode_user)
if leetcode_result.get('success', True):
results['data']['leetcode'] = leetcode_result['data']
else:
results['success'] = False
results['errors']['leetcode'] = leetcode_result.get('error', 'Unknown error')
# Fetch GitHub profile
if github_user:
github_result = get_github_profile(github_user)
if github_result.get('success', True):
results['data']['github'] = github_result['data']
else:
results['success'] = False
results['errors']['github'] = github_result.get('error', 'Unknown error')
# Fetch Codeforces profile
if codeforces_user:
codeforces_result = get_codeforces_profile(codeforces_user)
if codeforces_result.get('success', True):
results['data']['codeforces'] = codeforces_result['data']
else:
results['success'] = False
results['errors']['codeforces'] = codeforces_result.get('error', 'Unknown error')
# Fetch IPU student data
if enrollment_no:
try:
student_data = ipu_scraper.get_student_data(enrollment_no)
# Transform the data to match what the frontend expects
if student_data.get("status") == "success":
# Create the expected structure
transformed_data = {
'enrollment_no': student_data['student_info'].get('enroll_no', ''),
'name': student_data['student_info'].get('name', ''),
'img': student_data['student_info'].get('img', ''),
'results': student_data['academic_summary'].get('semester_results', []),
'programme': student_data['programme_info'].get('branch', {}),
'institute': student_data['programme_info'].get('institute', {}),
'subjects': [subject for result in student_data['academic_summary'].get('semester_results', [])
for subject in result.get('subject_results', [])],
'cgpa': student_data['academic_summary']['overall_performance'].get('cgpa', 0)
}
results['data']['ipu'] = transformed_data
else:
# If preprocessing failed, try to extract data from raw response
raw_data = student_data
if "data" in raw_data and "metadata" in raw_data:
transformed_data = {
'enrollment_no': raw_data['data'].get('enroll_no', ''),
'name': raw_data['data'].get('name', ''),
'img': raw_data['data'].get('img', ''),
'results': raw_data['data'].get('results', []),
'programme': raw_data['metadata'].get('programmeData', {}).get('branch', {}),
'institute': raw_data['metadata'].get('instituteData', {}),
'subjects': [],
'cgpa': raw_data['data'].get('cgpa', 0)
}
results['data']['ipu'] = transformed_data
else:
results['success'] = False
results['errors']['ipu'] = "Failed to process student data"
except Exception as e:
results['success'] = False
results['errors']['ipu'] = str(e)
# If all requests failed, return 400/500
if not results['data']:
return jsonify({
'success': False,
'error': 'All profile requests failed',
'details': results['errors']
}), 400 if any("not found" in str(e).lower() for e in results['errors'].values()) else 500
return jsonify(results)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True) |