File size: 19,318 Bytes
70694c9
 
 
 
 
 
 
 
7c5a0e0
2471374
7c5a0e0
a215102
 
70694c9
a215102
 
 
 
 
 
 
 
70694c9
1b1b918
1878cfc
 
a215102
 
 
 
 
 
 
 
 
70694c9
 
928edc3
1878cfc
 
2471374
1878cfc
1b1b918
093d429
1878cfc
 
70694c9
a215102
 
 
1878cfc
093d429
1878cfc
 
 
1b1b918
093d429
1878cfc
 
a215102
1878cfc
 
 
 
 
 
a215102
093d429
1878cfc
 
 
 
 
 
 
 
a215102
2471374
1878cfc
928edc3
1878cfc
 
 
 
 
 
928edc3
093d429
928edc3
 
 
1878cfc
 
a215102
1878cfc
a215102
7c5a0e0
1878cfc
 
a215102
1878cfc
 
a215102
1878cfc
1b1b918
093d429
1878cfc
70694c9
a215102
 
 
1878cfc
 
1b1b918
093d429
1878cfc
 
 
093d429
a215102
1878cfc
 
 
093d429
a215102
1b1b918
093d429
 
 
 
928edc3
a215102
093d429
 
 
a215102
093d429
 
 
 
 
 
edb1602
093d429
 
 
 
edb1602
 
 
 
 
7c5a0e0
90c1aa2
1878cfc
928edc3
093d429
 
a215102
1b1b918
093d429
5366108
093d429
 
 
 
7c5a0e0
093d429
 
 
 
 
 
 
 
 
1878cfc
093d429
 
90c1aa2
a215102
093d429
1b1b918
1878cfc
1b1b918
928edc3
1878cfc
 
 
 
 
 
 
093d429
 
1878cfc
 
 
 
 
 
 
 
70694c9
a215102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70694c9
093d429
 
 
 
 
70694c9
a215102
 
 
70694c9
a215102
 
 
 
 
70694c9
 
093d429
a215102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1878cfc
a215102
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
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import io
import base64
import os
from datetime import datetime, timedelta
import math
from pypinyin import lazy_pinyin, Style
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.gridspec as gridspec
from matplotlib.patches import FancyBboxPatch

# --- Constants for "Quick Print" (放映场次核对表) ---
SPLIT_TIME = "17:30"
BUSINESS_START = "09:30"
BUSINESS_END = "01:30"
BORDER_COLOR = '#A9A9A9'
DATE_COLOR = '#A9A9A9'

# --- Helper functions for "LED Screen" (放映时间核对表) ---
def get_font(size=14):
    """Loads a specific font file, falling back to a default if not found."""
    font_path = "simHei.ttc"
    if not os.path.exists(font_path):
        font_path = "SimHei.ttf"  # Fallback font
    # Add a final fallback for systems without Chinese fonts
    try:
        return font_manager.FontProperties(fname=font_path, size=size)
    except RuntimeError:
        # If the font file is not found, use a default font that should exist.
        # This will likely not render Chinese characters correctly but prevents crashing.
        return font_manager.FontProperties(family='sans-serif', size=size)


def get_pinyin_abbr(text):
    """Gets the first letter of the Pinyin for the first two Chinese characters of a text."""
    if not text:
        return ""
    # Extract the first two Chinese characters
    chars = [c for c in text if '\u4e00' <= c <= '\u9fff']
    chars = chars[:2]
    # Get the first letter of the pinyin for each character
    pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
    return ''.join(pinyin_list).upper()

# --- Processing logic for "LED Screen" (放映时间核对表) ---
def process_schedule_led(file):
    """Processes the '放映时间核对表.xls' file."""
    try:
        # Attempt to read the date from a specific cell
        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:
        # Fallback to the current date if reading fails
        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)
        df['Hall'] = df['Hall'].astype(str).str.extract(r'(\d+号)')

        # Convert times to datetime objects, handling overnight screenings
        df['StartTime_dt'] = pd.to_datetime(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
        )
        df['EndTime_dt'] = pd.to_datetime(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
        )
        df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
        df = df.sort_values(['Hall', 'StartTime_dt'])

        # Merge consecutive screenings of the same movie
        merged_rows = []
        for hall, group in df.groupby('Hall'):
            group = group.sort_values('StartTime_dt')
            current = None
            for _, row in group.iterrows():
                if current is None:
                    current = row.copy()
                else:
                    if 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)

        # Adjust start and end times
        merged_df['StartTime_dt'] = merged_df['StartTime_dt'] - timedelta(minutes=10)
        merged_df['EndTime_dt'] = merged_df['EndTime_dt'] - timedelta(minutes=5)

        merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
        merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')

        return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
    except Exception as e:
        st.error(f"An error occurred during file processing: {e}")
        return None, date_str

