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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import matplotlib.font_manager as font_manager
|
| 5 |
+
from matplotlib.lines import Line2D
|
| 6 |
+
import io
|
| 7 |
+
import base64
|
| 8 |
+
import os
|
| 9 |
+
from datetime import datetime, timedelta, time
|
| 10 |
+
from pypinyin import lazy_pinyin, Style
|
| 11 |
+
from matplotlib.backends.backend_pdf import PdfPages
|
| 12 |
+
import matplotlib.gridspec as gridspec
|
| 13 |
+
import math
|
| 14 |
+
|
| 15 |
+
# --- 常量和配置 ---
|
| 16 |
+
BUSINESS_START = "09:30"
|
| 17 |
+
BUSINESS_END = "01:30"
|
| 18 |
+
BORDER_COLOR = 'grey'
|
| 19 |
+
DATE_COLOR = '#A9A9A9'
|
| 20 |
+
A5_WIDTH_IN = 5.83
|
| 21 |
+
A5_HEIGHT_IN = 8.27
|
| 22 |
+
NUM_COLS = 3
|
| 23 |
+
|
| 24 |
+
# --- 字体清单 ---
|
| 25 |
+
ALL_FONTS = {
|
| 26 |
+
"思源黑体-常规 (推荐 LED 屏)": "SimHei.ttf",
|
| 27 |
+
"思源黑体-重体 (推荐散场表)": "SourceHanSansOLD-Heavy-2.otf",
|
| 28 |
+
"思源黑体-粗体": "SourceHanSansOLD-Bold-2.otf",
|
| 29 |
+
"思源宋体-常规": "SourceHanSansCN-Normal.otf",
|
| 30 |
+
"苹方-中黑": "PingFangSC-Medium.otf",
|
| 31 |
+
"苹方-半粗": "PingFangSC-Semibold.otf",
|
| 32 |
+
"苹方-极细": "PingFangSC-Ultralight.otf",
|
| 33 |
+
"阿里巴巴普惠体-常规": "Alibaba-PuHuiTi.ttf",
|
| 34 |
+
"阿里巴巴普惠体-粗体": "AlibabaPuHuiTi-Bold.otf",
|
| 35 |
+
"阿里巴巴普惠体-重体": "AlibabaPuHuiTi-Heavy.otf",
|
| 36 |
+
}
|
| 37 |
+
AVAILABLE_FONTS = {name: fname for name, fname in ALL_FONTS.items() if os.path.exists(fname)}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# --- 字体加载与文本处理函数 ---
|
| 41 |
+
|
| 42 |
+
def get_font_properties(font_path, size=14):
|
| 43 |
+
"""通用字体加载函数"""
|
| 44 |
+
if font_path and os.path.exists(font_path):
|
| 45 |
+
return font_manager.FontProperties(fname=font_path, size=size)
|
| 46 |
+
else:
|
| 47 |
+
st.warning(f"警告:未找到字体文件 '{font_path}',显示可能不正确。将使用默认字体。")
|
| 48 |
+
return font_manager.FontProperties(family='sans-serif', size=size)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_pinyin_abbr(text):
|
| 52 |
+
"""获取中文文本前两个字的拼音首字母"""
|
| 53 |
+
if not text: return ""
|
| 54 |
+
chars = [c for c in text if '\u4e00' <= c <= '\u9fff'][:2]
|
| 55 |
+
if not chars: return ""
|
| 56 |
+
pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
|
| 57 |
+
return ''.join(pinyin_list).upper()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def format_seq(n):
|
| 61 |
+
"""将数字或字符转换为带圈序号 (①, ②, ③...),非数字则直接返回"""
|
| 62 |
+
try:
|
| 63 |
+
n = int(n)
|
| 64 |
+
except (ValueError, TypeError):
|
| 65 |
+
return str(n)
|
| 66 |
+
if n <= 0: return str(n)
|
| 67 |
+
circled_chars = "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
|
| 68 |
+
if 1 <= n <= 50: return circled_chars[n - 1]
|
| 69 |
+
return f'({n})'
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# --- 核心数据处理函数 ---
|
| 73 |
+
|
| 74 |
+
def process_unified_schedule(file, split_time_str, time_adjustment_minutes=0):
|
| 75 |
+
"""
|
| 76 |
+
统一处理 '放映时间核对表.xls' 文件, 生成两种表格所需的数据。
|
| 77 |
+
"""
|
| 78 |
+
try:
|
| 79 |
+
date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
|
| 80 |
+
date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
|
| 81 |
+
base_date = pd.to_datetime(date_str).date()
|
| 82 |
+
except Exception:
|
| 83 |
+
date_str = datetime.today().strftime('%Y-%m-%d')
|
| 84 |
+
base_date = datetime.today().date()
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
|
| 88 |
+
df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
|
| 89 |
+
df['Hall'] = df['Hall'].ffill()
|
| 90 |
+
df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
|
| 91 |
+
except Exception as e:
|
| 92 |
+
st.error(f"读取排期数据时出错: {e}。请检查文件格式是否为'放映时间核对表'。")
|
| 93 |
+
return None, None, None, date_str
|
| 94 |
+
|
| 95 |
+
# 'LED屏排片表' 数据处理
|
| 96 |
+
led_df = df.copy()
|
| 97 |
+
try:
|
| 98 |
+
# **优化2**: 优先提取 'X号',失败则取第一个字符 + '号'
|
| 99 |
+
extracted = led_df['Hall'].astype(str).str.extract(r'(\d+号)')
|
| 100 |
+
fallback = led_df['Hall'].astype(str).str[0] + '号'
|
| 101 |
+
led_df['Hall'] = extracted[0].fillna(fallback)
|
| 102 |
+
|
| 103 |
+
led_df['StartTime_dt'] = pd.to_datetime(led_df['StartTime'], format='%H:%M', errors='coerce').apply(
|
| 104 |
+
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t)
|
| 105 |
+
led_df['EndTime_dt'] = pd.to_datetime(led_df['EndTime'], format='%H:%M', errors='coerce').apply(
|
| 106 |
+
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t)
|
| 107 |
+
led_df.loc[led_df['EndTime_dt'] < led_df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
|
| 108 |
+
led_df = led_df.sort_values(['Hall', 'StartTime_dt'])
|
| 109 |
+
merged_rows = []
|
| 110 |
+
for _, group in led_df.groupby('Hall'):
|
| 111 |
+
current = None
|
| 112 |
+
for _, row in group.sort_values('StartTime_dt').iterrows():
|
| 113 |
+
if current is None:
|
| 114 |
+
current = row.copy()
|
| 115 |
+
elif row['Movie'] == current['Movie']:
|
| 116 |
+
current['EndTime_dt'] = row['EndTime_dt']
|
| 117 |
+
else:
|
| 118 |
+
merged_rows.append(current)
|
| 119 |
+
current = row.copy()
|
| 120 |
+
if current is not None: merged_rows.append(current)
|
| 121 |
+
merged_df = pd.DataFrame(merged_rows)
|
| 122 |
+
merged_df['StartTime_dt'] -= timedelta(minutes=10)
|
| 123 |
+
merged_df['EndTime_dt'] -= timedelta(minutes=5)
|
| 124 |
+
merged_df['Seq'] = merged_df.groupby('Hall').cumcount() + 1
|
| 125 |
+
merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
|
| 126 |
+
merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
|
| 127 |
+
led_schedule_df = merged_df[['Hall', 'Seq', 'Movie', 'StartTime_str', 'EndTime_str']]
|
| 128 |
+
except Exception as e:
|
| 129 |
+
st.error(f"处理 'LED屏排片表' 数据时出错: {e}")
|
| 130 |
+
led_schedule_df = None
|
| 131 |
+
|
| 132 |
+
# '散场时间快捷打印' 数据处理
|
| 133 |
+
times_df = df.copy()
|
| 134 |
+
try:
|
| 135 |
+
# **优化2**: 优先提取数字,失败则取第一个字符
|
| 136 |
+
num_part = times_df['Hall'].str.extract(r'(\d+)')[0]
|
| 137 |
+
char_part = times_df['Hall'].astype(str).str[0]
|
| 138 |
+
times_df['Hall'] = num_part.fillna(char_part)
|
| 139 |
+
times_df.dropna(subset=['Hall', 'StartTime', 'EndTime'], inplace=True)
|
| 140 |
+
times_df['StartTime_dt'] = pd.to_datetime(times_df['StartTime'], format='%H:%M', errors='coerce').apply(
|
| 141 |
+
lambda t: datetime.combine(base_date, t.time()) if pd.notnull(t) else pd.NaT)
|
| 142 |
+
times_df['EndTime_dt'] = pd.to_datetime(times_df['EndTime'], format='%H:%M', errors='coerce').apply(
|
| 143 |
+
lambda t: datetime.combine(base_date, t.time()) if pd.notnull(t) else pd.NaT)
|
| 144 |
+
times_df.loc[times_df['EndTime_dt'] < times_df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
|
| 145 |
+
|
| 146 |
+
# **优化4**: 应用时间提前量
|
| 147 |
+
if time_adjustment_minutes > 0:
|
| 148 |
+
times_df['EndTime_dt'] -= timedelta(minutes=time_adjustment_minutes)
|
| 149 |
+
|
| 150 |
+
business_start_dt = datetime.combine(base_date, datetime.strptime(BUSINESS_START, "%H:%M").time())
|
| 151 |
+
business_end_dt = datetime.combine(base_date, datetime.strptime(BUSINESS_END, "%H:%M").time())
|
| 152 |
+
if business_end_dt < business_start_dt: business_end_dt += timedelta(days=1)
|
| 153 |
+
times_df = times_df[(times_df['EndTime_dt'] >= business_start_dt) & (times_df['EndTime_dt'] <= business_end_dt)]
|
| 154 |
+
times_df = times_df.sort_values('EndTime_dt')
|
| 155 |
+
split_dt = datetime.combine(base_date, split_time_str)
|
| 156 |
+
part1 = times_df[times_df['EndTime_dt'] <= split_dt].copy()
|
| 157 |
+
part2 = times_df[times_df['EndTime_dt'] > split_dt].copy()
|
| 158 |
+
|
| 159 |
+
# **优化1**: 使用 %H:%M 保证两位小时
|
| 160 |
+
part1['EndTime'] = part1['EndTime_dt'].dt.strftime('%H:%M')
|
| 161 |
+
part2['EndTime'] = part2['EndTime_dt'].dt.strftime('%H:%M')
|
| 162 |
+
|
| 163 |
+
times_part1_df = part1[['Hall', 'EndTime']]
|
| 164 |
+
times_part2_df = part2[['Hall', 'EndTime']]
|
| 165 |
+
except Exception as e:
|
| 166 |
+
st.error(f"处理 '散场时间表' 数据时出错: {e}")
|
| 167 |
+
times_part1_df, times_part2_df = None, None
|
| 168 |
+
|
| 169 |
+
return led_schedule_df, times_part1_df, times_part2_df, date_str
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# --- 'LED屏排片表' 布局生成函数 ---
|
| 173 |
+
def create_print_layout_led(data, date_str, font_path, generate_png=False):
|
| 174 |
+
if data is None or data.empty: return None
|
| 175 |
+
A4_width_in, A4_height_in = 8.27, 11.69
|
| 176 |
+
dpi = 300
|
| 177 |
+
total_content_rows = len(data)
|
| 178 |
+
layout_rows = max(total_content_rows, 25)
|
| 179 |
+
totalA = layout_rows + 2
|
| 180 |
+
row_height = A4_height_in / totalA
|
| 181 |
+
data = data.reset_index(drop=True)
|
| 182 |
+
data['hall_str'] = '$' + data['Hall'].str.replace('号', '') + '^{\#}$'
|
| 183 |
+
data['seq_str'] = data['Seq'].apply(format_seq)
|
| 184 |
+
data['pinyin_abbr'] = data['Movie'].apply(get_pinyin_abbr)
|
| 185 |
+
data['time_str'] = data['StartTime_str'] + ' - ' + data['EndTime_str']
|
| 186 |
+
temp_fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=dpi)
|
| 187 |
+
renderer = temp_fig.canvas.get_renderer()
|
| 188 |
+
base_font_size_pt = (row_height * 0.9) * 72
|
| 189 |
+
seq_font_size_pt = (row_height * 0.5) * 72
|
| 190 |
+
|
| 191 |
+
def get_col_width_in(series, font_size_pt, is_math=False):
|
| 192 |
+
if series.empty: return 0
|
| 193 |
+
font_prop = get_font_properties(font_path, font_size_pt)
|
| 194 |
+
longest_str_idx = series.astype(str).str.len().idxmax()
|
| 195 |
+
max_content = str(series.loc[longest_str_idx])
|
| 196 |
+
text_width_px, _, _ = renderer.get_text_width_height_descent(max_content, font_prop, ismath=is_math)
|
| 197 |
+
return (text_width_px / dpi) * 1.1
|
| 198 |
+
|
| 199 |
+
margin_col_width = row_height
|
| 200 |
+
hall_col_width = get_col_width_in(data['hall_str'], base_font_size_pt, is_math=True)
|
| 201 |
+
seq_col_width = get_col_width_in(data['seq_str'], seq_font_size_pt)
|
| 202 |
+
pinyin_col_width = get_col_width_in(data['pinyin_abbr'], base_font_size_pt)
|
| 203 |
+
time_col_width = get_col_width_in(data['time_str'], base_font_size_pt)
|
| 204 |
+
movie_col_width = A4_width_in - (
|
| 205 |
+
margin_col_width * 2 + hall_col_width + seq_col_width + pinyin_col_width + time_col_width)
|
| 206 |
+
plt.close(temp_fig)
|
| 207 |
+
col_widths = {'hall': hall_col_width, 'seq': seq_col_width, 'movie': movie_col_width, 'pinyin': pinyin_col_width,
|
| 208 |
+
'time': time_col_width}
|
| 209 |
+
col_x_starts = {}
|
| 210 |
+
current_x = margin_col_width
|
| 211 |
+
for col_name in ['hall', 'seq', 'movie', 'pinyin', 'time']:
|
| 212 |
+
col_x_starts[col_name] = current_x
|
| 213 |
+
current_x += col_widths[col_name]
|
| 214 |
+
|
| 215 |
+
def draw_figure(fig, ax):
|
| 216 |
+
renderer = fig.canvas.get_renderer()
|
| 217 |
+
for col_name in ['hall', 'seq', 'movie', 'pinyin']:
|
| 218 |
+
x_line = col_x_starts[col_name] + col_widths[col_name]
|
| 219 |
+
line_top_y, line_bottom_y = A4_height_in - row_height, row_height
|
| 220 |
+
ax.add_line(
|
| 221 |
+
Line2D([x_line, x_line], [line_bottom_y, line_top_y], color='gray', linestyle=':', linewidth=0.5))
|
| 222 |
+
last_hall_drawn = None
|
| 223 |
+
for i, row in data.iterrows():
|
| 224 |
+
y_bottom = A4_height_in - (i + 2) * row_height
|
| 225 |
+
y_center = y_bottom + row_height / 2
|
| 226 |
+
if row['Hall'] != last_hall_drawn:
|
| 227 |
+
ax.text(col_x_starts['hall'] + col_widths['hall'] / 2, y_center, row['hall_str'],
|
| 228 |
+
fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
|
| 229 |
+
last_hall_drawn = row['Hall']
|
| 230 |
+
ax.text(col_x_starts['seq'] + col_widths['seq'] / 2, y_center, row['seq_str'],
|
| 231 |
+
fontproperties=get_font_properties(font_path, seq_font_size_pt), ha='center', va='center')
|
| 232 |
+
ax.text(col_x_starts['pinyin'] + col_widths['pinyin'] / 2, y_center, row['pinyin_abbr'],
|
| 233 |
+
fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
|
| 234 |
+
ax.text(col_x_starts['time'] + col_widths['time'] / 2, y_center, row['time_str'],
|
| 235 |
+
fontproperties=get_font_properties(font_path, base_font_size_pt), ha='center', va='center')
|
| 236 |
+
movie_font_size = base_font_size_pt
|
| 237 |
+
movie_font_prop = get_font_properties(font_path, movie_font_size)
|
| 238 |
+
text_w_px, _, _ = renderer.get_text_width_height_descent(row['Movie'], movie_font_prop, ismath=False)
|
| 239 |
+
text_w_in = text_w_px / dpi
|
| 240 |
+
max_width_in = col_widths['movie'] * 0.9
|
| 241 |
+
if text_w_in > max_width_in:
|
| 242 |
+
movie_font_size *= (max_width_in / text_w_in)
|
| 243 |
+
movie_font_prop = get_font_properties(font_path, movie_font_size)
|
| 244 |
+
ax.text(col_x_starts['movie'] + 0.05, y_center, row['Movie'], fontproperties=movie_font_prop, ha='left',
|
| 245 |
+
va='center')
|
| 246 |
+
is_last_in_hall = (i == len(data) - 1) or (row['Hall'] != data.loc[i + 1, 'Hall'])
|
| 247 |
+
line_start_x, line_end_x = margin_col_width, A4_width_in - margin_col_width
|
| 248 |
+
if is_last_in_hall:
|
| 249 |
+
ax.add_line(Line2D([line_start_x, line_end_x], [y_bottom, y_bottom], color='black', linestyle='-',
|
| 250 |
+
linewidth=0.8))
|
| 251 |
+
else:
|
| 252 |
+
ax.add_line(Line2D([line_start_x, line_end_x], [y_bottom, y_bottom], color='gray', linestyle=':',
|
| 253 |
+
linewidth=0.5))
|
| 254 |
+
|
| 255 |
+
outputs = {}
|
| 256 |
+
fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=300)
|
| 257 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 258 |
+
ax.set_axis_off();
|
| 259 |
+
ax.set_xlim(0, A4_width_in);
|
| 260 |
+
ax.set_ylim(0, A4_height_in)
|
| 261 |
+
ax.text(margin_col_width, A4_height_in - row_height, date_str, fontproperties=get_font_properties(font_path, 10),
|
| 262 |
+
color=DATE_COLOR, ha='left', va='bottom', transform=ax.transData)
|
| 263 |
+
draw_figure(fig, ax)
|
| 264 |
+
pdf_buf = io.BytesIO()
|
| 265 |
+
fig.savefig(pdf_buf, format='pdf', dpi=dpi, bbox_inches='tight', pad_inches=0)
|
| 266 |
+
pdf_buf.seek(0)
|
| 267 |
+
outputs['pdf'] = f"data:application/pdf;base64,{base64.b64encode(pdf_buf.getvalue()).decode()}"
|
| 268 |
+
if generate_png:
|
| 269 |
+
png_buf = io.BytesIO()
|
| 270 |
+
fig.savefig(png_buf, format='png', dpi=dpi, bbox_inches='tight', pad_inches=0)
|
| 271 |
+
png_buf.seek(0)
|
| 272 |
+
outputs['png'] = f"data:image/png;base64,{base64.b64encode(png_buf.getvalue()).decode()}"
|
| 273 |
+
plt.close(fig)
|
| 274 |
+
return outputs
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# --- '散场时间表' 布局生成函数 ---
|
| 278 |
+
def create_print_layout_times(data, title, date_str, font_path, size_multiplier=1.1, hall_format='Default',
|
| 279 |
+
generate_png=False):
|
| 280 |
+
if data is None or data.empty: return None
|
| 281 |
+
|
| 282 |
+
def generate_figure():
|
| 283 |
+
total_items = len(data)
|
| 284 |
+
num_rows = math.ceil(total_items / NUM_COLS) if total_items > 0 else 1
|
| 285 |
+
data_area_height_in, cell_width_in = A5_HEIGHT_IN, A5_WIDTH_IN / NUM_COLS
|
| 286 |
+
cell_height_in = data_area_height_in / num_rows
|
| 287 |
+
target_width_pt, target_height_pt = (cell_width_in * 0.9) * 72, (cell_height_in * 0.9) * 72
|
| 288 |
+
font_size_based_on_width = target_width_pt / (8 * 0.6)
|
| 289 |
+
base_fontsize = min(font_size_based_on_width, target_height_pt) * size_multiplier
|
| 290 |
+
fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
|
| 291 |
+
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
|
| 292 |
+
gs = gridspec.GridSpec(num_rows, NUM_COLS, hspace=0, wspace=0, figure=fig)
|
| 293 |
+
data_values = data.values.tolist()
|
| 294 |
+
while len(data_values) % NUM_COLS != 0: data_values.append(['', ''])
|
| 295 |
+
rows_per_col_layout = math.ceil(len(data_values) / NUM_COLS)
|
| 296 |
+
sorted_data = [['', '']] * len(data_values)
|
| 297 |
+
for i, item in enumerate(data_values):
|
| 298 |
+
if item[0] and item[1]:
|
| 299 |
+
row_in_col, col_idx = i % rows_per_col_layout, i // rows_per_col_layout
|
| 300 |
+
new_index = row_in_col * NUM_COLS + col_idx
|
| 301 |
+
if new_index < len(sorted_data): sorted_data[new_index] = item
|
| 302 |
+
is_first_cell_with_data = True
|
| 303 |
+
for idx, (hall, end_time) in enumerate(sorted_data):
|
| 304 |
+
if hall and end_time:
|
| 305 |
+
row_grid, col_grid = idx // NUM_COLS, idx % NUM_COLS
|
| 306 |
+
ax = fig.add_subplot(gs[row_grid, col_grid])
|
| 307 |
+
for spine in ax.spines.values():
|
| 308 |
+
spine.set_visible(True);
|
| 309 |
+
spine.set_linestyle((0, (1, 2)))
|
| 310 |
+
spine.set_color(BORDER_COLOR);
|
| 311 |
+
spine.set_linewidth(0.75)
|
| 312 |
+
if is_first_cell_with_data:
|
| 313 |
+
ax.text(0.05, 0.95, f"{date_str} {title}",
|
| 314 |
+
fontproperties=get_font_properties(font_path, base_fontsize * 0.5), color=DATE_COLOR,
|
| 315 |
+
ha='left', va='top', transform=ax.transAxes)
|
| 316 |
+
is_first_cell_with_data = False
|
| 317 |
+
if hall_format == 'Superscript':
|
| 318 |
+
display_text = f'${str(hall)}^{{\#}}$ {end_time}'
|
| 319 |
+
elif hall_format == 'Circled':
|
| 320 |
+
display_text = f'{format_seq(hall)} {end_time}'
|
| 321 |
+
else: # Default
|
| 322 |
+
display_text = f"{str(hall)} {end_time}"
|
| 323 |
+
ax.text(0.5, 0.5, display_text, fontproperties=get_font_properties(font_path, base_fontsize),
|
| 324 |
+
ha='center', va='center', transform=ax.transAxes)
|
| 325 |
+
ax.set_xticks([]);
|
| 326 |
+
ax.set_yticks([]);
|
| 327 |
+
ax.set_facecolor('none')
|
| 328 |
+
return fig
|
| 329 |
+
|
| 330 |
+
fig_for_output = generate_figure()
|
| 331 |
+
outputs = {}
|
| 332 |
+
pdf_buffer = io.BytesIO()
|
| 333 |
+
with PdfPages(pdf_buffer) as pdf:
|
| 334 |
+
pdf.savefig(fig_for_output)
|
| 335 |
+
pdf_buffer.seek(0)
|
| 336 |
+
outputs['pdf'] = f"data:application/pdf;base64,{base64.b64encode(pdf_buffer.getvalue()).decode()}"
|
| 337 |
+
if generate_png:
|
| 338 |
+
png_buffer = io.BytesIO()
|
| 339 |
+
fig_for_output.savefig(png_buffer, format='png')
|
| 340 |
+
png_buffer.seek(0)
|
| 341 |
+
outputs['png'] = f'data:image/png;base64,{base64.b64encode(png_buffer.getvalue()).decode()}'
|
| 342 |
+
plt.close(fig_for_output)
|
| 343 |
+
return outputs
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def display_pdf(base64_pdf):
|
| 347 |
+
"""在Streamlit中嵌入显示PDF"""
|
| 348 |
+
return f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# --- Streamlit 主程序 ---
|
| 352 |
+
st.set_page_config(page_title="影院场次与散场时间快捷打印工具", layout="wide")
|
| 353 |
+
st.title("影院场次与散场时间快捷打印工具")
|
| 354 |
+
|
| 355 |
+
uploaded_file = st.file_uploader("请上传 `放映时间核对表.xls` 文件", type=["xls"])
|
| 356 |
+
|
| 357 |
+
with st.expander("⚙️ 显示与打印设置", expanded=False):
|
| 358 |
+
col1, col2 = st.columns(2)
|
| 359 |
+
with col1:
|
| 360 |
+
st.subheader("⚙️ 修改 LED 屏排片表设置")
|
| 361 |
+
led_font_name = st.selectbox("字体选择", options=list(AVAILABLE_FONTS.keys()), index=0, key="led_font")
|
| 362 |
+
led_font_path = AVAILABLE_FONTS.get(led_font_name)
|
| 363 |
+
generate_png_led = st.checkbox("生成 PNG 图片", value=False, key="png_led")
|
| 364 |
+
with col2:
|
| 365 |
+
st.subheader("⚙️ 散场时间表设置")
|
| 366 |
+
times_font_name = st.selectbox("字体选择", options=list(AVAILABLE_FONTS.keys()), index=1, key="times_font")
|
| 367 |
+
times_font_path = AVAILABLE_FONTS.get(times_font_name)
|
| 368 |
+
# **优化5**: 调整字体大小范围
|
| 369 |
+
font_size_multiplier = st.slider("字体大小调节", min_value=0.8, max_value=1.5, value=1.2, step=0.05,
|
| 370 |
+
help="调整字体在单元格内的相对大小")
|
| 371 |
+
split_time = st.time_input("白班 / 晚班分割时间", value=time(17, 0), help="散场时间在此时间点之前(含)的为白班")
|
| 372 |
+
# **优化4**: 增加时间提前设置
|
| 373 |
+
time_adjustment = st.slider("时间提前 (分钟)", min_value=0, max_value=10, value=0,
|
| 374 |
+
help="将所有散场时间提前 N 分钟显示")
|
| 375 |
+
hall_display_format = st.radio("影厅号格式", options=['Default', 'Superscript', 'Circled'],
|
| 376 |
+
format_func=lambda x:
|
| 377 |
+
{'Default': '默认 (2 18:28)', 'Superscript': '上标 (2# 18:28)',
|
| 378 |
+
'Circled': '带圈 (② 18:28)'}[x], horizontal=True)
|
| 379 |
+
generate_png_times = st.checkbox("生成 PNG 图片", value=False, key="png_times")
|
| 380 |
+
|
| 381 |
+
with st.expander("💡 使用帮助", expanded=False):
|
| 382 |
+
st.markdown("""
|
| 383 |
+
#### 功能简介
|
| 384 |
+
本工具用于将影院的 `放映时间核对表.xls` 文件快速转换为两种形式的打印页:
|
| 385 |
+
1. **修改 LED 屏幕排片表打印**:A4 竖版,详细列出影厅、场次、影片名、拼音缩写和时间范围,方便员工在修改 LED 屏幕时快速查阅和输入。
|
| 386 |
+
- 拼音缩写是为了在输入法如 QQ 拼音输入法等造词功能,拼音缩写填写快捷键,内容填写影片名字。
|
| 387 |
+
- 时间范围已经优化过了,默认提前了 10 分钟。
|
| 388 |
+
2. **散场时间打印**:A5 横版,以大字体分栏显示各影厅的散场时间,方便员工在疏散人群和清洁影厅时查阅。
|
| 389 |
+
- 可以在设置里面设置提前如 5 分钟,到时间就可以前往影厅在疏散人群和清洁影厅。
|
| 390 |
+
|
| 391 |
+
#### 操作步骤
|
| 392 |
+
1. **上传文件**:导出 `放映时间核对表.xls` 后,点击上方的 "Browse files" 按钮,选择您的 `放映时间核对表.xls` 文件。
|
| 393 |
+
2. **调整设置 (可选)**:点击上方的 "显示与打印设置" 打开设置面板,根据需要调整字体、大小、格式等。
|
| 394 |
+
3. **预览与打印**:
|
| 395 |
+
* 上传成功后,下方会自动生成预览。
|
| 396 |
+
* 默认显示 **PDF 预览**,这是最适合打印的格式。可以直接在预览界面点击 🖨️ 打印按钮,设置纸张大小即可打印。
|
| 397 |
+
* 如果勾选了 "生成 PNG 图片",可以切换到 **图片预览 (PNG)** 标签页查看或在新标签页中打开图片或下载图片后打印。
|
| 398 |
+
""")
|
| 399 |
+
|
| 400 |
+
# --- 主页面逻辑 ---
|
| 401 |
+
if uploaded_file:
|
| 402 |
+
with st.spinner("正在处理文件,请稍候..."):
|
| 403 |
+
led_data, times_part1, times_part2, date_str = process_unified_schedule(uploaded_file, split_time,
|
| 404 |
+
time_adjustment)
|
| 405 |
+
|
| 406 |
+
st.toast(f"文件处理完成!排期日期:**{date_str}**", icon="🎉")
|
| 407 |
+
|
| 408 |
+
# 显示 LED 屏排片表
|
| 409 |
+
st.header("修改 LED 屏幕排片表打印")
|
| 410 |
+
if led_data is not None and not led_data.empty:
|
| 411 |
+
led_output = create_print_layout_led(led_data, date_str, led_font_path, generate_png_led)
|
| 412 |
+
if led_output:
|
| 413 |
+
tabs = ["PDF 预览"]
|
| 414 |
+
if 'png' in led_output: tabs.append("PNG 预览")
|
| 415 |
+
tab_views = st.tabs(tabs)
|
| 416 |
+
with tab_views[0]:
|
| 417 |
+
st.markdown(display_pdf(led_output['pdf']), unsafe_allow_html=True)
|
| 418 |
+
if 'png' in led_output:
|
| 419 |
+
with tab_views[1]: st.image(led_output['png'], use_container_width=True)
|
| 420 |
+
else:
|
| 421 |
+
st.error("未能成功生成 '修改 LED 屏排片表'。请检查文件内容或格式。")
|
| 422 |
+
|
| 423 |
+
# 显示散场时间快捷打印
|
| 424 |
+
st.header("散场时间打印")
|
| 425 |
+
col1, col2 = st.columns(2)
|
| 426 |
+
with col1:
|
| 427 |
+
if times_part1 is not None and not times_part1.empty:
|
| 428 |
+
part1_output = create_print_layout_times(times_part1, "A", date_str, times_font_path, font_size_multiplier,
|
| 429 |
+
hall_display_format, generate_png_times)
|
| 430 |
+
if part1_output:
|
| 431 |
+
# **优化3**: 更改Tab标题
|
| 432 |
+
tabs1 = [f"白班 (≤ {split_time.strftime('%H:%M')}) PDF 预览"]
|
| 433 |
+
if 'png' in part1_output: tabs1.append(f"白班 (≤ {split_time.strftime('%H:%M')}) PNG 预览")
|
| 434 |
+
tab_views1 = st.tabs(tabs1)
|
| 435 |
+
with tab_views1[0]:
|
| 436 |
+
st.markdown(display_pdf(part1_output['pdf']), unsafe_allow_html=True)
|
| 437 |
+
if 'png' in part1_output:
|
| 438 |
+
with tab_views1[1]: st.image(part1_output['png'])
|
| 439 |
+
else:
|
| 440 |
+
st.info(f"白班 (≤ {split_time.strftime('%H:%M')}) 没有排期数据。")
|
| 441 |
+
|
| 442 |
+
with col2:
|
| 443 |
+
if times_part2 is not None and not times_part2.empty:
|
| 444 |
+
part2_output = create_print_layout_times(times_part2, "C", date_str, times_font_path, font_size_multiplier,
|
| 445 |
+
hall_display_format, generate_png_times)
|
| 446 |
+
if part2_output:
|
| 447 |
+
# **优化3**: 更改Tab标题
|
| 448 |
+
tabs2 = [f"晚班 (> {split_time.strftime('%H:%M')}) PDF 预览"]
|
| 449 |
+
if 'png' in part2_output: tabs2.append(f"晚班 (> {split_time.strftime('%H:%M')}) PNG 预览")
|
| 450 |
+
tab_views2 = st.tabs(tabs2)
|
| 451 |
+
with tab_views2[0]:
|
| 452 |
+
st.markdown(display_pdf(part2_output['pdf']), unsafe_allow_html=True)
|
| 453 |
+
if 'png' in part2_output:
|
| 454 |
+
with tab_views2[1]: st.image(part2_output['png'])
|
| 455 |
+
else:
|
| 456 |
+
st.info(f"晚班 (> {split_time.strftime('%H:%M')}) 没有排期数据。")
|
| 457 |
+
else:
|
| 458 |
+
st.info("👆 请先上传文件以生成预览。")
|