Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,31 +11,34 @@ from pypinyin import lazy_pinyin, Style
|
|
| 11 |
from matplotlib.backends.backend_pdf import PdfPages
|
| 12 |
|
| 13 |
def get_font(size=14):
|
| 14 |
-
"""Loads a
|
| 15 |
font_path = "simHei.ttc"
|
| 16 |
if not os.path.exists(font_path):
|
| 17 |
-
font_path = "SimHei.ttf"
|
| 18 |
return font_manager.FontProperties(fname=font_path, size=size)
|
| 19 |
|
| 20 |
def get_pinyin_abbr(text):
|
| 21 |
-
"""
|
| 22 |
if not text:
|
| 23 |
return ""
|
| 24 |
# Extract the first two Chinese characters
|
| 25 |
chars = [c for c in text if '\u4e00' <= c <= '\u9fff']
|
| 26 |
-
chars
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
|
| 29 |
return ''.join(pinyin_list).upper()
|
| 30 |
|
| 31 |
def process_schedule(file):
|
| 32 |
-
"""Processes the uploaded Excel file to extract and clean
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
|
| 36 |
date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
|
| 37 |
base_date = pd.to_datetime(date_str).date()
|
| 38 |
-
except
|
| 39 |
# Fallback to the current date if reading fails
|
| 40 |
date_str = datetime.today().strftime('%Y-%m-%d')
|
| 41 |
base_date = datetime.today().date()
|
|
@@ -44,8 +47,6 @@ def process_schedule(file):
|
|
| 44 |
# Read the main schedule data
|
| 45 |
df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
|
| 46 |
df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
|
| 47 |
-
|
| 48 |
-
# Clean and process the data
|
| 49 |
df['Hall'] = df['Hall'].ffill()
|
| 50 |
df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
|
| 51 |
df['Hall'] = df['Hall'].astype(str).str.extract(r'(\d+号)')
|
|
@@ -57,24 +58,24 @@ def process_schedule(file):
|
|
| 57 |
df['EndTime_dt'] = pd.to_datetime(df['EndTime'], format='%H:%M', errors='coerce').apply(
|
| 58 |
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
|
| 59 |
)
|
| 60 |
-
|
| 61 |
# Handle overnight screenings
|
| 62 |
df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
|
| 63 |
df = df.sort_values(['Hall', 'StartTime_dt'])
|
| 64 |
|
| 65 |
# Merge consecutive screenings of the same movie
|
| 66 |
merged_rows = []
|
| 67 |
-
for
|
| 68 |
group = group.sort_values('StartTime_dt')
|
| 69 |
current = None
|
| 70 |
for _, row in group.iterrows():
|
| 71 |
if current is None:
|
| 72 |
current = row.copy()
|
| 73 |
-
elif row['Movie'] == current['Movie']:
|
| 74 |
-
current['EndTime_dt'] = row['EndTime_dt']
|
| 75 |
else:
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
if current is not None:
|
| 79 |
merged_rows.append(current)
|
| 80 |
|
|
@@ -88,115 +89,115 @@ def process_schedule(file):
|
|
| 88 |
merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
|
| 89 |
|
| 90 |
return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
|
| 91 |
-
except
|
| 92 |
-
st.error(f"Error processing file: {e}")
|
| 93 |
return None, date_str
|
| 94 |
|
| 95 |
def create_print_layout(data, date_str):
|
| 96 |
-
"""Creates the PNG and PDF print layouts from the
|
| 97 |
if data is None or data.empty:
|
| 98 |
return None
|
| 99 |
|
| 100 |
-
#
|
| 101 |
png_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
|
| 102 |
png_ax = png_fig.add_subplot(111)
|
| 103 |
png_ax.set_axis_off()
|
| 104 |
png_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
|
| 105 |
|
|
|
|
| 106 |
pdf_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
|
| 107 |
pdf_ax = pdf_fig.add_subplot(111)
|
| 108 |
pdf_ax.set_axis_off()
|
| 109 |
pdf_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
|
| 110 |
-
|
| 111 |
-
def process_figure(fig, ax):
|
| 112 |
-
"""
|
| 113 |
-
# --- Dynamic Height and Font Size Calculation ---
|
| 114 |
-
halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号', '')))
|
| 115 |
-
num_movies = len(data)
|
| 116 |
-
num_separators = len(halls) - 1 if len(halls) > 1 else 0
|
| 117 |
-
|
| 118 |
-
# Total vertical slots = movies + separators + 2 for padding
|
| 119 |
-
total_slots = num_movies + num_separators + 2
|
| 120 |
-
available_height = 0.96 # Usable page height (0.98 top - 0.02 bottom)
|
| 121 |
-
line_height = available_height / total_slots
|
| 122 |
-
|
| 123 |
-
# Convert figure line height to font points (72 points per inch)
|
| 124 |
-
fig_height_inches = fig.get_figheight()
|
| 125 |
-
font_size_pt = (fig_height_inches * line_height) * 72 * 0.90 # 90% of line height
|
| 126 |
-
|
| 127 |
-
movie_font = get_font(font_size_pt)
|
| 128 |
-
hall_font = get_font(font_size_pt) # Use the same size for impact
|
| 129 |
date_font = get_font(12)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
for i, hall in enumerate(halls):
|
| 137 |
hall_data = data[data['Hall'] == hall]
|
| 138 |
-
|
| 139 |
-
|
| 140 |
movie_count = 1
|
|
|
|
| 141 |
for _, row in hall_data.iterrows():
|
| 142 |
-
#
|
| 143 |
-
# Hall number is printed only for the first movie of the hall
|
| 144 |
if movie_count == 1:
|
| 145 |
-
ax.text(0.03, y_position,
|
| 146 |
-
fontsize=
|
| 147 |
-
fontproperties=hall_font,
|
| 148 |
-
|
|
|
|
| 149 |
pinyin_abbr = get_pinyin_abbr(row['Movie'])
|
| 150 |
-
time_str = f"{row['StartTime_str']} - {row['EndTime_str']}"
|
| 151 |
-
|
| 152 |
-
# Define x-coordinates for each column
|
| 153 |
-
x_movie_name_end = 0.48
|
| 154 |
-
x_seq_no_start = 0.51
|
| 155 |
-
x_pinyin_start = 0.62
|
| 156 |
-
x_time_start = 0.75
|
| 157 |
|
| 158 |
-
#
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
fontproperties=movie_font,
|
|
|
|
| 162 |
|
| 163 |
-
# Sequence Number (
|
| 164 |
-
ax.text(
|
| 165 |
-
fontsize=
|
| 166 |
-
|
| 167 |
|
| 168 |
-
# Pinyin Abbreviation (
|
| 169 |
-
ax.text(
|
| 170 |
-
fontsize=
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
# Time (
|
| 174 |
-
ax.text(
|
| 175 |
-
fontsize=
|
| 176 |
-
|
| 177 |
|
| 178 |
-
y_position -=
|
| 179 |
movie_count += 1
|
| 180 |
|
| 181 |
-
#
|
| 182 |
-
if i <
|
| 183 |
-
|
| 184 |
-
ax.
|
| 185 |
-
color='black', linewidth=0.8, transform=ax.transAxes)
|
| 186 |
-
y_position -= line_height # Add space for the separator line
|
| 187 |
|
| 188 |
-
#
|
| 189 |
process_figure(png_fig, png_ax)
|
| 190 |
-
process_figure(pdf_fig, pdf_ax)
|
| 191 |
-
|
| 192 |
-
# Save PNG to
|
| 193 |
png_buffer = io.BytesIO()
|
| 194 |
png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.05)
|
| 195 |
png_buffer.seek(0)
|
| 196 |
image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
|
| 197 |
plt.close(png_fig)
|
| 198 |
|
| 199 |
-
# Save PDF to
|
| 200 |
pdf_buffer = io.BytesIO()
|
| 201 |
with PdfPages(pdf_buffer) as pdf:
|
| 202 |
pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
|
|
@@ -210,11 +211,13 @@ def create_print_layout(data, date_str):
|
|
| 210 |
}
|
| 211 |
|
| 212 |
def display_pdf(base64_pdf):
|
| 213 |
-
"""
|
| 214 |
-
pdf_display = f
|
|
|
|
|
|
|
| 215 |
return pdf_display
|
| 216 |
|
| 217 |
-
# --- Streamlit App
|
| 218 |
st.set_page_config(page_title="LED 屏幕时间表打印", layout="wide")
|
| 219 |
st.title("LED 屏幕时间表打印")
|
| 220 |
|
|
|
|
| 11 |
from matplotlib.backends.backend_pdf import PdfPages
|
| 12 |
|
| 13 |
def get_font(size=14):
|
| 14 |
+
"""Loads a font file, searching for common names."""
|
| 15 |
font_path = "simHei.ttc"
|
| 16 |
if not os.path.exists(font_path):
|
| 17 |
+
font_path = "SimHei.ttf"
|
| 18 |
return font_manager.FontProperties(fname=font_path, size=size)
|
| 19 |
|
| 20 |
def get_pinyin_abbr(text):
|
| 21 |
+
"""Gets the first letter of the Pinyin for the first two Chinese characters of a text."""
|
| 22 |
if not text:
|
| 23 |
return ""
|
| 24 |
# Extract the first two Chinese characters
|
| 25 |
chars = [c for c in text if '\u4e00' <= c <= '\u9fff']
|
| 26 |
+
if len(chars) < 2:
|
| 27 |
+
chars = chars + [''] * (2 - len(chars))
|
| 28 |
+
else:
|
| 29 |
+
chars = chars[:2]
|
| 30 |
+
# Get the first letter of the Pinyin
|
| 31 |
pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
|
| 32 |
return ''.join(pinyin_list).upper()
|
| 33 |
|
| 34 |
def process_schedule(file):
|
| 35 |
+
"""Processes the uploaded Excel file to extract and clean schedule data."""
|
| 36 |
try:
|
| 37 |
+
# Try to read the date from a specific cell
|
| 38 |
date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
|
| 39 |
date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
|
| 40 |
base_date = pd.to_datetime(date_str).date()
|
| 41 |
+
except:
|
| 42 |
# Fallback to the current date if reading fails
|
| 43 |
date_str = datetime.today().strftime('%Y-%m-%d')
|
| 44 |
base_date = datetime.today().date()
|
|
|
|
| 47 |
# Read the main schedule data
|
| 48 |
df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
|
| 49 |
df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
|
|
|
|
|
|
|
| 50 |
df['Hall'] = df['Hall'].ffill()
|
| 51 |
df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
|
| 52 |
df['Hall'] = df['Hall'].astype(str).str.extract(r'(\d+号)')
|
|
|
|
| 58 |
df['EndTime_dt'] = pd.to_datetime(df['EndTime'], format='%H:%M', errors='coerce').apply(
|
| 59 |
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
|
| 60 |
)
|
|
|
|
| 61 |
# Handle overnight screenings
|
| 62 |
df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
|
| 63 |
df = df.sort_values(['Hall', 'StartTime_dt'])
|
| 64 |
|
| 65 |
# Merge consecutive screenings of the same movie
|
| 66 |
merged_rows = []
|
| 67 |
+
for hall, group in df.groupby('Hall'):
|
| 68 |
group = group.sort_values('StartTime_dt')
|
| 69 |
current = None
|
| 70 |
for _, row in group.iterrows():
|
| 71 |
if current is None:
|
| 72 |
current = row.copy()
|
|
|
|
|
|
|
| 73 |
else:
|
| 74 |
+
if row['Movie'] == current['Movie']:
|
| 75 |
+
current['EndTime_dt'] = row['EndTime_dt']
|
| 76 |
+
else:
|
| 77 |
+
merged_rows.append(current)
|
| 78 |
+
current = row.copy()
|
| 79 |
if current is not None:
|
| 80 |
merged_rows.append(current)
|
| 81 |
|
|
|
|
| 89 |
merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
|
| 90 |
|
| 91 |
return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
|
| 92 |
+
except:
|
|
|
|
| 93 |
return None, date_str
|
| 94 |
|
| 95 |
def create_print_layout(data, date_str):
|
| 96 |
+
"""Creates the PNG and PDF print layouts from the schedule data."""
|
| 97 |
if data is None or data.empty:
|
| 98 |
return None
|
| 99 |
|
| 100 |
+
# Create PNG image for preview
|
| 101 |
png_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
|
| 102 |
png_ax = png_fig.add_subplot(111)
|
| 103 |
png_ax.set_axis_off()
|
| 104 |
png_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
|
| 105 |
|
| 106 |
+
# Create PDF image for download
|
| 107 |
pdf_fig = plt.figure(figsize=(8.27, 11.69), dpi=300)
|
| 108 |
pdf_ax = pdf_fig.add_subplot(111)
|
| 109 |
pdf_ax.set_axis_off()
|
| 110 |
pdf_fig.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
|
| 111 |
+
|
| 112 |
+
def process_figure(fig, ax, is_pdf=False):
|
| 113 |
+
"""Shared function to draw the schedule on a matplotlib figure."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
date_font = get_font(12)
|
| 115 |
+
|
| 116 |
+
# Calculate row height to fill the page
|
| 117 |
+
total_movies = len(data)
|
| 118 |
+
# Add 2 to the total to create top and bottom margins
|
| 119 |
+
total_divisions = total_movies + 2
|
| 120 |
+
|
| 121 |
+
available_height_ax = 0.98 - 0.02 # Use 96% of the page height
|
| 122 |
+
row_height_ax = available_height_ax / total_divisions
|
| 123 |
|
| 124 |
+
# Convert relative height to point size for fonts
|
| 125 |
+
fig_height_pts = fig.get_figheight() * 72
|
| 126 |
+
row_height_pts = row_height_ax * fig_height_pts
|
| 127 |
+
|
| 128 |
+
# Set font size to 90% of the calculated row height
|
| 129 |
+
font_size = row_height_pts * 0.9
|
| 130 |
+
hall_font_size = font_size * 0.8
|
| 131 |
|
| 132 |
+
hall_font = get_font(hall_font_size)
|
| 133 |
+
movie_font = get_font(font_size)
|
| 134 |
+
|
| 135 |
+
# Add date stamp to the top left
|
| 136 |
+
ax.text(0.00, 1.00, date_str, fontsize=12, color='#A9A9A9',
|
| 137 |
+
ha='left', va='top', fontproperties=date_font, transform=ax.transAxes, zorder=2)
|
| 138 |
+
|
| 139 |
+
halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号','')) if h else 0)
|
| 140 |
+
|
| 141 |
+
# Start drawing from the top, leaving one row_height as a margin
|
| 142 |
+
y_position = 0.98 - row_height_ax
|
| 143 |
|
| 144 |
for i, hall in enumerate(halls):
|
| 145 |
hall_data = data[data['Hall'] == hall]
|
| 146 |
+
hall_num = hall.replace("号", "")
|
| 147 |
+
hall_text = f"${hall_num}^{{\\#}}$"
|
| 148 |
movie_count = 1
|
| 149 |
+
|
| 150 |
for _, row in hall_data.iterrows():
|
| 151 |
+
# Hall Number (left-aligned)
|
|
|
|
| 152 |
if movie_count == 1:
|
| 153 |
+
ax.text(0.03, y_position, hall_text,
|
| 154 |
+
fontsize=hall_font_size, fontweight='bold',
|
| 155 |
+
ha='left', va='top', fontproperties=hall_font,
|
| 156 |
+
transform=ax.transAxes, zorder=2)
|
| 157 |
+
|
| 158 |
pinyin_abbr = get_pinyin_abbr(row['Movie'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
# New content order and alignment
|
| 161 |
+
# 1. Movie Name (right-aligned)
|
| 162 |
+
ax.text(0.55, y_position, row['Movie'],
|
| 163 |
+
fontsize=font_size, ha='right', va='top', fontproperties=movie_font,
|
| 164 |
+
transform=ax.transAxes, zorder=2)
|
| 165 |
|
| 166 |
+
# 2. Sequence Number (left-aligned)
|
| 167 |
+
ax.text(0.57, y_position, f"{movie_count}.",
|
| 168 |
+
fontsize=font_size, ha='left', va='top', fontproperties=movie_font,
|
| 169 |
+
transform=ax.transAxes, zorder=2)
|
| 170 |
|
| 171 |
+
# 3. Pinyin Abbreviation (left-aligned)
|
| 172 |
+
ax.text(0.63, y_position, pinyin_abbr,
|
| 173 |
+
fontsize=font_size, ha='left', va='top', fontproperties=movie_font,
|
| 174 |
+
transform=ax.transAxes, zorder=2)
|
| 175 |
+
|
| 176 |
+
# 4. Time (left-aligned)
|
| 177 |
+
ax.text(0.72, y_position, f"{row['StartTime_str']} - {row['EndTime_str']}",
|
| 178 |
+
fontsize=font_size, ha='left', va='top', fontproperties=movie_font,
|
| 179 |
+
transform=ax.transAxes, zorder=2)
|
| 180 |
|
| 181 |
+
y_position -= row_height_ax
|
| 182 |
movie_count += 1
|
| 183 |
|
| 184 |
+
# Draw a black line to separate halls
|
| 185 |
+
if i < len(halls) - 1:
|
| 186 |
+
line_y = y_position + (row_height_ax / 2)
|
| 187 |
+
ax.plot([0.03, 0.97], [line_y, line_y], color='black', linewidth=1, transform=ax.transAxes, zorder=1)
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
# Process both the PNG and PDF figures
|
| 190 |
process_figure(png_fig, png_ax)
|
| 191 |
+
process_figure(pdf_fig, pdf_ax, is_pdf=True)
|
| 192 |
+
|
| 193 |
+
# Save PNG to buffer
|
| 194 |
png_buffer = io.BytesIO()
|
| 195 |
png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.05)
|
| 196 |
png_buffer.seek(0)
|
| 197 |
image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
|
| 198 |
plt.close(png_fig)
|
| 199 |
|
| 200 |
+
# Save PDF to buffer
|
| 201 |
pdf_buffer = io.BytesIO()
|
| 202 |
with PdfPages(pdf_buffer) as pdf:
|
| 203 |
pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
|
|
|
|
| 211 |
}
|
| 212 |
|
| 213 |
def display_pdf(base64_pdf):
|
| 214 |
+
"""Generates the HTML to embed a PDF in Streamlit."""
|
| 215 |
+
pdf_display = f"""
|
| 216 |
+
<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>
|
| 217 |
+
"""
|
| 218 |
return pdf_display
|
| 219 |
|
| 220 |
+
# --- Streamlit App ---
|
| 221 |
st.set_page_config(page_title="LED 屏幕时间表打印", layout="wide")
|
| 222 |
st.title("LED 屏幕时间表打印")
|
| 223 |
|