Juggling commited on
Commit
65afd9e
·
verified ·
1 Parent(s): c010d15
Files changed (1) hide show
  1. workshops.py +108 -414
workshops.py CHANGED
@@ -4,12 +4,7 @@ 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'
@@ -43,13 +38,6 @@ class Schedule:
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:
@@ -90,6 +78,17 @@ def convert_df(df):
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.
@@ -110,13 +109,10 @@ def initialize_timeslots(df) -> dict:
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:
@@ -133,37 +129,26 @@ def find_all_schedules(people: list, availability: dict, schedule_obj: Schedule,
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
  seen = []
@@ -178,8 +163,8 @@ def make_df(schedules: list, descrip_dict: dict, og_slots: list):
178
  else:
179
  seen.append(curr_sched)
180
 
181
- #sorted_dict = dict(sorted(curr_sched.items(), key=lambda item: item[0]))
182
- sorted_dict = my_sort(curr_sched, og_slots)
183
  curr_times = sorted_dict.keys()
184
  curr_instructors = sorted_dict.values()
185
 
@@ -188,7 +173,7 @@ def make_df(schedules: list, descrip_dict: dict, og_slots: list):
188
  all_times.append("")
189
  all_instructors.append("")
190
 
191
- if len(schedules) > 1 or len(schedules) == 1:
192
  all_times.append(f"Schedule #{count}")
193
  all_instructors.append("")
194
  count += 1
@@ -200,41 +185,77 @@ def make_df(schedules: list, descrip_dict: dict, og_slots: list):
200
  if len(descrip_dict) == 0:
201
  all_instructors.append("; ". join(instructors))
202
 
 
203
  if len(descrip_dict) > 0:
204
- big_str = ""
205
-
206
  for person in instructors:
207
  if person in descrip_dict:
208
  descrip = descrip_dict[person]
209
  else:
210
  descrip = "Workshop"
211
-
212
- # {descrip} is a list bc they want to teach multiple workshops
213
- if '\n' in descrip:
214
- new_str = f"\n\n- {person}:\n{descrip}"
215
  else:
216
- new_str = f"\n\n- {person}: {descrip}"
217
-
218
- big_str += new_str
219
-
220
- all_instructors.append(big_str.strip())
221
-
222
- if len(curr_instructors) == 0:
223
- all_instructors.append('N/A')
224
 
225
 
226
  new_df = pd.DataFrame({
227
  "Schedule": all_times,
228
  "Instructor(s)": all_instructors
229
  })
230
- new_df['Instructor(s)'] = new_df['Instructor(s)'].astype(str)
231
 
232
  return new_df, count - 1
233
 
234
 
235
 
 
 
 
 
 
 
 
236
 
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  # Makes a dictionary where each key is the instructor's name and
239
  # the value is the workshop(s) they're teaching
240
  def get_description_dict(df):
@@ -265,10 +286,8 @@ def classify_schedules(people: list, schedules: list, partial_names: list, total
265
 
266
  all_names = pref_dict.keys()
267
 
268
-
269
- ## Evaluate each schedule ##
270
- overall_max = 0 # changes throughout the function
271
-
272
  for sched in schedules:
273
  if sched.num_timeslots_filled != max_timeslots_filled:
274
  continue
@@ -301,14 +320,12 @@ def classify_schedules(people: list, schedules: list, partial_names: list, total
301
  if len(valid_schedules) > 0:
302
  continue
303
  #print(f"teaching desired number of timeslots: {everyone_is_teaching}. At least one workshop per slot: {filled_all_timeslots}.\n{sched}\n")
304
- if sched.num_timeslots_filled > overall_max or sched.num_timeslots_filled == overall_max:
305
- overall_max = sched.num_timeslots_filled
306
-
307
- if sched.num_timeslots_filled not in incomplete_schedules:
308
- incomplete_schedules[sched.num_timeslots_filled] = []
309
- incomplete_schedules[sched.num_timeslots_filled].append(sched)
310
 
311
-
 
312
 
313
  if len(valid_schedules) > 0:
314
  return valid_schedules, []
@@ -318,36 +335,37 @@ def classify_schedules(people: list, schedules: list, partial_names: list, total
318
 
319
 
320
  # Parameters: schedules that have the max number of timeslots filled
321
- # Max number of workshops taught in filled timeslots
322
  # Returns: a list of all schedules that have the max number of workshops
323
  # To make it less overwhelming, it will return {cutoff} randomly
324
- def get_best_schedules(schedules: list, cutoff: str, max_workshops: int) -> list:
325
  cutoff = int(cutoff)
326
- best_schedules = []
 
327
  for sched in schedules:
328
- if sched.total_num_workshops != max_workshops:
329
- continue
330
- best_schedules.append(sched.timeslots)
331
-
 
 
332
  if cutoff == -1:
333
- return best_schedules
334
  else:
335
- if len(best_schedules) > cutoff:
336
  # Sample without replacement
337
- return random.sample(best_schedules, cutoff)
338
  else:
339
- return best_schedules
340
 
341
 
342
  # Big wrapper function that calls the other functions
343
- def main(df, capacity:int, num_results: int, og_slots: list):
344
  descrip_dict = get_description_dict(df)
345
 
346
  # Convert the df with everyone's availability to a usable format
347
  res = convert_df(df)
348
  people = res[0]
349
  availability = res[1]
350
- print(availability)
351
 
352
  partial_names = []
353
 
@@ -355,366 +373,42 @@ def main(df, capacity:int, num_results: int, og_slots: list):
355
 
356
  schedules = []
357
  schedule_obj = Schedule(timeslots)
358
- max_timeslots_list = [0]
359
- max_workshops_list = [0]
360
 
361
- find_all_schedules(people, availability, schedule_obj, capacity, schedules, max_timeslots_list, max_workshops_list)
362
 
363
  total_timeslots = len(timeslots)
364
 
365
 
366
- res = classify_schedules(people, schedules, partial_names, total_timeslots, max_timeslots_list[0])
367
  valid_schedules = res[0]
368
  decent_schedules = res[1]
369
 
370
 
371
  # Return schedules
372
  if len(valid_schedules) > 0:
373
- best_schedules = get_best_schedules(valid_schedules, num_results, max_workshops_list)
374
- res = make_df(best_schedules, descrip_dict, og_slots)
375
  new_df = res[0]
376
  count = res[1]
377
  if count == 1:
378
- results = "Good news! I was able to make a complete schedule."
379
  else:
380
- results = "Good news! I was able to make multiple complete schedules."
381
 
382
  else:
383
- best_schedules = get_best_schedules(decent_schedules, num_results, max_workshops_list)
384
- res = make_df(best_schedules, descrip_dict, og_slots)
385
  new_df = res[0]
386
  count = res[1]
387
- beginning = "Here"
388
  if count == 1:
389
  results = f"{beginning} is the best option."
390
  else:
391
  results = f"{beginning} are the best options."
392
-
393
- #results += "(Remember that \"complete\" schedules are ones where everyone is teaching their desired number of workshops and every timeslot is filled.)"
394
 
395
 
396
  directory = os.path.abspath(os.getcwd())
397
- path = directory + "/schedule.csv"
398
  new_df.to_csv(path, index=False)
399
- return results, new_df, path
400
-
401
-
402
-
403
-
404
- ##### ALL THE NEW STUFF WITH SUPABASE ETC. #####
405
- ### CONSTANTS ###
406
- NAME_COL = 'Juggler_Name'
407
- NUM_WORKSHOPS_COL = 'Num_Workshops'
408
- AVAIL_COL = 'Availability'
409
- DESCRIP_COL = 'Workshop_Descriptions'
410
- EMAIL_COL = 'Email'
411
- DELIMITER = ';'
412
- ALERT_TIME = None # leave warnings on screen indefinitely
413
- FORM_NOT_FOUND = 'Form not found'
414
- INCORRECT_PASSWORD = "The password is incorrect. Please check the password and try again. If you don't remember your password, please email jugglinggym@gmail.com."
415
- NUM_ROWS = 1
416
- NUM_COLS_SCHEDULES = 2
417
- NUM_COLS_ALL_RESPONSES = 4
418
- NUM_RESULTS = 10 # randomly get {NUM_RESULTS} results
419
-
420
-
421
- theme = gr.themes.Soft(
422
- primary_hue="cyan",
423
- secondary_hue="pink",
424
- font=[gr.themes.GoogleFont('sans-serif'), 'ui-sans-serif', 'system-ui', 'Montserrat'],
425
- )
426
-
427
- ### Connect to Supabase ###
428
- URL = os.environ['URL']
429
- API_KEY = os.environ['API_KEY']
430
- client = supabase.create_client(URL, API_KEY)
431
-
432
-
433
-
434
-
435
- ### DEFINE FUNCTIONS ###
436
- ## Multi-purpose function ##
437
- '''
438
- Returns a lowercased and stripped version of the schedule name.
439
- Returns: str
440
- '''
441
- def standardize(schedule_name: str):
442
- return schedule_name.lower().strip()
443
-
444
-
445
-
446
-
447
-
448
-
449
- ## Functions to manage/generate schedules ##
450
- '''
451
- Uses the name and password to get the form.
452
- Makes the buttons and other elements visible on the page.
453
- Returns:
454
- gr.Button: corresponds to find_form_btn
455
- gr.Column: corresponds to all_responses_group
456
- gr.Column: generate_schedules_explanation
457
- gr.Row: corresponds to generate_btns
458
- gr.Column: corresponds to open_close_btn_col
459
- gr.Button: corresponds to open_close_btn
460
- '''
461
- def make_visible(schedule_name:str, password: str):
462
- skip_output = gr.Button(), gr.Column(), gr.Column(), gr.Row(), gr.Column(), gr.Button()
463
-
464
- if len(schedule_name) == 0:
465
- gr.Warning('Please enter the form name.', ALERT_TIME)
466
- return skip_output
467
- if len(password) == 0:
468
- gr.Warning('Please enter the password.', ALERT_TIME)
469
- return skip_output
470
-
471
-
472
- response = client.table('Forms').select('password', 'status').eq('form_name', standardize(schedule_name)).execute()
473
- data = response.data
474
-
475
- if len(data) > 0:
476
- my_dict = data[0]
477
- if password != my_dict['password']:
478
- gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
479
- return skip_output
480
- else:
481
- if my_dict['status'] == 'open':
482
- gr.Info('', ALERT_TIME, title='Btw, the form is currently OPEN.')
483
- 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)
484
-
485
- elif my_dict['status'] == 'closed':
486
- gr.Info('', ALERT_TIME, title='Btw, the form is currently CLOSED.')
487
- 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)
488
-
489
- else:
490
- gr.Warning(f"There is no form called \"{schedule_name}\". Please check the spelling and try again.", ALERT_TIME)
491
- return skip_output
492
-
493
-
494
-
495
-
496
- '''
497
- Makes a blank schedule that we can return to prevent things from breaking.
498
- Returns: tuple with 3 elements:
499
- 0: str indicating that the form wasn't found
500
- 1: the DataFrame
501
- 2: the path to the DataFrame
502
- '''
503
- def make_blank_schedule():
504
- df = pd.DataFrame({
505
- 'Schedule': [],
506
- 'Instructors': []
507
- })
508
-
509
- directory = os.path.abspath(os.getcwd())
510
- path = directory + "/schedule.csv"
511
- df.to_csv(path, index=False)
512
- return FORM_NOT_FOUND, df, path
513
-
514
-
515
- '''
516
- Gets a the form responses from Supabase and converts them to a DataFrame
517
- Returns:
518
- if found: a dictionary with three keys: capacity (int), df (DataFrame), and slots (list)
519
- if not found: a string indicating the form was not found
520
- '''
521
- def get_df_from_db(schedule_name: str, password: str):
522
- response = client.table('Forms').select('password', 'capacity', 'responses', 'slots').eq('form_name', standardize(schedule_name)).execute()
523
- data = response.data
524
-
525
- if len(data) > 0:
526
- my_dict = data[0]
527
- if password != my_dict['password']:
528
- gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
529
- return FORM_NOT_FOUND
530
-
531
- # Convert to df
532
- df = pd.DataFrame(json.loads(my_dict['responses']))
533
- return {'capacity': my_dict['capacity'], 'df': df, 'slots': my_dict['slots']}
534
-
535
- else:
536
- gr.Warning(f"There is no form called \"{schedule_name}\". Please check the spelling and try again.", ALERT_TIME)
537
- return FORM_NOT_FOUND
538
-
539
-
540
- '''
541
- Puts all of the form responses into a DataFrame.
542
- Returns this DF along with the filepath.
543
- '''
544
- def get_all_responses(schedule_name:str, password:str):
545
- res = get_df_from_db(schedule_name, password)
546
-
547
- if res == FORM_NOT_FOUND:
548
- df = pd.DataFrame({
549
- NAME_COL: [],
550
- EMAIL_COL: [],
551
- NUM_WORKSHOPS_COL: [],
552
- AVAIL_COL: [],
553
- DESCRIP_COL: []
554
- })
555
-
556
- else:
557
- df = res['df']
558
- df[AVAIL_COL] = [elem.replace(DELIMITER, f"{DELIMITER} ") for elem in df[AVAIL_COL].to_list()]
559
-
560
- directory = os.path.abspath(os.getcwd())
561
- path = directory + "/all responses.csv"
562
- df.to_csv(path, index=False)
563
-
564
- if len(df) == 0:
565
- gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
566
- return gr.DataFrame(df, visible=True), gr.File(path, visible=True)
567
-
568
-
569
- '''
570
- Calls the algorithm to generate the best possible schedules,
571
- and returns a random subset of the results.
572
- (The same as generate_schedules_wrapper_all_results, except that this function only returns a subset of them.
573
- I had to make it into two separate functions in order to work with Gradio).
574
- Returns:
575
- DataFrame
576
- Filepath to DF (str)
577
- '''
578
- def generate_schedules_wrapper_subset_results(schedule_name: str, password: str):
579
- res = get_df_from_db(schedule_name, password)
580
- # Return blank schedule (should be impossible to get to this condition btw)
581
- if res == FORM_NOT_FOUND:
582
- to_return = make_blank_schedule()
583
- gr.Warning(FORM_NOT_FOUND, ALERT_TIME)
584
-
585
- else:
586
- df = res['df']
587
- if len(df) == 0:
588
- gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
589
- to_return = make_blank_schedule()
590
- else:
591
- gr.Info('', ALERT_TIME, title='Working on generating schedules! Please DO NOT click anything on this page.')
592
- to_return = main(df, res['capacity'], NUM_RESULTS, res['slots'])
593
- gr.Info('', ALERT_TIME, title=to_return[0])
594
-
595
-
596
- return gr.Textbox(to_return[0]), gr.DataFrame(to_return[1], visible=True), gr.File(to_return[2], visible=True)
597
-
598
-
599
- '''
600
- Calls the algorithm to generate the best possible schedules,
601
- and returns ALL of the results.
602
- (The same as generate_schedules_wrapper_subset_results, except that this function returns all of them.
603
- I had to make it into two separate functions in order to work with Gradio).
604
- Returns:
605
- DataFrame
606
- Filepath to DF (str)
607
- '''
608
- def generate_schedules_wrapper_all_results(schedule_name: str, password: str):
609
- res = get_df_from_db(schedule_name, password)
610
- # Return blank schedule (should be impossible to get to this condition btw)
611
- if res == FORM_NOT_FOUND:
612
- to_return = make_blank_schedule()
613
- gr.Warning(FORM_NOT_FOUND, ALERT_TIME)
614
-
615
- else:
616
- df = res['df']
617
- if len(df) == 0:
618
- gr.Warning('', ALERT_TIME, title='No one has filled out the form yet.')
619
- to_return = make_blank_schedule()
620
- else:
621
- gr.Info('', ALERT_TIME, title='Working on generating schedules! Please DO NOT click anything on this page.')
622
- placeholder = -1
623
- to_return = main(df, res['capacity'], placeholder, res['slots'])
624
- gr.Info('', ALERT_TIME, title=to_return[0])
625
-
626
- return gr.Textbox(to_return[0]), gr.DataFrame(to_return[1], visible=True), gr.File(to_return[2], visible=True)
627
-
628
-
629
-
630
-
631
- '''
632
- Opens/closes a form and changes the button after opening/closing the form.
633
- Returns: gr.Button
634
- '''
635
- def toggle_btn(schedule_name:str, password:str):
636
- response = client.table('Forms').select('password', 'capacity', 'status').eq('form_name', standardize(schedule_name)).execute()
637
- data = response.data
638
-
639
- if len(data) > 0:
640
- my_dict = data[0]
641
- if password != my_dict['password']:
642
- gr.Warning(INCORRECT_PASSWORD, ALERT_TIME)
643
- return FORM_NOT_FOUND
644
-
645
- curr_status = my_dict['status']
646
- if curr_status == 'open':
647
- client.table('Forms').update({'status': 'closed'}).eq('form_name', standardize(schedule_name)).execute()
648
- gr.Info('', ALERT_TIME, title="The form was closed successfully!")
649
- return gr.Button('Open Form')
650
-
651
- elif curr_status == 'closed':
652
- client.table('Forms').update({'status': 'open'}).eq('form_name', standardize(schedule_name)).execute()
653
- gr.Info('', ALERT_TIME, title="The form was opened successfully!")
654
- return gr.Button('Close Form')
655
-
656
- else:
657
- gr.Error('', ALERT_TIME, 'An unexpected error has ocurred.')
658
- return gr.Button()
659
-
660
- else:
661
- gr.Warning('', ALERT_TIME, title=f"There was no form called \"{schedule_name}\". Please check the spelling and try again.")
662
- return gr.Button()
663
-
664
-
665
-
666
-
667
- ### GRADIO ###
668
- with gr.Blocks() as demo:
669
- ### VIEW FORM RESULTS ###
670
- with gr.Tab('View Form Results'):
671
- with gr.Column() as btn_group:
672
- schedule_name = gr.Textbox(label="Form Name")
673
- password = gr.Textbox(label="Password")
674
- find_form_btn = gr.Button('Find Form', variant='primary')
675
-
676
- # 1. Get all responses
677
- with gr.Column(visible=False) as all_responses_col:
678
- gr.Markdown('# Download All Form Responses')
679
- gr.Markdown("Download everyone's responses to the form.")
680
- all_responses_btn = gr.Button('Download All Form Responses', variant='primary')
681
-
682
- with gr.Row() as all_responses_output_row:
683
- 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)
684
- file_out = gr.File(label = "Downloadable file", scale=1, visible=False)
685
-
686
- all_responses_btn.click(fn=get_all_responses, inputs=[schedule_name, password], outputs=[df_out, file_out])
687
-
688
-
689
- # 2. Generate schedules
690
- with gr.Column(visible=False) as generate_schedules_explanation_col:
691
- gr.Markdown('# Create Schedules based on Everyone\'s Preferences.')
692
-
693
- with gr.Row(visible=False) as generate_btns_row:
694
- generate_ten_results_btn = gr.Button('Generate a Subset of Schedules', variant='primary', visible=True)
695
- generate_all_results_btn = gr.Button('Generate All Possible Schedules', visible=True)
696
-
697
- with gr.Row(visible=True) as generated_schedules_output:
698
- text_out = gr.Textbox(label='Results')
699
- 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)
700
- generated_file_out = gr.File(label = "Downloadable schedule file", scale=1, visible=False)
701
-
702
- 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')
703
- 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')
704
-
705
-
706
- # 3. Open/close button
707
- with gr.Column(visible=False) as open_close_btn_col:
708
- gr.Markdown('# Open or Close Form')
709
- open_close_btn = gr.Button(variant='primary')
710
- open_close_btn.click(fn=toggle_btn, inputs=[schedule_name, password], outputs=[open_close_btn])
711
-
712
-
713
- 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])
714
-
715
-
716
-
717
-
718
- directory = os.path.abspath(os.getcwd())
719
- allowed = directory #+ "/schedules"
720
- demo.launch(allowed_paths=[allowed], show_error=True)
 
4
  import gradio as gr
5
  from collections import Counter
6
  import random
 
 
 
 
7
 
 
8
  # CONSTANTS
9
  NAME_COL = 'Juggler_Name'
10
  NUM_WORKSHOPS_COL = 'Num_Workshops'
 
38
  self.timeslots[time].remove(person)
39
 
40
 
 
 
 
 
 
 
 
41
  # Returns True if the person can teach during the slot, and False otherwise
42
  def can_teach(person: str, slot: list, capacity: int) -> bool:
43
  if len(slot) == capacity or len(slot) > capacity:
 
78
  return people, availability
79
 
80
 
81
+ # Returns False if curr is NaN, and True otherwise
82
+ def is_defined(curr):
83
+ # if curr != curr, then curr is NaN for some reason
84
+ if curr != curr:
85
+ return False
86
+ else:
87
+ return True
88
+
89
+ # Returns True if curr is defined and its length is greater than 0
90
+ def is_valid(curr):
91
+ return (is_defined(curr) and len(curr) > 0)
92
 
93
  # Makes a dictionary where each key is a timeslot and each value is a list.
94
  # If there's no partial schedule, each list will be empty.
 
109
 
110
 
111
  # Recursive function that generates all possible schedules
112
+ def find_all_schedules(people: list, availability: dict, schedule_obj: Schedule, capacity: int, schedules: list, max_list: list) -> None:
113
+ if schedule_obj.num_timeslots_filled > max_list[0] or schedule_obj.num_timeslots_filled == max_list[0]:
114
  schedules.append(copy.deepcopy(schedule_obj))
115
+ max_list[0] = schedule_obj.num_timeslots_filled
 
 
 
116
 
117
  # Base case
118
  if len(people) == 0:
 
129
 
130
  # Explore (assign everyone else to timeslots based on that decision)
131
  if len(people) == 1:
132
+ find_all_schedules([], availability, schedule_obj, capacity, schedules, max_list)
133
 
134
  else:
135
+ find_all_schedules(people[1:len(people)], availability, schedule_obj, capacity, schedules, max_list)
136
 
137
  # Unchoose (remove that person from the timeslot)
138
  schedule_obj.remove(person, time)
139
  # NOTE: this will not generate a full timeslot, but could still lead to a good schedule
140
  else:
141
  if len(people) == 1:
142
+ find_all_schedules([], availability, schedule_obj, capacity, schedules, max_list)
143
  else:
144
+ find_all_schedules(people[1:len(people)], availability, schedule_obj, capacity, schedules, max_list)
145
+
 
 
146
 
147
+ return
 
 
 
 
 
 
 
 
 
148
 
149
 
150
  # Makes an organized DataFrame given a list of schedules
151
+ def make_df(schedules: list, descrip_dict: dict):
152
  all_times = []
153
  all_instructors = []
154
  seen = []
 
163
  else:
164
  seen.append(curr_sched)
