File size: 5,930 Bytes
25b5602
 
acf91ea
 
 
25b5602
3614a09
25b5602
 
 
 
3614a09
25b5602
3614a09
25b5602
3614a09
 
 
 
25b5602
3614a09
 
25b5602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3614a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25b5602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import io

import pandas as pd
import streamlit as st

from search import get_solution
from utils import refine_time_parsing, get_day


def main():
    st.title("Curtin Timetable Picker")
    # st.write("Developed with ❤️ by Ren Jie")
    st.write(
        "Paste values in the format: Module, Class, Lecture, Tutorial (tab-separated)"
    )
    st.write(
        "Lecture and Tutorial Format is day, start_time , end_time. e.g. Mon 4.30pm to 6pm"
    )

    num_combi = st.number_input("Number of Combination", min_value=0, value=4)
    # Toggle to restrict back-to-back classes (end == start on same day)
    restrict_back_to_back = st.checkbox("Restrict back to back", value=False)

    # Initialize session state for the DataFrame
    if "df" not in st.session_state:
        st.session_state.df = pd.DataFrame(
            columns=["Module", "Class", "Lecture", "Tutorial"]
        )

    # Text area for pasting tabular data
    pasted_data = st.text_area("Paste data here (tab-separated):", height=200)

    # Convert pasted data to DataFrame
    if pasted_data:
        rows = [line.split("\t") for line in pasted_data.strip().split("\n")]
        st.session_state.df = pd.DataFrame(
            rows, columns=["Module", "Class", "Lecture", "Tutorial"]
        )

    # Display the editable table
    edited_df = st.data_editor(
        st.session_state.df, num_rows="dynamic", use_container_width=True
    )

    # Save changes
    st.session_state.df = edited_df

    # Button to run the solution
    if st.button("Run"):
        result_df = get_solution(edited_df, num_combi, restrict_back_to_back)
        if result_df is not None:
            st.session_state.solution_df = (
                result_df  # Store solution in session state
            )

            # Show result if available
            st.write("Generated Schedule:")
            st.dataframe(result_df)

            # Visualization per combination
            vis_df = result_df.copy()
            # populate start/end and day columns for lecture and tutorial
            vis_df = refine_time_parsing(vis_df, "Lecture")
            vis_df = refine_time_parsing(vis_df, "Tutorial")
            vis_df["lecture_day"] = vis_df["Lecture"].apply(get_day)
            vis_df["tutorial_day"] = vis_df["Tutorial"].apply(get_day)

            def minutes(t):
                return t.hour * 60 + t.minute

            days_order = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

            for combi in sorted(vis_df["Combi"].unique()):
                st.markdown(f"### Combination {combi}")
                sub = vis_df[vis_df["Combi"] == combi]
                # determine range
                starts = []
                ends = []
                for _, r in sub.iterrows():
                    if r.get("Lecture_Start") is not None:
                        starts.append(r.get("Lecture_Start"))
                        ends.append(r.get("Lecture_End"))
                    if r.get("Tutorial_Start") is not None:
                        starts.append(r.get("Tutorial_Start"))
                        ends.append(r.get("Tutorial_End"))
                if not starts or not ends:
                    st.write("No time data to visualize for this combination.")
                    continue
                min_min = min(minutes(t) for t in starts)
                max_min = max(minutes(t) for t in ends)
                # round to nearest 30
                min_min = (min_min // 30) * 30
                max_min = ((max_min + 29) // 30) * 30

                slots = [min_min + 30 * i for i in range((max_min - min_min) // 30)]
                slot_labels = []
                for m in slots:
                    hh = m // 60
                    mm = m % 60
                    slot_labels.append(f"{hh:02d}:{mm:02d}")

                grid = {d: ["" for _ in slots] for d in days_order}
                # fill grid
                for _, r in sub.iterrows():
                    # lecture
                    if r.get("lecture_day") in days_order and r.get("Lecture_Start") is not None:
                        d = r.get("lecture_day")
                        s = minutes(r.get("Lecture_Start"))
                        e = minutes(r.get("Lecture_End"))
                        for i, m in enumerate(slots):
                            if m >= s and m < e:
                                grid[d][i] = f"{r.get('Module')} ({r.get('Class')}) L"
                    # tutorial
                    if r.get("tutorial_day") in days_order and r.get("Tutorial_Start") is not None:
                        d = r.get("tutorial_day")
                        s = minutes(r.get("Tutorial_Start"))
                        e = minutes(r.get("Tutorial_End"))
                        for i, m in enumerate(slots):
                            if m >= s and m < e:
                                existing = grid[d][i]
                                add = f"{r.get('Module')} ({r.get('Class')}) T"
                                grid[d][i] = existing + " | " + add if existing else add

                import pandas as _pd

                df_grid = _pd.DataFrame(grid, index=slot_labels)
                # only show weekdays that actually appear
                used_days = [d for d in days_order if df_grid[d].astype(bool).any()]
                if not used_days:
                    st.write("No scheduled days for this combination.")
                else:
                    st.dataframe(df_grid[used_days])
        else:
            st.info("Schedule cannot be found", icon="ℹ️")

    # Download button
    if "solution_df" in st.session_state:
        csv_buffer = io.StringIO()
        st.session_state.solution_df.to_csv(csv_buffer, index=False)
        st.download_button(
            "Download Solution",
            csv_buffer.getvalue(),
            "table_data.csv",
            "text/csv",
        )


if __name__ == "__main__":
    main()