-
Notifications
You must be signed in to change notification settings - Fork 20
/
yj_to_folder.py
229 lines (175 loc) · 8.4 KB
/
yj_to_folder.py
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
import copy
import io
import os
from PIL import Image
from third_party.kfxlib.ion import IonAnnotation, IonList, IonSExp, IonString, IonStruct, IonSymbol, ion_type
from third_party.kfxlib.yj_book import YJ_Book
from third_party.kfxlib.yj_to_epub import FRAGMENT_NAME_SYMBOL, RETAIN_USED_FRAGMENTS
JPEG_QUALITY = 97
class KFX_CBZ(YJ_Book):
def __init__(self, file, ignore_hdv=False, hdv_png=True):
super().__init__(file)
self.book_symbols = set()
self.used_fragments = {}
self.processed_images = {}
self.ignore_hdv = ignore_hdv
self.hdv_png = hdv_png
self.decode_book()
def get_fragment(self, ftype=None, fid=None, delete=True):
if ion_type(fid) not in [IonString, IonSymbol]:
return fid
if ftype in self.book_data:
fragment_container = self.book_data[ftype]
elif ftype == "$393" and "$394" in self.book_data:
fragment_container = self.book_data["$394"]
else:
fragment_container = {}
data = fragment_container.pop(fid, None) if delete else fragment_container.get(fid)
if data is None:
used_data = self.used_fragments.get((ftype, fid))
if used_data is not None:
if RETAIN_USED_FRAGMENTS:
data = used_data
else:
data = IonStruct()
else:
data = IonStruct()
else:
self.used_fragments[(ftype, fid)] = copy.deepcopy(data) if RETAIN_USED_FRAGMENTS else True
return data
def get_named_fragment(self, structure, ftype=None, delete=True, name_symbol=None):
return self.get_fragment(ftype=ftype, fid=structure.pop(name_symbol or FRAGMENT_NAME_SYMBOL[ftype]), delete=delete)
def get_fragment_name(self, fragment_data, ftype, delete=True):
return self.get_structure_name(fragment_data, FRAGMENT_NAME_SYMBOL[ftype], delete)
def get_structure_name(self, structure, name_key, delete=True):
return structure.pop(name_key, None) if delete else structure.get(name_key, None)
def replace_ion_data(self, f):
data_type = ion_type(f)
if data_type is IonAnnotation:
return self.replace_ion_data(f.value)
if data_type is IonList:
return [self.replace_ion_data(fc) for fc in f]
if data_type is IonSExp:
return IonSExp([self.replace_ion_data(fc) for fc in f])
if data_type is IonStruct:
newf = IonStruct()
for fk, fv in f.items():
newf[self.replace_ion_data(fk)] = self.replace_ion_data(fv)
return newf
if data_type is IonSymbol:
self.book_symbols.add(f)
return f
def organize_fragments_by_type(self, fragment_list):
font_count = 0
categorized_data = {}
last_container_id = None
for fragment in fragment_list:
id = fragment.fid
self.book_symbols.add(id)
if fragment.ftype == "$270":
id = last_container_id = IonSymbol("%s:%s" % (fragment.value.get("$161", ""), fragment.value.get("$409", "")))
elif fragment.ftype == "$593":
id = last_container_id
elif fragment.ftype == "$262":
id = IonSymbol("%s-font-%03d" % (id, font_count))
font_count += 1
elif fragment.ftype == "$387":
id = IonSymbol("%s:%s" % (id, fragment.value["$215"]))
dt = categorized_data.setdefault(fragment.ftype, {})
if id not in dt:
dt[id] = self.replace_ion_data(fragment.value)
for category, ids in categorized_data.items():
if len(ids) == 1:
id = list(ids)[0]
if id == category:
categorized_data[category] = categorized_data[category][id]
return categorized_data
def process_content_list(self, content, num=[0]):
if "$146" in content:
contents = content.pop("$146", [])
for _content in contents:
self.process_content(_content, num)
def process_content(self, content, num=[0]):
if ion_type(content) is IonSymbol:
self.process_content(self.get_fragment(ftype="$608", fid=content), num)
if "$165" in content:
resource = content
else:
if "$176" in content:
story = self.get_named_fragment(content, ftype="$259")
self.process_content_list(story, num)
self.process_content_list(content, num)
data_type = content.pop("$159", None)
if not data_type or (data_type != "$270" and data_type != "$271"):
return
if "$175" in content:
resource_name = content["$175"]
elif "$164" in content:
resource_name = self.get_fragment_name(content, "$164")
else:
return
resource = self.get_fragment(ftype="$164", fid=resource_name)
name = resource_name
if "$635" in resource and not self.ignore_hdv:
resource_name = resource.pop("$635", [])[0]
resource = self.get_fragment(ftype="$164", fid=resource_name)
if not resource:
return
filename = os.path.join(self.output_path, self.filename_prefix + str(num[0]).zfill(3))
fixed_height = resource.pop("$67", None)
fixed_width = resource.pop("$66", None)
resource_height = resource.pop("$423", None) or fixed_height
resource_width = resource.pop("$422", None) or fixed_width
if "$636" in resource and not self.ignore_hdv:
tile_height = resource.pop("$638")
tile_width = resource.pop("$637")
tile_padding = resource.pop("$797", 0)
full_image = Image.new("RGB", (resource_width, resource_height))
separate_tiles_size = tile_count = 0
col = resource.pop("$636")
for y, row in enumerate(col):
top_padding = 0 if y == 0 else tile_padding
for x, location in enumerate(row):
left_padding = 0 if x == 0 else tile_padding
tile_raw_media = self.book_data["$417"][location]
if tile_raw_media is not None:
tile_count += 1
separate_tiles_size += len(tile_raw_media)
tile = Image.open(io.BytesIO(tile_raw_media))
crop = (left_padding, top_padding, tile_width + left_padding, tile_height + top_padding)
tile = tile.crop(crop)
full_image.paste(tile, (x * tile_width, y * tile_height))
tile.close()
if self.hdv_png:
full_image.save(filename + ".png", "png", optimize=True)
else:
full_image.save(filename + ".jpg", "jpeg", quality=JPEG_QUALITY, subsampling=0, optimize=True)
self.processed_images[name] = "hdv"
else:
raw_media = self.book_data["$417"][resource["$165"]]
mime = resource.pop("$162", None)
extension = "." + mime.split("/")[1]
with open(filename + extension, "wb") as f:
f.write(raw_media)
self.processed_images[name] = "normal"
num[0] += 1
def extract_to_folder(self, output_path, filename_prefix=""):
self.output_path = output_path
self.filename_prefix = filename_prefix
self.book_data = self.organize_fragments_by_type(self.fragments)
reading_order = self.get_reading_orders()[0]
pages = reading_order["$170"]
# TODO: parallelize page extraction?
# should be possible since the pages are all independent, but the
# constant acesses to the book data are not thread safe
# this would either require a thread safe rewrite of the book structure
# or creating a copy of the book object for each thread
i = 1
total_pages = len(pages)
for page in pages:
print(f"Section {i}/{total_pages} . . . \r", end="")
section = self.get_fragment(ftype="$260", fid=page)
page_template = section.pop("$141")[0]
content = self.get_fragment(ftype="$259", fid=page_template.pop("$176"))
self.process_content(content)
i += 1