165
 
166
+ # Sort dictionary by keys
167
+ sorted_dict = dict(sorted(curr_sched.items(), key=lambda item: item[0]))
168
  curr_times = sorted_dict.keys()
169
  curr_instructors = sorted_dict.values()
170
 
 
173
  all_times.append("")
174
  all_instructors.append("")
175
 
176
+ if len(schedules) > 0:
177
  all_times.append(f"Schedule #{count}")
178
  all_instructors.append("")
179
  count += 1
 
185
  if len(descrip_dict) == 0:
186
  all_instructors.append("; ". join(instructors))
187
 
188
+ # The format will be: Time: Instructor (Workshop); Instructor (Workshop)
189
  if len(descrip_dict) > 0:
190
+ string = ""
 
191
  for person in instructors:
192
  if person in descrip_dict:
193
  descrip = descrip_dict[person]
194
  else:
195
  descrip = "Workshop"
196
+ if len(descrip) > 0:
197
+ descrip = descrip.replace(DELIMITER, f" OR ")
198
+ string += f"{person} ({descrip}); "
 
199
  else:
200
+ string += f"{person}"
201
+ string = string.strip("; ")
202
+ all_instructors.append(string)
 
 
 
 
 
203
 
204
 
205
  new_df = pd.DataFrame({
206
  "Schedule": all_times,
207
  "Instructor(s)": all_instructors
208
  })
 
