File size: 24,591 Bytes
e93ba2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e45b222
e93ba2f
 
e45b222
e93ba2f
e45b222
 
e93ba2f
 
e45b222
e93ba2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e45b222
e93ba2f
 
 
 
 
 
 
 
 
 
 
 
 
 
e45b222
e93ba2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
from matplotlib.lines import Line2D
import io
import base64
import os
from datetime import datetime, timedelta, time
from pypinyin import lazy_pinyin, Style
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.gridspec as gridspec
import math

# --- 常量和配置 ---
BUSINESS_START = "09:30"
BUSINESS_END = "01:30"
BORDER_COLOR = 'grey'
DATE_COLOR = '#A9A9A9'
A5_WIDTH_IN = 5.83
A5_HEIGHT_IN = 8.27
NUM_COLS = 3

# --- 字体清单 ---
ALL_FONTS = {
    "思源黑体-常规 (推荐 LED 屏)": "SimHei.ttf",
    "思源黑体-重体 (推荐散场表)": "SourceHanSansOLD-Heavy-2.otf",
    "思源黑体-粗体": "SourceHanSansOLD-Bold-2.otf",
    "思源宋体-常规": "SourceHanSansCN-Normal.otf",
    "苹方-中黑": "PingFangSC-Medium.otf",
    "苹方-半粗": "PingFangSC-Semibold.otf",
    "苹方-极细": "PingFangSC-Ultralight.otf",
    "阿里巴巴普惠体-常规": "Alibaba-PuHuiTi.ttf",
    "阿里巴巴普惠体-粗体": "AlibabaPuHuiTi-Bold.otf",
    "阿里巴巴普惠体-重体": "AlibabaPuHuiTi-Heavy.otf",
}
AVAILABLE_FONTS = {name: fname for name, fname in ALL_FONTS.items() if os.path.exists(fname)}


# --- 字体加载与文本处理函数 ---

def get_font_properties(font_path, size=14):
    """通用字体加载函数"""
    if font_path and os.path.exists(font_path):
        return font_manager.FontProperties(fname=font_path, size=size)
    else:
        st.warning(f"警告:未找到字体文件 '{font_path}',显示可能不正确。将使用默认字体。")
        return font_manager.FontProperties(family='sans-serif', size=size)


def get_pinyin_abbr(text):
    """获取中文文本前两个字的拼音首字母"""
    if not text: return ""
    chars = [c for c in text if '\u4e00' <= c <= '\u9fff'][:2]
    if not chars: return ""
    pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
    return ''.join(pinyin_list).upper()


def format_seq(n):
    """将数字或字符转换为带圈序号 (①, ②, ③...),非数字则直接返回"""
    try:
        n = int(n)
    except (ValueError, TypeError):
        return str(n)
    if n <= 0: return str(n)
    circled_chars = "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
    if 1 <= n <= 50: return circled_chars[n - 1]
    return f'({n})'


# --- 核心数据处理函数 ---

