Juggling commited on
Commit
0745697
·
verified ·
1 Parent(s): 339158a

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +3 -9
  2. requirements.txt +1 -0
  3. workshops.py +721 -0
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Schedule Buddy Updated
3
- emoji: 😻
4
- colorFrom: pink
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 5.9.1
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Schedule_Buddy_Updated
3
+ app_file: workshops.py
 
 
4
  sdk: gradio
5
+ sdk_version: 5.7.1
 
 
6
  ---
 
 
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ supabase
workshops.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import copy
3
+ import os
4
+ import gradio as gr
5
+ from collections import Counter
6
+ import random
7
+ import re
8
+ from datetime import date
9
+ import supabase
10
+ import json
11
+
12
+ ###### OG FUNCTIONS TO GENERATE SCHEDULES ######
13
+ # CONSTANTS
14
+ NAME_COL = 'Juggler_Name'
15
+ NUM_WORKSHOPS_COL = 'Num_Workshops'
16
+ AVAIL_COL = 'Availability'
17
+ DESCRIP_COL = 'Workshop_Descriptions'
18
+ DELIMITER = ';'
19
+
20
+ class Schedule:
21
+ def __init__(self, timeslots: dict):
22
+ self.num_timeslots_filled = 0
23
+ self.total_num_workshops = 0
24
+
25
+ for time,instructors in timeslots.items():
26
+ curr_len = len(instructors)
27
+ if curr_len > 0:
28
+ self.num_timeslots_filled += 1
29
+ self.total_num_workshops += curr_len
30
+
31
+ self.timeslots = timeslots
32
+
33
+ def add(self, person: str, time: str):
34
+ self.total_num_workshops += 1
35
+ if len(self.timeslots[time]) == 0:
36
+ self.num_timeslots_filled += 1
37
+ self.timeslots[time].append(person)
38
+
39
+ def remove(self, person: str, time: str):
40
+ self.total_num_workshops -= 1
41
+ if len(self.timeslots[time]) == 1:
42
+ self.num_timeslots_filled -= 1
43
+ self.timeslots[time].remove(person)
44
+
45
+
46
+ def print(self):
47
+ print(f"# timeslots filled: {self.num_timeslots_filled}")
48
+ print(f"# workshops: {self.total_num_workshops}")
49
+ for time,instructors in self.timeslots.items():
50
+ print(f"{time}: {', '.join(instructors)}")
51
+
52
+
53
+ # Returns True if the person can teach during the slot, and False otherwise
54
+ def can_teach(person: str, slot: list, capacity: int) -> bool:
55
+ if len(slot) == capacity or len(slot) > capacity:
56
+ return False
57
+
58
+ # No one can teach two workshops at once
59
+ if person in slot:
60
+ return False
61
+
62
+ return True
63
+
64
+
65
+ # Extracts relevant information from the df with availability and puts it into a useable format
66
+ def convert_df(df):
67
+ people = []
68
+ # Key: person's name
69
+ # Value: a list of their availability
70
+ availability = {}
71
+ seen = set()
72
+ for row in range(len(df)):
73
+ # TODO: make sure no people with the same name fill out the form
74
+ name = df.loc[row, NAME_COL]
75
+
76
+ number = df.loc[row, NUM_WORKSHOPS_COL]
77
+ if number == 1:
78
+ people.append(name)
79
+
80
+ # Add people who are teaching multiple workshops to the list more than once
81
+ else:
82
+ for i in range(number):
83
+ people.append(name)
84
+
85
+ curr_avail = df.loc[row, AVAIL_COL]
86
+ curr_avail = curr_avail.split(DELIMITER)
87
+ curr_avail = [elem.strip() for elem in curr_avail]
88
+ availability[name] = curr_avail
89
+
90
+ return people, availability
91
+
92
+
93
+
94
+ # Makes a dictionary where each key is a timeslot and each value is a list.
95
+ # If there's no partial schedule, each list will be empty.
96
+ # If there's a partial schedule, each list will include the people teaching during that slot.
97
+ def initialize_timeslots(df) -> dict:
98
+ all_timeslots = set()
99
+ availability = df[AVAIL_COL]
100
+ for elem in availability:
101
+ curr_list = elem.split(DELIMITER)
102
+ for inner in curr_list:
103
+ all_timeslots.add(inner.strip())
104
+
105
+ to_return = {}
106
+ for slot in all_timeslots:
107
+ to_return[slot] = []
108
+
109
+ return to_return
110
+
111
+
112
+ # Recursive function that generates all possible schedules
113
+ def find_all_schedules(people: list, availability: dict, schedule_obj: Schedule, capacity: int, schedules: list, max_timeslots_list: list, max_workshops_list: list) -> None:
114
+ if schedule_obj.num_timeslots_filled > max_timeslots_list[0] or schedule_obj.num_timeslots_filled == max_timeslots_list[0]:
115
+ schedules.append(copy.deepcopy(schedule_obj))
116
+ max_timeslots_list[0] = schedule_obj.num_timeslots_filled
117
+ # Keep track of total number of workshops taught
118
+ if schedule_obj.total_num_workshops > max_workshops_list[0] or schedule_obj.total_num_workshops == max_workshops_list[0]:
119
+ max_workshops_list[0] = schedule_obj.total_num_workshops
120
+
121
+ # Base case
122
+ if len(people) == 0:
123
+ return
124
+
125
+
126
+ # Recursive cases
127
+ person = people[0]
128
+
129
+ for time in availability[person]:
130
+ if can_teach(person, schedule_obj.timeslots[time], capacity):
131
+ # Choose (put that person in that timeslot)
132
+ schedule_obj.add(person, time)
133
+
134
+ # Explore (assign everyone else to timeslots based on that decision)
135
+ if len(people) == 1:
136
+ find_all_schedules([], availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
137
+
138
+ else:
139
+ find_all_schedules(people[1:len(people)], availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
140
+
141
+ # Unchoose (remove that person from the timeslot)
142
+ schedule_obj.remove(person, time)
143
+ # NOTE: this will not generate a full timeslot, but could still lead to a good schedule
144
+ else:
145
+ if len(people) == 1:
146
+ find_all_schedules([], availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
147
+ else:
148
+ find_all_schedules(people[1:len(people)], availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
149
+
150
+ return
151
+
152
+
153
+ # Puts the schedule in the correct order
154
+ def my_sort(curr_sched: dict, og_slots: list):
155
+ # example {'4 pm': ['logan', 'andrew'], '1 pm': ['graham', 'joyce'], '3 pm': ['logan', 'dan'], '2 pm': ['graham', 'dan']}
156
+ to_return = {}
157
+ for elem in og_slots:
158
+ if elem in curr_sched:
159
+ to_return[elem] = curr_sched[elem]
160
+ else:
161
+ to_return[elem] = []
162
+ return to_return
163
+
164
+
165
+ # Makes an organized DataFrame given a list of schedules
166
+ def make_df(schedules: list, descrip_dict: dict, og_slots: list):
167
+ all_times = []
168
+ all_instructors = []
169
+
170
+ count = 1
171
+
172
+ for i in range (len(schedules)):
173
+ curr_sched = schedules[i]
174
+
175
+ #sorted_dict = dict(sorted(curr_sched.items(), key=lambda item: item[0]))
176
+ sorted_dict = my_sort(curr_sched, og_slots)
177
+ curr_times = sorted_dict.keys()
178
+ curr_instructors = sorted_dict.values()
179
+
180
+ # Include an empty row between schedules
181
+ if count != 1:
182
+ all_times.append("")
183
+ all_instructors.append("")
184
+
185
+ if len(schedules) > 1 or len(schedules) == 1:
186
+ all_times.append(f"Schedule #{count}")
187
+ all_instructors.append("")
188
+ count += 1
189
+
190
+ for slot in curr_times:
191
+ all_times.append(slot)
192
+
193
+ for instructors in curr_instructors:
194
+ if len(descrip_dict) == 0:
195
+ all_instructors.append("; ". join(instructors))
196
+
197
+ if len(descrip_dict) > 0:
198
+ big_str = ""
199
+
200
+ for person in instructors:
201
+ if person in descrip_dict:
202
+ descrip = descrip_dict[person]
203
+ else:
204
+ descrip = "Workshop"
205
+
206
+ # {descrip} is a list bc they want to teach multiple workshops
207
+ if '\n' in descrip:
208
+ new_str = f"\n\n- {person}:\n{descrip}"
209
+ else:
210
+ new_str = f"\n\n- {person}: {descrip}"
211
+
212
+ big_str += new_str
213
+
214
+ all_instructors.append(big_str.strip())
215
+
216
+ if len(curr_instructors) == 0:
217
+ all_instructors.append('N/A')
218
+
219
+
220
+ new_df = pd.DataFrame({
221
+ "Schedule": all_times,
222
+ "Instructor(s)": all_instructors
223
+ })
224
+ new_df['Instructor(s)'] = new_df['Instructor(s)'].astype(str)
225
+
226
+ return new_df, count - 1
227
+
228
+
229
+
230
+
231
+
232
+ # Makes a dictionary where each key is the instructor's name and
233
+ # the value is the workshop(s) they're teaching
234
+ def get_description_dict(df):
235
+ new_dict = {}
236
+ for row in range(len(df)):
237
+ name = df.loc[row, NAME_COL]
238
+ new_dict[name] = df.loc[row, DESCRIP_COL]
239
+ return new_dict
240
+
241
+
242
+ # Classifies schedules into two categories: complete and incomplete:
243
+ # Complete = everyone is teaching desired number of timeslots and each timeslot is filled
244
+ # NOTE: I'm using "valid" instead of "complete" as a variable name so that I don't mix it up
245
+ # Incomplete = not complete
246
+ def classify_schedules(people: list, schedules: list, partial_names: list, total_timeslots: int, max_timeslots_filled: int) -> tuple:
247
+ valid_schedules = []
248
+
249
+ # Key: score
250
+ # Value: schedules with that score
251
+ incomplete_schedules = {}
252
+
253
+ # Get frequency of items in the list
254
+ # Key: person
255
+ # Value: number of workshops they WANT to teach
256
+ pref_dict = Counter(people)
257
+
258
+ pref_dict.update(Counter(partial_names))
259
+
260
+ all_names = pref_dict.keys()
261
+
262
+
263
+ ## Evaluate each schedule ##
264
+ overall_max = 0 # changes throughout the function
265
+
266
+ for sched in schedules:
267
+ if sched.num_timeslots_filled != max_timeslots_filled:
268
+ continue
269
+ # Key: person
270
+ # Value: how many workshops they're ACTUALLY teaching in this schedule
271
+ freq_dict = {}
272
+ for name in all_names:
273
+ freq_dict[name] = 0
274
+
275
+ for timeslot, instructor_list in sched.timeslots.items():
276
+ for instructor in instructor_list:
277
+ if instructor in freq_dict:
278
+ freq_dict[instructor] += 1
279
+ else:
280
+ print("there is a serious issue!!!!")
281
+
282
+ # See if everyone is teaching their desired number of workshops
283
+ everyone_is_teaching = True
284
+ for teacher, freq in freq_dict.items():
285
+ if freq != pref_dict[teacher]:
286
+ #print(f"teacher: {teacher}. preference: {pref_dict[teacher]}. actual frequency: {freq}")
287
+ everyone_is_teaching = False
288
+ break
289
+
290
+ filled_all_timeslots = (sched.num_timeslots_filled == total_timeslots)
291
+ if everyone_is_teaching and filled_all_timeslots:
292
+ valid_schedules.append(sched)
293
+ else:
294
+ # No need to add to incomplete_schedules if there's at least one valid schedule
295
+ if len(valid_schedules) > 0:
296
+ continue
297
+ #print(f"teaching desired number of timeslots: {everyone_is_teaching}. At least one workshop per slot: {filled_all_timeslots}.\n{sched}\n")
298
+ if sched.num_timeslots_filled > overall_max or sched.num_timeslots_filled == overall_max:
299
+ overall_max = sched.num_timeslots_filled
300
+
301
+ if sched.num_timeslots_filled not in incomplete_schedules:
302
+ incomplete_schedules[sched.num_timeslots_filled] = []
303
+ incomplete_schedules[sched.num_timeslots_filled].append(sched)
304
+
305
+
306
+
307
+ if len(valid_schedules) > 0:
308
+ return valid_schedules, []
309
+ else:
310
+ return [], incomplete_schedules[overall_max]
311
+
312
+
313
+
314
+ # Parameters: schedules that have the max number of timeslots filled
315
+ # Max number of workshops taught in filled timeslots
316
+ # Returns: a list of all schedules that have the max number of workshops
317
+ # To make it less overwhelming, it will return {cutoff} randomly
318
+ def get_best_schedules(schedules: list, cutoff: str, max_workshops: int) -> list:
319
+ cutoff = int(cutoff)
320
+ seen = []
321
+ best_schedules = []
322
+
323
+ for sched in schedules:
324
+ if sched.total_num_workshops != max_workshops:
325
+ continue
326
+
327
+ if sched in seen:
328
+ continue
329
+ else:
330
+ seen.append(sched)
331
+ best_schedules.append(sched.timeslots)
332
+
333
+ if cutoff == -1:
334
+ return best_schedules
335
+ else:
336
+ if len(best_schedules) > cutoff:
337
+ # Sample without replacement
338
+ return random.sample(best_schedules, cutoff)
339
+ else:
340
+ return best_schedules
341
+
342
+
343
+ # Big wrapper function that calls the other functions
344
+ def main(df, capacity:int, num_results: int, og_slots: list):
345
+ descrip_dict = get_description_dict(df)
346
+
347
+ # Convert the df with everyone's availability to a usable format
348
+ res = convert_df(df)
349
+ people = res[0]
350
+ availability = res[1]
351
+ print(availability)
352
+
353
+ partial_names = []
354
+
355
+ timeslots = initialize_timeslots(df)
356
+
357
+ schedules = []
358
+ schedule_obj = Schedule(timeslots)
359
+ max_timeslots_list = [0]
360
+ max_workshops_list = [0]
361
+
362
+ find_all_schedules(people, availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
363
+
364
+ total_timeslots = len(timeslots)
365
+
366
+
367
+ res = classify_schedules(people, schedules, partial_names, total_timeslots, max_timeslots_list[0])
368
+ valid_schedules = res[0]
369
+ decent_schedules = res[1]
370
+
371
+
372
+ # Return schedules
373
+ if len(valid_schedules) > 0:
374
+ best_schedules = get_best_schedules(valid_schedules, num_results, max_workshops_list[0])
375
+ res = make_df(best_schedules, descrip_dict, og_slots)
376
+ new_df = res[0]
377
+ count = res[1]
378
+ if count == 1:
379
+ results = "Good news! I was able to make a complete schedule."
380
+ else:
381
+ results = "Good news! I was able to make multiple complete schedules."
382
+
383
+ else:
384
+ best_schedules = get_best_schedules(decent_schedules, num_results, max_workshops_list[0])
385
+ res = make_df(best_schedules, descrip_dict, og_slots)
386
+ new_df = res[0]
387
+ count = res[1]
388
+ beginning = "Here"
389
+ if count == 1:
390
+ results = f"{beginning} is the best option."
391
+ else:
392
+ results = f"{beginning} are the best options."
393
+
394
+ #results += "(Remember that \"complete\" schedules are ones where everyone is teaching their desired number of workshops and every timeslot is filled.)"
395
+
396
+
397
+ directory = os.path.abspath(os.getcwd())
398
+ path = directory + "/schedule.csv"
399
+ new_df.to_csv(path, index=False)
400
+ return results, new_df, path
401
+
402
+
403
+
404
+
405
+ ##### ALL THE NEW STUFF WITH SUPABASE ETC. #####
406
+ ### CONSTANTS ###
407
+ NAME_COL = 'Juggler_Name'
408
+ NUM_WORKSHOPS_COL = 'Num_Workshops'
409
+ AVAIL_COL = 'Availability'
410
+ DESCRIP_COL = 'Workshop_Descriptions'
411
+ EMAIL_COL = 'Email'
412
+ DELIMITER = ';'
413
+ ALERT_TIME = None # leave warnings on screen indefinitely
414
+ FORM_NOT_FOUND = 'Form not found'
415
+ INCORRECT_PASSWORD = "The password is incorrect. Please check the password and try again. If you don't remember your password, please email [email protected]."
416
+ NUM_ROWS = 1
417
+ NUM_COLS_SCHEDULES = 2
418
+ NUM_COLS_ALL_RESPONSES = 4
419
+ NUM_RESULTS = 10 # randomly get {NUM_RESULTS} results
420
+
421
+
422
+ theme = gr.themes.Soft(
423
+ primary_hue="cyan",
424
+ secondary_hue="pink",
425
+ font=[gr.themes.GoogleFont('sans-serif'), 'ui-sans-serif', 'system-ui', 'Montserrat'],
426
+ )
427
+
428
+ ### Connect to Supabase ###
429
+ URL = os.environ['URL']
430
+ API_KEY = os.environ['API_KEY']
431
+ client = supabase.create_client(URL, API_KEY)
432
+
433
+
434
+
435
+
436
+ ### DEFINE FUNCTIONS ###
437
+ ## Multi-purpose function ##
438
+ '''
439
+ Returns a lowercased and stripped version of the schedule name.
440
+ Returns: str
441
+ '''
442
+ def standardize(schedule_name: str):
443
+ return schedule_name.lower().strip()
444
+
445
+
446
+
447
+
448
+
449
+
450
+ ## Functions to manage/generate schedules ##
451
+ '''
452
+ Uses the name and password to get the form.
453
+ Makes the buttons and other elements visible on the page.
454
+ Returns:
455
+ gr.Button: corresponds to find_form_btn
456
+ gr.Column: corresponds to all_responses_group
457
+ gr.Column: generate_schedules_explanation
458
+ gr.Row: corresponds to generate_btns
459
+ gr.Column: corresponds to open_close_btn_col
460
+ gr.Button: corresponds to open_close_btn
461
+ '''
462
+ def make_visible(schedule_name:str, password: str):
463
+ skip_output = gr.Button(), gr.Column(), gr.Column(), gr.Row(), gr.Column(), gr.Button()
464
+
465
+ if len(schedule_name) == 0:
466
+ gr.Warning('Please enter the form name.', ALERT_TIME)
467
+ return skip_output
468
+ if len(password) == 0:
469
+ gr.Warning('Please enter the password.', ALERT_TIME)
470
+ return skip_output
471
+
472
+
473
+ response = client.table('Forms').select('password', 'status').eq('form_name', standardize(schedule_name)).execute()
474
+ data = response.data
475
+
476
+ if len(data) > 0:
477
+ my_dict = data[0]
478
+ if password != my_dict['password']:
479
+ gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
480
+ return skip_output
481
+ else:
482
+ if my_dict['status'] == 'open':
483
+ gr.Info('', ALERT_TIME, title='Btw, the form is currently OPEN.')
484
+ return gr.Button(variant='secondary'), gr.Column(visible=True), gr.Column(visible=True), gr.Row(visible=True), gr.Column(visible=True), gr.Button("Close Form", visible=True)
485
+
486
+ elif my_dict['status'] == 'closed':
487
+ gr.Info('', ALERT_TIME, title='Btw, the form is currently CLOSED.')
488
+ return gr.Button(variant='secondary'), gr.Column(visible=True), gr.Column(visible=True), gr.Row(visible=True),gr.Column(visible=True), gr.Button("Open Form", visible=True)
489
+
490
+ else:
491
+ gr.Warning(f"There is no form called \"{schedule_name}\". Please check the spelling and try again.", ALERT_TIME)
492
+ return skip_output
493
+
494
+
495
+
496
+
497
+ '''
498
+ Makes a blank schedule that we can return to prevent things from breaking.
499
+ Returns: tuple with 3 elements:
500
+ 0: str indicating that the form wasn't found
501
+ 1: the DataFrame
502
+ 2: the path to the DataFrame
503
+ '''
504
+ def make_blank_schedule():
505
+ df = pd.DataFrame({
506
+ 'Schedule': [],
507
+ 'Instructors': []
508
+ })
509
+
510
+ directory = os.path.abspath(os.getcwd())
511
+ path = directory + "/schedule.csv"
512
+ df.to_csv(path, index=False)
513
+ return FORM_NOT_FOUND, df, path
514
+
515
+
516
+ '''
517
+ Gets a the form responses from Supabase and converts them to a DataFrame
518
+ Returns:
519
+ if found: a dictionary with three keys: capacity (int), df (DataFrame), and slots (list)
520
+ if not found: a string indicating the form was not found
521
+ '''
522
+ def get_df_from_db(schedule_name: str, password: str):
523
+ response = client.table('Forms').select('password', 'capacity', 'responses', 'slots').eq('form_name', standardize(schedule_name)).execute()
524
+ data = response.data
525
+
526
+ if len(data) > 0:
527
+ my_dict = data[0]
528
+ if password != my_dict['password']:
529
+ gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
530
+ return FORM_NOT_FOUND
531
+
532
+ # Convert to df
533
+ df = pd.DataFrame(json.loads(my_dict['responses']))
534
+ return {'capacity': my_dict['capacity'], 'df': df, 'slots': my_dict['slots']}
535
+
536
+ else:
537
+ gr.Warning(f"There is no form called \"{schedule_name}\". Please check the spelling and try again.", ALERT_TIME)
538
+ return FORM_NOT_FOUND
539
+
540
+
541
+ '''
542
+ Puts all of the form responses into a DataFrame.
543
+ Returns this DF along with the filepath.
544
+ '''
545
+ def get_all_responses(schedule_name:str, password:str):
546
+ res = get_df_from_db(schedule_name, password)
547
+
548
+ if res == FORM_NOT_FOUND:
549
+ df = pd.DataFrame({
550
+ NAME_COL: [],
551
+ EMAIL_COL: [],
552
+ NUM_WORKSHOPS_COL: [],
553
+ AVAIL_COL: [],
554
+ DESCRIP_COL: []
555
+ })
556
+
557
+ else:
558
+ df = res['df']
559
+ df[AVAIL_COL] = [elem.replace(DELIMITER, f"{DELIMITER} ") for elem in df[AVAIL_COL].to_list()]
560
+
561
+ directory = os.path.abspath(os.getcwd())
562
+ path = directory + "/all responses.csv"
563
+ df.to_csv(path, index=False)
564
+
565
+ if len(df) == 0:
566
+ gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
567
+ return gr.DataFrame(df, visible=True), gr.File(path, visible=True)
568
+
569
+
570
+ '''
571
+ Calls the algorithm to generate the best possible schedules,
572
+ and returns a random subset of the results.
573
+ (The same as generate_schedules_wrapper_all_results, except that this function only returns a subset of them.
574
+ I had to make it into two separate functions in order to work with Gradio).
575
+ Returns:
576
+ DataFrame
577
+ Filepath to DF (str)
578
+ '''
579
+ def generate_schedules_wrapper_subset_results(schedule_name: str, password: str):
580
+ res = get_df_from_db(schedule_name, password)
581
+ # Return blank schedule (should be impossible to get to this condition btw)
582
+ if res == FORM_NOT_FOUND:
583
+ to_return = make_blank_schedule()
584
+ gr.Warning(FORM_NOT_FOUND, ALERT_TIME)
585
+
586
+ else:
587
+ df = res['df']
588
+ if len(df) == 0:
589
+ gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
590
+ to_return = make_blank_schedule()
591
+ else:
592
+ gr.Info('', ALERT_TIME, title='Working on generating schedules! Please DO NOT click anything on this page.')
593
+ to_return = main(df, res['capacity'], NUM_RESULTS, res['slots'])
594
+ gr.Info('', ALERT_TIME, title=to_return[0])
595
+
596
+
597
+ return gr.Textbox(to_return[0]), gr.DataFrame(to_return[1], visible=True), gr.File(to_return[2], visible=True)
598
+
599
+
600
+ '''
601
+ Calls the algorithm to generate the best possible schedules,
602
+ and returns ALL of the results.
603
+ (The same as generate_schedules_wrapper_subset_results, except that this function returns all of them.
604
+ I had to make it into two separate functions in order to work with Gradio).
605
+ Returns:
606
+ DataFrame
607
+ Filepath to DF (str)
608
+ '''
609
+ def generate_schedules_wrapper_all_results(schedule_name: str, password: str):
610
+ res = get_df_from_db(schedule_name, password)
611
+ # Return blank schedule (should be impossible to get to this condition btw)
612
+ if res == FORM_NOT_FOUND:
613
+ to_return = make_blank_schedule()
614
+ gr.Warning(FORM_NOT_FOUND, ALERT_TIME)
615
+
616
+ else:
617
+ df = res['df']
618
+ if len(df) == 0:
619
+ gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
620
+ to_return = make_blank_schedule()
621
+ else:
622
+ gr.Info('', ALERT_TIME, title='Working on generating schedules! Please DO NOT click anything on this page.')
623
+ placeholder = -1
624
+ to_return = main(df, res['capacity'], placeholder, res['slots'])
625
+ gr.Info('', ALERT_TIME, title=to_return[0])
626
+
627
+ return gr.Textbox(to_return[0]), gr.DataFrame(to_return[1], visible=True), gr.File(to_return[2], visible=True)
628
+
629
+
630
+
631
+
632
+ '''
633
+ Opens/closes a form and changes the button after opening/closing the form.
634
+ Returns: gr.Button
635
+ '''
636
+ def toggle_btn(schedule_name:str, password:str):
637
+ response = client.table('Forms').select('password', 'capacity', 'status').eq('form_name', standardize(schedule_name)).execute()
638
+ data = response.data
639
+
640
+ if len(data) > 0:
641
+ my_dict = data[0]
642
+ if password != my_dict['password']:
643
+ gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
644
+ return FORM_NOT_FOUND
645
+
646
+ curr_status = my_dict['status']
647
+ if curr_status == 'open':
648
+ client.table('Forms').update({'status': 'closed'}).eq('form_name', standardize(schedule_name)).execute()
649
+ gr.Info('', ALERT_TIME, title="The form was closed successfully!")
650
+ return gr.Button('Open Form')
651
+
652
+ elif curr_status == 'closed':
653
+ client.table('Forms').update({'status': 'open'}).eq('form_name', standardize(schedule_name)).execute()
654
+ gr.Info('', ALERT_TIME, title="The form was opened successfully!")
655
+ return gr.Button('Close Form')
656
+
657
+ else:
658
+ gr.Error('', ALERT_TIME, 'An unexpected error has ocurred.')
659
+ return gr.Button()
660
+
661
+ else:
662
+ gr.Warning('', ALERT_TIME, title=f"There was no form called \"{schedule_name}\". Please check the spelling and try again.")
663
+ return gr.Button()
664
+
665
+
666
+
667
+
668
+ ### GRADIO ###
669
+ with gr.Blocks() as demo:
670
+ ### VIEW FORM RESULTS ###
671
+ with gr.Tab('View Form Results'):
672
+ with gr.Column() as btn_group:
673
+ schedule_name = gr.Textbox(label="Form Name")
674
+ password = gr.Textbox(label="Password")
675
+ find_form_btn = gr.Button('Find Form', variant='primary')
676
+
677
+ # 1. Get all responses
678
+ with gr.Column(visible=False) as all_responses_col:
679
+ gr.Markdown('# Download All Form Responses')
680
+ gr.Markdown("Download everyone's responses to the form.")
681
+ all_responses_btn = gr.Button('Download All Form Responses', variant='primary')
682
+
683
+ with gr.Row() as all_responses_output_row:
684
+ df_out = gr.DataFrame(row_count = (NUM_ROWS, "dynamic"),col_count = (NUM_COLS_ALL_RESPONSES, "dynamic"),headers=[NAME_COL, NUM_WORKSHOPS_COL, AVAIL_COL, DESCRIP_COL],wrap=True,scale=4,visible=False)
685
+ file_out = gr.File(label = "Downloadable file", scale=1, visible=False)
686
+
687
+ all_responses_btn.click(fn=get_all_responses, inputs=[schedule_name, password], outputs=[df_out, file_out])
688
+
689
+
690
+ # 2. Generate schedules
691
+ with gr.Column(visible=False) as generate_schedules_explanation_col:
692
+ gr.Markdown('# Create Schedules based on Everyone\'s Preferences.')
693
+
694
+ with gr.Row(visible=False) as generate_btns_row:
695
+ generate_ten_results_btn = gr.Button('Generate a Subset of Schedules', variant='primary', visible=True)
696
+ generate_all_results_btn = gr.Button('Generate All Possible Schedules', visible=True)
697
+
698
+ with gr.Row(visible=True) as generated_schedules_output:
699
+ text_out = gr.Textbox(label='Results')
700
+ generated_df_out = gr.DataFrame(row_count = (NUM_ROWS, "dynamic"),col_count = (NUM_COLS_SCHEDULES, "dynamic"),headers=["Schedule", "Instructors"],wrap=True,scale=3, visible=False)
701
+ generated_file_out = gr.File(label = "Downloadable schedule file", scale=1, visible=False)
702
+
703
+ generate_ten_results_btn.click(fn=generate_schedules_wrapper_subset_results, inputs=[schedule_name, password], outputs=[text_out, generated_df_out, generated_file_out], api_name='generate_random_schedules')
704
+ generate_all_results_btn.click(fn=generate_schedules_wrapper_all_results, inputs=[schedule_name, password], outputs=[text_out, generated_df_out, generated_file_out], api_name='generate_all_schedules')
705
+
706
+
707
+ # 3. Open/close button
708
+ with gr.Column(visible=False) as open_close_btn_col:
709
+ gr.Markdown('# Open or Close Form')
710
+ open_close_btn = gr.Button(variant='primary')
711
+ open_close_btn.click(fn=toggle_btn, inputs=[schedule_name, password], outputs=[open_close_btn])
712
+
713
+
714
+ find_form_btn.click(fn=make_visible, inputs=[schedule_name, password], outputs=[find_form_btn, all_responses_col, generate_schedules_explanation_col, generate_btns_row, open_close_btn_col, open_close_btn])
715
+
716
+
717
+
718
+
719
+ directory = os.path.abspath(os.getcwd())
720
+ allowed = directory #+ "/schedules"
721
+ demo.launch(allowed_paths=[allowed], show_error=True)