Ethscriptions commited on
Commit
928edc3
·
verified ·
1 Parent(s): 7c5a0e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -89
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 specific font file, falling back to a default if not found."""
15
  font_path = "simHei.ttc"
16
  if not os.path.exists(font_path):
17
- font_path = "SimHei.ttf" # Fallback font
18
  return font_manager.FontProperties(fname=font_path, size=size)
19
 
20
  def get_pinyin_abbr(text):
21
- """Generates a two-letter pinyin abbreviation from 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
- # Attempt to read the date from the Excel file
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()
@@ -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 _, 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
- elif row['Movie'] == current['Movie']:
74
- current['EndTime_dt'] = row['EndTime_dt']
75
  else:
76
- merged_rows.append(current)
77
- current = row.copy()
 
 
 
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 Exception as e:
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 processed schedule data."""
97
  if data is None or data.empty:
98
  return None
99
 
100
- # --- Figure Setup 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()
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
- """Helper function to draw the schedule on a given matplotlib figure axis."""
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
- ax.text(0.01, 0.99, date_str, fontsize=12, color='#A9A9A9',
132
- ha='left', va='top', fontproperties=date_font, transform=ax.transAxes)
 
 
 
 
 
133
 
134
- y_position = 0.98
 
 
 
 
 
 
 
 
 
 
135
 
136
  for i, hall in enumerate(halls):
137
  hall_data = data[data['Hall'] == hall]
138
- hall_num_text = f"${hall.replace('', '')}^{{\\#}}$" # Format hall number with #
139
-
140
  movie_count = 1
 
141
  for _, row in hall_data.iterrows():
142
- # --- Content Layout and Alignment ---
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, hall_num_text,
146
- fontsize=font_size_pt, fontweight='bold', ha='left', va='top',
147
- fontproperties=hall_font, transform=ax.transAxes)
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
- # Movie Name (Right-aligned)
159
- ax.text(x_movie_name_end, y_position, row['Movie'],
160
- fontsize=font_size_pt, ha='right', va='top',
161
- fontproperties=movie_font, transform=ax.transAxes)
 
162
 
163
- # Sequence Number (Left-aligned)
164
- ax.text(x_seq_no_start, y_position, f"{movie_count}.",
165
- fontsize=font_size_pt, ha='left', va='top',
166
- fontproperties=movie_font, transform=ax.transAxes)
167
 
168
- # Pinyin Abbreviation (Left-aligned)
169
- ax.text(x_pinyin_start, y_position, pinyin_abbr,
170
- fontsize=font_size_pt, ha='left', va='top',
171
- fontproperties=movie_font, transform=ax.transAxes)
172
-
173
- # Time (Left-aligned)
174
- ax.text(x_time_start, y_position, time_str,
175
- fontsize=font_size_pt, ha='left', va='top',
176
- fontproperties=movie_font, transform=ax.transAxes)
177
 
178
- y_position -= line_height
179
  movie_count += 1
180
 
181
- # --- Hall Separator Line ---
182
- if i < num_separators:
183
- # Draw a black line to separate halls
184
- ax.axhline(y=y_position + (line_height / 2), xmin=0.02, xmax=0.98,
185
- color='black', linewidth=0.8, transform=ax.transAxes)
186
- y_position -= line_height # Add space for the separator line
187
 
188
- # Generate both PNG and PDF outputs
189
  process_figure(png_fig, png_ax)
190
- process_figure(pdf_fig, pdf_ax)
191
-
192
- # Save PNG to a memory buffer
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 a memory buffer
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
- """Embeds the PDF in the Streamlit app for display."""
214
- pdf_display = f'<iframe src="{base64_pdf}" width="100%" height="800" type="application/pdf"></iframe>'
 
 
215
  return pdf_display
216
 
217
- # --- Streamlit App Main Interface ---
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