kreemyyyy commited on
Commit
dce160d
Β·
verified Β·
1 Parent(s): a9b8a85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -0
app.py CHANGED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import tempfile
4
+ import os
5
+ from openpyxl import load_workbook
6
+ from openpyxl.styles import Alignment
7
+
8
+ def adjust_excel_formatting(file_path):
9
+ wb = load_workbook(file_path)
10
+ ws = wb.active
11
+ for col in ws.columns:
12
+ max_length = 0
13
+ col_letter = col[0].column_letter
14
+ for cell in col:
15
+ if cell.value:
16
+ max_length = max(max_length, len(str(cell.value)))
17
+ cell.alignment = Alignment(wrap_text=True)
18
+ ws.column_dimensions[col_letter].width = max_length + 2
19
+ wb.save(file_path)
20
+
21
+ def process_file_a_to_b(input_file):
22
+ try:
23
+ # Read the Excel file, skipping the first row (OVERNIGHT/MORNING header)
24
+ input_df = pd.read_excel(input_file.name, header=1)
25
+
26
+ # Get the date columns (all columns except the first one which contains model names)
27
+ date_columns = input_df.columns[1:].tolist()
28
+
29
+ # Melt the dataframe to long format
30
+ df_long = input_df.melt(
31
+ id_vars=[input_df.columns[0]], # First column (Model names)
32
+ var_name='DATE',
33
+ value_name='CHATTER'
34
+ )
35
+
36
+ # Clean up the data
37
+ df_long = df_long[df_long['CHATTER'].notna()] # Remove empty cells
38
+ df_long = df_long[df_long['CHATTER'] != ''] # Remove empty strings
39
+ df_long = df_long[df_long['CHATTER'] != 'OFF'] # Remove 'OFF' entries
40
+
41
+ # Group by chatter and date, collect all models
42
+ grouped = df_long.groupby(['CHATTER', 'DATE'])[input_df.columns[0]].apply(
43
+ lambda x: ', '.join(sorted(x))
44
+ ).reset_index()
45
+
46
+ # Pivot to get chatters as rows and dates as columns
47
+ pivoted = grouped.pivot(
48
+ index='CHATTER',
49
+ columns='DATE',
50
+ values=input_df.columns[0]
51
+ )
52
+
53
+ # Reorder columns to match original date order
54
+ pivoted = pivoted[date_columns]
55
+
56
+ # Define the expected order of chatters
57
+ expected_chatters = [
58
+ 'VELJKO2', 'VELJKO3', 'MARKO', 'GODDARD', 'ALEKSANDER', 'FEELIP',
59
+ 'DENIS', 'TOME', 'MILA', 'VELJKO', 'DAMJAN', 'DULE', 'CONRAD',
60
+ 'ALEXANDER', 'VEJKO3'
61
+ ]
62
+
63
+ # Reindex with expected order, keeping any additional chatters at the end
64
+ final_df = pivoted.reindex(expected_chatters + [x for x in pivoted.index if x not in expected_chatters])
65
+
66
+ # Fill empty cells with 'OFF'
67
+ final_df = final_df.fillna('OFF')
68
+
69
+ # Reset index and rename the index column to 'CHATTER'
70
+ final_df = final_df.reset_index()
71
+ final_df = final_df.rename(columns={'index': 'CHATTER'})
72
+
73
+ return final_df
74
+ except Exception as e:
75
+ return pd.DataFrame({"Error": [str(e)]})
76
+
77
+ def process_file_b_to_a(input_file):
78
+ try:
79
+ # Read the Excel file
80
+ input_df = pd.read_excel(input_file.name, header=0)
81
+
82
+ # Get the date columns (all columns except the first one which contains chatter names)
83
+ date_columns = input_df.columns[1:].tolist()
84
+
85
+ # Melt the dataframe to long format
86
+ df_long = input_df.melt(
87
+ id_vars=[input_df.columns[0]], # First column (Chatter names)
88
+ var_name='DATE',
89
+ value_name='MODEL'
90
+ )
91
+
92
+ # Clean up the data
93
+ df_long = df_long[df_long['MODEL'].notna()] # Remove empty cells
94
+ df_long = df_long[df_long['MODEL'] != ''] # Remove empty strings
95
+ df_long = df_long[df_long['MODEL'] != 'OFF'] # Remove 'OFF' entries
96
+
97
+ # Split comma-separated models into separate rows
98
+ df_long['MODEL'] = df_long['MODEL'].str.split(', ')
99
+ df_long = df_long.explode('MODEL')
100
+
101
+ # Group by model and date, collect all chatters
102
+ grouped = df_long.groupby(['MODEL', 'DATE'])[input_df.columns[0]].apply(
103
+ lambda x: ', '.join(sorted(x))
104
+ ).reset_index()
105
+
106
+ # Pivot to get models as rows and dates as columns
107
+ pivoted = grouped.pivot(
108
+ index='MODEL',
109
+ columns='DATE',
110
+ values=input_df.columns[0]
111
+ )
112
+
113
+ # Reorder columns to match original date order
114
+ pivoted = pivoted[date_columns]
115
+
116
+ # Sort models alphabetically
117
+ final_df = pivoted.sort_index()
118
+
119
+ # Fill empty cells with 'OFF'
120
+ final_df = final_df.fillna('OFF')
121
+
122
+ # Reset index to make MODEL a column
123
+ final_df = final_df.reset_index()
124
+
125
+ return final_df
126
+ except Exception as e:
127
+ return pd.DataFrame({"Error": [str(e)]})
128
+
129
+ def convert_schedule(file, direction):
130
+ if direction == "Format A β†’ Format B":
131
+ df = process_file_a_to_b(file)
132
+ else:
133
+ df = process_file_b_to_a(file)
134
+ # Save to temp file for download
135
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:
136
+ df.to_excel(tmp.name, index=False)
137
+ adjust_excel_formatting(tmp.name)
138
+ tmp.seek(0)
139
+ data = tmp.read()
140
+ return df, (tmp.name,)
141
+
142
+ def download_file(file_tuple):
143
+ return file_tuple[0]
144
+
145
+ demo = gr.Blocks()
146
+ with demo:
147
+ gr.Markdown("# πŸ“… Schedule Converter")
148
+ gr.Markdown("Upload your schedule Excel file, select conversion direction, and download the result.")
149
+ with gr.Row():
150
+ file = gr.File(label="Upload Schedule File", type="file")
151
+ direction = gr.Dropdown([
152
+ "Format A β†’ Format B",
153
+ "Format B β†’ Format A"
154
+ ], value="Format A β†’ Format B", label="Conversion Direction")
155
+ with gr.Row():
156
+ process_btn = gr.Button("Process File", variant="primary")
157
+ reset_btn = gr.Button("Upload New File")
158
+ output_table = gr.Dataframe(label="Preview", wrap=True)
159
+ download_button = gr.Button("Download Processed File", visible=False)
160
+ temp_file_path = gr.State(value=None)
161
+ def reset_components():
162
+ return [None, pd.DataFrame(), None, gr.update(visible=False)]
163
+ def process_and_show(file, direction):
164
+ df, out_path = convert_schedule(file, direction)
165
+ if out_path:
166
+ return df, out_path, gr.update(visible=True)
167
+ return df, None, gr.update(visible=False)
168
+ process_btn.click(
169
+ process_and_show,
170
+ inputs=[file, direction],
171
+ outputs=[output_table, temp_file_path, download_button]
172
+ )
173
+ reset_btn.click(
174
+ reset_components,
175
+ outputs=[file, output_table, temp_file_path, download_button]
176
+ )
177
+ download_button.click(
178
+ download_file,
179
+ inputs=temp_file_path,
180
+ outputs=gr.File(label="Processed Schedule")
181
+ )
182
+
183
+ demo.launch()