Neurolingua commited on
Commit
2c21544
1 Parent(s): 6bba00e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +557 -555
app.py CHANGED
@@ -1,555 +1,557 @@
1
- import joblib
2
- from flask import Flask, render_template, request, jsonify,session
3
- from werkzeug.utils import secure_filename
4
- import os
5
- from student_functions import extract_text_from_pdf_s,generate_ai_response,generate_project_idea,generate_project_idea_questions,generate_quiz,generate_response_from_pdf,generate_step_by_step_explanation,perform_ocr,study_plan,ConversationBufferMemory,get_first_youtube_video_link,content_translate,summarise_text,content_translate
6
- from teacher_function import evaluate,extract_text_from_image,extract_text_from_pdf,generate_questions_from_text,generate_student_report,generate_timetable_module,cluster_topics,generate_timetable_weak
7
- import shutil
8
- from ai71 import AI71
9
- import re
10
- from flask import Flask, render_template, request, jsonify,session,current_app,send_from_directory
11
-
12
- AI71_API_KEY = "api71-api-df260d58-62e0-46c9-b549-62daa9c409be"
13
- UPLOAD_FOLDER = 'uploads'
14
- ALLOWED_EXTENSIONS = {'pdf', 'jpg', 'jpeg' , 'png'}
15
-
16
- app = Flask(__name__)
17
- app.secret_key = 'your_unique_secret_key' # Add this line
18
- if os.path.exists('uploads'):
19
- shutil.rmtree('uploads')
20
- app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
21
- memory = ConversationBufferMemory()
22
- database=joblib.load('database.pkl')
23
- teacher_data=database[0]
24
- student_data=database[1]
25
- def allowed_file(filename):
26
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
27
-
28
-
29
- @app.route('/')
30
- def index():
31
- return render_template('index.html')
32
-
33
- @app.route('/student')
34
- def student():
35
- student = {
36
- 'name': session.get('student_name'),
37
- 'id': session.get('student_id'),
38
- 'school': session.get('student_school'),
39
- 'dob': session.get('student_dob'),
40
- 'email': session.get('student_email'),
41
- 'subjects_interested': session.get('student_subjects_interested', []),
42
- 'subjects_needing_improvement': session.get('student_subjects_needing_improvement', [])
43
- }
44
- return render_template('student.html', student=student)
45
-
46
- @app.route('/student_login', methods=['POST'])
47
- def student_login():
48
- data = request.json
49
- name = data.get('name')
50
- password = data.get('password')
51
-
52
- # Verify credentials
53
- for student in student_data:
54
- if student['name'] == name and student['password'] == password:
55
- # Set session data
56
- session['student_name'] = student['name']
57
- session['student_id'] = student.get('id', 'N/A') # If ID is not in data, default to 'N/A'
58
- session['student_school'] = student['school']
59
- session['student_dob'] = student['dob']
60
- session['student_email'] = student['email']
61
- session['student_subjects_interested'] = student['interests']
62
- session['student_subjects_needing_improvement'] = [student['areas_to_improve']]
63
- return jsonify({'success': True})
64
-
65
- return jsonify({'success': False})
66
-
67
-
68
- @app.route('/teacher_login', methods=['POST'])
69
- def teacher_login():
70
- data = request.json
71
- name = data.get('name')
72
- password = data.get('password')
73
-
74
- # Verify credentials
75
- for teacher in teacher_data:
76
- if teacher['name'] == name and teacher['password'] == password:
77
- # Set session data
78
- session['teacher_name'] = teacher['name']
79
- session['teacher_id'] = teacher['teacher_id']
80
- session['teacher_school'] = teacher['school']
81
- session['teacher_dob'] = teacher['date_of_birth']
82
- session['teacher_email'] = teacher['email']
83
- session['teacher_subjects_taught'] = teacher['subjects_taught']
84
- session['teacher_classes'] = teacher['classes']
85
- session['teacher_performance'] = teacher['teaching_performance']
86
- session['teacher_qualifications'] = teacher['qualifications']
87
- session['teacher_years_of_experience'] = teacher['years_of_experience']
88
- session['weekly_class_performance']= teacher['weekly_class_performance']
89
- return jsonify({'success': True})
90
-
91
- return jsonify({'success': False})
92
-
93
- @app.route('/teacher')
94
- def teacher():
95
- teacher = {
96
- 'name': session.get('teacher_name'),
97
- 'id': session.get('teacher_id'),
98
- 'school': session.get('teacher_school'),
99
- 'dob': session.get('teacher_dob'),
100
- 'email': session.get('teacher_email'),
101
- 'subjects_taught': session.get('teacher_subjects_taught', []),
102
- 'classes': session.get('teacher_classes', []),
103
- 'performance': session.get('teacher_performance', {}),
104
- 'qualifications': session.get('teacher_qualifications', []),
105
- 'years_of_experience': session.get('teacher_years_of_experience', 0),
106
- 'weekly_class_performance': session.get('teacher_weekly_class_performance', {})
107
- }
108
- return render_template('teacher.html', teacher=teacher)
109
-
110
- @app.route('/student_pdfqa', methods=['GET', 'POST'])
111
- def student_pdfqa():
112
- if request.method == 'POST':
113
- file = request.files.get('pdf-file')
114
- if file and allowed_file(file.filename):
115
- filename = secure_filename(file.filename)
116
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
117
- file.save(file_path)
118
-
119
- pdf_text = extract_text_from_pdf_s(file_path)
120
- return jsonify({'message': f'PDF uploaded and processed. You can now ask questions.', 'pdf_text': pdf_text})
121
- else:
122
- return jsonify({'message': 'Invalid file type. Please upload a PDF.'}), 400
123
-
124
- return render_template('student_pdfqa.html')
125
-
126
- @app.route('/ask_pdf_question', methods=['POST'])
127
- def ask_pdf_question():
128
- data = request.json
129
- query = data['query']
130
- pdf_text = data['pdf_text']
131
-
132
- response = generate_response_from_pdf(query, pdf_text)[:-6]
133
- return jsonify({'response': response})
134
-
135
- @app.route('/student_aitutor')
136
- def student_aitutor():
137
- return render_template('student_aitutor.html')
138
-
139
- @app.route('/chat', methods=['POST'])
140
- def chat():
141
- data = request.json
142
- query = data['message']
143
- response = generate_ai_response(query)
144
- return jsonify({'response': response})
145
-
146
- @app.route('/upload_image_for_ocr', methods=['POST'])
147
- def upload_image_for_ocr():
148
- if 'image-file' not in request.files:
149
- return jsonify({'error': 'No file part'}), 400
150
- file = request.files['image-file']
151
- if file.filename == '':
152
- return jsonify({'error': 'No selected file'}), 400
153
- if file and allowed_file(file.filename):
154
- filename = secure_filename(file.filename)
155
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
156
- file.save(file_path)
157
-
158
- extracted_text = perform_ocr(file_path)
159
- ai_response = generate_ai_response(extracted_text)
160
-
161
- return jsonify({'ai_response': ai_response})
162
- return jsonify({'error': 'Invalid file type'}), 400
163
-
164
-
165
- @app.route('/student_projectideas')
166
- def student_projectideas():
167
- return render_template('student_projectideas.html')
168
-
169
- @app.route('/student_quiz')
170
- def student_quiz():
171
- return render_template('student_quiz.html')
172
-
173
- @app.route('/update_student_areas', methods=['POST'])
174
- def update_student_areas():
175
- data = request.json
176
- student_id = data.get('student_id')
177
- areas_to_improve = data.get('areas_to_improve')
178
-
179
- # Find the student in the database
180
- student = next((s for s in student_data if s['email'] == student_id), None)
181
-
182
- if student:
183
- # Update the student's areas to improve
184
- student['areas_to_improve'] = areas_to_improve
185
- return jsonify({'status': 'success'})
186
- else:
187
- return jsonify({'status': 'error', 'message': 'Student not found'}), 404
188
- @app.route('/get_student_profile', methods=['GET'])
189
- def get_student_profile():
190
- # For demonstration, assume `student_id` is passed in query parameters
191
- student_id = request.args.get('student_id')
192
- student = next((s for s in student_data if s['email'] == student_id), None)
193
-
194
- if student:
195
- return jsonify({
196
- 'status': 'success',
197
- 'areas_to_improve': student.get('areas_to_improve', [])
198
- })
199
- else:
200
- return jsonify({'status': 'error', 'message': 'Student not found'}), 404
201
-
202
-
203
- def calculate_score_and_grade(llm_response):
204
- pattern = r'Assigned marks: (\d+)/(\d+)'
205
- matches = re.findall(pattern, llm_response)
206
-
207
- total_score = sum(int(score) for score, max_score in matches)
208
- max_possible_score = sum(int(max_score) for score, max_score in matches)
209
-
210
- percentage = (total_score / max_possible_score) * 100 if max_possible_score > 0 else 0
211
-
212
- if percentage > 90:
213
- grade = 'O'
214
- elif 80 <= percentage <= 90:
215
- grade = 'A'
216
- elif 70 <= percentage < 80:
217
- grade = 'B'
218
- elif 60 <= percentage < 70:
219
- grade = 'C'
220
- elif 50 <= percentage < 60:
221
- grade = 'D'
222
- else:
223
- grade = 'Fail'
224
-
225
- return total_score, max_possible_score, percentage, grade
226
- @app.route('/student_reward_points')
227
- def student_reward_points():
228
- return render_template('student_reward_points.html')
229
-
230
- @app.route('/generate_quiz', methods=['POST'])
231
- def generate_quiz_route():
232
- data = request.json
233
- subject = data['subject']
234
- topic = data['topic']
235
- count = int(data['num-questions'])
236
- difficulty = data['difficulty']
237
-
238
- quiz = generate_quiz(subject, topic, count, difficulty)
239
- return jsonify({'quiz': quiz})
240
-
241
- @app.route('/generate_project_idea', methods=['POST'])
242
- def generate_project_idea_route():
243
- data = request.json
244
- subject = data['subject']
245
- topic = data['topic']
246
- plan = data['plan']
247
-
248
- project_idea = generate_project_idea(subject, topic, plan)
249
- return jsonify({'project_idea': project_idea})
250
-
251
- @app.route('/homework')
252
- def homework():
253
- return render_template('homework.html')
254
-
255
- @app.route('/student_courses')
256
- def student_courses():
257
- return render_template('student_courses.html')
258
-
259
- @app.route('/search_youtube', methods=['POST'])
260
- def search_youtube():
261
- data = request.json
262
- query = data['query']
263
-
264
- try:
265
- video_link, video_title = get_first_youtube_video_link(query)
266
- video_id = video_link.split('v=')[1]
267
- return jsonify({
268
- 'videoId': video_id,
269
- 'videoTitle': video_title
270
- })
271
- except Exception as e:
272
- return jsonify({'error': f'An error occurred: {str(e)}'}), 500
273
-
274
- @app.route('/ask_followup', methods=['POST'])
275
- def ask_followup_route():
276
- data = request.json
277
- project_idea = data['project_idea']
278
- query = data['query']
279
-
280
- response = generate_project_idea_questions(project_idea, query)
281
- return jsonify({'response': response})
282
-
283
- @app.route('/student_studyplans')
284
- def student_studyplans():
285
- return render_template('student_studyplans.html')
286
-
287
- @app.route('/generate_study_plan', methods=['POST'])
288
- def generate_study_plan_route():
289
- data = request.json
290
- subjects = data['subjects']
291
- hours = data['hours']
292
- area_lag = data['areaLag'] # Ensure the key matches
293
- goal = data['goal']
294
- learning_style = data['learningStyle']
295
-
296
- study_plan_text = study_plan(subjects, hours, area_lag, goal)
297
- return jsonify({'study_plan': study_plan_text})
298
-
299
-
300
- @app.route('/student_stepexplanation')
301
- def student_stepexplanation():
302
- return render_template('student_stepexplanation.html')
303
-
304
-
305
- @app.route('/evaluate-answers', methods=['POST'])
306
- def evaluate_answers():
307
- data = request.json
308
- questions = data['questions']
309
- answers = data['answers']
310
- max_marks = 5 # As per your requirement
311
-
312
- evaluations = []
313
- for question, answer in zip(questions, answers):
314
- if answer.strip() == "":
315
- evaluation = "Description: No answer provided.\nAssigned marks: 0\nTotal marks: 5"
316
- else:
317
- evaluation = evaluate(question, answer, max_marks)
318
- evaluations.append(evaluation)
319
-
320
- return jsonify({"evaluations": evaluations})
321
-
322
- @app.route('/translate', methods=['POST'])
323
- def translate():
324
- data = request.json
325
- text = data.get('text', '')
326
- # Mock translation function
327
- translated_text = content_translate(text)
328
- return jsonify({"translated_text": translated_text})
329
-
330
- @app.route('/generate_step_by_step_explanation', methods=['POST'])
331
- def generate_step_by_step_explanation_route():
332
- data = request.get_json()
333
- question = data['question']
334
- answer = generate_step_by_step_explanation(question)
335
- return jsonify({'answer': answer})
336
-
337
- @app.route('/speak')
338
- def speak():
339
- return render_template('student_speakai.html')
340
-
341
- @app.route('/generate_ai_timetable', methods=['POST'])
342
- def generate_ai_timetable():
343
- academic_topics = request.form['academic_topics'].split(',')
344
- hours_per_day = request.form['hours_per_day']
345
-
346
- clustered_topics = cluster_topics(academic_topics)
347
- special_timetable = generate_timetable_weak(clustered_topics, hours_per_day)
348
-
349
- return jsonify({
350
- 'clustered_topics': clustered_topics,
351
- 'special_timetable': special_timetable
352
- })
353
-
354
-
355
- @app.route('/ai_timetable')
356
- def ai_timetable():
357
- return render_template('ai_timetable.html')
358
-
359
- @app.route('/summarise_video')
360
- def summarise_video():
361
- return render_template('student_summarise_video.html')
362
-
363
- @app.route('/summarize_video', methods=['POST'])
364
- def summarize_video_route():
365
- data = request.json
366
- url = data.get('url')
367
- if url:
368
- try:
369
- summary = summarise_text(url)
370
- return jsonify({'summary': summary})
371
- except Exception as e:
372
- return jsonify({'error': str(e)}), 500
373
- else:
374
- return jsonify({'error': 'No URL provided'}), 400
375
-
376
-
377
- @app.route('/generate-questions-hw', methods=['GET'])
378
- def generate_questions():
379
- messages = [
380
- {"role": "system", "content": "You are a helpful assistant."},
381
- {"role": "user", "content": (
382
- "Generate 5 questions for a Math Assignment on 'trigonometry Basics'. "
383
- "Include a mix of both theoretical and numerical questions."
384
- )}
385
- ]
386
-
387
- questions = []
388
- for chunk in AI71(AI71_API_KEY).chat.completions.create(
389
- model="tiiuae/falcon-180b-chat",
390
- messages=messages,
391
- stream=True,
392
- ):
393
- if chunk.choices[0].delta.content:
394
- questions.append(chunk.choices[0].delta.content)
395
-
396
- # Join all chunks to create the complete list of questions
397
- complete_questions = ''.join(questions).split('\n')
398
-
399
- return jsonify({'questions': complete_questions})
400
-
401
- @app.route('/assign_grade', methods=['POST'])
402
- def assign_grade():
403
- data = request.json
404
- result = data['result']
405
- total_score, max_possible_score, percentage, grade = calculate_score_and_grade(result)
406
- return jsonify({
407
- 'total_score': total_score,
408
- 'max_possible_score': max_possible_score,
409
- 'percentage': percentage,
410
- 'grade': grade
411
- })
412
-
413
- @app.route('/generate_timetable', methods=['POST'])
414
- def generate_timetable():
415
- data = request.json
416
- hours_per_day = data.get('hours_per_day')
417
- days_per_week = data.get('days_per_week')
418
- semester_end_date = data.get('semester_end_date')
419
- subjects = data.get('subjects', [])
420
-
421
- # Input validation
422
- if not hours_per_day or not days_per_week or not semester_end_date or not subjects:
423
- return jsonify({"error": "Missing required parameters"}), 400
424
-
425
- try:
426
- timetable=generate_timetable_module(data,hours_per_day,days_per_week,semester_end_date,subjects)
427
-
428
- return jsonify({"timetable": timetable})
429
-
430
- except Exception as e:
431
- return jsonify({"error": str(e)}), 500
432
-
433
-
434
- @app.route('/generate-paper', methods=['GET', 'POST'])
435
- def generate_paper():
436
- if request.method == 'POST':
437
- no_of_questions = int(request.form['no_of_questions'])
438
- total_marks = int(request.form['total_marks'])
439
- no_of_parts = int(request.form['no_of_parts'])
440
- marks_per_part = int(request.form['marks_per_part'])
441
- test_duration = request.form['test_duration']
442
- pdf_file = request.files['pdf_file']
443
-
444
- if pdf_file:
445
- # Secure the file name and save the file to the upload folder
446
- filename = secure_filename(pdf_file.filename)
447
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
448
- pdf_file.save(file_path)
449
-
450
- # Extract text from the curriculum PDF
451
- curriculum_text = extract_text_from_pdf(file_path)
452
-
453
- # Generate questions
454
- questions = generate_questions_from_text(curriculum_text, no_of_questions, marks_per_part, no_of_parts)
455
-
456
- # Optionally, remove the saved file after use
457
- os.remove(file_path)
458
-
459
- return render_template('teacher_paper_gen.html', questions=questions)
460
-
461
- return render_template('teacher_paper_gen.html')
462
-
463
-
464
- @app.route('/eval', methods=['GET', 'POST'])
465
- def eval():
466
- if request.method == 'POST':
467
- input_type = request.form['input_type']
468
- question_text = ""
469
- answer_text = ""
470
- max_marks = request.form['max_marks']
471
-
472
- if input_type == 'file':
473
- question_file = request.files['question_file']
474
- answer_file = request.files['answer_file']
475
-
476
- if question_file and answer_file:
477
- question_path = os.path.join(app.config['UPLOAD_FOLDER'], question_file.filename)
478
- answer_path = os.path.join(app.config['UPLOAD_FOLDER'], answer_file.filename)
479
-
480
- question_file.save(question_path)
481
- answer_file.save(answer_path)
482
-
483
- if question_path.endswith('.pdf'):
484
- question_text = extract_text_from_pdf(question_path)
485
- else:
486
- question_text = extract_text_from_image(question_path)
487
-
488
- if answer_path.endswith('.pdf'):
489
- answer_text = extract_text_from_pdf(answer_path)
490
- else:
491
- answer_text = extract_text_from_image(answer_path)
492
-
493
- elif input_type == 'text':
494
- question_text = request.form['question_text']
495
- answer_text = request.form['answer_text']
496
-
497
- evaluation_result = evaluate(question_text, answer_text, max_marks)
498
- print(f"Question Text: {question_text}") # Debugging line
499
- print(f"Answer Text: {answer_text}") # Debugging line
500
- print(f"Evaluation Result: {evaluation_result}") # Debugging line
501
-
502
- return render_template('teacher_result.html', result=evaluation_result)
503
-
504
- return render_template('teacher_eval.html')
505
-
506
- @app.route('/get_students')
507
- def get_students():
508
-
509
- return jsonify(student_data)
510
-
511
-
512
- @app.route('/get_audio_files', methods=['GET'])
513
- def get_audio_files():
514
- audio_folder = os.path.join(app.root_path, 'speech')
515
- audio_files = [{'name': file, 'url': f'/speech/{file}'} for file in os.listdir(audio_folder) if
516
- file.endswith('.mp3')]
517
-
518
- current_app.logger.info(f"Found audio files: {audio_files}")
519
-
520
- return jsonify({'audio_files': audio_files})
521
-
522
-
523
- @app.route('/speech/<path:filename>')
524
- def serve_audio(filename):
525
- return send_from_directory(os.path.join(app.root_path, 'speech'), filename)
526
-
527
-
528
-
529
- @app.route('/generate_report', methods=['POST'])
530
- def generate_report():
531
- student_data = request.json
532
- report = generate_student_report(
533
- student_data['name'],
534
- student_data['age'],
535
- student_data['cgpa'],
536
- student_data['course_pursuing'],
537
- student_data['assigned_test_score'],
538
- student_data['ai_test_score'],
539
- student_data['interests'],
540
- student_data['areas_to_improve'],
541
- student_data['courses_taken']
542
- )
543
- return jsonify({'report': report})
544
-
545
-
546
-
547
-
548
- if __name__ == '__main__':
549
- if os.path.exists('uploads'):
550
- shutil.rmtree('uploads')
551
- os.makedirs('uploads')
552
- else:
553
- os.makedirs('uploads')
554
- app.run( port=5000, debug=True)
555
-
 
 
 
