SstudizeSA/roadmapV2
0
1import json2from fastapi import FastAPI, HTTPException3from pydantic import BaseModel4import openai5from typing import List, Dict, Any6import os7 8app = FastAPI()9 10# Pydantic models for request body11class StudyInput(BaseModel):12 overall_study_pattern: str13 memorization_study_pattern: str14 problem_solving_study_pattern: str15 visualization_study_pattern: str16 obstacle_study_pattern: str17 new_topic_approach: str18 old_topic_approach: str19 topic_ratio: str20 hours_of_study: str21 hours_of_study_weekends: str22 revision_days: str23 test_days: str24 physicsStartIndex: int25 chemistryStartIndex: int26 mathematicsStartIndex: int27 completed_phy_chapters: List[str]28 completed_chem_chapters: List[str]29 completed_maths_chapters: List[str]30 31# Function to remove completed chapters32def remove_completed_chapters(subject_data, completed_chapters):33 subject_data["chapters"] = [chapter for chapter in subject_data["chapters"]34 if chapter["chapter"] not in completed_chapters]35 return subject_data36 37# Function to get data at index38def get_data_at_index(json_data, index):39 if 0 <= index < len(json_data['chapters']):40 return json_data['chapters'][index]41 else:42 return {}43 44@app.post("/generate_roadmap")45async def generate_roadmap(study_input: StudyInput):46 # Load JSON data for each subject47 # Note: You'll need to adjust the file paths or include these JSON files in your Docker image48 with open('Physics.json', 'r', encoding='utf-8') as file:49 phy = json.load(file)50 with open('Chemistry.json', 'r', encoding='utf-8') as file:51 chem = json.load(file)52 with open('Maths.json', 'r', encoding='utf-8') as file:53 maths = json.load(file)54 55 # Remove completed chapters56 phy = remove_completed_chapters(phy, study_input.completed_phy_chapters)57 chem = remove_completed_chapters(chem, study_input.completed_chem_chapters)58 maths = remove_completed_chapters(maths, study_input.completed_maths_chapters)59 60 # Get data at specified indices61 phy = get_data_at_index(phy, study_input.physicsStartIndex)62 chem = get_data_at_index(chem, study_input.chemistryStartIndex)63 maths = get_data_at_index(maths, study_input.mathematicsStartIndex)64 # Prepare user persona65 user_persona = f"""66 You are required to generate a highly personalized roadmap for a student studying Physics, Chemistry, and Mathematics for the JEE Main exam.67 The roadmap should be tailored based on the following student-specific details:68 69 1. *Study Preferences:*70 - Study Pattern: {study_input.overall_study_pattern}71 - Memorization Approach: {study_input.memorization_study_pattern}72 - Problem-Solving Approach: {study_input.problem_solving_study_pattern}73 - Visualization Approach: {study_input.visualization_study_pattern}74 75 2. *Handling Challenges:*76 - If unable to understand a topic: {study_input.obstacle_study_pattern}77 - Approach to New Topics: {study_input.new_topic_approach}78 - Approach to Previously Encountered Topics: {study_input.old_topic_approach}79 80 3. *Study Hours:*81 - Weekdays: {study_input.hours_of_study} hours/day82 - Weekends: {study_input.hours_of_study_weekends} hours/day83 - Time Allocation Ratio (Physics:Chemistry:Mathematics): {study_input.topic_ratio}84 - By weekdays I mean day 1, day 2 , day 3 , day 4 , day 585 - By weekends I mean day 6 , day 786 4. *Revision and Test Strategy:*87 - The days of the week when you do revision : {study_input.revision_days}88 - The days of the week when you give tests : {study_input.test_days}89 """90 output_structure = """{91 "schedule": [92 {93 "dayNumber": int,94 "subjects": [95 {96 "name": "string",97 "tasks": [98 {99 "type": "string",100 "topic": "string",101 "time": "string"102 }103 ]104 }105 ]106 }107 ]108}109"""110 # Prepare system prompt111 sys_prompt = f"""112 You are required to generate a highly personalized roadmap for a student studying Physics, Chemistry, and Mathematics for the JEE Main exam.113 The roadmap should be tailored based on the following student-specific details:114 115 The roadmap must be provided in the following format:116 {output_structure}117 118 Do not include anything other than the roadmap, and ensure the focus remains strictly on the subjects {phy}, {chem}, and {maths} and associated chapters.119 MAKE SURE THAT YOU MAKE THE ROADMAP FOR ALL THE THREE CHAPTERS EACH OF PHYSICS , CHEMISTRY AND MATHS TO COMPLETE THOSE CHAPTERS WITH 4 ASPECTS i.e "CONCEPT UNDERSTANDING","QUESTION PRACTICE","REVISION","TEST". ALSO INCLUDE TIME FOR EACH TASK THAT YOU GENERATE120 MAKE SURE THAT WE FIRST COMPLETE 1) CONCEPT UNDERSTANDING , 2) QUESTION PRACTICE FOR EVERY SUBTOPIC AND THEN REVISION AND TEST FOR WHOLE CHAPTER TOGETHER.121 MAKE SURE THAT WE INCULDE EACH SUBTOPIC OF EACH CHAPTER FROM {phy},{chem} and {maths} IS FINISHED122 YOU ARE NOT CONSTRAINED TO CREATE A ROADMAP FOR ONLY 'X' NUMBER OF DAYS , YOU CAN EXTEND TILL THE TOPICS ARE FINISHED BUT ONLY STICK TO THE TIMEFRAME ALLOTED FOR EACH SUBJECT AND DO NOT GO ABOVE OR BELOW THAT TIME FRAME.123 Make sure you make the roadmap for 7-10 days only.124 """125 126 # Make OpenAI API call127 openai.api_key = os.getenv("KEY") # Replace with your actual API key or use environment variables128 try:129 response = openai.ChatCompletion.create(130 model="gpt-4o-mini",131 messages=[132 {133 "role": "system",134 "content": sys_prompt + "MAKE SURE YOU VERY VERY STRUCTLY FOLLOW THE JSON STRUCTURE BECAUSE I WILL PARSE YOUR OUTPUT TO JSON"135 },136 {137 "role": "user",138 "content": user_persona139 }140 ]141 )142 143 answer = response['choices'][0]['message']['content'].strip()144 145 # Second OpenAI API call146 response = openai.ChatCompletion.create(147 model="gpt-4o-mini",148 messages=[149 {150 "role": "system",151 "content": f'''152 you created a very good roadmap {answer} but you make sure that you dont forget any subtopics from Physics : {phy}, Chemistry : {chem} and Maths : {maths}. ensure that the style is same as the previous roadmap.153 MAKE SURE YOU VERY VERY STRUCTLY FOLLOW THE JSON STRUCTURE BECAUSE I WILL PARSE YOUR OUTPUT TO JSON.154 DO not include json at the top of the answer155 '''156 },157 {158 "role": "user",159 "content": "Generate"160 }161 ]162 )163 164 final_answer = response['choices'][0]['message']['content'].strip()165 parsed_json = json.loads(final_answer)166 167 return parsed_json168 except Exception as e:169 raise HTTPException(status_code=500, detail=str(e))170 171if __name__ == "__main__":172 import uvicorn173 uvicorn.run(app, host="0.0.0.0", port=8000)174 