Advertisement
Guest User

fix_shueisha.py

a guest
Mar 13th, 2022
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. """
  2. usage:
  3.    $ python3 fix_shueisha.py [EPUB_FILE]...
  4.    $ ls | grep *.epub | python3 fix_shueisha.py
  5. """
  6. import sys
  7. from zipfile import ZipFile
  8. from io import BytesIO, TextIOWrapper
  9.  
  10.  
  11. def fix_container(input_buffer):
  12.     output_buffer = TextIOWrapper(BytesIO(), encoding="utf-8")
  13.     for line in TextIOWrapper(input_buffer, encoding="utf-8"):
  14.         if "advanced.opf" in line and not line.startswith("<!--"):
  15.             line = f"<!--{line[:-1]}-->{line[-1]}"
  16.         output_buffer.write(line)
  17.     output_buffer.seek(0)
  18.     return output_buffer
  19.  
  20.  
  21. def fix_opf(input_buffer):
  22.     output_buffer = TextIOWrapper(BytesIO(), encoding="utf-8")
  23.     for line in TextIOWrapper(input_buffer, encoding="utf-8"):
  24.         if "cover.jpg" in line and 'properties="cover-image"' not in line:
  25.             line = line.replace("href", 'properties="cover-image" href')
  26.         output_buffer.write(line)
  27.     output_buffer.seek(0)
  28.     return output_buffer
  29.  
  30.  
  31. def fix(epub_name):
  32.     filters = {
  33.         "META-INF/container.xml": fix_container,
  34.         "OPS/standard.opf": fix_opf,
  35.     }
  36.     archive = {}
  37.     with ZipFile(epub_name) as zipfile:
  38.         for info in zipfile.infolist():
  39.             if info.filename in filters:
  40.                 with zipfile.open(info) as f:
  41.                     archive[info.filename] = filters[info.filename](f)
  42.             else:
  43.                 with zipfile.open(info) as f:
  44.                     archive[info.filename] = TextIOWrapper(BytesIO(f.read()), encoding="utf-8")
  45.     with ZipFile(epub_name, "w") as zipfile:
  46.         for filename, io in archive.items():
  47.             with zipfile.open(filename, "w") as f:
  48.                 f.write(io.buffer.read())
  49.  
  50.  
  51. def main():
  52.     epub_list = sys.argv[1:] or sys.stdin
  53.     for epub in epub_list:
  54.         print(epub.strip(), end="...")
  55.         fix(epub.strip())
  56.         print("done")
  57.  
  58.  
  59. if __name__ == "__main__":
  60.     main()
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement