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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -107
app.py CHANGED
@@ -6,64 +6,64 @@ import io
6
  import base64
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
 
50
  try:
 
51
  df = pd.read_excel(file, header=9, usecols=[1, 2, 4, 5])
52
  df.columns = ['Hall', 'StartTime', 'EndTime', 'Movie']
 
 
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')
68
  current = None
69
  for _, row in group.iterrows():
@@ -71,7 +71,7 @@ def process_schedule(file):
71
  current = row.copy()
72
  else:
73
  if row['Movie'] == current['Movie']:
74
- current['EndTime_dt'] = row['EndTime_dt']
75
  else:
76
  merged_rows.append(current)
77
  current = row.copy()
@@ -80,24 +80,24 @@ def process_schedule(file):
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
 
 
87
  merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
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 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,81 +108,79 @@ 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, 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()
@@ -193,7 +191,7 @@ def create_print_layout(data, date_str):
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)
198
  pdf_buffer.seek(0)
199
  pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
@@ -205,45 +203,28 @@ def create_print_layout(data, date_str):
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("无法处理文件,或文件中没有找到有效排期。请检查文件格式或内容是否正确。")
 
6
  import base64
7
  import os
8
  from datetime import datetime, timedelta
 
 
 
9
  from matplotlib.backends.backend_pdf import PdfPages
10
+ from pypinyin import lazy_pinyin, Style
11
 
12
  def get_font(size=14):
13
  """Loads the SimHei font for Chinese character support."""