def process_unified_schedule(file, split_time_str, time_adjustment_minutes=0):
    """
    统一处理 '放映时间核对表.xls' 文件, 生成两种表格所需的数据。
    """
    try:
        date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
        date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
        base_date = pd.to_datetime(date_str).date()
    except Exception:
        date_str = datetime.today().strftime('%Y-%m-%d')
        base_date = datetime.today().date()

    try:
        df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
        df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
        df['Hall'] = df['Hall'].ffill()
        df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
    except Exception as e:
        st.error(f"读取排期数据时出错: {e}。请检查文件格式是否为'放映时间核对表'。")
        return None, None, None, date_str

    # 'LED屏排片表' 数据处理
    led_df = df.copy()
    try:
        # **优化2**: 优先提取 'X号',失败则取第一个字符 + '号'
        extracted = led_df['Hall'].astype(str).str.extract(r'(\d+号)')
        fallback = led_df['Hall'].astype(str).str[0] + '号'
        led_df['Hall'] = extracted[0].fillna(fallback)

        led_df['StartTime_dt'] = pd.to_datetime(led_df['StartTime'], format='%H:%M', errors='coerce').apply(
            lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t)
        led_df['EndTime_dt'] = pd.to_datetime(led_df['EndTime'], format='%H:%M', errors='coerce').apply(
            lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t)
        led_df.loc[led_df['EndTime_dt'] < led_df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
        led_df = led_df.sort_values(['Hall', 'StartTime_dt'])
        merged_rows = []
        for _, group in led_df.groupby('Hall'):
            current = None
            for _, row in group.sort_values('StartTime_dt').iterrows():
                if current is None:
                    current = row.copy()
                elif row['Movie'] == current['Movie']:
                    current['EndTime_dt'] = row['EndTime_dt']
                else:
                    merged_rows.append(current)
                    current = row.copy()
            if current is not None: merged_rows.append(current)
        merged_df = pd.DataFrame(merged_rows)
        merged_df['StartTime_dt'] -= timedelta(minutes=10)
        merged_df['EndTime_dt'] -= timedelta(minutes=5)
        merged_df['Seq'] = merged_df.groupby('Hall').cumcount() + 1
        merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
        merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
        led_schedule_df = merged_df[['Hall', 'Seq', 'Movie', 'StartTime_str', 'EndTime_str']]
    except Exception as e:
        st.error(f"处理 'LED屏排片表' 数据时出错: {e}")
        led_schedule_df = None

    # '散场时间快捷打印' 数据处理
    times_df = df.copy()
    try:
        # **优化2**: 优先提取数字,失败则取第一个字符
        num_part = times_df['Hall'].str.extract(r'(\d+)')[0]
        char_part = times_df['Hall'].astype(str).str[0]
        times_df['Hall'] = num_part.fillna(char_part)
        times_df.dropna(subset=['Hall', 'StartTime', 'EndTime'], inplace=True)
        times_df['StartTime_dt'] = pd.to_datetime(times_df['StartTime'], format='%H:%M', errors='coerce').apply(
            lambda t: datetime.combine(base_date, t.time()) if pd.notnull(t) else pd.NaT)
        times_df['EndTime_dt'] = pd.to_datetime(times_df['EndTime'], format='%H:%M', errors='coerce').apply(
            lambda t: datetime.combine(base_date, t.time()) if pd.notnull(t) else pd.NaT)
        times_df.loc[times_df['EndTime_dt'] < times_df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)

        # **优化4**: 应用时间提前量
        if time_adjustment_minutes > 0:
            times_df['EndTime_dt'] -= timedelta(minutes=time_adjustment_minutes)

        business_start_dt = datetime.combine(base_date, datetime.strptime(BUSINESS_START, "%H:%M").time())
        business_end_dt = datetime.combine(base_date, datetime.strptime(BUSINESS_END, "%H:%M").time())
        if business_end_dt < business_start_dt: business_end_dt += timedelta(days=1)
        times_df = times_df[(times_df['EndTime_dt'] >= business_start_dt) & (times_df['EndTime_dt'] <= business_end_dt)]
        times_df = times_df.sort_values('EndTime_dt')
        split_dt = datetime.combine(base_date, split_time_str)
        part1 = times_df[times_df['EndTime_dt'] <= split_dt].copy()
        part2 = times_df[times_df['EndTime_dt'] > split_dt].copy()

        # **优化1**: 使用 %H:%M 保证两位小时
        part1['EndTime'] = part1['EndTime_dt'].dt.strftime('%H:%M')
        part2['EndTime'] = part2['EndTime_dt'].dt.strftime('%H:%M')

        times_part1_df = part1[['Hall', 'EndTime']]
        times_part2_df = part2[['Hall', 'EndTime']]
    except Exception as e:
        st.error(f"处理 '散场时间表' 数据时出错: {e}")
        times_part1_df, times_part2_df = None, None

    return led_schedule_df, times_part1_df, times_part2_df, date_str


# --- 'LED屏排片表' 布局生成函数 ---
def create_print_layout_led(data, date_str, font_path, generate_png=False):
    if data is None or data.empty: return None
    A4_width_in, A4_height_in = 8.27, 11.69
    dpi = 300
    total_content_rows = len(data)
    layout_rows = max(total_content_rows, 25)
    totalA = layout_rows + 2
    row_height = A4_height_in / totalA
    data = data.reset_index(drop=True)
    data['hall_str'] = '$' + data['Hall'].str.replace('号', '') + '^{\#}$'
    data['seq_str'] = data['Seq'].apply(format_seq)
    data['pinyin_abbr'] = data['Movie'].apply(get_pinyin_abbr)
    data['time_str'] = data['StartTime_str'] + ' - ' + data['EndTime_str']
    temp_fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=dpi)
    renderer = temp_fig.canvas.get_renderer()
    base_font_size_pt = (row_height * 0.9) * 72
    seq_font_size_pt = (row_height * 0.5) * 72

    def get_col_width_in(series, font_size_pt, is_math=False):
        if series.empty: return 0
        font_prop = get_font_properties(font_path, font_size_pt)
        longest_str_idx = series.astype(str).str.len().idxmax()
        max_content = str(series.loc[longest_str_idx])
        text_width_px, _, _ = renderer.get_text_width_height_descent(max_content, font_prop, ismath=is_math)
        return (text_width_px / dpi) * 1.1

    margin_col_width = row_height
    hall_col_width = get_col_width_in(data['hall_str'], base_font_size_pt, is_math=True)
    seq_col_width = get_col_width_in(data['seq_str'], seq_font_size_pt)
    pinyin_col_width = get_col_width_in(data['pinyin_abbr'], base_font_size_pt)
    time_col_width = get_col_width_in(data['time_str'], base_font_size_pt)
    movie_col_width = A4_width_in - (
                margin_col_width * 2 + hall_col_width + seq_col_width + pinyin_col_width + time_col_width)
    plt.close(temp_fig)
    col_widths = {'hall': hall_col_width, 'seq': seq_col_width, 'movie': movie_col_width, 'pinyin': pinyin_col_width,
                  'time': time_col_width}
    col_x_starts = {}
    current_x = margin_col_width
    for col_name in ['hall', 'seq', 'movie', 'pinyin', 'time']:
        col_x_starts[col_name] = current_x
        current_x += col_widths[col_name]

    def draw_figure(fig, ax):
        renderer = fig.canvas.get_renderer()
        for col_name in ['hall', 'seq', 'movie', 'pinyin']:
            x_line = col_x_starts[col_name] + col_widths[col_name]
            line_top_y, line_bottom_y = A4_height_in - row_height, row_height
            ax.add_line(
                Line2D([x_line, x_line], [line_bottom_y, line_top_y], color='gray', linestyle=':', linewidth=0.5))
        last_hall_drawn = None
        for i, row in data.iterrows():
            y_bottom = A4_height_in - (i + 2) * row_height
            y_center = y_bottom + row_height / 2
            if row['Hall'] != last_hall_drawn:
                ax.text(col_x_starts['hall'] + col_widths['hall'] / 2, y_center, row['hall_str'],
                        fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
                last_hall_drawn = row['Hall']
            ax.text(col_x_starts['seq'] + col_widths['seq'] / 2, y_center, row['seq_str'],
                    fontproperties=get_font_properties(font_path, seq_font_size_pt), ha='center', va='center')
            ax.text(col_x_starts['pinyin'] + col_widths['pinyin'] / 2, y_center, row['pinyin_abbr'],
                    fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
            ax.text(col_x_starts['time'] + col_widths['time'] / 2, y_center, row['time_str'],
                    fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
            movie_font_size = base_font_size_pt
            movie_font_prop = get_font_properties(font_path, movie_font_size)
            text_w_px, _, _ = renderer.get_text_width_height_descent(row['Movie'], movie_font_prop, ismath=False)
            text_w_in = text_w_px / dpi
            max_width_in = col_widths['movie'] * 0.9
            if text_w_in > max_width_in:
                movie_font_size *= (max_width_in / text_w_in)
                movie_font_prop = get_font_properties(font_path, movie_font_size)
            ax.text(col_x_starts['movie'] + 0.05, y_center, row['Movie'], fontproperties=movie_font_prop, ha='left',
                    va='center')
            is_last_in_hall = (i == len(data) - 1) or (row['Hall'] != data.loc[i + 1, 'Hall'])
            line_start_x, line_end_x = margin_col_width, A4_width_in - margin_col_width
            if is_last_in_hall:
                ax.add_line(Line2D([line_start_x, line_end_x], [y_bottom, y_bottom], color='black', linestyle='-',
                                   linewidth=0.8))
            else:
                ax.add_line(Line2D([line_start_x, line_end_x], [y_bottom, y_bottom], color='gray', linestyle=':',
                                   linewidth=0.5))

    outputs = {}
    fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=300)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_axis_off();
    ax.set_xlim(0, A4_width_in);
    ax.set_ylim(0, A4_height_in)
    ax.text(margin_col_width, A4_height_in - row_height, date_str, fontproperties=get_font_properties(font_path, 10),
            color=DATE_COLOR, ha='left', va='bottom', transform=ax.transData)
    draw_figure(fig, ax)
    pdf_buf = io.BytesIO()
    fig.savefig(pdf_buf, format='pdf', dpi=dpi, bbox_inches='tight', pad_inches=0)
    pdf_buf.seek(0)
    outputs['pdf'] = f"data:application/pdf;base64,{base64.b64encode(pdf_buf.getvalue()).decode()}"
    if generate_png:
        png_buf = io.BytesIO()
        fig.savefig(png_buf, format='png', dpi=dpi, bbox_inches='tight', pad_inches=0)
        png_buf.seek(0)
        outputs['png'] = f"data:image/png;base64,{base64.b64encode(png_buf.getvalue()).decode()}"
    plt.close(fig)
    return outputs


# --- '散场时间表' 布局生成函数 ---
def create_print_layout_times(data, title, date_str, font_path, size_multiplier=1.1, hall_format='Default',
                              generate_png=False):
    if data is None or data.empty: return None

    def generate_figure():
        total_items = len(data)
        num_rows = math.ceil(total_items / NUM_COLS) if total_items > 0 else 1
        data_area_height_in, cell_width_in = A5_HEIGHT_IN, A5_WIDTH_IN / NUM_COLS
        cell_height_in = data_area_height_in / num_rows
        target_width_pt, target_height_pt = (cell_width_in * 0.9) * 72, (cell_height_in * 0.9) * 72
        font_size_based_on_width = target_width_pt / (8 * 0.6)
        base_fontsize = min(font_size_based_on_width, target_height_pt) * size_multiplier
        fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
        fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
        gs = gridspec.GridSpec(num_rows, NUM_COLS, hspace=0, wspace=0, figure=fig)
        data_values = data.values.tolist()
        while len(data_values) % NUM_COLS != 0: data_values.append(['', ''])
        rows_per_col_layout = math.ceil(len(data_values) / NUM_COLS)
        sorted_data = [['', '']] * len(data_values)
        for i, item in enumerate(data_values):
            if item[0] and item[1]:
                row_in_col, col_idx = i % rows_per_col_layout, i // rows_per_col_layout
                new_index = row_in_col * NUM_COLS + col_idx
                if new_index < len(sorted_data): sorted_data[new_index] = item
        is_first_cell_with_data = True
        for idx, (hall, end_time) in enumerate(sorted_data):
            if hall and end_time:
                row_grid, col_grid = idx // NUM_COLS, idx % NUM_COLS
                ax = fig.add_subplot(gs[row_grid, col_grid])
                for spine in ax.spines.values():
                    spine.set_visible(True);
                    spine.set_linestyle((0, (1, 2)))
                    spine.set_color(BORDER_COLOR);
                    spine.set_linewidth(0.75)
                if is_first_cell_with_data:
                    ax.text(0.05, 0.95, f"{date_str} {title}",
                            fontproperties=get_font_properties(font_path, base_fontsize * 0.5), color=DATE_COLOR,
                            ha='left', va='top', transform=ax.transAxes)
                    is_first_cell_with_data = False
                if hall_format == 'Superscript':
                    display_text = f'${str(hall)}^{{\#}}$ {end_time}'
                elif hall_format == 'Circled':
                    display_text = f'{format_seq(hall)} {end_time}'
                else:  # Default
                    display_text = f"{str(hall)} {end_time}"
                ax.text(0.5, 0.5, display_text, fontproperties=get_font_properties(font_path, base_fontsize),
                        ha='center', va='center', transform=ax.transAxes)
                ax.set_xticks([]);
                ax.set_yticks([]);
                ax.set_facecolor('none')
        return fig

    fig_for_output = generate_figure()
    outputs = {}
    pdf_buffer = io.BytesIO()
    with PdfPages(pdf_buffer) as pdf:
        pdf.savefig(fig_for_output)
    pdf_buffer.seek(0)
    outputs['pdf'] = f"data:application/pdf;base64,{base64.b64encode(pdf_buffer.getvalue()).decode()}"
    if generate_png:
        png_buffer = io.BytesIO()
        fig_for_output.savefig(png_buffer, format='png')
        png_buffer.seek(0)
        outputs['png'] = f'data:image/png;base64,{base64.b64encode(png_buffer.getvalue()).decode()}'
    plt.close(fig_for_output)
    return outputs


def display_pdf(base64_pdf):
    """在Streamlit中嵌入显示PDF"""
    return f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'


# --- Streamlit 主程序 ---
st.set_page_config(page_title="影院场次与散场时间快捷打印工具", layout="wide")
st.title("影院场次与散场时间快捷打印工具")

uploaded_file = st.file_uploader("请上传 `放映时间核对表.xls` 文件", type=["xls"])

with st.expander("⚙️ 显示与打印设置", expanded=False):
    col1, col2 = st.columns(2)
    with col1:
        st.subheader("⚙️ 修改 LED 屏排片表设置")
        led_font_name = st.selectbox("字体选择", options=list(AVAILABLE_FONTS.keys()), index=0, key="led_font")
        led_font_path = AVAILABLE_FONTS.get(led_font_name)
        generate_png_led = st.checkbox("生成 PNG 图片", value=False, key="png_led")
    with col2:
        st.subheader("⚙️ 散场时间表设置")
        times_font_name = st.selectbox("字体选择", options=list(AVAILABLE_FONTS.keys()), index=1, key="times_font")
        times_font_path = AVAILABLE_FONTS.get(times_font_name)
        # **优化5**: 调整字体大小范围
        font_size_multiplier = st.slider("字体大小调节", min_value=0.8, max_value=1.5, value=1.2, step=0.05,
                                         help="调整字体在单元格内的相对大小")
        split_time = st.time_input("白班 / 晚班分割时间", value=time(17, 0), help="散场时间在此时间点之前(含)的为白班")
        # **优化4**: 增加时间提前设置
        time_adjustment = st.slider("时间提前 (分钟)", min_value=0, max_value=10, value=0,
                                    help="将所有散场时间提前 N 分钟显示")
        hall_display_format = st.radio("影厅号格式", options=['Default', 'Superscript', 'Circled'],
                                       format_func=lambda x:
                                       {'Default': '默认 (2 18:28)', 'Superscript': '上标 (2# 18:28)',
                                        'Circled': '带圈 (② 18:28)'}[x], horizontal=True)
        generate_png_times = st.checkbox("生成 PNG 图片", value=False, key="png_times")

with st.expander("💡 使用帮助", expanded=False):
    st.markdown("""
    #### 🖨️ 功能简介
    本工具用于将影院的 `放映时间核对表.xls` 文件快速转换为两种形式的打印页:
    1.  **修改 LED 屏幕排片表打印**:A4 竖版,详细列出影厅、场次、影片名、拼音缩写和时间范围,方便员工在修改 LED 屏幕时快速查阅和输入。
    - 拼音缩写是为了在输入法如 QQ 拼音输入法等造词功能,拼音缩写填写快捷键,内容填写影片名字,更快捷输入。
    - 时间范围已经优化过了,默认提前了 10 分钟。
    2.  **散场时间打印**:A5 竖版,以大字体分栏显示各影厅的散场时间,方便员工在疏散人群和清洁影厅时查阅。
    - 内容分三列,顺序是每列从上到下。
    - 可以在设置里面设置提前如 5 分钟,到时间就可以前往影厅在疏散人群和清洁影厅。

    #### ⬇️ 操作步骤
    1.  **上传文件**:导出 `放映时间核对表.xls` 后,点击上方的 "Browse files" 按钮,选择您的 `放映时间核对表.xls` 文件。
    2.  **调整设置 (可选)**:点击上方的 "显示与打印设置" 打开设置面板,根据需要调整字体、大小、格式等。
    3.  **预览与打印**:
        *   上传成功后,下方会自动生成预览。
        *   默认显示 **PDF 预览**,这是最适合打印的格式。可以直接在预览界面点击 🖨️ 打印按钮,设置纸张大小即可打印。
        *   如果勾选了 "生成 PNG 图片",可以切换到 **图片预览 (PNG)** 标签页查看或在新标签页中打开图片或下载图片后打印。
    """)

# --- 主页面逻辑 ---
if uploaded_file:
    with st.spinner("正在处理文件,请稍候..."):
        led_data, times_part1, times_part2, date_str = process_unified_schedule(uploaded_file, split_time,
                                                                                time_adjustment)

    st.toast(f"文件处理完成!排期日期:**{date_str}**", icon="🎉")

    # 显示 LED 屏排片表
    st.header("🖥️ 修改 LED 屏幕排片表打印")
    if led_data is not None and not led_data.empty:
        led_output = create_print_layout_led(led_data, date_str, led_font_path, generate_png_led)
        if led_output:
            tabs = ["PDF 预览"]
            if 'png' in led_output: tabs.append("PNG 预览")
            tab_views = st.tabs(tabs)
            with tab_views[0]:
                st.markdown(display_pdf(led_output['pdf']), unsafe_allow_html=True)
            if 'png' in led_output:
                with tab_views[1]: st.image(led_output['png'], use_container_width=True)
    else:
        st.error("未能成功生成 '修改 LED 屏排片表'。请检查文件内容或格式。")

    # 显示散场时间快捷打印
    st.header("🔚 散场时间打印")
    col1, col2 = st.columns(2)
    with col1:
        if times_part1 is not None and not times_part1.empty:
            part1_output = create_print_layout_times(times_part1, "A", date_str, times_font_path, font_size_multiplier,
                                                     hall_display_format, generate_png_times)
            if part1_output:
                # **优化3**: 更改Tab标题
                tabs1 = [f"白班 (≤ {split_time.strftime('%H:%M')}) PDF 预览"]
                if 'png' in part1_output: tabs1.append(f"白班 (≤ {split_time.strftime('%H:%M')}) PNG 预览")
                tab_views1 = st.tabs(tabs1)
                with tab_views1[0]:
                    st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True)
                if 'png' in part1_output:
                    with tab_views1[1]: st.image(part1_output['png'])
        else:
            st.info(f"白班 (≤ {split_time.strftime('%H:%M')}) 没有排期数据。")

    with col2:
        if times_part2 is not None and not times_part2.empty:
            part2_output = create_print_layout_times(times_part2, "C", date_str, times_font_path, font_size_multiplier,
                                                     hall_display_format, generate_png_times)
            if part2_output:
                # **优化3**: 更改Tab标题
                tabs2 = [f"晚班 (> {split_time.strftime('%H:%M')}) PDF 预览"]
                if 'png' in part2_output: tabs2.append(f"晚班 (> {split_time.strftime('%H:%M')}) PNG 预览")
                tab_views2 = st.tabs(tabs2)
                with tab_views2[0]:
                    st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True)
                if 'png' in part2_output:
                    with tab_views2[1]: st.image(part2_output['png'])
        else:
            st.info(f"晚班 (> {split_time.strftime('%H:%M')}) 没有排期数据。")
else:
    st.info("👆 请先上传文件以生成预览。")