Spaces:
Running
Running
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 matplotlib.patches import FancyBboxPatch | |
from pypinyin import lazy_pinyin, Style | |
from matplotlib.backends.backend_pdf import PdfPages | |
def get_font(size=14): | |
"""Loads the SimHei font for Chinese character support.""" | |
font_path = "simHei.ttc" | |
if not os.path.exists(font_path): | |
# Fallback for different OS or font naming | |
font_path = "SimHei.ttf" | |
if not os.path.exists(font_path): | |
# If font is still not found, return None and let matplotlib use its default | |
st.warning(f"Font file not found at {font_path}. Chinese characters may not display correctly.") | |
return None | |
return font_manager.FontProperties(fname=font_path, size=size) | |
def get_pinyin_abbr(text): | |
"""获取文本前两个汉字的拼音首字母""" | |
if not text: | |
return "" | |
# 提取前两个汉字 | |
chars = [c for c in text if '\u4e00' <= c <= '\u9fff'] | |
if len(chars) < 2: | |
chars = chars + [''] * (2 - len(chars)) | |
else: | |
chars = chars[:2] | |
# 获取拼音首字母 | |
pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER) | |
return ''.join(pinyin_list).upper() | |
def process_schedule(file): | |
"""Processes the uploaded Excel file to extract and clean schedule data.""" | |
try: | |
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: | |
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+号)') | |
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']) | |
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) | |
# 将开始时间统一提前10分钟,结束时间统一提前5分钟 | |
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"Error processing schedule data: {e}") | |
return None, date_str | |
def create_print_layout(data, date_str): | |
"""Generates the print-friendly PDF and PNG layouts from the schedule data.""" | |
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, is_pdf=False): | |
"""The core drawing function to render the schedule onto a matplotlib axis.""" | |
ax.set_ylim(0, 1) # Use a 0-1 coordinate system for consistent positioning | |
# Sort halls numerically | |
halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号', '')) if h and h.replace('号', '').isdigit() else 0) | |
num_halls = len(halls) | |
num_movie_rows = len(data) | |
# 1. Calculate total vertical slots required to fill the page | |
num_separators = num_halls - 1 if num_halls > 1 else 0 | |
total_slots = num_movie_rows + num_separators + 2 # movies + separators + top/bottom padding | |
if total_slots == 0: return | |
# 2. Calculate the height of each slot | |
slot_height = 1.0 / total_slots | |
# 3. Calculate font size to be 90% of the slot height | |
figure_height_inches = 11.69 | |
font_size_points = (slot_height * figure_height_inches) * 0.9 * 72 # (height in inches) * 90% * 72 points/inch | |
movie_font_size = font_size_points | |
hall_font_size = movie_font_size * 0.8 | |
date_font = get_font(12) | |
hall_font = get_font(hall_font_size) | |
movie_font = get_font(movie_font_size) | |
# Draw the date at the top | |
ax.text(0.00, 1.00, date_str, fontsize=12, color='#A9A9A9', | |
ha='left', va='top', fontproperties=date_font, transform=ax.transAxes, zorder=3) | |
# 4. Initialize Y position, starting below the top padding slot | |
y_position = 1.0 - slot_height | |
# 5. Loop through each hall and its movies to draw the schedule | |
for i, hall in enumerate(halls): | |
hall_data = data[data['Hall'] == hall] | |
movie_count = 1 | |
for _, row in hall_data.iterrows(): | |
# Draw Hall Number (only for the first movie of the hall) | |
if movie_count == 1: | |
hall_num = hall.replace("号", "") | |
hall_text = f"${hall_num}^{{\\#}}$" # Use LaTeX for superscript '#' | |
ax.text(0.03, y_position, hall_text, | |
fontsize=hall_font_size, fontweight='bold', | |
ha='left', va='top', fontproperties=hall_font, | |
transform=ax.transAxes, zorder=2) | |
# Draw Pinyin Abbreviation and Movie Title | |
pinyin_abbr = get_pinyin_abbr(row['Movie']) | |
ax.text(0.20, y_position, f"{movie_count}. {pinyin_abbr} {row['Movie']}", | |
fontsize=movie_font_size, ha='left', va='top', fontproperties=movie_font, | |
transform=ax.transAxes, zorder=2, clip_on=True) | |
# Draw Time Information | |
ax.text(0.95, y_position, f"{row['StartTime_str']} - {row['EndTime_str']}", | |
fontsize=movie_font_size, ha='right', va='top', fontproperties=movie_font, | |
transform=ax.transAxes, zorder=2) | |
y_position -= slot_height # Move down for the next movie | |
movie_count += 1 | |
# After a hall's schedule, draw a separator line (if not the last hall) | |
if i < num_halls - 1: | |
# The line is drawn in the middle of the dedicated separator slot | |
line_y = y_position - (slot_height / 2) | |
ax.plot([0.03, 0.97], [line_y, line_y], color='black', linewidth=0.8, transform=ax.transAxes, zorder=1) | |
y_position -= slot_height # Move down past the separator slot | |
# Process and render the layout for both figure objects | |
process_figure(png_fig, png_ax) | |
process_figure(pdf_fig, pdf_ax, is_pdf=True) | |
# Save PNG to a buffer | |
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) | |
# Save PDF to a buffer | |
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}" | |
} | |
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 | |
# --- Streamlit App Main --- | |
st.set_page_config(page_title="LED 屏幕时间表打印", layout="wide") | |
st.title("LED 屏幕时间表打印") | |
uploaded_file = st.file_uploader("选择打开【放映时间核对表.xls】文件", accept_multiple_files=False, type=["xls", "xlsx"]) | |
if uploaded_file: | |
with st.spinner("文件正在处理中,请稍候..."): | |
schedule, date_str = process_schedule(uploaded_file) | |
if schedule is not None and not schedule.empty: | |
output = create_print_layout(schedule, date_str) | |
st.success("处理完成!请在下方预览和下载。") | |
# Create tabs to switch between PDF and PNG views | |
tab1, tab2 = st.tabs(["PDF 预览 (推荐打印)", "PNG 预览"]) | |
with tab1: | |
st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True) | |
st.download_button( | |
label="下载 PDF 文件", | |
data=base64.b64decode(output['pdf'].split(',')[1]), | |
file_name=f"Schedule_{date_str}.pdf", | |
mime="application/pdf" | |
) | |
with tab2: | |
st.image(output['png'], use_container_width=True) | |
st.download_button( | |
label="下载 PNG 图像", | |
data=base64.b64decode(output['png'].split(',')[1]), | |
file_name=f"Schedule_{date_str}.png", | |
mime="image/png" | |
) | |
else: | |
st.error("无法处理文件,或文件中没有找到有效排期。请检查文件格式或内容是否正确。") |