Team Ai
Apppublic

abhi-bit-2/Genetic_Algorithm

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
frontend.py117 linesDownload Raw Back to root
1import gradio as gr2import requests3import pandas as pd4import os5 6BACKEND_URL = os.environ.get("BACKEND_URL", "http://localhost:8000")7 8def get_stats():9    try:10        response = requests.get(f"{BACKEND_URL}/stats")11        if response.status_code == 200:12            stats = response.json()13            return f"Branches: {stats['branches']} | Courses: {stats['courses']} | Teachers: {stats['teachers']}"14        return "Could not fetch stats"15    except:16        return "Backend not reachable"17 18def init_database():19    try:20        response = requests.post(f"{BACKEND_URL}/initialize")21        return response.json().get("message", "Success")22    except Exception as e:23        return f"Error: {str(e)}"24 25def add_course(code, name, branch):26    try:27        response = requests.post(f"{BACKEND_URL}/courses", params={28            "course_code": code,29            "course_name": name,30            "branch_name": branch31        })32        return response.json().get("message", "Success")33    except Exception as e:34        return f"Error: {str(e)}"35 36def generate_timetable(generations):37    try:38        response = requests.post(f"{BACKEND_URL}/generate", params={"generations": generations})39        if response.status_code == 200:40            data = response.json()41            if data["status"] == "success":42                return pd.DataFrame(data["data"]), "โœ… Generation Complete!"43            return None, f"Error: {data.get('detail', 'Unknown error')}"44        return None, f"Error: {response.text}"45    except Exception as e:46        return None, f"Exception: {str(e)}"47 48def get_current_timetable():49    try:50        response = requests.get(f"{BACKEND_URL}/timetable")51        if response.status_code == 200:52            data = response.json()53            if data:54                return pd.DataFrame(data)55            return pd.DataFrame(columns=["No data found"])56        return pd.DataFrame(columns=["Error fetching data"])57    except Exception as e:58        return pd.DataFrame(columns=[f"Exception: {str(e)}"])59 60def get_branches():61    try:62        response = requests.get(f"{BACKEND_URL}/branches")63        return response.json()64    except:65        return []66 67# UI Theme and Layout68with gr.Blocks(title="Timetable Generator") as demo:69    gr.Markdown("# ๐Ÿ—“๏ธ Institutional Timetable Generator")70    71    # ... (rest of the blocks code remains same)72    # I'll just replace the whole block for safety73 74    with gr.Row():75        stats_box = gr.Textbox(value=get_stats(), label="System Stats", interactive=False)76        refresh_btn = gr.Button("๐Ÿ”„ Refresh Stats", variant="secondary", size="sm")77    78    with gr.Tabs():79        with gr.Tab("Home & Database"):80            gr.Markdown("### โš™๏ธ Database Management")81            init_btn = gr.Button("๐Ÿ”จ Reinitialize Database with Sample Data", variant="stop")82            db_output = gr.Textbox(label="Database Status")83            init_btn.click(init_database, outputs=[db_output])84            85        with gr.Tab("Manage Courses"):86            gr.Markdown("### โž• Add New Course")87            with gr.Row():88                c_code = gr.Textbox(label="Course Code (e.g., CSE101)")89                c_name = gr.Textbox(label="Course Name")90                c_branch = gr.Dropdown(choices=get_branches(), label="Branch")91            92            add_btn = gr.Button("Add Course", variant="primary")93            add_output = gr.Textbox(label="Status")94            95            add_btn.click(add_course, inputs=[c_code, c_name, c_branch], outputs=[add_output])96            97        with gr.Tab("Generate Timetable"):98            gr.Markdown("### ๐Ÿงฌ Genetic Algorithm Engine")99            gen_slider = gr.Slider(minimum=10, maximum=300, value=100, step=10, label="Generations (Complexity)")100            gen_btn = gr.Button("๐Ÿš€ Start Generation Process", variant="primary")101            gen_status = gr.Textbox(label="Progress")102            gen_df = gr.DataFrame(label="Preview Result")103            104            gen_btn.click(generate_timetable, inputs=[gen_slider], outputs=[gen_df, gen_status])105            106        with gr.Tab("Final Timetable"):107            gr.Markdown("### ๐Ÿ“‹ View Generated Schedule")108            view_btn = gr.Button("๐Ÿ“ฅ Fetch Current Timetable", variant="primary")109            view_df = gr.DataFrame(label="Current Schedule")110            111            view_btn.click(get_current_timetable, outputs=[view_df])112 113    refresh_btn.click(get_stats, outputs=[stats_box])114 115if __name__ == "__main__":116    demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())117