end-print / app.py
Ethscriptions's picture
Update app.py
5422259 verified
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
from matplotlib.patches import FancyBboxPatch # 新增导入
SPLIT_TIME = "17:30"
BUSINESS_START = "09:30"
BUSINESS_END = "01:30"
BORDER_COLOR = '#A9A9A9'
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 = datetime.strptime(f"{base_date} {SPLIT_TIME}", "%Y-%m-%d %H:%M")
split_time_for_comparison = df['time_for_comparison'].apply(
lambda x: datetime.combine(base_date, split_time.time())
)
part1 = df[df['time_for_comparison'] <= split_time_for_comparison].copy()
part2 = df[df['time_for_comparison'] > split_time_for_comparison].copy()
# 格式化时间显示
for part in [part1, part2]:
part['EndTime'] = part['EndTime'].dt.strftime('%-I:%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
# --- 创建 PNG 图形 ---
png_fig = plt.figure(figsize=(5.83, 8.27), dpi=300) # A5 竖向
png_ax_container = png_fig.add_subplot(111) # 创建一个容器轴,用于隐藏外部边框
png_ax_container.set_axis_off()
# 减小边距,例如从 0.05 减小到 0.02
png_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
# --- 创建 PDF 图形 ---
pdf_fig = plt.figure(figsize=(5.83, 8.27), dpi=300) # A5 竖向
pdf_ax_container = pdf_fig.add_subplot(111)
pdf_ax_container.set_axis_off()
# 减小边距,例如从 0.05 减小到 0.02
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'] # 确保字体可用
# 计算行数和总数
total_items = len(data)
num_cols = 3
num_rows = math.ceil(total_items / num_cols)
# 创建网格 (在 figure 内部创建)
# 减小子图间距 hspace/wspace,减小日期行高度比例 height_ratios
gs = gridspec.GridSpec(num_rows + 1, num_cols, hspace=0.05, wspace=0.05, height_ratios=[0.1] + [1] * num_rows, figure=fig) # 将日期行放在顶部
# 调整基础字体大小,避免过大或过小
# A5 宽度大约 1749 像素 @ 300dpi, 高度 2481
# 每列宽度约 1749 * 0.9 / 3 = 525 像素
# 每行高度约 (2481 * 0.9 * (1 / (1.2))) / num_rows
# 字体大小与单元格大小相关,这里用经验值调整
available_height_per_row = (8.27 * 0.9 * (1 / 1.2)) / num_rows if num_rows > 0 else 1
base_fontsize = min(40, max(10, available_height_per_row * 72 * 0.5)) # 72 points per inch, 估算系数
data_values = data.values.tolist()
# 补全空位,确保是3的倍数
while len(data_values) % num_cols != 0:
data_values.append(['', ''])
rows_per_col_layout = math.ceil(len(data_values) / num_cols) # 按列优先排列的行数
# 按列优先排序数据 (Z字形)
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 # +1 因为日期占了第0行
col_grid = idx % num_cols
if row_grid < num_rows + 1: # 确保索引在网格内
ax = fig.add_subplot(gs[row_grid, col_grid]) # 使用 fig.add_subplot
# --- 修改开始:绘制圆角矩形 ---
# 隐藏原始边框
for spine in ax.spines.values():
spine.set_visible(False)
# 创建圆角矩形 Patch
bbox = FancyBboxPatch(
(0.01, 0.01), # 左下角坐标 (稍微内缩一点避免接触边缘)
0.98, 0.98, # 宽度和高度 (占满大部分区域)
boxstyle="round,pad=0,rounding_size=0.02", # 圆角样式,rounding_size 控制圆角程度
edgecolor=BORDER_COLOR,
facecolor='none', # 无填充色
linewidth=0.5,
transform=ax.transAxes, # 使用相对坐标
clip_on=False # 避免被裁剪
)
# 添加 Patch 到 Axes
ax.add_patch(bbox)
# --- 修改结束 ---
display_text = f"{hall}{end_time}"
ax.text(0.5, 0.5, display_text,
fontsize=base_fontsize,
fontweight='bold',
ha='center',
va='center',
transform=ax.transAxes) # 使用相对坐标
ax.set_xticks([])
ax.set_yticks([])
else:
print(f"Warning: Index out of bounds - idx={idx}, row_grid={row_grid}, col_grid={col_grid}")
# 添加日期信息到第一个子图的顶部
ax_date = fig.add_subplot(gs[0, :]) # 跨越第一行的所有列
ax_date.text(0.01, 0.5, f"{date_str} {title}", # 调整位置和对齐
fontsize=base_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 ---
png_buffer = io.BytesIO()
# 可以尝试减小 pad_inches, even set to 0
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 ---
pdf_buffer = io.BytesIO()
with PdfPages(pdf_buffer) as pdf:
# 可以尝试减小 pad_inches, even set to 0
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}'
}
# --- 新增 PDF 显示函数 ---
def display_pdf(base64_pdf):
"""在Streamlit中嵌入显示PDF"""
pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
return pdf_display
# Streamlit 界面
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:
# 生成包含 PNG 和 PDF 的字典
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:
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:
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("夜班部分没有数据")