# --- Layout generation for "LED Screen" (放映时间核对表) ---
def create_print_layout_led(data, date_str):
    """Generates PNG and PDF layouts for the 'LED Screen' schedule."""
    if data is None or data.empty:
        return None

    # Create figures for PNG and PDF output with A4 dimensions
    png_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
    png_ax = png_fig.add_subplot(111)
    png_ax.set_axis_off()
    png_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)

    pdf_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
    pdf_ax = pdf_fig.add_subplot(111)
    pdf_ax.set_axis_off()
    pdf_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)

    def process_figure(fig, ax):
        halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号','')) if h else 0)

        num_separators = len(halls) - 1
        total_layout_rows = len(data) + num_separators + 2
        
        available_height = 0.96
        row_height = available_height / total_layout_rows

        fig_height_inches = fig.get_figheight()
        row_height_points = row_height * fig_height_inches * 72
        font_size = row_height_points * 0.9

        date_font = get_font(font_size * 0.8)
        hall_font = get_font(font_size)
        movie_font = get_font(font_size)

        col_hall_left = 0.0
        col_movie_right = 0.50
        col_seq_left = 0.52
        col_pinyin_left = 0.62
        col_time_left = 0.75

        ax.text(col_hall_left, 0.99, date_str, color='#A9A9A9',
                ha='left', va='top', fontproperties=date_font, transform=ax.transAxes)
        
        y_position = 0.98 - row_height
        
        for i, hall in enumerate(halls):
            hall_data = data[data['Hall'] == hall]
            
            if i > 0:
                ax.axhline(y=y_position + row_height / 2, xmin=col_hall_left, xmax=0.97, color='black', linewidth=0.7)
                y_position -= row_height

            movie_count = 1
            for _, row in hall_data.iterrows():
                if movie_count == 1:
                    ax.text(col_hall_left, y_position, f"{hall.replace('号', '')}#",
                            ha='left', va='center', fontweight='bold',
                            fontproperties=hall_font, transform=ax.transAxes)
                
                ax.text(col_movie_right, y_position, row['Movie'],
                        ha='right', va='center', fontproperties=movie_font, transform=ax.transAxes)

                ax.text(col_seq_left, y_position, f"{movie_count}.",
                        ha='left', va='center', fontproperties=movie_font, transform=ax.transAxes)

                pinyin_abbr = get_pinyin_abbr(row['Movie'])
                ax.text(col_pinyin_left, y_position, pinyin_abbr,
                        ha='left', va='center', fontproperties=movie_font, transform=ax.transAxes)
                
                ax.text(col_time_left, y_position, f"{row['StartTime_str']}-{row['EndTime_str']}",
                        ha='left', va='center', fontproperties=movie_font, transform=ax.transAxes)

                y_position -= row_height
                movie_count += 1

    process_figure(png_fig, png_ax)
    process_figure(pdf_fig, pdf_ax)
    
    png_buffer = io.BytesIO()
    png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.05)
    png_buffer.seek(0)
    image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
    plt.close(png_fig)
    
    pdf_buffer = io.BytesIO()
    with PdfPages(pdf_buffer) as pdf:
        pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
    pdf_buffer.seek(0)
    pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
    plt.close(pdf_fig)
    
    return {
        'png': f"data:image/png;base64,{image_base64}",
        'pdf': f"data:application/pdf;base64,{pdf_base64}"
    }