1
+ import joblib
2
+ from flask import Flask, render_template, request, jsonify,session
3
+ from werkzeug.utils import secure_filename
4
+ import os
5
+ from student_functions import extract_text_from_pdf_s,generate_ai_response,generate_project_idea,generate_project_idea_questions,generate_quiz,generate_response_from_pdf,generate_step_by_step_explanation,perform_ocr,study_plan,ConversationBufferMemory,get_first_youtube_video_link,content_translate,summarise_text,content_translate
6
+ from teacher_function import evaluate,extract_text_from_image,extract_text_from_pdf,generate_questions_from_text,generate_student_report,generate_timetable_module,cluster_topics,generate_timetable_weak
7
+ import shutil
8
+ from ai71 import AI71
9
+ import re
10
+ from flask import Flask, render_template, request, jsonify,session,current_app,send_from_directory
11
+ from pathlib import Path
12
+
13
+ AI71_API_KEY = "api71-api-df260d58-62e0-46c9-b549-62daa9c409be"
14
+ UPLOAD_FOLDER = 'uploads'
15
+ ALLOWED_EXTENSIONS = {'pdf', 'jpg', 'jpeg' , 'png'}
16
+
17
+ app = Flask(__name__)
18
+ app.secret_key = 'your_unique_secret_key' # Add this line
19
+ if os.path.exists('uploads'):
20
+ shutil.rmtree('uploads')
21
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
22
+ memory = ConversationBufferMemory()
23
+ database=joblib.load('database.pkl')
24
+ teacher_data=database[0]
25
+ student_data=database[1]
26
+ def allowed_file(filename):
27
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
28
+
29
+
30
+ @app.route('/')
31
+ def index():
32
+ return render_template('index.html')
33
+
34
+ @app.route('/student')
35
+ def student():
36
+ student = {
37
+ 'name': session.get('student_name'),
38
+ 'id': session.get('student_id'),
39
+ 'school': session.get('student_school'),
40
+ 'dob': session.get('student_dob'),
41
+ 'email': session.get('student_email'),
42
+ 'subjects_interested': session.get('student_subjects_interested', []),
43
+ 'subjects_needing_improvement': session.get('student_subjects_needing_improvement', [])
44
+ }
45
+ return render_template('student.html', student=student)
46
+
47
+ @app.route('/student_login', methods=['POST'])
48
+ def student_login():
49
+ data = request.json
50
+ name = data.get('name')
51
+ password = data.get('password')
52
+
53
+ # Verify credentials
54
+ for student in student_data:
55
+ if student['name'] == name and student['password'] == password:
56
+ # Set session data
57
+ session['student_name'] = student['name']
58
+ session['student_id'] = student.get('id', 'N/A') # If ID is not in data, default to 'N/A'
59
+ session['student_school'] = student['school']
60
+ session['student_dob'] = student['dob']
61
+ session['student_email'] = student['email']
62
+ session['student_subjects_interested'] = student['interests']
63
+ session['student_subjects_needing_improvement'] = [student['areas_to_improve']]
64
+ return jsonify({'success': True})
65
+
66
+ return jsonify({'success': False})
67
+
68
+
69
+ @app.route('/teacher_login', methods=['POST'])
70
+ def teacher_login():
71
+ data = request.json
72
+ name = data.get('name')
73
+ password = data.get('password')
74
+
75
+ # Verify credentials
76
+ for teacher in teacher_data:
77
+ if teacher['name'] == name and teacher['password'] == password:
78
+ # Set session data
79
+ session['teacher_name'] = teacher['name']
80
+ session['teacher_id'] = teacher['teacher_id']
81
+ session['teacher_school'] = teacher['school']
82
+ session['teacher_dob'] = teacher['date_of_birth']
83
+ session['teacher_email'] = teacher['email']
84
+ session['teacher_subjects_taught'] = teacher['subjects_taught']
85
+ session['teacher_classes'] = teacher['classes']
86
+ session['teacher_performance'] = teacher['teaching_performance']
87
+ session['teacher_qualifications'] = teacher['qualifications']
88
+ session['teacher_years_of_experience'] = teacher['years_of_experience']
89
+ session['weekly_class_performance']= teacher['weekly_class_performance']
90
+ return jsonify({'success': True})
91
+
92
+ return jsonify({'success': False})
93
+
94
+ @app.route('/teacher')
95
+ def teacher():
96
+ teacher = {
97
+ 'name': session.get('teacher_name'),
98
+ 'id': session.get('teacher_id'),
99
+ 'school': session.get('teacher_school'),
100
+ 'dob': session.get('teacher_dob'),
101
+ 'email': session.get('teacher_email'),
102
+ 'subjects_taught': session.get('teacher_subjects_taught', []),
103
+ 'classes': session.get('teacher_classes', []),
104
+ 'performance': session.get('teacher_performance', {}),
105
+ 'qualifications': session.get('teacher_qualifications', []),
106
+ 'years_of_experience': session.get('teacher_years_of_experience', 0),
107
+ 'weekly_class_performance': session.get('teacher_weekly_class_performance', {})
108
+ }
109
+ return render_template('teacher.html', teacher=teacher)
110
+
111
+ @app.route('/student_pdfqa', methods=['GET', 'POST'])
112
+ def student_pdfqa():
113
+ if request.method == 'POST':
114
+ file = request.files.get('pdf-file')
115
+ if file and allowed_file(file.filename):
116
+ filename = secure_filename(file.filename)
117
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
118
+ file.save(file_path)
119
+
120
+ pdf_text = extract_text_from_pdf_s(file_path)
121
+ return jsonify({'message': f'PDF uploaded and processed. You can now ask questions.', 'pdf_text': pdf_text})
122
+ else:
123
+ return jsonify({'message': 'Invalid file type. Please upload a PDF.'}), 400
124
+
125
+ return render_template('student_pdfqa.html')
126
+
127
+ @app.route('/ask_pdf_question', methods=['POST'])
128
+ def ask_pdf_question():
129
+ data = request.json
130
+ query = data['query']
131
+ pdf_text = data['pdf_text']
132
+
133
+ response = generate_response_from_pdf(query, pdf_text)[:-6]
134
+ return jsonify({'response': response})
135
+
136
+ @app.route('/student_aitutor')
137
+ def student_aitutor():
138
+ return render_template('student_aitutor.html')
139
+
140
+ @app.route('/chat', methods=['POST'])
141
+ def chat():
142
+ data = request.json
143
+ query = data['message']
144
+ response = generate_ai_response(query)
145
+ return jsonify({'response': response})
146
+
147
+ @app.route('/upload_image_for_ocr', methods=['POST'])
148
+ def upload_image_for_ocr():
149
+ if 'image-file' not in request.files:
150
+ return jsonify({'error': 'No file part'}), 400
151
+ file = request.files['image-file']
152
+ if file.filename == '':
153
+ return jsonify({'error': 'No selected file'}), 400
154
+ if file and allowed_file(file.filename):
155
+ filename = secure_filename(file.filename)
156
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
157
+ file.save(file_path)
158
+
159
+ extracted_text = perform_ocr(file_path)
160
+ ai_response = generate_ai_response(extracted_text)
161
+
162
+ return jsonify({'ai_response': ai_response})
163
+ return jsonify({'error': 'Invalid file type'}), 400
164
+
165
+
166
+ @app.route('/student_projectideas')
167
+ def student_projectideas():
168
+ return render_template('student_projectideas.html')
169
+
170
+ @app.route('/student_quiz')
171
+ def student_quiz():
172
+ return render_template('student_quiz.html')
173
+
174
+ @app.route('/update_student_areas', methods=['POST'])
175
+ def update_student_areas():
176
+ data = request.json
177
+ student_id = data.get('student_id')
178
+ areas_to_improve = data.get('areas_to_improve')
179
+
180
+ # Find the student in the database
181
+ student = next((s for s in student_data if s['email'] == student_id), None)
182
+
183
+ if student:
184
+ # Update the student's areas to improve
185
+ student['areas_to_improve'] = areas_to_improve
186
+ return jsonify({'status': 'success'})
187
+ else:
188
+ return jsonify({'status': 'error', 'message': 'Student not found'}), 404
189
+ @app.route('/get_student_profile', methods=['GET'])
190
+ def get_student_profile():
191
+ # For demonstration, assume `student_id` is passed in query parameters
192
+ student_id = request.args.get('student_id')
193
+ student = next((s for s in student_data if s['email'] == student_id), None)
194
+
195
+ if student:
196
+ return jsonify({
197
+ 'status': 'success',
198
+ 'areas_to_improve': student.get('areas_to_improve', [])
199
+ })
200
+ else:
201
+ return jsonify({'status': 'error', 'message': 'Student not found'}), 404
202
+
203
+
204
+ def calculate_score_and_grade(llm_response):
205
+ pattern = r'Assigned marks: (\d+)/(\d+)'
206
+ matches = re.findall(pattern, llm_response)
207
+
208
+ total_score = sum(int(score) for score, max_score in matches)
209
+ max_possible_score = sum(int(max_score) for score, max_score in matches)
210
+
211
+ percentage = (total_score / max_possible_score) * 100 if max_possible_score > 0 else 0
212
+
213
+ if percentage > 90:
214
+ grade = 'O'
215
+ elif 80 <= percentage <= 90:
216
+ grade = 'A'
217
+ elif 70 <= percentage < 80:
218
+ grade = 'B'
219
+ elif 60 <= percentage < 70:
220
+ grade = 'C'
221
+ elif 50 <= percentage < 60:
222
+ grade = 'D'
223
+ else:
224
+ grade = 'Fail'
225
+
226
+ return total_score, max_possible_score, percentage, grade
227
+ @app.route('/student_reward_points')
228
+ def student_reward_points():
229
+ return render_template('student_reward_points.html')
230
+
231
+ @app.route('/generate_quiz', methods=['POST'])
232
+ def generate_quiz_route():
233
+ data = request.json
234
+ subject = data['subject']
235
+ topic = data['topic']
236
+ count = int(data['num-questions'])
237
+ difficulty = data['difficulty']
238
+
239
+ quiz = generate_quiz(subject, topic, count, difficulty)
240
+ return jsonify({'quiz': quiz})
241
+
242
+ @app.route('/generate_project_idea', methods=['POST'])
243
+ def generate_project_idea_route():
244
+ data = request.json
245
+ subject = data['subject']
246
+ topic = data['topic']
247
+ plan = data['plan']
248
+
249
+ project_idea = generate_project_idea(subject, topic, plan)
250
+ return jsonify({'project_idea': project_idea})
251
+
252
+ @app.route('/homework')
253
+ def homework():
254
+ return render_template('homework.html')
255
+
256
+ @app.route('/student_courses')
257
+ def student_courses():
258
+ return render_template('student_courses.html')
259
+
260
+ @app.route('/search_youtube', methods=['POST'])
261
+ def search_youtube():
262
+ data = request.json
263
+ query = data['query']
264
+
265
+ try:
266
+ video_link, video_title = get_first_youtube_video_link(query)
267
+ video_id = video_link.split('v=')[1]
268
+ return jsonify({
269
+ 'videoId': video_id,
270
+ 'videoTitle': video_title
271
+ })
272
+ except Exception as e:
273
+ return jsonify({'error': f'An error occurred: {str(e)}'}), 500
274
+
275
+ @app.route('/ask_followup', methods=['POST'])
276
+ def ask_followup_route():
277
+ data = request.json
278
+ project_idea = data['project_idea']
279
+ query = data['query']
280
+
281
+ response = generate_project_idea_questions(project_idea, query)
282
+ return jsonify({'response': response})
283
+
284
+ @app.route('/student_studyplans')
285
+ def student_studyplans():
286
+ return render_template('student_studyplans.html')
287
+
288
+ @app.route('/generate_study_plan', methods=['POST'])
289
+ def generate_study_plan_route():
290
+ data = request.json
291
+ subjects = data['subjects']
292
+ hours = data['hours']
293
+ area_lag = data['areaLag'] # Ensure the key matches
294
+ goal = data['goal']
295
+ learning_style = data['learningStyle']
296
+
297
+ study_plan_text = study_plan(subjects, hours, area_lag, goal)
298
+ return jsonify({'study_plan': study_plan_text})
299
+
300
+
301
+ @app.route('/student_stepexplanation')
302
+ def student_stepexplanation():
303
+ return render_template('student_stepexplanation.html')
304
+
305
+
306
+ @app.route('/evaluate-answers', methods=['POST'])
307
+ def evaluate_answers():
308
+ data = request.json
309
+ questions = data['questions']
310
+ answers = data['answers']
311
+ max_marks = 5 # As per your requirement
312
+
313
+ evaluations = []
314
+ for question, answer in zip(questions, answers):
315
+ if answer.strip() == "":
316
+ evaluation = "Description: No answer provided.\nAssigned marks: 0\nTotal marks: 5"
317
+ else:
318
+ evaluation = evaluate(question, answer, max_marks)
319
+ evaluations.append(evaluation)
320
+
321
+ return jsonify({"evaluations": evaluations})
322
+
323
+ @app.route('/translate', methods=['POST'])
324
+ def translate():
325
+ data = request.json
326
+ text = data.get('text', '')
327
+ # Mock translation function
328
+ translated_text = content_translate(text)
329
+ return jsonify({"translated_text": translated_text})
330
+
331
+ @app.route('/generate_step_by_step_explanation', methods=['POST'])
332
+ def generate_step_by_step_explanation_route():
333
+ data = request.get_json()
334
+ question = data['question']
335
+ answer = generate_step_by_step_explanation(question)
336
+ return jsonify({'answer': answer})
337
+
338
+ @app.route('/speak')
339
+ def speak():
340
+ return render_template('student_speakai.html')
341
+
342
+ @app.route('/generate_ai_timetable', methods=['POST'])
343
+ def generate_ai_timetable():
344
+ academic_topics = request.form['academic_topics'].split(',')
345
+ hours_per_day = request.form['hours_per_day']
346
+
347
+ clustered_topics = cluster_topics(academic_topics)
348
+ special_timetable = generate_timetable_weak(clustered_topics, hours_per_day)
349
+
350
+ return jsonify({
351
+ 'clustered_topics': clustered_topics,
352
+ 'special_timetable': special_timetable
353
+ })
354
+
355
+
356
+ @app.route('/ai_timetable')
357
+ def ai_timetable():
358
+ return render_template('ai_timetable.html')
359
+
360
+ @app.route('/summarise_video')
361
+ def summarise_video():
362
+ return render_template('student_summarise_video.html')
363
+
364
+ @app.route('/summarize_video', methods=['POST'])
365
+ def summarize_video_route():
366
+ data = request.json
367
+ url = data.get('url')
368
+ if url:
369
+ try:
370
+ summary = summarise_text(url)
371
+ return jsonify({'summary': summary})
372
+ except Exception as e:
373
+ return jsonify({'error': str(e)}), 500
374
+ else:
375
+ return jsonify({'error': 'No URL provided'}), 400
376
+
377
+
378
+ @app.route('/generate-questions-hw', methods=['GET'])
379
+ def generate_questions():
380
+ messages = [
381
+ {"role": "system", "content": "You are a helpful assistant."},
382
+ {"role": "user", "content": (
383
+ "Generate 5 questions for a Math Assignment on 'trigonometry Basics'. "
384
+ "Include a mix of both theoretical and numerical questions."
385
+ )}
386
+ ]
387
+
388
+ questions = []
389
+ for chunk in AI71(AI71_API_KEY).chat.completions.create(
390
+ model="tiiuae/falcon-180b-chat",
391
+ messages=messages,
392
+ stream=True,
393
+ ):
394
+ if chunk.choices[0].delta.content:
395
+ questions.append(chunk.choices[0].delta.content)
396
+
397
+ # Join all chunks to create the complete list of questions
398
+ complete_questions = ''.join(questions).split('\n')
399
+
400
+ return jsonify({'questions': complete_questions})
401
+
402
+ @app.route('/assign_grade', methods=['POST'])
403
+ def assign_grade():
404
+ data = request.json
405
+ result = data['result']
406
+ total_score, max_possible_score, percentage, grade = calculate_score_and_grade(result)
407
+ return jsonify({
408
+ 'total_score': total_score,
409
+ 'max_possible_score': max_possible_score,
410
+ 'percentage': percentage,
411
+ 'grade': grade
412
+ })
413
+
414
+ @app.route('/generate_timetable', methods=['POST'])
415
+ def generate_timetable():
416
+ data = request.json
417
+ hours_per_day = data.get('hours_per_day')
418
+ days_per_week = data.get('days_per_week')
419
+ semester_end_date = data.get('semester_end_date')
420
+ subjects = data.get('subjects', [])
421
+
422
+ # Input validation
423
+ if not hours_per_day or not days_per_week or not semester_end_date or not subjects:
424
+ return jsonify({"error": "Missing required parameters"}), 400
425
+
426
+ try:
427
+ timetable=generate_timetable_module(data,hours_per_day,days_per_week,semester_end_date,subjects)
428
+
429
+ return jsonify({"timetable": timetable})
430
+
431
+ except Exception as e:
432
+ return jsonify({"error": str(e)}), 500
433
+
434
+
435
+ @app.route('/generate-paper', methods=['GET', 'POST'])
436
+ def generate_paper():
437
+ if request.method == 'POST':
438
+ no_of_questions = int(request.form['no_of_questions'])
439
+ total_marks = int(request.form['total_marks'])
440
+ no_of_parts = int(request.form['no_of_parts'])
441
+ marks_per_part = int(request.form['marks_per_part'])
442
+ test_duration = request.form['test_duration']
443
+ pdf_file = request.files['pdf_file']
444
+
445
+ if pdf_file:
446
+ # Secure the file name and save the file to the upload folder
447
+ filename = secure_filename(pdf_file.filename)
448
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
449
+ pdf_file.save(file_path)
450
+
451
+ # Extract text from the curriculum PDF
452
+ curriculum_text = extract_text_from_pdf(file_path)
453
+
454
+ # Generate questions
455
+ questions = generate_questions_from_text(curriculum_text, no_of_questions, marks_per_part, no_of_parts)
456
+
457
+ # Optionally, remove the saved file after use
458
+ os.remove(file_path)
459
+
460
+ return render_template('teacher_paper_gen.html', questions=questions)
461
+
462
+ return render_template('teacher_paper_gen.html')
463
+
464
+
465
+ @app.route('/eval', methods=['GET', 'POST'])
466
+ def eval():
467
+ if request.method == 'POST':
468
+ input_type = request.form['input_type']
469
+ question_text = ""
470
+ answer_text = ""
471
+ max_marks = request.form['max_marks']
472
+
473
+ if input_type == 'file':
474
+ question_file = request.files['question_file']
475
+ answer_file = request.files['answer_file']
476
+
477
+ if question_file and answer_file:
478
+ question_path = os.path.join(app.config['UPLOAD_FOLDER'], question_file.filename)
479
+ answer_path = os.path.join(app.config['UPLOAD_FOLDER'], answer_file.filename)
480
+
481
+ question_file.save(question_path)
482
+ answer_file.save(answer_path)
483
+
484
+ if question_path.endswith('.pdf'):
485
+ question_text = extract_text_from_pdf(question_path)
486
+ else:
487
+ question_text = extract_text_from_image(question_path)
488
+
489
+ if answer_path.endswith('.pdf'):
490
+ answer_text = extract_text_from_pdf(answer_path)
491
+ else:
492
+ answer_text = extract_text_from_image(answer_path)
493
+
494
+ elif input_type == 'text':
495
+ question_text = request.form['question_text']
496
+ answer_text = request.form['answer_text']
497
+
498
+ evaluation_result = evaluate(question_text, answer_text, max_marks)
499
+ print(f"Question Text: {question_text}") # Debugging line
500
+ print(f"Answer Text: {answer_text}") # Debugging line
501
+ print(f"Evaluation Result: {evaluation_result}") # Debugging line
502
+
503
+ return render_template('teacher_result.html', result=evaluation_result)
504
+
505
+ return render_template('teacher_eval.html')
506
+
507
+ @app.route('/get_students')
508
+ def get_students():
509
+
510
+ return jsonify(student_data)
511
+
512
+
513
+ @app.route('/get_audio_files', methods=['GET'])
514
+ def get_audio_files():
515
+ audio_folder = os.path.join(app.root_path, 'speech')
516
+ audio_files = [{'name': file, 'url': f'/speech/{file}'} for file in os.listdir(audio_folder) if
517
+ file.endswith('.mp3')]
518
+
519
+ current_app.logger.info(f"Found audio files: {audio_files}")
520
+
521
+ return jsonify({'audio_files': audio_files})
522
+
523
+
524
+ @app.route('/speech/<path:filename>')
525
+ def serve_audio(filename):
526
+ return send_from_directory(os.path.join(app.root_path, 'speech'), filename)
527
+
528
+
529
+
530
+ @app.route('/generate_report', methods=['POST'])
531
+ def generate_report():
532
+ student_data = request.json
533
+ report = generate_student_report(
534
+ student_data['name'],
535
+ student_data['age'],
536
+ student_data['cgpa'],
537
+ student_data['course_pursuing'],
538
+ student_data['assigned_test_score'],
539
+ student_data['ai_test_score'],
540
+ student_data['interests'],
541
+ student_data['areas_to_improve'],
542
+ student_data['courses_taken']
543
+ )
544
+ return jsonify({'report': report})
545
+
546
+
547
+
548
+
549
+ if __name__ == '__main__':
550
+ directory = Path('uploads')
551
+ if os.path.exists('uploads'):
552
+ shutil.rmtree('uploads')
553
+ directory.mkdir(parents=True, exist_ok=True)
554
+ else:
555
+ directory.mkdir(parents=True, exist_ok=True)
556
+ app.run( port=5000, debug=True)
557
+