Ethscriptions commited on
Commit
5cdc7e0
·
verified ·
1 Parent(s): 8157de9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -200
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"
@@ -14,187 +15,196 @@ BORDER_COLOR = '#A9A9A9'
14
  DATE_COLOR = '#A9A9A9'
15
 
16
  def process_schedule(file):
17
- """处理上传的 Excel 文件,生成排序和分组后的打印内容"""
18
- try:
19
- # 读取 Excel,跳过前 8 行
20
- df = pd.read_excel(file, skiprows=8)
21
-
22
- # 提取所需列 (G9, H9, J9)
23
- df = df.iloc[:, [6, 7, 9]] # G, H, J 列
24
- df.columns = ['Hall', 'StartTime', 'EndTime']
25
-
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']
34
-
35
- # 转换时间为 datetime 对象
36
- base_date = datetime.today().date()
37
- df['StartTime'] = pd.to_datetime(df['StartTime'])
38
- df['EndTime'] = pd.to_datetime(df['EndTime'])
39
-
40
- # 设置基准时间
41
- business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
42
- business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
43
-
44
- # 处理跨天情况
45
- if business_end < business_start:
46
- business_end += timedelta(days=1)
47
-
48
- # 标准化所有时间到同一天
49
- for idx, row in df.iterrows():
50
- end_time = row['EndTime']
51
- if end_time.hour < 9:
52
- df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
53
-
54
- if row['StartTime'].hour >= 21 and end_time.hour < 9:
55
- df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
56
-
57
- # 筛选营业时间内的场次
58
- df['time_for_comparison'] = df['EndTime'].apply(
59
- lambda x: datetime.combine(base_date, x.time())
60
- )
61
-
62
- df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
63
-
64
- valid_times = (
65
- ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
66
- (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time())))
67
- )
68
-
69
- df = df[valid_times]
70
-
71
- # 按散场时间排序
72
- df = df.sort_values('EndTime')
73
-
74
- # 分割数据
75
- split_time = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
76
- split_time_for_comparison = df['time_for_comparison'].apply(
77
- lambda x: datetime.combine(base_date, split_time.time())
78
- )
79
-
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")
@@ -203,24 +213,24 @@ st.title("散厅时间快捷打印")
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("夜班部分没有数据")
 
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"
 
15
  DATE_COLOR = '#A9A9A9'
16
 
17
  def process_schedule(file):