# --- Processing logic for "Quick Print" (放映场次核对表) ---
def process_schedule_quick(file):
    """Processes the '放映场次核对表.xls' file."""
    try:
        df = pd.read_excel(file, skiprows=8)
        df = df.iloc[:, [6, 7, 9]]
        df.columns = ['Hall', 'StartTime', 'EndTime']
        df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
        df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str) + ' '
        
        base_date = datetime.today().date()
        df['StartTime'] = pd.to_datetime(df['StartTime'])
        df['EndTime'] = pd.to_datetime(df['EndTime'])

        business_start = datetime.strptime(f"{base_date} {BUSINESS_START}", "%Y-%m-%d %H:%M")
        business_end = datetime.strptime(f"{base_date} {BUSINESS_END}", "%Y-%m-%d %H:%M")
        if business_end < business_start:
            business_end += timedelta(days=1)

        for idx, row in df.iterrows():
            end_time = row['EndTime']
            if end_time.hour < 9:
                df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
            if row['StartTime'].hour >= 21 and end_time.hour < 9:
                df.at[idx, 'EndTime'] = end_time + timedelta(days=1)
        
        df['time_for_comparison'] = df['EndTime'].apply(lambda x: datetime.combine(base_date, x.time()))
        df.loc[df['time_for_comparison'].dt.hour < 9, 'time_for_comparison'] += timedelta(days=1)
        
        valid_times = (
            (df['time_for_comparison'] >= datetime.combine(base_date, business_start.time())) &
            (df['time_for_comparison'] <= datetime.combine(base_date + timedelta(days=1), business_end.time()))
        )
        df = df[valid_times]
        df = df.sort_values('EndTime')
        
        split_time_dt = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
        
        part1 = df[df['time_for_comparison'] <= split_time_dt].copy()
        part2 = df[df['time_for_comparison'] > split_time_dt].copy()

        for part in [part1, part2]:
            part['EndTime'] = part['EndTime'].dt.strftime('%-H:%M')
        
        date_df = pd.read_excel(file, skiprows=5, nrows=1, usecols=[2], header=None)
        date_cell = date_df.iloc[0, 0]
        
        try:
            if isinstance(date_cell, str):
                date_str = datetime.strptime(date_cell, '%Y-%m-%d').strftime('%Y-%m-%d')
            else:
                date_str = pd.to_datetime(date_cell).strftime('%Y-%m-%d')
        except:
            date_str = datetime.today().strftime('%Y-%m-%d')
            
        return part1[['Hall', 'EndTime']], part2[['Hall', 'EndTime']], date_str

    except Exception as e:
        st.error(f"处理文件时出错: {str(e)}")
        return None, None, None

# --- Layout generation for "Quick Print" (放映场次核对表) ---
def create_print_layout_quick(data, title, date_str):
    """Creates print layout for the 'Quick Print' schedule."""
    if data.empty:
        return None

    png_fig = plt.figure(figsize=(5.83, 8.27), dpi=300) # A5
    png_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)

    pdf_fig = plt.figure(figsize=(5.83, 8.27), dpi=300) # A5
    pdf_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)

    def process_figure(fig, is_pdf=False):
        plt.rcParams['font.family'] = 'sans-serif'
        plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'Heiti TC', 'SimHei']

        total_items = len(data)
        num_cols = 3
        num_rows = math.ceil(total_items / num_cols)

        gs = gridspec.GridSpec(num_rows + 1, num_cols, hspace=0.05, wspace=0.05, height_ratios=[0.1] + [1] * num_rows, figure=fig)

        target_width_px = 1
        if total_items > 0:
            ax_temp = fig.add_subplot(gs[1, 0])
            fig.canvas.draw()
            target_width_px = ax_temp.get_window_extent().width * 0.90
            ax_temp.remove()

        available_height_per_row = (8.27 * 0.9 * (1 / 1.2)) / num_rows if num_rows > 0 else 1
        date_fontsize = min(40, max(10, available_height_per_row * 72 * 0.5))

        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 = i % rows_per_col_layout
                col_idx = 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

        for idx, (hall, end_time) in enumerate(sorted_data):
            if hall and end_time:
                row_grid = idx // num_cols + 1
                col_grid = idx % num_cols

                if row_grid < num_rows + 1:
                    ax = fig.add_subplot(gs[row_grid, col_grid])
                    for spine in ax.spines.values():
                        spine.set_visible(False)

                    bbox = FancyBboxPatch(
                        (0.01, 0.01), 0.98, 0.98,
                        boxstyle="round,pad=0,rounding_size=0.02",
                        edgecolor=BORDER_COLOR, facecolor='none',
                        linewidth=0.5, transform=ax.transAxes, clip_on=False
                    )
                    ax.add_patch(bbox)

                    display_text = f"{hall}{end_time}"
                    t = ax.text(0.5, 0.5, display_text,
                                fontweight='bold', ha='center', va='center',
                                transform=ax.transAxes)
                    
                    current_size = 120
                    while current_size > 1:
                        t.set_fontsize(current_size)
                        text_bbox = t.get_window_extent(renderer=fig.canvas.get_renderer())
                        if text_bbox.width <= target_width_px:
                            break
                        current_size -= 2

                    ax.set_xticks([])
                    ax.set_yticks([])

        ax_date = fig.add_subplot(gs[0, :])
        ax_date.text(0.01, 0.5, f"{date_str} {title}",
                     fontsize=date_fontsize * 0.5,
                     color=DATE_COLOR, fontweight='bold',
                     ha='left', va='center', transform=ax_date.transAxes)
        for spine in ax_date.spines.values():
            spine.set_visible(False)
        ax_date.set_xticks([])
        ax_date.set_yticks([])
        ax_date.set_facecolor('none')

    process_figure(png_fig)
    process_figure(pdf_fig, is_pdf=True)

    png_buffer = io.BytesIO()
    png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.02)
    png_buffer.seek(0)
    png_base64 = base64.b64encode(png_buffer.getvalue()).decode()
    plt.close(png_fig)

    pdf_buffer = io.BytesIO()
    with PdfPages(pdf_buffer) as pdf:
        pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.02)
    pdf_buffer.seek(0)
    pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
    plt.close(pdf_fig)

    return {
        'png': f'data:image/png;base64,{png_base64}',
        'pdf': f'data:application/pdf;base64,{pdf_base64}'
    }