209
 
210
  return new_df, count - 1
211
 
212
 
213
 
214
+ # Returns the stripped version of the column name
215
+ # or the default one if the user didn't input a column name
216
+ def get_var_name(var, default):
217
+ if var is None or len(var) == 0:
218
+ return default
219
+ else:
220
+ return var.strip()
221
 
222
 
223
+ # Returns an error message, empty DataFrame, and blank csv file
224
+ def error_msg(message: str):
225
+ empty = pd.DataFrame({"Schedule": ["ERROR"], "Instructor": ["ERROR"]})
226
+ directory = os.path.abspath(os.getcwd())
227
+ path = directory + "/schedules/ERROR.csv"
228
+ empty.to_csv(path, index=False)
229
+ return "ERROR: " + message, empty, path
230
+
231
+
232
+ # Returns column names that aren't in the csv file
233
+ def find_missing_cols(df_columns: list, names: list, file: str) -> str:
234
+ missing = []
235
+ for elem in names:
236
+ if elem not in df_columns:
237
+ missing.append(elem)
238
+
239
+ double_check = f"""These are the columns in your file: {"; ".join(df_columns)}. Please double check your spelling/punctuation and try again."""
240
+
241
+ if len(missing) == 0:
242
+ return ""
243
+ elif len(missing) == 1:
244
+ return f'I cannot find this column in the {file} file you uploaded: {missing[0]}. {double_check}'
245
+ elif len(missing) == 2:
246
+ return f'I cannot find these columns in the {file} file you uploaded: {missing[0]} and {missing[1]}. {double_check}'
247
+ else:
248
+ message = f"I cannot find these columns in the {file} file you uploaded: "
249
+ for i in range(len(missing)):
250
+ col = missing[i]
251
+ if i != len(missing) - 1:
252
+ message += col + ", "
253
+ else:
254
+ message += "and " + col + ". "
255
+ message += double_check
256
+ return message
257
+
258
+
259
  # Makes a dictionary where each key is the instructor's name and
