Spaces:
Sleeping
Sleeping
| 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】的文件。") |