18
+ """处理上传的 Excel 文件,生成排序和分组后的打印内容"""
19
+ try:
20
+ # 读取 Excel,跳过前 8 行
21
+ df = pd.read_excel(file, skiprows=8)
22
+
23
+ # 提取所需列 (G9, H9, J9)
24
+ df = df.iloc[:, [6, 7, 9]] # G, H, J 列
25
+ df.columns = ['Hall', 'StartTime', 'EndTime']
26
+
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']
35
+
36
+ # 转换时间为 datetime 对象
37
+ base_date = datetime.today().date()
38
+ df['StartTime'] = pd.to_datetime(df['StartTime'])
39
+ df['EndTime'] = pd.to_datetime(df['EndTime'])
40
+
41
+ # 设置基准时间
42
+ business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
43
+ business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
44
+
45
+ # 处理跨天情况
46
+ if business_end < business_start:
47
+ business_end += timedelta(days=1)
48
+
49
+ # 标准化所有时间到同一天
50
+ for idx, row in df.iterrows():
51
+ end_time = row['EndTime']
52
+ if end_time.hour < 9:
53
+ df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
54
+
55
+ if row['StartTime'].hour >= 21 and end_time.hour < 9:
56
+ df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
57
+
58
+ # 筛选营业时间内的场次
59
+ df['time_for_comparison'] = df['EndTime'].apply(
60
+ lambda x: datetime.combine(base_date, x.time())
61
+ )
62
+
63
+ df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
64
+
65
+ valid_times = (
66
+ ((df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
67
+ (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time())))
68
+ )
69
+
70
+ df = df[valid_times]
71
+
72
+ # 按散场时间排序
73
+ df = df.sort_values('EndTime')
74
+
75
+ # 分割数据
76
+ split_time = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
77
+ split_time_for_comparison = df['time_for_comparison'].apply(
78
+ lambda x: datetime.combine(base_date, split_time.time())
79
+ )
80
+
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')
87
+
88
+ # 读取日期信息
89
+ date_df = pd.read_excel(
90
+ file,
91
+ skiprows=5,
92
+ nrows=1,
93
+ usecols=[2],
94
+ header=None
95
+ )
96
+ date_cell = date_df.iloc[0, 0]
97
+
98
+ try:
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
+ # 计算最大字符数
134
+ max_char_count = 0
135
+ for hall, end_time in data.values:
136
+ # 清理LaTeX标记并计算实际显示字符数
137
+ clean_hall = re.sub(r'\$.*?\$', '#', hall)
138
+ clean_text = f"{clean_hall}{end_time}"
139
+ current_count = len(clean_text)
140
+ max_char_count = max(max_char_count, current_count)
141
+
142
+ # 动态计算基础字号(确保最长文本占90%宽度)
143
+ cell_width_inches = 5.83 / 3 # 每列宽度(A5横向)
144
+ available_width = cell_width_inches * 0.9 * 72 # 转换为点数(1英寸=72点)
145
+ avg_char_width = 0.6 # 经验值(Arial字体字符宽度系数)
146
+ base_fontsize = available_width / (max_char_count * avg_char_width)
147
+ base_fontsize = min(30, base_fontsize) # 最大不超过30pt
148
+
149
+ # 填充数据
150
+ data_values = data.values.tolist()
151
+ while len(data_values) % 3 != 0:
152
+ data_values.append(['', ''])
153
+
154
+ sorted_data = [['', '']] * len(data_values)
155
+
156
+ for i, item in enumerate(data_values):
157
+ if item[0] and item[1]:
158
+ row = i % math.ceil(len(data_values)/3)
159
+ col = i // math.ceil(len(data_values)/3)
160
+ new_index = row * 3 + col
161
+ if new_index < len(sorted_data):
162
+ sorted_data[new_index] = item
163
+
164
+ for idx, (hall, end_time) in enumerate(sorted_data):
165
+ if hall and end_time:
166
+ row = idx // 3
167
+ col = idx % 3
168
+
169
+ ax = plt.subplot(gs[row, col])
170
+
171
+ for spine in ax.spines.values():
172
+ spine.set_color(BORDER_COLOR)
173
+ spine.set_linewidth(0.5)
174
+
175
+ ax.text(0.5, 0.5, f"{hall}{end_time}",
176
+ fontsize=base_fontsize,
177
+ fontweight='bold',
178
+ ha='center',
179
+ va='center')
180
+
181
+ ax.set_xlim(-0.02, 1.02)
182
+ ax.set_ylim(-0.02, 1.02)
183
+ ax.set_xticks([])
184
+ ax.set_yticks([])
185
+
186
+ # 添加日期信息
187
+ ax_date = plt.subplot(gs[0, 0])
188
+ ax_date.text(0.05, 0.95, f"{date_str} {title}",
189
+ fontsize=base_fontsize * 0.4,
190
+ color=DATE_COLOR,
191
+ fontweight='bold',
192
+ ha='left',
193
+ va='top')
194
+
195
+ for spine in ax_date.spines.values():
196
+ spine.set_visible(False)
197
+ ax_date.set_xticks([])
198
+ ax_date.set_yticks([])
199
+
200
+ # 转换为图片
201
+ buffer = io.BytesIO()
202
+ plt.savefig(buffer, format='png', bbox_inches='tight', pad_inches=0.05)
203
+ buffer.seek(0)
204
+ image_base64 = base64.b64encode(buffer.getvalue()).decode()
205
+ plt.close()
206
+
207
+ return f'data:image/png;base64,{image_base64}'
208
 
209
  # Streamlit 界面
210
  st.set_page_config(page_title="散厅时间快捷打印", layout="wide")
 
213
  uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls", "xlsx"])
214
 
215
  if uploaded_file:
216
+ part1, part2, date_str = process_schedule(uploaded_file)
217
+
218
+ if part1 is not None and part2 is not None:
219
+ part1_image = create_print_layout(part1, "A", date_str)
220
+ part2_image = create_print_layout(part2, "C", date_str)
221
+
222
+ col1, col2 = st.columns(2)
223
+
224
+ with col1:
225
+ st.subheader("白班散场预览(时间 ≤ 17:30)")
226
+ if part1_image:
227
+ st.image(part1_image)
228
+ else:
229
+ st.info("白班部分没有数据")
230
+
231
+ with col2:
232
+ st.subheader("夜班散场预览(时间 > 17:30)")
233
+ if part2_image:
234
+ st.image(part2_image)
235
+ else:
236
+ st.info("夜班部分没有数据")