Ethscriptions commited on
Commit
5366108
·
verified ·
1 Parent(s): 90c1aa2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -73
app.py CHANGED
@@ -7,39 +7,43 @@ import base64
7
  import os
8
  from datetime import datetime, timedelta
9
  import math
 
10
  from pypinyin import lazy_pinyin, Style
11
  from matplotlib.backends.backend_pdf import PdfPages
12
 
13
  def get_font(size=14):
14
- """Finds an available SimHei font for Chinese character support."""
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 movie schedule data."""
36
  try:
37
- # Try to read the date from the specified 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()
45
 
@@ -49,19 +53,15 @@ def process_schedule(file):
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
- # Convert times to datetime objects
54
  df['StartTime_dt'] = pd.to_datetime(df['StartTime'], format='%H:%M', errors='coerce').apply(
55
  lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
56
  )
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
- # Handle overnight screenings
61
  df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
62
  df = df.sort_values(['Hall', 'StartTime_dt'])
63
 
64
- # Merge consecutive screenings of the same movie
65
  merged_rows = []
66
  for hall, group in df.groupby('Hall'):
67
  group = group.sort_values('StartTime_dt')
@@ -80,7 +80,7 @@ def process_schedule(file):
80
 
81
  merged_df = pd.DataFrame(merged_rows)
82
 
83
- # Adjust start and end times
84
  merged_df['StartTime_dt'] = merged_df['StartTime_dt'] - timedelta(minutes=10)
85
  merged_df['EndTime_dt'] = merged_df['EndTime_dt'] - timedelta(minutes=5)
86
 
@@ -89,15 +89,15 @@ def process_schedule(file):
89
 
90
  return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
91
  except Exception as e:
92
- st.error(f"An error occurred during data processing: {e}")
93
  return None, date_str
94
 
95
  def create_print_layout(data, date_str):
96
- """Creates PNG and PDF layouts of the schedule, replacing boxes with separator lines."""
97
  if data is None or data.empty:
98
  return None
99
 
100
- # --- Create figures for PNG and PDF ---
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()
@@ -108,81 +108,90 @@ def create_print_layout(data, date_str):
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
- # --- Font and Layout Setup ---
113
- date_font = get_font(12)
114
- # Increased font size to better fill the page
115
- font_size_multiplier = 1.3
116
- movie_font_size = 14 * font_size_multiplier
117
- hall_font_size = movie_font_size * 0.8
118
- hall_font = get_font(hall_font_size)
119
- movie_font = get_font(movie_font_size)
120
 
121
- ax.text(0.00, 1.00, date_str, fontsize=12 * font_size_multiplier, color='#A9A9A9',
122
- ha='left', va='top', fontproperties=date_font, transform=ax.transAxes, zorder=2)
 
123
 
124
- halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号','')) if h else 0)
 
 
 
125
 
126
- # --- Dynamic Layout Calculation ---
127
- num_movie_lines = len(data)
128
- num_gaps = len(halls) - 1
129
- total_lines = num_movie_lines + num_gaps if num_gaps > 0 else num_movie_lines
 
130
 
131
- available_height = 0.95 # Use 95% of vertical space
132
- y_start = 0.98
133
- line_height = available_height / total_lines if total_lines > 0 else 0.04
134
- y_position = y_start
135
 
136
- # --- Drawing Loop ---
 
 
 
 
 
 
 
137
  for i, hall in enumerate(halls):
138
  hall_data = data[data['Hall'] == hall]
139
- hall_num = hall.replace("号", "")
140
- hall_text = f"${hall_num}^{{\\#}}$"
141
 
142
- for movie_idx, (_, row) in enumerate(hall_data.iterrows()):
143
- # Print hall number (only for the first movie in the block)
144
- if movie_idx == 0:
 
 
145
  ax.text(0.03, y_position, hall_text,
146
  fontsize=hall_font_size, fontweight='bold',
147
  ha='left', va='top', fontproperties=hall_font,
148
  transform=ax.transAxes, zorder=2)
149
-
 
150
  pinyin_abbr = get_pinyin_abbr(row['Movie'])
151
-
152
- # Print movie name
153
- ax.text(0.20, y_position, f"{movie_idx + 1}. {pinyin_abbr} {row['Movie']}",
154
  fontsize=movie_font_size, ha='left', va='top', fontproperties=movie_font,
155
- transform=ax.transAxes, zorder=2, clip_on=True,
156
- bbox=dict(boxstyle="square,pad=0.0", fc="none", ec="none", alpha=0))
157
-
158
- # Print time information
159
  ax.text(0.95, y_position, f"{row['StartTime_str']} - {row['EndTime_str']}",
160
  fontsize=movie_font_size, ha='right', va='top', fontproperties=movie_font,
161
  transform=ax.transAxes, zorder=2)
162
 
163
- y_position -= line_height
 
164
 
165
- # After a hall's movies, add a black separator line
166
- if i < len(halls) - 1:
167
- # The line is drawn in the middle of the allocated gap space
168
- line_y = y_position + (line_height / 2)
169
- ax.plot([0.03, 0.97], [line_y, line_y], color='black', linewidth=1, transform=ax.transAxes, zorder=1)
170
 
171
- # Move position down to account for the gap
172
- y_position -= line_height
173
 
174
- # --- Process and Save Figures ---
175
  process_figure(png_fig, png_ax)
176
- process_figure(pdf_fig, pdf_ax)
177
 
178
- # Save PNG to buffer
179
  png_buffer = io.BytesIO()
180
  png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.05)
181
  png_buffer.seek(0)
182
  image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
183
  plt.close(png_fig)
184
 
185
- # Save PDF to buffer
186
  pdf_buffer = io.BytesIO()
187
  with PdfPages(pdf_buffer) as pdf:
188
  pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
@@ -196,30 +205,45 @@ def create_print_layout(data, date_str):
196
  }
197
 
198
  def display_pdf(base64_pdf):
199
- """Embeds the PDF in an iframe for display in Streamlit."""
200
- pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
 
 
201
  return pdf_display
202
 
203
- # --- Streamlit App UI ---
204
- st.set_page_config(page_title="LED Screen Schedule Print", layout="wide")
205
- st.title("LED Screen Schedule Print")
206
 
207
- uploaded_file = st.file_uploader("Select 'Screening Time Checklist.xls' file", type=["xls"])
208
 
209
  if uploaded_file:
210
- with st.spinner("Processing file, please wait..."):
211
  schedule, date_str = process_schedule(uploaded_file)
212
  if schedule is not None and not schedule.empty:
213
  output = create_print_layout(schedule, date_str)
214
 
215
- # Create tabs for PDF and PNG previews
216
- tab1, tab2 = st.tabs(["PDF Preview", "PNG Preview"])
 
 
217
 
218
  with tab1:
219
  st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True)
 
 
 
 
 
 
220
 
221
  with tab2:
222
  st.image(output['png'], use_container_width=True)
 
 
 
 
 
 
223
  else:
224
- st.error("Could not process the file. Please check if the file format or content is correct.")
225
-
 
7
  import os
8
  from datetime import datetime, timedelta
9
  import math
10
+ from matplotlib.patches import FancyBboxPatch
11
  from pypinyin import lazy_pinyin, Style
12
  from matplotlib.backends.backend_pdf import PdfPages
13
 
14
  def get_font(size=14):
15
+ """Loads the SimHei font for Chinese character support."""
16
  font_path = "simHei.ttc"
17
  if not os.path.exists(font_path):
18
+ # Fallback for different OS or font naming
19
  font_path = "SimHei.ttf"
20
+ if not os.path.exists(font_path):
21
+ # If font is still not found, return None and let matplotlib use its default
22
+ st.warning(f"Font file not found at {font_path}. Chinese characters may not display correctly.")
23
+ return None
24
  return font_manager.FontProperties(fname=font_path, size=size)
25
 
26
  def get_pinyin_abbr(text):
27
+ """获取文本前两个汉字的拼音首字母"""
28
  if not text:
29
  return ""
30
+ # 提取前两个汉字
31
  chars = [c for c in text if '\u4e00' <= c <= '\u9fff']
32
  if len(chars) < 2:
33
  chars = chars + [''] * (2 - len(chars))
34
  else:
35
  chars = chars[:2]
36
+ # 获取拼音首字母
37
  pinyin_list = lazy_pinyin(chars, style=Style.FIRST_LETTER)
38
  return ''.join(pinyin_list).upper()
39
 
40
  def process_schedule(file):
41
+ """Processes the uploaded Excel file to extract and clean schedule data."""
42
  try:
 
43
  date_df = pd.read_excel(file, header=None, skiprows=7, nrows=1, usecols=[3])
44
  date_str = pd.to_datetime(date_df.iloc[0, 0]).strftime('%Y-%m-%d')
45
  base_date = pd.to_datetime(date_str).date()
46
+ except Exception:
 
47
  date_str = datetime.today().strftime('%Y-%m-%d')
48
  base_date = datetime.today().date()
49
 
 
53
  df['Hall'] = df['Hall'].ffill()
54
  df.dropna(subset=['StartTime', 'EndTime', 'Movie'], inplace=True)
55
  df['Hall'] = df['Hall'].astype(str).str.extract(r'(\d+号)')
 
 
56
  df['StartTime_dt'] = pd.to_datetime(df['StartTime'], format='%H:%M', errors='coerce').apply(
57
  lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
58
  )
59
  df['EndTime_dt'] = pd.to_datetime(df['EndTime'], format='%H:%M', errors='coerce').apply(
60
  lambda t: t.replace(year=base_date.year, month=base_date.month, day=base_date.day) if pd.notnull(t) else t
61
  )
 
62
  df.loc[df['EndTime_dt'] < df['StartTime_dt'], 'EndTime_dt'] += timedelta(days=1)
63
  df = df.sort_values(['Hall', 'StartTime_dt'])
64
 
 
65
  merged_rows = []
66
  for hall, group in df.groupby('Hall'):
67
  group = group.sort_values('StartTime_dt')
 
80
 
81
  merged_df = pd.DataFrame(merged_rows)
82
 
83
+ # 将开始时间统一提前10分钟,结束时间统一提前5分钟
84
  merged_df['StartTime_dt'] = merged_df['StartTime_dt'] - timedelta(minutes=10)
85
  merged_df['EndTime_dt'] = merged_df['EndTime_dt'] - timedelta(minutes=5)
86
 
 
89
 
90
  return merged_df[['Hall', 'Movie', 'StartTime_str', 'EndTime_str']], date_str
91
  except Exception as e:
92
+ st.error(f"Error processing schedule data: {e}")
93
  return None, date_str
94
 
95
  def create_print_layout(data, date_str):
96
+ """Generates the print-friendly PDF and PNG layouts from the schedule data."""
97
  if data is None or data.empty:
98
  return None
99
 
100
+ # Create figures for PNG and PDF output with A4 dimensions
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()
 
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, is_pdf=False):
112
+ """The core drawing function to render the schedule onto a matplotlib axis."""
113
+ ax.set_ylim(0, 1) # Use a 0-1 coordinate system for consistent positioning
114
+
115
+ # Sort halls numerically
116
+ halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号', '')) if h and h.replace('号', '').isdigit() else 0)
117
+ num_halls = len(halls)
118
+ num_movie_rows = len(data)
 
119
 
120
+ # 1. Calculate total vertical slots required to fill the page
121
+ num_separators = num_halls - 1 if num_halls > 1 else 0
122
+ total_slots = num_movie_rows + num_separators + 2 # movies + separators + top/bottom padding
123
 
124
+ if total_slots == 0: return
125
+
126
+ # 2. Calculate the height of each slot
127
+ slot_height = 1.0 / total_slots
128
 
129
+ # 3. Calculate font size to be 90% of the slot height
130
+ figure_height_inches = 11.69
131
+ font_size_points = (slot_height * figure_height_inches) * 0.9 * 72 # (height in inches) * 90% * 72 points/inch
132
+ movie_font_size = font_size_points
133
+ hall_font_size = movie_font_size * 0.8
134
 
135
+ date_font = get_font(12)
136
+ hall_font = get_font(hall_font_size)
137
+ movie_font = get_font(movie_font_size)
 
138
 
139
+ # Draw the date at the top
140
+ ax.text(0.00, 1.00, date_str, fontsize=12, color='#A9A9A9',
141
+ ha='left', va='top', fontproperties=date_font, transform=ax.transAxes, zorder=3)
142
+
143
+ # 4. Initialize Y position, starting below the top padding slot
144
+ y_position = 1.0 - slot_height
145
+
146
+ # 5. Loop through each hall and its movies to draw the schedule
147
  for i, hall in enumerate(halls):
148
  hall_data = data[data['Hall'] == hall]
149
+ movie_count = 1
 
150
 
151
+ for _, row in hall_data.iterrows():
152
+ # Draw Hall Number (only for the first movie of the hall)
153
+ if movie_count == 1:
154
+ hall_num = hall.replace("号", "")
155
+ hall_text = f"${hall_num}^{{\\#}}$" # Use LaTeX for superscript '#'
156
  ax.text(0.03, y_position, hall_text,
157
  fontsize=hall_font_size, fontweight='bold',
158
  ha='left', va='top', fontproperties=hall_font,
159
  transform=ax.transAxes, zorder=2)
160
+
161
+ # Draw Pinyin Abbreviation and Movie Title
162
  pinyin_abbr = get_pinyin_abbr(row['Movie'])
163
+ ax.text(0.20, y_position, f"{movie_count}. {pinyin_abbr} {row['Movie']}",
 
 
164
  fontsize=movie_font_size, ha='left', va='top', fontproperties=movie_font,
165
+ transform=ax.transAxes, zorder=2, clip_on=True)
166
+
167
+ # Draw Time Information
 
168
  ax.text(0.95, y_position, f"{row['StartTime_str']} - {row['EndTime_str']}",
169
  fontsize=movie_font_size, ha='right', va='top', fontproperties=movie_font,
170
  transform=ax.transAxes, zorder=2)
171
 
172
+ y_position -= slot_height # Move down for the next movie
173
+ movie_count += 1
174
 
175
+ # After a hall's schedule, draw a separator line (if not the last hall)
176
+ if i < num_halls - 1:
177
+ # The line is drawn in the middle of the dedicated separator slot
178
+ line_y = y_position - (slot_height / 2)
179
+ ax.plot([0.03, 0.97], [line_y, line_y], color='black', linewidth=0.8, transform=ax.transAxes, zorder=1)
180
 
181
+ y_position -= slot_height # Move down past the separator slot
 
182
 
183
+ # Process and render the layout for both figure objects
184
  process_figure(png_fig, png_ax)
185
+ process_figure(pdf_fig, pdf_ax, is_pdf=True)
186
 
187
+ # Save PNG to a buffer
188
  png_buffer = io.BytesIO()
189
  png_fig.savefig(png_buffer, format='png', bbox_inches='tight', pad_inches=0.05)
190
  png_buffer.seek(0)
191
  image_base64 = base64.b64encode(png_buffer.getvalue()).decode()
192
  plt.close(png_fig)
193
 
194
+ # Save PDF to a buffer
195
  pdf_buffer = io.BytesIO()
196
  with PdfPages(pdf_buffer) as pdf:
197
  pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
 
205
  }
206
 
207
  def display_pdf(base64_pdf):
208
+ """Generates the HTML to embed and display a PDF in Streamlit."""
209
+ pdf_display = f"""
210
+ <iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>
211
+ """
212
  return pdf_display
213
 
214
+ # --- Streamlit App Main ---
215
+ st.set_page_config(page_title="LED 屏幕时间表打印", layout="wide")
216
+ st.title("LED 屏幕时间表打印")
217
 
218
+ uploaded_file = st.file_uploader("选择打开【放映时间核对表.xls】文件", accept_multiple_files=False, type=["xls", "xlsx"])
219
 
220
  if uploaded_file:
221
+ with st.spinner("文件正在处理中,请稍候..."):
222
  schedule, date_str = process_schedule(uploaded_file)
223
  if schedule is not None and not schedule.empty:
224
  output = create_print_layout(schedule, date_str)
225
 
226
+ st.success("处理完成!请在下方预览和下载。")
227
+
228
+ # Create tabs to switch between PDF and PNG views
229
+ tab1, tab2 = st.tabs(["PDF 预览 (推荐打印)", "PNG 预览"])
230
 
231
  with tab1:
232
  st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True)
233
+ st.download_button(
234
+ label="下载 PDF 文件",
235
+ data=base64.b64decode(output['pdf'].split(',')[1]),
236
+ file_name=f"Schedule_{date_str}.pdf",
237
+ mime="application/pdf"
238
+ )
239
 
240
  with tab2:
241
  st.image(output['png'], use_container_width=True)
242
+ st.download_button(
243
+ label="下载 PNG 图像",
244
+ data=base64.b64decode(output['png'].split(',')[1]),
245
+ file_name=f"Schedule_{date_str}.png",
246
+ mime="image/png"
247
+ )
248
  else:
249
+ st.error("无法处理文件,或文件中没有找到有效排期。请检查文件格式或内容是否正确。")