Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import pandas as pd | |
| import datetime | |
| from openai import OpenAI | |
| import os | |
| # π Setup API Key (store as HF_SECRET) | |
| openai_api_key = os.getenv("OPENAI_API_KEY") | |
| client = OpenAI(api_key=openai_api_key) | |
| def generate_plan(subjects, exam_date, hours_per_day): | |
| subjects = [s.strip() for s in subjects.split(",")] | |
| exam_date = pd.to_datetime(exam_date) | |
| today = pd.to_datetime("today").normalize() | |
| total_days = (exam_date - today).days | |
| if total_days <= 0 or not subjects: | |
| return "Invalid input", None, None | |
| total_hours = total_days * hours_per_day | |
| hours_per_subject = total_hours // len(subjects) | |
| # Simple schedule | |
| schedule = [] | |
| for i in range(total_days): | |
| date = today + pd.Timedelta(days=i) | |
| subject = subjects[i % len(subjects)] | |
| schedule.append({ | |
| "Date": date.date(), | |
| "Subject": subject, | |
| "Hours": round(hours_per_day / len(subjects), 2) | |
| }) | |
| df = pd.DataFrame(schedule) | |
| # Generate Tip from LLM | |
| prompt = f"""Generate a short, motivating study tip for a student studying {', '.join(subjects)} with {hours_per_day} hours per day until {exam_date.date()}.""" | |
| response = client.chat.completions.create( | |
| model="gpt-4", | |
| messages=[{"role": "user", "content": prompt}] | |
| ) | |
| tip = response.choices[0].message.content.strip() | |
| return tip, df, df.to_csv(index=False) | |
| # Gradio interface | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## π Personalized Study Plan Generator") | |
| subjects = gr.Textbox(label="Enter subjects (comma-separated)") | |
| exam_date = gr.Textbox(label="Enter exam date (YYYY-MM-DD)") | |
| hours = gr.Slider(1, 12, step=1, label="Hours per day") | |
| btn = gr.Button("Generate Plan") | |
| output_tip = gr.Textbox(label="AI Study Tip") | |
| output_table = gr.Dataframe(label="Study Plan") | |
| download_csv = gr.File(label="Download CSV") | |
| def generate_and_show(subjects, exam_date, hours): | |
| tip, df, csv = generate_plan(subjects, exam_date, hours) | |
| with open("study_plan.csv", "w") as f: | |
| f.write(csv) | |
| return tip, df, "study_plan.csv" | |
| btn.click(fn=generate_and_show, inputs=[subjects, exam_date, hours], | |
| outputs=[output_tip, output_table, download_csv]) | |
| demo.launch() | |