ghtmarco commited on
Commit
b2691e2
·
verified ·
1 Parent(s): 5fa79f1

Upload schedule_ai.py

Browse files
Files changed (1) hide show
  1. src/schedule_ai.py +214 -0
src/schedule_ai.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import os
3
+ from dotenv import load_dotenv
4
+ import re
5
+ import joblib
6
+ import pandas as pd
7
+ import numpy as np
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+ class SimpleScheduler:
11
+ def __init__(self):
12
+ load_dotenv()
13
+ api_key = os.getenv('GEMINI_API_KEY')
14
+ genai.configure(api_key=api_key)
15
+ self.model = genai.GenerativeModel('gemini-2.0-flash-exp')
16
+
17
+ # Load ML model dan scaler
18
+ try:
19
+ self.rf_model = joblib.load('Models/random_forest_model.pkl')
20
+ self.scaler = joblib.load('Models/scaler.pkl')
21
+ except Exception as e:
22
+ print(f"Warning: Could not load ML models: {str(e)}")
23
+ self.rf_model = None
24
+ self.scaler = None
25
+
26
+ def generate_schedule(self, duration, goals, available_hours, considerations):
27
+ """Generate schedule using Gemini with improved formatting"""
28
+ duration_lower = duration.lower()
29
+
30
+ # Select appropriate prompt based on duration
31
+ if "year" in duration_lower:
32
+ prompt = self._create_yearly_prompt(goals, available_hours, considerations)
33
+ elif "month" in duration_lower:
34
+ prompt = self._create_monthly_prompt(goals, available_hours, considerations)
35
+ else: # weekly
36
+ prompt = self._create_weekly_prompt(goals, available_hours, considerations)
37
+
38
+ try:
39
+ response = self.model.generate_content(prompt)
40
+ return self._format_output(response.text, duration, goals, available_hours, considerations)
41
+ except Exception as e:
42
+ raise Exception(f"Error generating schedule: {str(e)}")
43
+
44
+ def _get_priority(self, hour):
45
+ """Determine priority based on hour of day"""
46
+ if hour < 12:
47
+ return "HIGH"
48
+ elif hour < 15:
49
+ return "MEDIUM"
50
+ else:
51
+ return "LOW"
52
+
53
+ def _format_time(self, time_str):
54
+ """Format time string consistently"""
55
+ # Remove any spaces and AM/PM
56
+ time_str = time_str.replace(" ", "").upper()
57
+
58
+ # Convert to 24-hour format if needed
59
+ if "AM" in time_str or "PM" in time_str:
60
+ hour = int(time_str.split(":")[0])
61
+ if "PM" in time_str and hour != 12:
62
+ hour += 12
63
+ return f"{hour:02d}:00"
64
+
65
+ return time_str
66
+
67
+ def _format_output(self, schedule, duration, goals, available_hours, considerations):
68
+ """Format the output with clean and consistent structure"""
69
+
70
+ # Create header
71
+ header = f"""SCHEDULE OVERVIEW
72
+ -------------------------------------------
73
+ Duration: {duration}
74
+ Goals: {goals}
75
+ Available Hours: {available_hours} hours/day
76
+ Considerations: {considerations}
77
+ -------------------------------------------\n"""
78
+
79
+ # Process schedule content
80
+ formatted_schedule = ""
81
+ current_section = None
82
+
83
+ for line in schedule.strip().split('\n'):
84
+ line = line.strip()
85
+
86
+ # Skip unnecessary lines
87
+ if not line or "[Continue" in line or "rest" in line.lower():
88
+ continue
89
+
90
+ # Process QUARTER sections for yearly schedule
91
+ if "QUARTER" in line.upper():
92
+ formatted_schedule += f"\n{line}\n{'=' * len(line)}\n"
93
+ continue
94
+
95
+ # Process Week sections
96
+ elif "WEEK" in line.upper() and "-" in line:
97
+ week_info = line.replace('**', '').strip()
98
+ formatted_schedule += f"\n{week_info}\n{'-' * len(week_info)}\n"
99
+ continue
100
+
101
+ # Process day headers for weekly schedule
102
+ elif any(day in line.upper() for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']):
103
+ day = line.split(':')[0].strip()
104
+ formatted_schedule += f"\n{day}:\n"
105
+ continue
106
+
107
+ # Process time blocks
108
+ elif ':' in line:
109
+ try:
110
+ # Split into time and task
111
+ parts = line.split(':', 1)
112
+ if len(parts) < 2:
113
+ continue
114
+
115
+ time_str = self._format_time(parts[0])
116
+ task = parts[1].strip()
117
+
118
+ # Clean up task text
119
+ task = task.split('[')[0].strip() # Remove existing priority if any
120
+
121
+ # Get hour for priority
122
+ hour = int(time_str.split(':')[0])
123
+ priority = self._get_priority(hour)
124
+
125
+ # Format schedule entry
126
+ formatted_schedule += f" {time_str}: {task} [{priority}]\n"
127
+ except Exception:
128
+ # If processing fails, add line as is
129
+ formatted_schedule += f" {line}\n"
130
+
131
+ # Add other lines that might be important
132
+ elif line.strip() and not line.startswith('*'):
133
+ formatted_schedule += f"{line}\n"
134
+
135
+ return header + formatted_schedule
136
+
137
+ def _create_weekly_prompt(self, goals, available_hours, considerations):
138
+ return f"""
139
+ Create a WEEKLY schedule for: {goals}
140
+ Available Hours: {available_hours}/day
141
+ Consider: {considerations}
142
+
143
+ Format exactly as follows:
144
+
145
+ MONDAY:
146
+ 09:00: [Morning activity]
147
+ 10:00: [Morning activity]
148
+ 11:00: [Morning activity]
149
+ 12:00: Lunch Break
150
+ 13:00: [Afternoon activity]
151
+ 14:00: [Afternoon activity]
152
+ 15:00: [Late activity]
153
+ 16:00: [Break/Gym if needed]
154
+
155
+ TUESDAY:
156
+ [Same format]
157
+
158
+ Continue for each day including SATURDAY and SUNDAY.
159
+ Use 24-hour format (09:00, 14:00).
160
+ Keep descriptions brief and specific.
161
+ Include breaks and considerations.
162
+ """
163
+
164
+ def _create_monthly_prompt(self, goals, available_hours, considerations):
165
+ return f"""
166
+ Create a MONTHLY schedule for: {goals}
167
+ Available Hours: {available_hours}/day
168
+ Consider: {considerations}
169
+
170
+ Format as follows:
171
+
172
+ WEEK 1:
173
+ Monday-Friday:
174
+ 09:00: [Morning activity]
175
+ 10:00: [Morning activity]
176
+ 11:00: [Morning activity]
177
+ 12:00: Lunch Break
178
+ 13:00: [Afternoon activity]
179
+ 14:00: [Afternoon activity]
180
+ 15:00: [Late activity]
181
+ 16:00: [Break/Gym if needed]
182
+
183
+ WEEK 2:
184
+ [Same format]
185
+
186
+ Continue for 4 weeks.
187
+ Use 24-hour format.
188
+ Keep descriptions brief and specific.
189
+ Include breaks and considerations.
190
+ """
191
+
192
+ def _create_yearly_prompt(self, goals, available_hours, considerations):
193
+ return f"""
194
+ Create a YEARLY schedule for: {goals}
195
+ Available Hours: {available_hours}/day
196
+ Consider: {considerations}
197
+
198
+ Format exactly as:
199
+
200
+ QUARTER 1 (January-March)
201
+
202
+ Week 1-4 - [Phase Name]
203
+ 09:00: [Primary morning activity]
204
+ 11:00: [Late morning activity]
205
+ 14:00: [Afternoon activity]
206
+
207
+ Week 5-8 - [Next Phase]
208
+ [Same format]
209
+
210
+ Continue for all quarters.
211
+ Use 24-hour format.
212
+ Focus on major milestones.
213
+ Keep descriptions brief and specific.
214
+ """