Ethscriptions commited on
Commit
d99d789
·
verified ·
1 Parent(s): 56713b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -192
app.py CHANGED
@@ -6,6 +6,7 @@ import io
6
  import base64
7
  import matplotlib.gridspec as gridspec
8
  import math
 
9
 
10
  SPLIT_TIME = "17:30"
11
  BUSINESS_START = "09:30"
@@ -26,8 +27,8 @@ def process_schedule(file):
26
  # 清理数据
27
  df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
28
 
29
- # 关键修改:影厅格式转换为带LaTeX上标井号
30
- df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str) + r'$^{\#}$' # <-- 修正后的表达式
31
 
32
  # 保存原始时间字符串用于诊断
33
  df['original_end'] = df['EndTime']
@@ -80,196 +81,6 @@ def process_schedule(file):
80
  part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy()
81
  part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy()
82
 
83
- # 格式化时间显示
84
- for part in [part1, part2]:
85
- part['EndTime'] = part['EndTime'].dt.strftime('%-I:%M')
86
-
87
- # 关键修改:精确读取C6单元格
88
- date_df = pd.read_excel(
89
- file,
90
- skiprows=5, # 跳过前5行(0-4)
91
- nrows=1, # 只读1行
92
- usecols=[2], # 第三列(C列)
93
- header=None # 无表头
94
- )
95
- date_cell = date_df.iloc[0, 0]
96
-
97
- try:
98
- # 处理不同日期格式
99
- if isinstance(date_cell, str):
100
- date_str = datetime.strptime(date_cell, '%Y-%m-%d').strftime('%Y-%m-%d')
101
- else:
102
- date_str = pd.to_datetime(date_cell).strftime('%Y-%m-%d')
103
- except:
104
- date_str = datetime.today().strftime('%Y-%m-%d')
105
-
106
- return part1[['Hall', 'EndTime']], part2[['Hall', 'EndTime']], date_str
107
-
108
- except Exception as e:
109
- st.error(f"处理文件时出错: {str(e)}")
110
- return None, None, None
111
-
112
- def create_print_layout(data, title, date_str):
113
- """创建打印布局"""
114
- if data.empty:
115
- return None
116
-
117
- # 设置 A5 纸张竖向尺寸
118
- fig = plt.figure(figsize=(5.83, 8.27), dpi=300)
119
- plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
120
-
121
- # 设置字体
122
- plt.rcParams['font.family'] = 'sans-serif'
123
- plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
124
-
125
- # 计算行数和总数
126
- total_items = len(data)
127
- num_cols = 3
128
- num_rows = math.ceil(total_items / num_cols)
129
-
130
- # 创建网格
131
- gs = gridspec.GridSpec(num_rows + 1, num_cols, hspace=0.1, wspace=0.1, height_ratios=[1] * num_rows + [0.2])
132
-
133
- base_fontsize = min(30, 265 / num_rows)
134
-
135
- data_values = data.values.tolist()
136
-
137
- while len(data_values) % 3 != 0:
138
- data_values.append(['', ''])
139
-
140
- rows_per_col = math.ceil(len(data_values) / 3)
141
-
142
- sorted_data = [['', '']] * len(data_values)
143
-
144
- for i, item in enumerate(data_values):
145
- if item[0] and item[1]:
146
- row = i % rows_per_col
147
- col = i // rows_per_col
148
- new_index = row * 3 + col
149
- if new_index < len(sorted_data):
150
- sorted_data[new_index] = item
151
-
152
- for idx, (hall, end_time) in enumerate(sorted_data):
153
- if hall and end_time:
154
- row = idx // 3
155
- col = idx % 3
156
-
157
- ax = plt.subplot(gs[row, col])
158
-
159
- for spine in ax.spines.values():
160
- spine.set_color(BORDER_COLOR)
161
- spine.set_linewidth(0.5)
162
-
163
- display_text = f"{hall}{end_time}"
164
- ax.text(0.5, 0.5, display_text,
165
- fontsize=base_fontsize,
166
- fontweight='bold',
167
- ha='center',
168
- va='center')
169
-
170
- ax.set_xlim(-0.02, 1.02)
171
- ax.set_ylim(-0.02, 1.02)
172
-
173
- ax.set_xticks([])
174
- ax.set_yticks([])
175
-
176
- # 添加日期信息
177
- ax_date = plt.subplot(gs[0, 0])
178
- ax_date.text(0.05, 0.95, f"{date_str} {title}",
179
- fontsize=base_fontsize * 0.4,
180
- color=DATE_COLOR,
181
- fontweight='bold',
182
- ha='left',
183
- va='top')
184
-
185
- for spine in ax_date.spines.values():
186
- spine.set_visible(False)
187
- ax_date.set_xticks([])
188
- ax_date.set_yticks([])
189
-
190
- # 转换为图片
191
- buffer = io.BytesIO()
192
- plt.savefig(buffer, format='png', bbox_inches='tight', pad_inches=0.05)
193
- buffer.seek(0)
194
- image_base64 = base64.b64encode(buffer.getvalue()).decode()
195
- plt.close()
196
-
197
- return f'data:image/png;base64,{image_base64}'
198
-
199
- # Streamlit 界面
200
- st.set_page_config(page_title="散厅时间快捷打印", layout="wide")
201
- st.title("散厅时间快捷打印")
202
-
203
- uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls", "xlsx"])
204
-
205
- if uploaded_file:
206
- part1, part2, date_str = process_schedule(uploaded_file)
207
-
208
- if part1 is not None and part2 is not None:
209
- part1_image = create_print_layout(part1, "A", date_str)
210
- part2_image = create_print_layout(part2, "C", date_str)
211
-
212
- col1, col2 = st.columns(2)
213
-
214
- with col1:
215
- st.subheader("白班散场预览(时间 ≤ 17:30)")
216
- if part1_image:
217
- st.image(part1_image)
218
- else:
219
- st.info("白班部分没有数据")
220
-
221
- with col2:
222
- st.subheader("夜班散场预览(时间 > 17:30)")
223
- if part2_image:
224
- st.image(part2_image)
225
- else:
226
- st.info("夜班部分没有数据") base_date = datetime.today().date()
227
- df['StartTime'] = pd.to_datetime(df['StartTime'])
228
- df['EndTime'] = pd.to_datetime(df['EndTime'])
229
-
230
- # 设置基准时间
231
- business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
232
- business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
233
-
234
- # 处理跨天情况
235
- if business_end < business_start:
236
- business_end += timedelta(days=1)
237
-
238
- # 标准化所有时间到同一天
239
- for idx, row in df.iterrows():
240
- end_time = row['EndTime']
241
- if end_time.hour < 9:
242
- df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
243
-
244
- if row['StartTime'].hour >= 21 and end_time.hour < 9:
245
- df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
246
-
247
- # 筛选营业时间内的场次
248
- df['time_for_comparison'] = df['EndTime'].apply(
249
- lambda x: datetime.combine(base_date, x.time())
250
- )
251
-
252
- df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
253
-
254
- valid_times = (
255
- ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
256
- (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time())))
257
- )
258
-
259
- df = df[valid_times]
260
-
261
- # 按散场时间排序
262
- df = df.sort_values('EndTime')
263
-
264
- # 分割数据
265
- split_time = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
266
- split_time_for_comparison = df['time_for_comparison'].apply(
267
- lambda x: datetime.combine(base_date, split_time.time())
268
- )
269
-
270
- part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy()
271
- part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy()
272
-
273
  # 格式化时间显示
274
  for part in [part1, part2]:
275
  part['EndTime'] = part['EndTime'].dt.strftime('%-I:%M')
 
6
  import base64
7
  import matplotlib.gridspec as gridspec
8
  import math
9
+ import re # 新增正则模块
10
 
11
  SPLIT_TIME = "17:30"
12
  BUSINESS_START = "09:30"
 
27
  # 清理数据
28
  df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
29
 
30
+ # 转换影厅格式为带LaTeX上标井号
31
+ df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str) + r'$^{\#}$'
32
 
33
  # 保存原始时间字符串用于诊断
34
  df['original_end'] = df['EndTime']
 
81
  part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy()
82
  part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy()
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # 格式化时间显示
85
  for part in [part1, part2]:
86
  part['EndTime'] = part['EndTime'].dt.strftime('%-I:%M')