-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_chapters.py
More file actions
340 lines (275 loc) · 11.5 KB
/
Copy pathsplit_chapters.py
File metadata and controls
340 lines (275 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import os
import re
import sys
import shutil
import math
from pathlib import Path
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
print("Pillow is required. Install with: pip install Pillow")
sys.exit(1)
def get_sorted_images(folder):
exts = {'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif'}
files = [f for f in os.listdir(folder) if Path(f).suffix.lower() in exts]
files.sort(key=lambda x: Path(x).stem)
return files
def parse_chapter_pages(input_str):
pages = []
for part in input_str.split(','):
part = part.strip()
if '-' in part:
start, end = part.split('-', 1)
pages.extend(range(int(start.strip()), int(end.strip()) + 1))
else:
pages.append(int(part))
return sorted(set(pages))
def extract_number(filename):
stem = Path(filename).stem
digits = ''.join(c for c in stem if c.isdigit())
return int(digits) if digits else 0
def detect_volumes(source):
pattern = re.compile(r'^(volume|vol)\s*(\d+)', re.IGNORECASE)
volumes = []
for item in os.listdir(source):
full_path = source / item
if full_path.is_dir():
match = pattern.match(item)
if match:
num = int(match.group(2))
volumes.append((num, full_path))
volumes.sort(key=lambda x: x[0])
return [v[1] for v in volumes]
def create_preview_grid(images, labels, temp_path, volume_label=None):
thumbs = []
for img_path in images:
img = Image.open(img_path)
img.thumbnail((200, 280))
thumbs.append(img)
count = len(thumbs)
cols = math.ceil(math.sqrt(count))
rows = math.ceil(count / cols)
cell_w, cell_h = 220, 340
header_h = 40 if volume_label else 0
grid = Image.new('RGB', (cols * cell_w, rows * cell_h + header_h), (40, 40, 40))
draw = ImageDraw.Draw(grid)
try:
font = ImageFont.truetype("arial.ttf", 18)
title_font = ImageFont.truetype("arial.ttf", 22)
except OSError:
font = ImageFont.load_default()
title_font = font
if volume_label:
bbox = draw.textbbox((0, 0), volume_label, font=title_font)
tw = bbox[2] - bbox[0]
tx = (cols * cell_w - tw) // 2
draw.text((tx, 10), volume_label, fill=(255, 255, 255), font=title_font)
for i, (thumb, label) in enumerate(zip(thumbs, labels)):
r, c = divmod(i, cols)
x_offset = c * cell_w + (cell_w - thumb.width) // 2
y_offset = header_h + r * cell_h + 30
grid.paste(thumb, (x_offset, y_offset))
text = f"Ch.{label}"
bbox = draw.textbbox((0, 0), text, font=font)
tw = bbox[2] - bbox[0]
tx = c * cell_w + (cell_w - tw) // 2
ty = header_h + r * cell_h + 5
draw.text((tx, ty), text, fill=(255, 255, 255), font=font)
grid.save(temp_path)
return temp_path
def process_single_volume(volume_path, start_chapter, output_dir, volume_label=None):
all_images = get_sorted_images(volume_path)
if not all_images:
print(f" Error: No image files found in {volume_path.name}.")
return start_chapter
print(f"\n Found {len(all_images)} images.")
print(f" First file: {all_images[0]}")
print(f" Last file: {all_images[-1]}")
print()
toc_input = input(" Enter chapter starting pages from ToC (comma-separated): ")
toc_pages = parse_chapter_pages(toc_input)
first_filename = input(" Enter first chapter's first page filename (e.g. 005.png): ").strip()
first_chapter_num = start_chapter
offset = extract_number(first_filename) - toc_pages[0]
print(f"\n Calculated offset: {offset}")
chapters = []
for i, page in enumerate(toc_pages):
ch_num = first_chapter_num + i
start_file_num = page + offset
if i + 1 < len(toc_pages):
end_file_num = toc_pages[i + 1] + offset - 1
else:
end_file_num = extract_number(all_images[-1]) + offset
chapters.append((ch_num, start_file_num, end_file_num))
print("\n --- Chapter Preview ---")
cover_images = []
cover_labels = []
for ch_num, start_num, end_num in chapters:
matching = [f for f in all_images if extract_number(f) == start_num]
if matching:
cover_path = str(volume_path / matching[0])
cover_images.append(cover_path)
cover_labels.append(str(ch_num))
print(f" Ch.{ch_num}: {matching[0]} (files {start_num} - {end_num})")
else:
print(f" Ch.{ch_num}: WARNING - no file found for number {start_num}")
temp_preview = volume_path / "chapter_preview_TEMP.png"
create_preview_grid(cover_images, cover_labels, str(temp_preview), volume_label)
print(f"\n Preview saved to: {temp_preview}")
print(" Opening preview...")
if sys.platform == 'win32':
os.startfile(str(temp_preview))
elif sys.platform == 'darwin':
os.system(f'open "{temp_preview}"')
else:
os.system(f'xdg-open "{temp_preview}"')
confirm = input("\n Does the preview look correct? (y/n): ").strip().lower()
temp_preview.unlink(missing_ok=True)
if confirm != 'y':
print(" Skipped this volume.")
return start_chapter
rename_choice = input(" Rename files sequentially? (Y/n): ").strip().lower()
rename = rename_choice != 'n'
print("\n Copying files...")
for ch_num, start_num, end_num in chapters:
folder_name = f"{ch_num:03d}"
dest = output_dir / folder_name
dest.mkdir(exist_ok=True)
counter = 1
for f in all_images:
num = extract_number(f)
if start_num <= num <= end_num:
if rename:
new_name = f"{counter:03d}{Path(f).suffix}"
else:
new_name = f
shutil.copy2(str(volume_path / f), str(dest / new_name))
counter += 1
print(f" Ch.{ch_num}: {counter - 1} files -> {folder_name}/")
return first_chapter_num + len(toc_pages)
def main():
if len(sys.argv) < 2:
print("Usage: python split_chapters.py <manga_folder>")
sys.exit(1)
source = Path(sys.argv[1]).resolve()
if not source.is_dir():
print(f"Error: '{source}' is not a valid directory.")
sys.exit(1)
print("Mode: [1] Single volume [2] Batch (multiple volumes)")
mode = input("Select mode (1/2): ").strip()
if mode == '2':
volumes = detect_volumes(source)
if not volumes:
print("\nNo volume folders detected (Volume X / Vol X pattern).")
manual = input("Enter volume folder names separated by commas: ").strip()
if not manual:
print("No volumes specified. Exiting.")
sys.exit(1)
volumes = []
for name in manual.split(','):
name = name.strip()
vol_path = source / name
if vol_path.is_dir():
volumes.append(vol_path)
else:
print(f" Warning: '{name}' not found, skipping.")
if not volumes:
print("No valid volumes found. Exiting.")
sys.exit(1)
else:
print(f"\nDetected {len(volumes)} volumes:")
for i, v in enumerate(volumes, 1):
img_count = len(get_sorted_images(v))
print(f" {i}. {v.name} ({img_count} images)")
confirm = input("\nProceed with these volumes? (y/n): ").strip().lower()
if confirm != 'y':
print("Cancelled.")
sys.exit(0)
output_dir = source / "chapters"
output_dir.mkdir(exist_ok=True)
first_ch = int(input("\nEnter first chapter number (e.g. 1): "))
current_chapter = first_ch
for i, vol_path in enumerate(volumes, 1):
vol_label = f"Vol {i}"
print(f"\n{'='*50}")
print(f"Processing {vol_path.name} ({i}/{len(volumes)})")
print(f"{'='*50}")
current_chapter = process_single_volume(
vol_path, current_chapter, output_dir, vol_label
)
print(f"\n{'='*50}")
print(f"Batch processing complete!")
print(f"Output: {output_dir}")
print(f"{'='*50}")
else:
all_images = get_sorted_images(source)
if not all_images:
print("Error: No image files found in the folder.")
sys.exit(1)
print(f"\nFound {len(all_images)} images.")
print(f"First file: {all_images[0]}")
print(f"Last file: {all_images[-1]}")
print()
toc_input = input("Enter chapter starting pages from ToC (comma-separated): ")
toc_pages = parse_chapter_pages(toc_input)
first_filename = input("Enter first chapter's first page filename (e.g. 005.png): ").strip()
first_chapter_num = int(input("Enter first chapter number (e.g. 1): "))
offset = extract_number(first_filename) - toc_pages[0]
print(f"\nCalculated offset: {offset}")
chapters = []
for i, page in enumerate(toc_pages):
ch_num = first_chapter_num + i
start_file_num = page + offset
if i + 1 < len(toc_pages):
end_file_num = toc_pages[i + 1] + offset - 1
else:
end_file_num = extract_number(all_images[-1]) + offset
chapters.append((ch_num, start_file_num, end_file_num))
print("\n--- Chapter Preview ---")
cover_images = []
cover_labels = []
for ch_num, start_num, end_num in chapters:
matching = [f for f in all_images if extract_number(f) == start_num]
if matching:
cover_path = str(source / matching[0])
cover_images.append(cover_path)
cover_labels.append(str(ch_num))
print(f"Ch.{ch_num}: {matching[0]} (files {start_num} - {end_num})")
else:
print(f"Ch.{ch_num}: WARNING - no file found for number {start_num}")
temp_preview = source / "chapter_preview_TEMP.png"
create_preview_grid(cover_images, cover_labels, str(temp_preview))
print(f"\nPreview saved to: {temp_preview}")
print("Opening preview...")
if sys.platform == 'win32':
os.startfile(str(temp_preview))
elif sys.platform == 'darwin':
os.system(f'open "{temp_preview}"')
else:
os.system(f'xdg-open "{temp_preview}"')
confirm = input("\nDoes the preview look correct? (y/n): ").strip().lower()
temp_preview.unlink(missing_ok=True)
if confirm != 'y':
print("Cancelled. No files were copied.")
sys.exit(0)
rename_choice = input("Rename files sequentially? (Y/n): ").strip().lower()
rename = rename_choice != 'n'
print("\nCopying files...")
for ch_num, start_num, end_num in chapters:
folder_name = f"{ch_num:03d}"
dest = source / folder_name
dest.mkdir(exist_ok=True)
counter = 1
for f in all_images:
num = extract_number(f)
if start_num <= num <= end_num:
if rename:
new_name = f"{counter:03d}{Path(f).suffix}"
else:
new_name = f
shutil.copy2(str(source / f), str(dest / new_name))
counter += 1
print(f" Ch.{ch_num}: {counter - 1} files -> {folder_name}/")
print("\nDone!")
if __name__ == "__main__":
main()