14
+ # Prioritize 'simHei.ttc' if it exists, otherwise fall back to 'SimHei.ttf'
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
+ chars = chars[:2]
27
+ # Get the first letter of the pinyin for each character
 
 
 
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 movie schedule data."""
33
  try:
34
+ # Try to read the date from a specific cell
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 Exception:
39
+ # Fallback to the current date if reading fails
40
  date_str = datetime.today().strftime('%Y-%m-%d')
41
  base_date = datetime.today().date()
42
 
43
  try:
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
+ # Data cleaning
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 _, group in df.groupby('Hall'):
67
  group = group.sort_values('StartTime_dt')
68
  current = None
69
  for _, row in group.iterrows():
 
71
  current = row.copy()
72
  else:
73
  if row['Movie'] == current['Movie']:
74
+ current['EndTime_dt'] = row['EndTime_dt'] # Extend the end time
75
  else:
76
  merged_rows.append(current)
77
  current = row.copy()
 
80
 
81
  merged_df = pd.DataFrame(merged_rows)
82
 
83
+ # Adjust times: start 10 mins earlier, end 5 mins earlier
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
 
87
+ # Format times back to strings
88
  merged_df['StartTime_str'] = merged_df['StartTime_dt'].dt.strftime('%H:%M')
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 Exception:
 
93
  return None, date_str
94
 
95
  def create_print_layout(data, date_str):
96
+ """Generates the print layout as PNG and PDF files based on the schedule data."""
97
  if data is None or data.empty:
98
  return None
99
+
100
+ # Create figures for PNG and PDF output
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):
112
+ """A helper function to draw the schedule on a given matplotlib Axes object."""
113
+ halls = sorted(data['Hall'].unique(), key=lambda h: int(h.replace('号','')) if h else 0)
114
+
115
+ # --- Dynamic Row and Font Size Calculation ---
116
+ total_movie_lines = len(data)
117
+ if total_movie_lines == 0:
118
+ return
119
 
 
 
120
  num_halls = len(halls)
 
 
 
121
  num_separators = num_halls - 1 if num_halls > 1 else 0
 
 
 
122
 
123
+ # Total vertical slots include movies, separators, and padding
124
+ num_slots = total_movie_lines + num_separators + 2 # "+2" for top/bottom padding
125
+
126
+ ax_top = 0.98
127
+ ax_bottom = 0.02
128
+ ax_height_fraction = ax_top - ax_bottom
129
+ fig_height_inches = 11.69
130
+
131
+ # Calculate font size to be 90% of the calculated row height
132
+ slot_height_points = (fig_height_inches * ax_height_fraction * 72) / num_slots
133
+ font_size = slot_height_points * 0.9
134
 
135
+ content_font = get_font(font_size)
136
+ hall_font = get_font(font_size * 1.1) # Hall font is slightly larger
137
  date_font = get_font(12)
 
 
 
 
 
 
138
 
139
+ # --- Drawing Logic ---
140
+ ax.text(0.0, 1.0, date_str, color='#A9A9A9',
141
+ ha='left', va='top', fontproperties=date_font, transform=ax.transAxes)
142
+
143
+ line_height = ax_height_fraction / num_slots
144
+ y_position = ax_top - line_height # Start after top padding
145
 
 
146
  for i, hall in enumerate(halls):
147
  hall_data = data[data['Hall'] == hall]
148
+ hall_num = hall.replace("号", "")
149
+
150
+ # Use a flag to print the hall number only once per hall
151
+ is_first_movie_in_hall = True
152
  movie_count = 1
153
 
154
  for _, row in hall_data.iterrows():
155
+ # Display Hall Number once for the block, on the same line as the first movie
156
+ if is_first_movie_in_hall:
157
+ ax.text(0.03, y_position, f"${hall_num}^{{\\#}}$",
158
+ fontweight='bold', ha='left', va='top',
159
+ fontproperties=hall_font, transform=ax.transAxes, zorder=2)
160
+ is_first_movie_in_hall = False
161
+
162
+ # --- New Content Layout ---
163
+ # Left-aligned content: Seq. Number, Pinyin, Time
164
+ ax.text(0.12, y_position, f"{movie_count}.", fontproperties=content_font, ha='left', va='top', transform=ax.transAxes)
165
+ ax.text(0.18, y_position, get_pinyin_abbr(row['Movie']), fontproperties=content_font, ha='left', va='top', transform=ax.transAxes)
166
+ ax.text(0.28, y_position, f"{row['StartTime_str']} - {row['EndTime_str']}", fontproperties=content_font, ha='left', va='top', transform=ax.transAxes)
167
+
168
+ # Right-aligned content: Movie Name
169
+ ax.text(0.97, y_position, row['Movie'], fontproperties=content_font, ha='right', va='top', transform=ax.transAxes, clip_on=True)
 
 
 
 
170
 
171
+ y_position -= line_height
172
  movie_count += 1
173
 
174
+ # --- Separator Line ---
175
+ if i < num_separators:
176
+ # The line is drawn in the middle of the separator's allocated slot
177
+ line_y = y_position + (line_height / 2)
178
+ ax.axhline(y=line_y, color='black', linewidth=0.8, xmin=0.03, xmax=0.97)
179
+ y_position -= line_height # Move down past the separator slot
 
180
 
181
+ # Process both the PNG and PDF figures
182
  process_figure(png_fig, png_ax)
183
+ process_figure(pdf_fig, pdf_ax)
184
 
185
  # Save PNG to a buffer
186
  png_buffer = io.BytesIO()
 
191
 
192
  # Save PDF to a buffer
193
  pdf_buffer = io.BytesIO()
194
+ with PdfPages(pdf_buffer, 'w') as pdf:
195
  pdf.savefig(pdf_fig, bbox_inches='tight', pad_inches=0.05)
196
  pdf_buffer.seek(0)
197
  pdf_base64 = base64.b64encode(pdf_buffer.getvalue()).decode()
 
203
  }
204
 
205
  def display_pdf(base64_pdf):
206
+ """Embeds the PDF in the Streamlit app for display."""
207
+ return f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
 
 
 
208
 
209
+ # --- Streamlit App UI ---
210
  st.set_page_config(page_title="LED 屏幕时间表打印", layout="wide")
211
  st.title("LED 屏幕时间表打印")
212
 
213
+ uploaded_file = st.file_uploader("选择打开【放映时间核对表.xls】文件", type=["xls"])
214
 
215
  if uploaded_file:
216
  with st.spinner("文件正在处理中,请稍候..."):
217
  schedule, date_str = process_schedule(uploaded_file)
218
+ if schedule is not None:
219
  output = create_print_layout(schedule, date_str)
220
 
221
+ # Create tabs for PDF and PNG previews
222
+ tab1, tab2 = st.tabs(["PDF 预览", "PNG 预览"])
 
 
223
 
224
  with tab1:
225
  st.markdown(display_pdf(output['pdf']), unsafe_allow_html=True)
 
 
 
 
 
 
226
 
227
  with tab2:
228
  st.image(output['png'], use_container_width=True)
 
 
 
 
 
 
229
  else:
230
+ st.error("无法处理文件,请检查文件格式或内容是否正确。")