260
  # the value is the workshop(s) they're teaching
261
  def get_description_dict(df):
 
286
 
287
  all_names = pref_dict.keys()
288
 
289
+ # Evaluate each schedule
290
+ overall_max = 0
 
 
291
  for sched in schedules:
292
  if sched.num_timeslots_filled != max_timeslots_filled:
293
  continue
 
320
  if len(valid_schedules) > 0:
321
  continue
322
  #print(f"teaching desired number of timeslots: {everyone_is_teaching}. At least one workshop per slot: {filled_all_timeslots}.\n{sched}\n")
323
+ if sched.num_timeslots_filled not in incomplete_schedules:
324
+ incomplete_schedules[sched.num_timeslots_filled] = []
325
+ incomplete_schedules[sched.num_timeslots_filled].append(sched)
 
 
 
326
 
327
+ if sched.num_timeslots_filled > overall_max:
328
+ overall_max = sched.num_timeslots_filled
329
 
330
  if len(valid_schedules) > 0:
331
  return valid_schedules, []
 
335
 
336
 
337
  # Parameters: schedules that have the max number of timeslots filled
 
338
  # Returns: a list of all schedules that have the max number of workshops
339
  # To make it less overwhelming, it will return {cutoff} randomly
340
+ def get_best_schedules(schedules: list, cutoff: str) -> list:
341
  cutoff = int(cutoff)
