Spaces:
Running
Running
File size: 11,539 Bytes
e522499 7704499 e522499 79debab e522499 cd91a84 8319975 e522499 8319975 e522499 7704499 79debab b7d31cf 79debab 7704499 8319975 79debab 7704499 8319975 79debab 7704499 8319975 cd91a84 8319975 79debab e522499 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 cd91a84 8319975 79debab cd91a84 8319975 79debab 8319975 79debab 8319975 79debab cd91a84 79debab e522499 8319975 e522499 79debab e522499 8319975 cd91a84 8319975 e522499 79debab e522499 8319975 28f28d0 8319975 28f28d0 95f254d 8319975 79debab 8319975 cd91a84 8319975 cd91a84 8319975 e522499 8319975 e522499 8319975 e522499 8319975 e522499 8319975 e522499 8319975 e522499 8319975 cd91a84 e522499 8319975 7704499 e522499 cd91a84 e522499 cd91a84 34b21e7 cd91a84 8319975 cd91a84 7704499 cd91a84 7704499 8319975 7704499 95f254d e522499 7704499 cd91a84 7704499 8319975 7704499 95f254d e522499 95f254d |
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 |
import pandas as pd
import streamlit as st
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import io
import base64
import matplotlib.gridspec as gridspec
import math
from matplotlib.backends.backend_pdf import PdfPages
# The 'FancyBboxPatch' is no longer needed for the new border style.
SPLIT_TIME = "17:30"
BUSINESS_START = "09:30"
BUSINESS_END = "01:30"
BORDER_COLOR = 'gray' # Changed to gray for the new style
DATE_COLOR = '#A9A9A9'
def process_schedule(file):
"""处理上传的 Excel 文件,生成排序和分组后的打印内容"""
try:
# 读取 Excel,跳过前 8 行
df = pd.read_excel(file, skiprows=8)
# 提取所需列 (G9, H9, J9)
df = df.iloc[:, [6, 7, 9]] # G, H, J 列
df.columns = ['Hall', 'StartTime', 'EndTime']
# 清理数据
df = df.dropna(subset=['Hall', 'StartTime', 'EndTime'])
# 转换影厅格式为 "#" 格式 (移除末尾空格)
df['Hall'] = df['Hall'].str.extract(r'(\d+)号').astype(str)
# 保存原始时间字符串用于诊断
df['original_end'] = df['EndTime']
# 转换时间为 datetime 对象
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_obj = datetime.strptime(SPLIT_TIME, "%H:%M").time()
split_datetime = datetime.combine(base_date, split_time_obj)
part1 = df[df['time_for_comparison'] <= split_datetime].copy()
part2 = df[df['time_for_comparison'] > split_datetime].copy()
# 格式化时间显示
for part in [part1, part2]:
# Use '%-H' for 24-hour format without leading zero on Linux/macOS
# Use '%#H' on Windows. A more cross-platform way is to format and remove later.
# Let's stick to '%H:%M' for universal 24-hour format e.g., "09:30"
part['EndTime'] = part['EndTime'].dt.strftime('%H:%M')
# 关键修改:精确读取C6单元格
date_df = pd.read_excel(
file,
skiprows=5, # 跳过前5行(0-4)
nrows=1, # 只读1行
usecols=[2], # 第三列(C列)
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
def create_print_layout(data, title, date_str):
"""创建打印布局 (PNG 和 PDF)"""
if data.empty:
return None
# --- A5 Paper Dimensions in inches for precise layout ---
A5_WIDTH_IN = 5.83
A5_HEIGHT_IN = 8.27
NUM_COLS = 3
# --- Create Figures for PNG and PDF ---
png_fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
pdf_fig = plt.figure(figsize=(A5_WIDTH_IN, A5_HEIGHT_IN), dpi=300)
# --- Internal drawing function to apply changes to both figures ---
def process_figure(fig):
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
total_items = len(data)
if total_items == 0:
plt.close(fig)
return
# --- 1. Redesign Print Layout ---
# Calculate number of rows needed
num_rows = math.ceil(total_items / NUM_COLS)
# Remove all padding from the figure edges
fig.subplots_adjust(left=0, right=1, top=0.95, bottom=0)
# Create a grid with no space between cells. A small top row for the date.
gs = gridspec.GridSpec(
num_rows + 1,
NUM_COLS,
hspace=0,
wspace=0,
height_ratios=[0.3] + [1] * num_rows, # Make date row shorter
figure=fig
)
data_values = data.values.tolist()
# Pad data with empty values to make it a multiple of NUM_COLS
while len(data_values) % NUM_COLS != 0:
data_values.append(['', ''])
# --- Sort data column-first (Z-pattern) ---
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
# --- Dynamic Font Size Calculation ---
def get_dynamic_fontsize(text, cell_width_inches):
if not text:
return 1
# This factor is empirical, adjusts font size to fill ~90% of cell width
# A lower factor (e.g., 0.5) results in larger text.
ASPECT_RATIO_FACTOR = 0.55
num_chars = len(text)
# Formula: (target_width_points) / (num_characters * aspect_ratio)
fontsize = (cell_width_inches * 0.9 * 72) / (num_chars * ASPECT_RATIO_FACTOR)
return max(10, fontsize) # Return at least size 10
cell_width_inches = A5_WIDTH_IN / NUM_COLS
# --- Draw each data cell ---
for idx, (hall, end_time) in enumerate(sorted_data):
if hall and end_time:
row_grid = idx // NUM_COLS + 1 # +1 to skip date row
col_grid = idx % NUM_COLS
ax = fig.add_subplot(gs[row_grid, col_grid])
display_text = f"{hall} {end_time}"
# Calculate optimal font size
fontsize = get_dynamic_fontsize(display_text, cell_width_inches)
ax.text(0.5, 0.5, display_text,
fontsize=fontsize,
fontweight='bold',
ha='center',
va='center',
transform=ax.transAxes)
# --- 2. Change Cell Border ---
# Set a dotted gray border
for spine in ax.spines.values():
spine.set_visible(True)
spine.set_linestyle((0, (1, 2))) # Dotted line: (0, (on, off))
spine.set_edgecolor(BORDER_COLOR)
spine.set_linewidth(1.5)
ax.set_xticks([])
ax.set_yticks([])
ax.set_facecolor('none')
# --- Add date and title information to the top row ---
ax_date = fig.add_subplot(gs[0, :])
ax_date.text(0.01, 0.5, f"{date_str} {title}",
fontsize=12,
color=DATE_COLOR,
fontweight='bold',
ha='left',
va='center',
transform=ax_date.transAxes)
# Hide the border for the date cell
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 both the PNG and PDF figures with the new layout
process_figure(png_fig)
process_figure(pdf_fig)
# --- Save PNG ---
png_buffer = io.BytesIO()
# Use pad_inches=0 because we handled margins with subplots_adjust
png_fig.savefig(png_buffer, format='png', pad_inches=0)
png_buffer.seek(0)
png_base64 = base64.b64encode(png_buffer.getvalue()).decode()
plt.close(png_fig)
# --- Save PDF ---
pdf_buffer = io.BytesIO()
with PdfPages(pdf_buffer) as pdf:
# Use pad_inches=0 for PDF as well
pdf.savefig(pdf_fig, pad_inches=0)
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}'
}
# --- PDF display function ---
def display_pdf(base64_pdf):
"""Embeds PDF in Streamlit for display"""
pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
return pdf_display
# Streamlit UI
st.set_page_config(page_title="散厅时间快捷打印", layout="wide")
st.title("散厅时间快捷打印")
uploaded_file = st.file_uploader("上传【放映场次核对表.xls】文件", type=["xls"])
if uploaded_file:
part1, part2, date_str = process_schedule(uploaded_file)
if part1 is not None and part2 is not None:
# Generate outputs containing both PNG and PDF data
part1_output = create_print_layout(part1, "A", date_str)
part2_output = create_print_layout(part2, "C", date_str)
col1, col2 = st.columns(2)
with col1:
st.subheader("白班散场预览(时间 ≤ 17:30)")
if part1_output:
# Use tabs to show both PDF and PNG previews
tab1_1, tab1_2 = st.tabs(["PDF 预览", "PNG 预览"])
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:
# Use tabs to show both PDF and PNG previews
tab2_1, tab2_2 = st.tabs(["PDF 预览", "PNG 预览"])
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("夜班部分没有数据") |