abhi-bit-2/Genetic_Algorithm
0
1from fastapi import FastAPI, HTTPException2from fastapi.middleware.cors import CORSMiddleware3from typing import List, Optional4import sqlite35import os6from simplified_genetic_algorithm import genetic_algorithm7from db_operations import initialize_database, fetch_data_from_db, insert_timetable_into_db8 9app = FastAPI(title="Timetable Generator API")10 11# Add CORS middleware12app.add_middleware(13 CORSMiddleware,14 allow_origins=["*"],15 allow_credentials=True,16 allow_methods=["*"],17 allow_headers=["*"],18)19 20# Initialize database on startup21@app.on_event("startup")22async def startup_event():23 if not os.path.exists("timetable.db"):24 print("Initializing database...")25 initialize_database()26 27@app.get("/")28async def root():29 return {"message": "Welcome to the Timetable Generator API", "status": "running"}30 31@app.post("/generate")32async def generate_timetable(generations: int = 100):33 try:34 # Fetch branches35 with sqlite3.connect("timetable.db") as conn:36 cursor = conn.cursor()37 cursor.execute("SELECT branch_name FROM branches")38 branches = [branch[0] for branch in cursor.fetchall()]39 40 if not branches:41 raise HTTPException(status_code=400, detail="No branches found in database")42 43 # Run genetic algorithm44 result = genetic_algorithm(branches, generations=generations)45 46 if result:47 schedule, professor_schedules = result48 # Save to DB49 insert_timetable_into_db(schedule)50 51 # Format output for JSON52 formatted_schedule = []53 for day in range(len(schedule)):54 for slot in range(len(schedule[day])):55 slot_data = schedule[day][slot]56 if slot_data:57 if isinstance(slot_data, list):58 for class_data in slot_data:59 formatted_schedule.append({60 "day": day,61 "slot": slot,62 "course_code": class_data.course_code,63 "course_name": class_data.course_name,64 "teacher": class_data.teacher,65 "room": class_data.room,66 "branch": class_data.branch67 })68 else:69 formatted_schedule.append({70 "day": day,71 "slot": slot,72 "course_code": slot_data.course_code,73 "course_name": slot_data.course_name,74 "teacher": slot_data.teacher,75 "room": slot_data.room,76 "branch": slot_data.branch77 })78 79 return {80 "status": "success",81 "message": "Timetable generated successfully",82 "data": formatted_schedule83 }84 else:85 raise HTTPException(status_code=500, detail="Failed to generate a valid timetable")86 87 except Exception as e:88 raise HTTPException(status_code=500, detail=str(e))89 90@app.get("/timetable")91async def get_timetable():92 try:93 with sqlite3.connect("timetable.db") as conn:94 conn.row_factory = sqlite3.Row95 cursor = conn.cursor()96 cursor.execute("SELECT * FROM timetable")97 rows = cursor.fetchall()98 return [dict(row) for row in rows]99 except Exception as e:100 raise HTTPException(status_code=500, detail=str(e))101 102@app.post("/initialize")103async def init_db():104 try:105 initialize_database()106 return {"status": "success", "message": "Database initialized with sample data"}107 except Exception as e:108 raise HTTPException(status_code=500, detail=str(e))109 110@app.get("/stats")111async def get_stats():112 try:113 with sqlite3.connect("timetable.db") as conn:114 cursor = conn.cursor()115 cursor.execute("SELECT COUNT(*) FROM branches")116 branches = cursor.fetchone()[0]117 cursor.execute("SELECT COUNT(*) FROM courses")118 courses = cursor.fetchone()[0]119 cursor.execute("SELECT COUNT(*) FROM teachers")120 teachers = cursor.fetchone()[0]121 return {122 "branches": branches,123 "courses": courses,124 "teachers": teachers125 }126 except Exception as e:127 raise HTTPException(status_code=500, detail=str(e))128 129@app.post("/courses")130async def add_new_course(course_code: str, course_name: str, branch_name: str):131 try:132 from db_operations import add_course133 success = add_course(course_code, course_name, branch_name)134 if success:135 return {"status": "success", "message": f"Course {course_code} added"}136 else:137 raise HTTPException(status_code=400, detail="Failed to add course")138 except Exception as e:139 raise HTTPException(status_code=500, detail=str(e))140 141@app.delete("/courses/{course_code}")142async def remove_course(course_code: str):143 try:144 from db_operations import delete_course145 success = delete_course(course_code)146 if success:147 return {"status": "success", "message": f"Course {course_code} deleted"}148 else:149 raise HTTPException(status_code=400, detail="Failed to delete course")150 except Exception as e:151 raise HTTPException(status_code=500, detail=str(e))152 153@app.get("/branches")154async def list_branches():155 try:156 with sqlite3.connect("timetable.db") as conn:157 cursor = conn.cursor()158 cursor.execute("SELECT branch_name FROM branches")159 return [r[0] for r in cursor.fetchall()]160 except Exception as e:161 raise HTTPException(status_code=500, detail=str(e))162 163if __name__ == "__main__":164 import uvicorn165 uvicorn.run(app, host="0.0.0.0", port=8000)166 