Spaces:
Sleeping
Sleeping
| # app/main.py | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| import openai | |
| import json | |
| from datetime import datetime | |
| import os | |
| from typing import List, Dict, Any | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| # Initialize FastAPI | |
| app = FastAPI() | |
| # Define input schema | |
| class RoadmapInput(BaseModel): | |
| start_date: str # YYYY-MM-DD | |
| end_date: str # YYYY-MM-DD | |
| subject_name: str | |
| chapter_names: List[str] | |
| # Utility functions | |
| def findtoday(): | |
| return datetime.today().date() | |
| def generate_roadmap(user_persona, sys_prompt): | |
| """Generate roadmap using OpenAI API""" | |
| try: | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4o-mini", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": sys_prompt + "MAKE SURE YOU VERY VERY STRICTLY FOLLOW THE JSON STRUCTURE LOGICALLY BECAUSE I WILL PARSE YOUR OUTPUT TO JSON. DO NOT GIVEN ANYTHING ELSE IN THE OUPUT EXPECT A JSON OUTPUT IN STRING FORMAT" | |
| }, | |
| { | |
| "role": "user", | |
| "content": user_persona | |
| } | |
| ] | |
| ) | |
| answer = response['choices'][0]['message']['content'].strip() | |
| if not answer: | |
| raise ValueError("Received empty response from the API.") | |
| # Debugging: Log the raw response | |
| print("Raw API Response:", answer) | |
| # Parse the JSON | |
| parsed_json = json.loads(answer) | |
| return parsed_json | |
| except json.JSONDecodeError as e: | |
| raise HTTPException(status_code=500, detail=f"Error parsing JSON: {e}. Response: {answer}") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error generating roadmap: {e}") | |
| # API endpoint | |
| def generate_roadmap_endpoint(input_data: RoadmapInput): | |
| # Load JSON data for subjects (example structure) | |
| with open('Physics.json', 'r', encoding='utf-8') as file: | |
| phy = json.load(file) | |
| with open('Chemistry.json', 'r', encoding='utf-8') as file: | |
| chem = json.load(file) | |
| with open('Maths.json', 'r', encoding='utf-8') as file: | |
| maths = json.load(file) | |
| # Helper function to filter chapters | |
| def filter_chapter(subject_data, chapter_name): | |
| subject_data["chapters"] = [chapter for chapter in subject_data["chapters"] if chapter["chapter"] == chapter_name] | |
| return subject_data | |
| # Get chapter data | |
| chapters = [] | |
| for chapter_name in input_data.chapter_names: | |
| if input_data.subject_name.lower() == 'physics': | |
| chapters.append(filter_chapter(phy, chapter_name)) | |
| elif input_data.subject_name.lower() == 'chemistry': | |
| chapters.append(filter_chapter(chem, chapter_name)) | |
| elif input_data.subject_name.lower() == 'maths': | |
| chapters.append(filter_chapter(maths, chapter_name)) | |
| # User persona and system prompt | |
| user_persona = f""" | |
| You are required to generate a highly personalized roadmap for a student focusing on the subject: {input_data.subject_name} with chapters: {input_data.chapter_names}. | |
| The roadmap must include tasks for the following aspects: | |
| 1. Concept Understanding | |
| 2. Question Practice | |
| 3. Revision | |
| 4. Test (scheduled on the end date: {input_data.end_date}) | |
| The roadmap must have the following additional requirements: | |
| - Include a `date` field for each day's schedule. | |
| - Ensure all tasks are completed within the date range ({input_data.start_date} to {input_data.end_date}). | |
| - Allocate sufficient time for each task, focusing on thorough understanding and exam readiness. | |
| - Today's date is {findtoday()}. | |
| Focus strictly on the subject: '{input_data.subject_name}' with chapters: '{input_data.chapter_names}'. | |
| Subtopics for this chapter: {chapters}. | |
| """ | |
| output_structure = """{ | |
| "schedule": [ | |
| { | |
| "dayNumber": int, | |
| "date": YYYY-MM-DD, | |
| "subjects": [ | |
| { | |
| "name": "string", | |
| "tasks": [ | |
| { | |
| "ChapterName": "string", | |
| "type": "string", | |
| "topic": "string", | |
| "time": "string" | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| """ | |
| sys_prompt = f""" | |
| You are required to generate a highly personalized roadmap for a student in {input_data.subject_name} for the JEE Main exam. | |
| Focus only on the chapters: {input_data.chapter_names}. | |
| Include all the subtopics; the hours can be reduced as it is revision only, but make sure you include all the subtopics. | |
| The roadmap must adhere to the JSON structure below: | |
| {output_structure} | |
| Make sure: | |
| 1. The roadmap starts on {input_data.start_date} and ends on {input_data.end_date}. Do not include any extra fields and make sure the roadmap structure is logically correct according to JSON. | |
| 2. A test is scheduled on the end date. | |
| 3. The tasks include "Revision of Concept Understanding," "Revision of Question Practice," and "Practice Test." | |
| IMPORTANT: The output should not include any other words like 'json' etc. at the start it should only start with "curly braces" of the json output | |
| """ | |
| # Generate the roadmap | |
| roadmap = generate_roadmap(user_persona, sys_prompt) | |
| return roadmap | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) |