Skip to content

Commit a05faa2

Browse files
committed
Refactor chunk size validation and PDF splitting logic for clarity and error handling
1 parent f047bfc commit a05faa2

File tree

1 file changed

+19
-23
lines changed

1 file changed

+19
-23
lines changed

main.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ def parse_chunk_size(chunk_input):
7373
if chunk_size <= 0:
7474
raise ValueError("Chunk size must be a positive integer.")
7575
return chunk_size
76-
except ValueError:
77-
raise ValueError("Chunk size must be a positive integer.")
76+
except ValueError as e:
77+
raise ValueError("Chunk size must be a positive integer.") from e
7878

7979

8080
def check_overwrite_single_file(output_path, parsed_input=None):
@@ -157,40 +157,36 @@ def split_pdf(input_path, chunk_size, output_path):
157157
"""Split a PDF into multiple files with specified chunk size."""
158158
doc = fitz.open(input_path)
159159
total_pages = len(doc)
160-
160+
161161
if chunk_size <= 0:
162162
doc.close()
163163
raise ValueError("Chunk size must be a positive integer.")
164-
164+
165165
# Determine output naming
166166
output_file = Path(output_path)
167167
base_name = output_file.stem
168168
output_dir = output_file.parent
169-
169+
170170
created_files = []
171-
chunk_num = 1
172-
173-
for start_page in range(0, total_pages, chunk_size):
171+
for chunk_num, start_page in enumerate(range(0, total_pages, chunk_size), start=1):
174172
end_page = min(start_page + chunk_size, total_pages)
175-
173+
176174
# Create new document for this chunk
177175
new_doc = fitz.open()
178176
new_doc.insert_pdf(doc, from_page=start_page, to_page=end_page - 1)
179-
177+
180178
# Generate output filename
181179
output_filename = output_dir / f"{base_name}_part{chunk_num}.pdf"
182180
new_doc.save(str(output_filename))
183181
new_doc.close()
184-
182+
185183
created_files.append(str(output_filename))
186-
chunk_num += 1
187-
188184
doc.close()
189-
185+
190186
num_chunks = len(created_files)
191187
message = f"Successfully split PDF into {num_chunks} file{'s' if num_chunks > 1 else ''}"
192188
message += f"\n\nCreated {num_chunks} PDF{'s' if num_chunks > 1 else ''} in:\n{output_dir}"
193-
189+
194190
return message
195191

196192

@@ -478,7 +474,7 @@ def _create_output_section(self):
478474

479475
def _update_label(self, label, text, active=False):
480476
"""Update a label with truncated text and appropriate styling."""
481-
display_text = text if len(text) < 80 else "..." + text[-77:]
477+
display_text = text if len(text) < 80 else f"...{text[-77:]}"
482478
label.setText(display_text)
483479
color = "#ffffff" if active else "#888888"
484480
label.setStyleSheet(f"color: {color}; padding: 5px;")
@@ -549,30 +545,30 @@ def process_pdf(self):
549545
input_type = self.current_mode.section_title.lower()
550546
QMessageBox.warning(self, "Error", f"Please enter {input_type}.")
551547
return
552-
548+
553549
self.status_label.setText("Processing...")
554550
self.status_label.setStyleSheet("color: #aaaaaa;")
555551
QApplication.processEvents()
556-
552+
557553
try:
558554
# Validate output path
559555
self._ensure_output_path()
560-
556+
561557
# Parse/validate input using mode-specific parser
562558
try:
563559
parsed_input = self.current_mode.parse_input_func(page_input)
564560
except (ValueError, AttributeError) as e:
565-
raise ValueError(f"Invalid input:\n{str(e)}")
566-
561+
raise ValueError(f"Invalid input:\n{str(e)}") from e
562+
567563
# Check for file overwrites using mode-specific checker
568564
if self.current_mode.check_overwrite_func(self.output_path, parsed_input):
569565
if not self._confirm_overwrite():
570566
return
571-
567+
572568
# Execute the core PDF manipulation function
573569
message = self.current_mode.core_func(self.input_path, parsed_input, self.output_path)
574570
self._show_success(message)
575-
571+
576572
except Exception as e:
577573
self.status_label.setText("Failed")
578574
self.status_label.setStyleSheet("color: #f44336;")

0 commit comments

Comments
 (0)