# --- Generic Helper to Display PDF ---
def display_pdf(base64_pdf):
    """Generates the HTML to embed and display a PDF in Streamlit."""
    pdf_display = f"""
    <iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>
    """
    return pdf_display

# --- Main Streamlit App ---
st.set_page_config(page_title="影院排期打印工具", layout="wide")
st.title("影院排期打印工具")

uploaded_file = st.file_uploader(
    "选择【放映时间核对表.xls】或【放映场次核对表.xls】文件",
    accept_multiple_files=False,
    type=["xls"]
)

if uploaded_file:
    with st.spinner("文件正在处理中,请稍候..."):
        # --- Route to the correct processor based on filename ---

        # 1. Logic for "LED 屏幕时间表打印"
        if "放映时间核对表" in uploaded_file.name:
            st.subheader("LED 屏幕时间表")
            schedule, date_str = process_schedule_led(uploaded_file)
            if schedule is not None:
                output = create_print_layout_led(schedule, date_str)
                if output:
                    tab1, tab2 = st.tabs(["PDF 预览", "PNG 预览"])
                    with tab1:
                        st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True)
                    with tab2:
                        st.image(output['png'], use_container_width=True)
                else:
                    st.info("没有可显示的数据。")
            else:
                st.error("无法处理文件,请检查文件格式或内容是否正确。")

        # 2. Logic for "散厅时间快捷打印"
        elif "放映场次核对表" in uploaded_file.name:
            part1_data, part2_data, date_str = process_schedule_quick(uploaded_file)

            if part1_data is not None and part2_data is not None:
                part1_output = create_print_layout_quick(part1_data, "A", date_str)
                part2_output = create_print_layout_quick(part2_data, "C", date_str)

                col1, col2 = st.columns(2)

                with col1:
                    st.subheader("白班散场预览(时间 ≤ 17:30)")
                    if part1_output:
                        tab1_1, tab1_2 = st.tabs(["PDF 预览 ", "PNG 预览 "]) # Added space to make keys unique
                        with tab1_1:
                            st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True)
                        with tab1_2:
                            st.image(part1_output['png'])
                    else:
                        st.info("白班部分没有数据")

                with col2:
                    st.subheader("夜班散场预览(时间 > 17:30)")
                    if part2_output:
                        tab2_1, tab2_2 = st.tabs(["PDF 预览  ", "PNG 预览  "]) # Added spaces to make keys unique
                        with tab2_1:
                            st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True)
                        with tab2_2:
                            st.image(part2_output['png'])
                    else:
                        st.info("夜班部分没有数据")
            else:
                st.error("无法处理文件,请检查文件格式或内容是否正确。")
        
        # 3. Fallback for incorrect file
        else:
            st.warning("文件名不匹配。请上传名为【放映时间核对表.xls】或【放映场次核对表.xls】的文件。")