Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,55 +2,66 @@ import pandas as pd
|
|
2 |
import streamlit as st
|
3 |
import matplotlib.pyplot as plt
|
4 |
import matplotlib.font_manager as font_manager
|
|
|
5 |
import io
|
6 |
import base64
|
7 |
import os
|
8 |
from datetime import datetime, timedelta
|
9 |
-
import math
|
10 |
-
from matplotlib.patches import FancyBboxPatch, Rectangle
|
11 |
from pypinyin import lazy_pinyin, Style
|
12 |
from matplotlib.backends.backend_pdf import PdfPages
|
13 |
|
14 |
def get_font(size=14):
|
15 |
-
"""Loads
|
|
|
16 |
font_path = "simHei.ttc"
|
17 |
if not os.path.exists(font_path):
|
|
|
18 |
font_path = "SimHei.ttf"
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
return font_manager.FontProperties(size=size)
|
23 |
-
|
|
|
|
|
|
|
24 |
|
25 |
def get_pinyin_abbr(text):
|
26 |
-
"""Gets the first letter of the Pinyin for the first two Chinese characters."""
|
27 |
if not text:
|
28 |
return ""
|
|
|
29 |
chars = [c for c in text if '\u4e00' <= c <= '\u9fff'][:2]
|
30 |
if not chars:
|
31 |
return ""
|
32 |
-
|
|
|
|
|
33 |
|
34 |
def process_schedule(file):
|
35 |
-
"""
|
|
|
|
|
|
|
36 |
try:
|
37 |
-
# Try to read the date from
|
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 Exception:
|
42 |
-
# Fallback to today's date
|
|
|
43 |
base_date = datetime.today().date()
|
44 |
-
date_str = base_date.strftime('%Y-%m-%d')
|
45 |
|
46 |
try:
|
47 |
df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
|
48 |
df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
|
|
|
|
|
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+号)')
|
52 |
-
|
53 |
-
|
54 |
# Convert times to datetime objects
|
55 |
df['StartTime_dt'] = pd.to_datetime(df['StartTime'], format='%H:%M', errors='coerce').apply(
|
56 |
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
|
@@ -62,228 +73,218 @@ def process_schedule(file):
|
|
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
|
66 |
merged_rows = []
|
67 |
-
for
|
68 |
current = None
|
69 |
for _, row in group.sort_values('StartTime_dt').iterrows():
|
70 |
if current is None:
|
71 |
current = row.copy()
|
72 |
elif row['Movie'] == current['Movie']:
|
73 |
-
current['EndTime_dt'] = row['EndTime_dt']
|
74 |
else:
|
75 |
merged_rows.append(current)
|
76 |
current = row.copy()
|
77 |
if current is not None:
|
78 |
merged_rows.append(current)
|
79 |
-
|
80 |
-
if not merged_rows:
|
81 |
-
return None, date_str
|
82 |
-
|
83 |
merged_df = pd.DataFrame(merged_rows)
|
84 |
|
85 |
# Adjust times as per original logic
|
86 |
merged_df['StartTime_dt'] -= timedelta(minutes=10)
|
87 |
merged_df['EndTime_dt'] -= timedelta(minutes=5)
|
88 |
|
|
|
|
|
|
|
89 |
merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
|
90 |
merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
|
91 |
|
92 |
-
return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
|
93 |
except Exception as e:
|
94 |
-
st.error(f"Error processing
|
95 |
return None, date_str
|
96 |
|
97 |
-
def get_text_dimensions(text, font_props, fig):
|
98 |
-
"""Helper function to calculate the width and height of a text string in inches."""
|
99 |
-
renderer = fig.canvas.get_renderer()
|
100 |
-
t = fig.text(0, 0, text, fontproperties=font_props, visible=False)
|
101 |
-
bbox = t.get_window_extent(renderer=renderer)
|
102 |
-
t.remove()
|
103 |
-
return bbox.width / fig.dpi, bbox.height / fig.dpi
|
104 |
-
|
105 |
-
def find_font_size(target_height_inches, font_path, fig, text_to_measure="Xg"):
|
106 |
-
"""Finds the font size (in points) that results in a given text height (in inches)."""
|
107 |
-
low, high = 0, 100 # Binary search range for font size
|
108 |
-
best_size = 10
|
109 |
-
|
110 |
-
for _ in range(10): # 10 iterations for precision
|
111 |
-
mid = (low + high) / 2
|
112 |
-
if mid <= 0: break
|
113 |
-
props = font_manager.FontProperties(fname=font_path, size=mid)
|
114 |
-
_, h = get_text_dimensions(text_to_measure, props, fig)
|
115 |
-
if h > target_height_inches:
|
116 |
-
high = mid
|
117 |
-
else:
|
118 |
-
best_size = mid
|
119 |
-
low = mid
|
120 |
-
return best_size
|
121 |
|
122 |
def create_print_layout(data, date_str):
|
123 |
-
"""
|
|
|
|
|
124 |
if data is None or data.empty:
|
125 |
return None
|
126 |
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
total_A = len(data) + 2 # Total rows + top/bottom margin
|
131 |
-
row_height = A4_HEIGHT_IN / total_A
|
132 |
-
side_margin_width = row_height # Left/right blank columns width
|
133 |
-
content_width = A4_WIDTH_IN - 2 * side_margin_width
|
134 |
-
target_font_height = row_height * 0.9
|
135 |
|
136 |
-
#
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
master_font = get_font(size=master_font_size)
|
141 |
|
142 |
-
# Prepare
|
143 |
-
data
|
144 |
-
data['
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
max_pinyin_content = max(data['Pinyin'], key=len) if not data['Pinyin'].empty else "PY"
|
149 |
-
max_time_content = max(data['TimeStr'], key=len)
|
150 |
-
|
151 |
-
w_hall, _ = get_text_dimensions(max_hall_content, master_font, dummy_fig)
|
152 |
-
w_seq, _ = get_text_dimensions(max_seq_content, master_font, dummy_fig)
|
153 |
-
w_pinyin, _ = get_text_dimensions(max_pinyin_content, master_font, dummy_fig)
|
154 |
-
w_time, _ = get_text_dimensions(max_time_content, master_font, dummy_fig)
|
155 |
-
plt.close(dummy_fig)
|
156 |
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
col_width_time = w_time * 1.1
|
161 |
-
|
162 |
-
col_width_movie = content_width - (col_width_hall + col_width_seq + col_width_pinyin + col_width_time)
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
-
#
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
|
175 |
-
ax.set_xlim(0, A4_WIDTH_IN)
|
176 |
-
ax.set_ylim(0, A4_HEIGHT_IN)
|
177 |
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
x_pos[2] = x_pos[1] + col_width_hall
|
183 |
-
x_pos[3] = x_pos[2] + col_width_seq
|
184 |
-
x_pos[4] = x_pos[3] + col_width_movie
|
185 |
-
x_pos[5] = x_pos[4] + col_width_pinyin
|
186 |
-
x_pos[6] = x_pos[5] + col_width_time
|
187 |
|
188 |
-
|
189 |
-
|
190 |
-
|
|
|
|
|
|
|
|
|
191 |
|
192 |
-
|
193 |
-
|
194 |
-
|
|
|
|
|
195 |
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
ax.text(x_pos[1] + col_width_hall / 2, y_center, hall_num_text,
|
210 |
-
ha='center', va='center', fontproperties=master_font)
|
211 |
-
drawn_halls.add(hall_name)
|
212 |
-
|
213 |
-
# Column 2: Sequence Number
|
214 |
-
ax.text(x_pos[2] + col_width_seq / 2, y_center, f"{i+1}.",
|
215 |
-
ha='center', va='center', fontproperties=master_font)
|
216 |
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
temp_fig = plt.figure()
|
222 |
-
w_movie, _ = get_text_dimensions(row['Movie'], font_movie, temp_fig)
|
223 |
-
plt.close(temp_fig)
|
224 |
-
|
225 |
-
if w_movie > movie_cell_inner_width:
|
226 |
-
scale_factor = movie_cell_inner_width / w_movie
|
227 |
-
font_movie.set_size(font_movie.get_size() * scale_factor)
|
228 |
|
229 |
-
|
230 |
-
|
|
|
231 |
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
239 |
|
240 |
-
|
|
|
241 |
|
242 |
-
|
243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
244 |
|
245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
|
247 |
-
# --- Save figures to in-memory buffers ---
|
248 |
-
png_buffer = io.BytesIO()
|
249 |
-
output_figs['png'].savefig(png_buffer, format='png', bbox_inches=None, pad_inches=0)
|
250 |
-
plt.close(output_figs['png'])
|
251 |
-
|
252 |
-
pdf_buffer = io.BytesIO()
|
253 |
-
output_figs['pdf'].savefig(pdf_buffer, format='pdf', bbox_inches=None, pad_inches=0)
|
254 |
-
plt.close(output_figs['pdf'])
|
255 |
-
|
256 |
-
# Encode for display
|
257 |
-
png_buffer.seek(0)
|
258 |
-
image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
|
259 |
-
pdf_buffer.seek(0)
|
260 |
-
pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
|
261 |
-
|
262 |
-
return {
|
263 |
-
'png': f"data:image/png;base64,{image_base64}",
|
264 |
-
'pdf': f"data:application/pdf;base64,{pdf_base64}"
|
265 |
-
}
|
266 |
|
267 |
def display_pdf(base64_pdf):
|
268 |
"""Generates the HTML to embed a PDF in Streamlit."""
|
269 |
-
|
|
|
270 |
|
271 |
# --- Streamlit App ---
|
272 |
-
st.set_page_config(page_title="LED Screen Schedule
|
273 |
-
st.title("LED Screen Schedule
|
274 |
|
275 |
-
uploaded_file = st.file_uploader("Select the '
|
276 |
|
277 |
if uploaded_file:
|
278 |
with st.spinner("Processing file, please wait..."):
|
279 |
schedule, date_str = process_schedule(uploaded_file)
|
280 |
if schedule is not None and not schedule.empty:
|
281 |
output = create_print_layout(schedule, date_str)
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
|
|
|
|
288 |
else:
|
289 |
-
st.error("Could not process the file. Please check
|
|
|
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
|
|
|
|
|
10 |
from pypinyin import lazy_pinyin, Style
|
11 |
from matplotlib.backends.backend_pdf import PdfPages
|
12 |
|
13 |
def get_font(size=14):
|
14 |
+
"""Loads a specific TrueType font, defaulting to a common Chinese font."""
|
15 |
+
# Prioritize the .ttc file if it exists
|
16 |
font_path = "simHei.ttc"
|
17 |
if not os.path.exists(font_path):
|
18 |
+
# Fallback to the .ttf file
|
19 |
font_path = "SimHei.ttf"
|
20 |
+
# If neither exists, matplotlib will use its default font.
|
21 |
+
# For best results, ensure one of these fonts is in the same directory as the script.
|
22 |
+
if os.path.exists(font_path):
|
23 |
+
return font_manager.FontProperties(fname=font_path, size=size)
|
24 |
+
else:
|
25 |
+
# Fallback to a generic font if SimHei is not found
|
26 |
+
st.warning("SimHei font not found. Display may not be correct. Please add simHei.ttc or SimHei.ttf.")
|
27 |
+
return font_manager.FontProperties(family='sans-serif', size=size)
|
28 |
|
29 |
def get_pinyin_abbr(text):
|
30 |
+
"""Gets the first letter of the Pinyin for the first two Chinese characters of a text."""
|
31 |
if not text:
|
32 |
return ""
|
33 |
+
# Extract the first two Chinese characters
|
34 |
chars = [c for c in text if '\u4e00' <= c <= '\u9fff'][:2]
|
35 |
if not chars:
|
36 |
return ""
|
37 |
+
# Get the first letter of the pinyin for each character
|
38 |
+
pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
|
39 |
+
return ''.join(pinyin_list).upper()
|
40 |
|
41 |
def process_schedule(file):
|
42 |
+
"""
|
43 |
+
Processes the uploaded Excel file to extract and clean the movie schedule data.
|
44 |
+
Adds a sequence number for movies within each hall.
|
45 |
+
"""
|
46 |
try:
|
47 |
+
# Try to read the date from the specified cell
|
48 |
date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
|
49 |
date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
|
50 |
base_date = pd.to_datetime(date_str).date()
|
51 |
except Exception:
|
52 |
+
# Fallback to today's date if reading fails
|
53 |
+
date_str = datetime.today().strftime('%Y-%m-%d')
|
54 |
base_date = datetime.today().date()
|
|
|
55 |
|
56 |
try:
|
57 |
df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
|
58 |
df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
|
59 |
+
|
60 |
+
# Clean and format the data
|
61 |
df['Hall'] = df['Hall'].ffill()
|
62 |
df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
|
63 |
df['Hall'] = df['Hall'].astype(str).str.extract(r'(\d+号)')
|
64 |
+
|
|
|
65 |
# Convert times to datetime objects
|
66 |
df['StartTime_dt'] = pd.to_datetime(df['StartTime'], format='%H:%M', errors='coerce').apply(
|
67 |
lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
|
|
|
73 |
df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
|
74 |
df = df.sort_values(['Hall', 'StartTime_dt'])
|
75 |
|
76 |
+
# Merge consecutive screenings of the same movie
|
77 |
merged_rows = []
|
78 |
+
for _, group in df.groupby('Hall'):
|
79 |
current = None
|
80 |
for _, row in group.sort_values('StartTime_dt').iterrows():
|
81 |
if current is None:
|
82 |
current = row.copy()
|
83 |
elif row['Movie'] == current['Movie']:
|
84 |
+
current['EndTime_dt'] = row['EndTime_dt'] # Extend the end time
|
85 |
else:
|
86 |
merged_rows.append(current)
|
87 |
current = row.copy()
|
88 |
if current is not None:
|
89 |
merged_rows.append(current)
|
90 |
+
|
|
|
|
|
|
|
91 |
merged_df = pd.DataFrame(merged_rows)
|
92 |
|
93 |
# Adjust times as per original logic
|
94 |
merged_df['StartTime_dt'] -= timedelta(minutes=10)
|
95 |
merged_df['EndTime_dt'] -= timedelta(minutes=5)
|
96 |
|
97 |
+
# Add a sequence number for each movie within its hall
|
98 |
+
merged_df['Seq'] = merged_df.groupby('Hall').cumcount() + 1
|
99 |
+
|
100 |
merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
|
101 |
merged_df['EndTime_str'] = merged_df['EndTime_dt'].dt.strftime('%H:%M')
|
102 |
|
103 |
+
return merged_df[['Hall', 'Seq', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
|
104 |
except Exception as e:
|
105 |
+
st.error(f"Error processing schedule data: {e}. Please check the file format.")
|
106 |
return None, date_str
|
107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
def create_print_layout(data, date_str):
|
110 |
+
"""
|
111 |
+
Generates PNG and PDF print layouts for the movie schedule based on a dynamic grid.
|
112 |
+
"""
|
113 |
if data is None or data.empty:
|
114 |
return None
|
115 |
|
116 |
+
# --- 1. Layout and Column Calculation ---
|
117 |
+
A4_width_in, A4_height_in = 8.27, 11.69 # A4 size in inches
|
118 |
+
dpi = 300
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
+
# Calculate total rows and row height based on A4 size
|
121 |
+
total_content_rows = len(data)
|
122 |
+
totalA = total_content_rows + 2 # Add 2 for top/bottom margin rows
|
123 |
+
row_height = A4_height_in / totalA
|
|
|
124 |
|
125 |
+
# Prepare data strings for width calculation
|
126 |
+
data = data.reset_index(drop=True)
|
127 |
+
data['hall_str'] = data['Hall'].str.replace('号', '') + '#'
|
128 |
+
data['seq_str'] = data['Seq'].astype(str) + '.'
|
129 |
+
data['pinyin_abbr'] = data['Movie'].apply(get_pinyin_abbr)
|
130 |
+
data['time_str'] = data['StartTime_str'] + ' - ' + data['EndTime_str']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
+
# Create a temporary figure to access the renderer for text width calculation
|
133 |
+
temp_fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=dpi)
|
134 |
+
renderer = temp_fig.canvas.get_renderer()
|
|
|
|
|
|
|
135 |
|
136 |
+
# Base font size is 90% of the row height (converted from inches to points)
|
137 |
+
base_font_size_pt = (row_height * 0.9) * 72
|
138 |
+
|
139 |
+
def get_col_width_in(series, font_size_pt):
|
140 |
+
"""Calculates the required width for a column in inches."""
|
141 |
+
if series.empty:
|
142 |
+
return 0
|
143 |
+
font_prop = get_font(font_size_pt)
|
144 |
+
# Find the string with the maximum visual length in the series
|
145 |
+
longest_str_idx = series.astype(str).str.len().idxmax()
|
146 |
+
max_content = str(series.loc[longest_str_idx])
|
147 |
+
# Get width in pixels from the renderer
|
148 |
+
text_width_px, _, _ = renderer.get_text_width_height_descent(max_content, font_prop, ismath=False)
|
149 |
+
# Convert to inches and add a 10% buffer
|
150 |
+
return (text_width_px / dpi) * 1.1
|
151 |
|
152 |
+
# Calculate widths for fixed-content columns
|
153 |
+
margin_col_width = row_height # Left/right margins are as wide as the rows are high
|
154 |
+
hall_col_width = get_col_width_in(data['hall_str'], base_font_size_pt)
|
155 |
+
seq_col_width = get_col_width_in(data['seq_str'], base_font_size_pt)
|
156 |
+
pinyin_col_width = get_col_width_in(data['pinyin_abbr'], base_font_size_pt)
|
157 |
+
time_col_width = get_col_width_in(data['time_str'], base_font_size_pt)
|
|
|
|
|
|
|
158 |
|
159 |
+
# The movie title column takes the remaining width
|
160 |
+
movie_col_width = A4_width_in - (margin_col_width * 2 + hall_col_width + seq_col_width + pinyin_col_width + time_col_width)
|
161 |
+
|
162 |
+
plt.close(temp_fig) # Close the temporary figure
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
+
# Store column widths and their horizontal starting positions
|
165 |
+
col_widths = {'hall': hall_col_width, 'seq': seq_col_width, 'movie': movie_col_width, 'pinyin': pinyin_col_width, 'time': time_col_width}
|
166 |
+
col_x_starts = {}
|
167 |
+
current_x = margin_col_width
|
168 |
+
for col_name in ['hall', 'seq', 'movie', 'pinyin', 'time']:
|
169 |
+
col_x_starts[col_name] = current_x
|
170 |
+
current_x += col_widths[col_name]
|
171 |
|
172 |
+
# --- 2. Drawing ---
|
173 |
+
def draw_figure(fig, ax):
|
174 |
+
"""The common drawing function to be applied to both PNG and PDF figures."""
|
175 |
+
# Get a renderer from the actual figure we are drawing on
|
176 |
+
renderer = fig.canvas.get_renderer()
|
177 |
|
178 |
+
# Draw vertical dotted grid lines between columns
|
179 |
+
for col_name in ['hall', 'seq', 'movie', 'pinyin']:
|
180 |
+
x_line = col_x_starts[col_name] + col_widths[col_name]
|
181 |
+
line_top_y = A4_height_in - row_height
|
182 |
+
line_bottom_y = row_height
|
183 |
+
ax.add_line(Line2D([x_line, x_line], [line_bottom_y, line_top_y], color='gray', linestyle=':', linewidth=0.5))
|
184 |
+
|
185 |
+
# --- Draw Content and Horizontal Lines for each row ---
|
186 |
+
last_hall_drawn = None
|
187 |
+
for i, row in data.iterrows():
|
188 |
+
y_bottom = A4_height_in - (i + 2) * row_height # Y-coordinate of the row's bottom line
|
189 |
+
y_center = y_bottom + row_height / 2 # Y-coordinate of the row's vertical center
|
190 |
+
|
191 |
+
# --- Draw Cell Content ---
|
192 |
+
# Hall Number (only for the first row of each hall)
|
193 |
+
if row['Hall'] != last_hall_drawn:
|
194 |
+
ax.text(col_x_starts['hall'] + col_widths['hall'] / 2, y_center, row['hall_str'],
|
195 |
+
fontproperties=get_font(base_font_size_pt), ha='center', va='center')
|
196 |
+
last_hall_drawn = row['Hall']
|
197 |
|
198 |
+
# Sequence Number
|
199 |
+
ax.text(col_x_starts['seq'] + col_widths['seq'] / 2, y_center, row['seq_str'],
|
200 |
+
fontproperties=get_font(base_font_size_pt), ha='center', va='center')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
|
202 |
+
# Pinyin Abbreviation
|
203 |
+
ax.text(col_x_starts['pinyin'] + col_widths['pinyin'] / 2, y_center, row['pinyin_abbr'],
|
204 |
+
fontproperties=get_font(base_font_size_pt), ha='center', va='center')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
+
# Time String
|
207 |
+
ax.text(col_x_starts['time'] + col_widths['time'] / 2, y_center, row['time_str'],
|
208 |
+
fontproperties=get_font(base_font_size_pt), ha='center', va='center')
|
209 |
|
210 |
+
# Movie Title (with special font scaling to fit)
|
211 |
+
movie_font_size = base_font_size_pt
|
212 |
+
movie_font_prop = get_font(movie_font_size)
|
213 |
+
text_w_px, _, _ = renderer.get_text_width_height_descent(row['Movie'], movie_font_prop, ismath=False)
|
214 |
+
text_w_in = text_w_px / dpi
|
215 |
+
|
216 |
+
max_width_in = col_widths['movie'] * 0.9 # Target 90% of cell width
|
217 |
+
if text_w_in > max_width_in:
|
218 |
+
# If text is too wide, reduce font size proportionally
|
219 |
+
movie_font_size *= (max_width_in / text_w_in)
|
220 |
+
movie_font_prop = get_font(movie_font_size)
|
221 |
+
|
222 |
+
ax.text(col_x_starts['movie'] + 0.05, y_center, row['Movie'], # Left-aligned with padding
|
223 |
+
fontproperties=movie_font_prop, ha='left', va='center')
|
224 |
|
225 |
+
# --- Draw Horizontal Lines ---
|
226 |
+
is_last_in_hall = (i == len(data) - 1) or (row['Hall'] != data.loc[i + 1, 'Hall'])
|
227 |
|
228 |
+
if is_last_in_hall:
|
229 |
+
# Draw a solid black line to separate halls
|
230 |
+
line_start_x = margin_col_width
|
231 |
+
line_end_x = A4_width_in - margin_col_width
|
232 |
+
ax.add_line(Line2D([line_start_x, line_end_x], [y_bottom, y_bottom], color='black', linestyle='-', linewidth=0.8))
|
233 |
+
else:
|
234 |
+
# Draw a dotted gray line for rows within a hall
|
235 |
+
ax.add_line(Line2D([margin_col_width, A4_width_in - margin_col_width], [y_bottom, y_bottom], color='gray', linestyle=':', linewidth=0.5))
|
236 |
+
|
237 |
+
# --- 3. Setup Figures and Generate Output ---
|
238 |
+
outputs = {}
|
239 |
+
for format_type in ['png', 'pdf']:
|
240 |
+
fig = plt.figure(figsize=(A4_width_in, A4_height_in), dpi=dpi)
|
241 |
+
ax = fig.add_axes([0, 0, 1, 1]) # Use the whole figure area for drawing
|
242 |
+
ax.set_axis_off()
|
243 |
+
ax.set_xlim(0, A4_width_in)
|
244 |
+
ax.set_ylim(0, A4_height_in)
|
245 |
|
246 |
+
# Add date string to the top margin area
|
247 |
+
ax.text(margin_col_width, A4_height_in - (row_height/2), date_str,
|
248 |
+
fontproperties=get_font(10), color='#A9A9A9', ha='left', va='center')
|
249 |
+
|
250 |
+
draw_figure(fig, ax)
|
251 |
+
|
252 |
+
buf = io.BytesIO()
|
253 |
+
fig.savefig(buf, format=format_type, dpi=dpi, bbox_inches='tight', pad_inches=0)
|
254 |
+
buf.seek(0)
|
255 |
+
|
256 |
+
data_uri = base64.b64encode(buf.getvalue()).decode()
|
257 |
+
mime_type = 'image/png' if format_type == 'png' else 'application/pdf'
|
258 |
+
outputs[format_type] = f"data:{mime_type};base64,{data_uri}"
|
259 |
+
|
260 |
+
plt.close(fig)
|
261 |
+
|
262 |
+
return outputs
|
263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
264 |
|
265 |
def display_pdf(base64_pdf):
|
266 |
"""Generates the HTML to embed a PDF in Streamlit."""
|
267 |
+
pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
|
268 |
+
return pdf_display
|
269 |
|
270 |
# --- Streamlit App ---
|
271 |
+
st.set_page_config(page_title="LED Screen Schedule Printer", layout="wide")
|
272 |
+
st.title("LED Screen Schedule Printer")
|
273 |
|
274 |
+
uploaded_file = st.file_uploader("Select the '放映时间核对表.xls' file", accept_multiple_files=False, type=["xls", "xlsx"])
|
275 |
|
276 |
if uploaded_file:
|
277 |
with st.spinner("Processing file, please wait..."):
|
278 |
schedule, date_str = process_schedule(uploaded_file)
|
279 |
if schedule is not None and not schedule.empty:
|
280 |
output = create_print_layout(schedule, date_str)
|
281 |
+
|
282 |
+
tab1, tab2 = st.tabs(["PDF Preview", "PNG Preview"])
|
283 |
+
|
284 |
+
with tab1:
|
285 |
+
st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True)
|
286 |
+
|
287 |
+
with tab2:
|
288 |
+
st.image(output['png'], use_container_width=True)
|
289 |
else:
|
290 |
+
st.error("Could not process the file. Please check if the file format and content are correct.")
|