342
+ overall_max = 0
343
+ best_schedules = {}
344
  for sched in schedules:
345
+ if sched.total_num_workshops not in best_schedules:
346
+ best_schedules[sched.total_num_workshops] = []
347
+ best_schedules[sched.total_num_workshops].append(sched.timeslots)
348
+ if sched.total_num_workshops > overall_max:
349
+ overall_max = sched.total_num_workshops
350
+ all_best_schedules = best_schedules[overall_max]
351
  if cutoff == -1:
352
+ return all_best_schedules
353
  else:
354
+ if len(all_best_schedules) > cutoff:
355
  # Sample without replacement
356
+ return random.sample(all_best_schedules, cutoff)
357
  else:
358
+ return all_best_schedules
359
 
360
 
361
  # Big wrapper function that calls the other functions
362
+ def main(df, capacity:int, num_results: int):
363
  descrip_dict = get_description_dict(df)
364
 
365
  # Convert the df with everyone's availability to a usable format
366
  res = convert_df(df)
367
  people = res[0]
368
  availability = res[1]
 
369
 
370
  partial_names = []
371
 
 
373
 
374
  schedules = []
375
  schedule_obj = Schedule(timeslots)
376
+ max_list = [0]
 
377
 
378
+ find_all_schedules(people, availability, schedule_obj, capacity, schedules, max_list)
379
 
380
  total_timeslots = len(timeslots)
381
 
382
 
383
+ res = classify_schedules(people, schedules, partial_names, total_timeslots, max_list[0])
384
  valid_schedules = res[0]
385
  decent_schedules = res[1]
386
 
387
 
388
  # Return schedules
389
  if len(valid_schedules) > 0:
390
+ best_schedules = get_best_schedules(valid_schedules, num_results)
391
+ res = make_df(best_schedules, descrip_dict)
392
  new_df = res[0]
393
  count = res[1]
394
  if count == 1:
395
+ results = "Good news! I was able to make a schedule."
396
  else:
397
+ results = "Good news! I was able to make multiple schedules."
398
 
399
  else:
400
+ best_schedules = get_best_schedules(decent_schedules, num_results)
401
+ res = make_df(best_schedules, descrip_dict)
402
  new_df = res[0]
403
  count = res[1]
404
+ beginning = "Unfortunately, I wasn't able to make a complete schedule, but here"
405
  if count == 1:
406
  results = f"{beginning} is the best option."
407
  else:
408
  results = f"{beginning} are the best options."
 
 
409
 
410
 
411
  directory = os.path.abspath(os.getcwd())
412
+ path = directory + "/schedules/schedule.csv"
413
  new_df.to_csv(path, index=False)
414
+ return results, new_df, path