1
0
mirror of https://github.com/ciromattia/kcc synced 2026-04-25 10:28:58 +00:00

Compare commits

..

46 Commits
2.8 ... 2.10

Author SHA1 Message Date
Paweł Jastrzębski
b068d82ccf Made split filenames more idiot-proof 2013-05-28 13:57:11 +02:00
Paweł Jastrzębski
43ca5ac5b9 py2exe fix 2013-05-28 13:28:09 +02:00
Ciro Mattia Gonano
18c3ab2340 2.10 release 2013-05-28 12:56:59 +02:00
Ciro Mattia Gonano
87eaba184e Update README 2013-05-28 12:21:58 +02:00
Ciro Mattia Gonano
97b5d8a2ee Merge branch 'master' of github.com:ciromattia/kcc 2013-05-28 12:18:58 +02:00
Ciro Mattia Gonano
7c3a762107 Add "1" if sanitized filename already exists (fixes #50) 2013-05-28 12:17:08 +02:00
Paweł Jastrzębski
0b90af77da Disabled cropping and page number cutting for blank pages (close #43) 2013-05-28 12:07:45 +02:00
Paweł Jastrzębski
28dcab8ee8 Multiprocessing - final final touches + Code cleanup (close #39) 2013-05-28 11:24:37 +02:00
Paweł Jastrzębski
6c468a5291 dirImgProcess - multiprocessing 2013-05-28 08:47:24 +02:00
Paweł Jastrzębski
d090d8c2e8 Refactoring of dirImgProcess 2013-05-27 20:06:47 +02:00
Paweł Jastrzębski
aba315866e Small tweaks 2013-05-27 18:54:39 +02:00
Paweł Jastrzębski
e981aa4520 Added some comments 2013-05-27 18:46:54 +02:00
Paweł Jastrzębski
e603622021 Removed redundant --panelviewhorizontal 2013-05-27 18:26:53 +02:00
Paweł Jastrzębski
3e007965b2 Fixed panel order for horizontal pages when --rotate is enabled 2013-05-27 15:21:16 +02:00
Paweł Jastrzębski
c0610360a3 Updated README (I hate Markdown) 2013-05-27 09:21:09 +02:00
Paweł Jastrzębski
ff8f6e073f Updated README 2013-05-27 09:18:28 +02:00
Paweł Jastrzębski
aadb5407d2 Updated README 2013-05-27 09:00:01 +02:00
Paweł Jastrzębski
2e4d5eb958 Updated README 2013-05-27 08:54:51 +02:00
Ciro Mattia Gonano
33fb13a66e Merge branch 'master' of github.com:ciromattia/kcc 2013-05-20 18:23:03 +02:00
Ciro Mattia Gonano
4dc69aa1c4 Add default value for saveToDir() last param 2013-05-20 18:22:35 +02:00
Paweł Jastrzębski
b3681a3ceb Fixed merge 2013-05-16 11:49:49 +02:00
Ciro Mattia Gonano
348dcc4275 Merge pull request #49 from ciromattia/HorizontalPanelView
Horizontal Panel View
2013-05-16 01:20:31 -07:00
Ciro Mattia Gonano
39e69119ac Merge branch 'master' into HorizontalPanelView
Conflicts:
	kcc/comic2ebook.py
2013-05-16 10:19:48 +02:00
Paweł Jastrzębski
8c57926978 Disabling landscape mode as it is broken in this mode 2013-05-07 22:16:33 +02:00
Paweł Jastrzębski
8b1965054f Added --panelviewhorizontal option 2013-05-07 11:03:44 +02:00
Paweł Jastrzębski
18993069e3 Quantization must be disabled. 2013-04-30 12:57:32 +02:00
Ciro Mattia Gonano
7e6c8cc768 Update README 2013-04-30 10:29:40 +02:00
Ciro Mattia Gonano
3ae44d2fcb Merge pull request #47 from ciromattia/KindleFire
Kindle Fire support
2013-04-30 01:27:30 -07:00
Ciro Mattia Gonano
a6eb3936e4 Don't force upscale on Kindle Fire (let users choose if they want it) 2013-04-30 10:27:04 +02:00
Paweł Jastrzębski
bb24d3ca30 Preliminary support for horizontal Panel View. 2013-04-29 22:38:24 +02:00
Paweł Jastrzębski
7e191c0be5 Experimental support of Kindle Fire - Tweaks 2013-04-29 17:51:14 +02:00
Paweł Jastrzębski
d9ea165bbb Experimental support of Kindle Fire 2013-04-29 17:19:06 +02:00
Ciro Mattia Gonano
148211a5c7 Update for 2.9 release. 2013-04-19 12:14:24 +02:00
Ciro Mattia Gonano
23e07f47f0 Merge pull request #46 from ciromattia/slugify
Filenames slugification
2013-04-19 02:27:54 -07:00
Ciro Mattia Gonano
724156c554 Small fixes 2013-04-12 01:36:51 +02:00
Ciro Mattia Gonano
b972e4c746 Remove Windows silly 'thumbs.db' too 2013-04-11 12:33:14 +02:00
Ciro Mattia Gonano
f0afa1fff2 Convert dot char to hyphen.
Removes UNIX-hidden files and dirs from the final archive (prevents .DS_Store and stuff)
2013-04-11 12:18:02 +02:00
Ciro Mattia Gonano
a36c05f0c5 Merge from master 2013-04-11 12:00:51 +02:00
Ciro Mattia Gonano
4f3a66b4eb Update README.md 2013-04-11 12:59:01 +03:00
Ciro Mattia Gonano
6369c7ea44 Update after merging of #44 2013-04-11 12:54:16 +03:00
Ciro Mattia Gonano
f1b8aff8d4 Merge pull request #44 from devernay/master
Support more input image formats: GIF, TIFF, ...
2013-04-11 02:50:37 -07:00
Ciro Mattia Gonano
be270aa797 Add number padding and lowering for file names (not directory) 2013-04-11 11:49:29 +02:00
Ciro Mattia Gonano
f33d355024 Filenames slugifications (#28, #31, #9, #8) 2013-04-11 10:34:33 +02:00
Ciro Mattia Gonano
6f913b026e rarfile updated to 2.6 2013-04-11 09:34:20 +02:00
Ciro Mattia Gonano
220b4e0954 Add an option to generate a CBZ skipping all the EPUB/Mobi stuff.
Prevent output files to overwrite the source (add _kcc if duplicate is detected)
Fixes #45
2013-04-10 12:29:31 +02:00
Frédéric Devernay
bac4a4fd86 support more input image formats 2013-04-04 14:09:21 +02:00
9 changed files with 627 additions and 378 deletions

157
README.md
View File

@@ -1,4 +1,4 @@
# KCC # KCC
`KCC` (a.k.a. `KindleComicConverter`) is a Python app to convert comic files or folders to ePub or Panel View MOBI. `KCC` (a.k.a. `KindleComicConverter`) is a Python app to convert comic files or folders to ePub or Panel View MOBI.
It was initally developed for Kindle but since v2.2 it outputs valid ePub 2.0 so _**despite its name, KCC is It was initally developed for Kindle but since v2.2 it outputs valid ePub 2.0 so _**despite its name, KCC is
@@ -6,16 +6,27 @@ actually a comic 2 epub converter that every ereader owner can happily use**_.
It can also optionally optimize images by applying a number of transformations. It can also optionally optimize images by applying a number of transformations.
### A word of warning
**KCC** _is not_ [Amazon's Kindle Comic Creator](http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1001103761) nor is in any way endorsed by Amazon.
Amazon's tool is for comic _publishers_ and involves a lot of manual effort, while **KCC** is for comic _readers_.
If you want to read some comments over *Amazon's kc2* you can take a look at [this](http://www.mobileread.com/forums/showthread.php?t=207461&page=7#96) and [that](http://www.mobileread.com/forums/showthread.php?t=211047) threads on Mobileread.
_kc2_ in no way is a replacement for **KCC** so you can be quite confident we'll going to carry on developing our little monster ;)
## BINARY RELEASES ## BINARY RELEASES
You can find the latest released binary at the following links: You can find the latest released binary at the following links:
- OS X: [https://dl.dropbox.com/u/16806101/KindleComicConverter_osx_2.8.zip](https://dl.dropbox.com/u/16806101/KindleComicConverter_osx_2.8.zip) - OS X: [https://dl.dropbox.com/u/16806101/KindleComicConverter_osx_2.10.zip](https://dl.dropbox.com/u/16806101/KindleComicConverter_osx_2.10.zip)
- Win64: [https://dl.dropbox.com/u/16806101/KindleComicConverter_win-amd64_2.8.zip](https://dl.dropbox.com/u/16806101/KindleComicConverter_win-amd64_2.7.zip) - Win64: [https://dl.dropbox.com/u/16806101/KindleComicConverter_win-amd64_2.10.zip](https://dl.dropbox.com/u/16806101/KindleComicConverter_win-amd64_2.10.zip)
- Win32: [http://pawelj.vulturis.eu/Shared/KindleComicConverter_win-x86_2.8.zip](http://pawelj.vulturis.eu/Shared/KindleComicConverter_win-x86_2.8.zip) *(thanks to [AcidWeb](https://github.com/AcidWeb))* - Win32: [http://pawelj.vulturis.eu/Shared/KindleComicConverter_win-x86_2.10.zip](http://pawelj.vulturis.eu/Shared/KindleComicConverter_win-x86_2.10.zip)
- Linux: Just download sourcecode and launch `python kcc.py` *(Provided you have Python and Pillow installed)* - Linux: Just download sourcecode and launch `python kcc.py` *(Provided you have Python and Pillow installed)*
## AWKCC .NET GUI
![AWKCC](http://pawelj.vulturis.eu/Shared/CurrentAWKCC.png)
[All-in-one package for Windows users](http://www.mobileread.com/forums/showpost.php?p=2444957&postcount=3)
## INPUT FORMATS ## INPUT FORMATS
`kcc` can understand and convert, at the moment, the following file types: `kcc` can understand and convert, at the moment, the following file types:
- PNG, JPG - PNG, JPG, GIF, TIFF, BMP
- Folders - Folders
- CBZ, ZIP - CBZ, ZIP
- CBR, RAR *(With `unrar` executable)* - CBR, RAR *(With `unrar` executable)*
@@ -47,10 +58,11 @@ Options:
--version show program's version number and exit --version show program's version number and exit
-h, --help show this help message and exit -h, --help show this help message and exit
-p PROFILE, --profile=PROFILE -p PROFILE, --profile=PROFILE
Device profile (Choose one among K1, K2, K3, K4NT, K4T, KDX, KDXG or KHD) [Default=KHD] Device profile (Choose one among K1, K2, K3, K4NT, K4T, KDX, KDXG, KHD, KF, KFHD, KFHD8) [Default=KHD]
-t TITLE, --title=TITLE -t TITLE, --title=TITLE
Comic title [Default=filename] Comic title [Default=filename]
-m, --manga-style Manga style (Right-to-left reading and splitting) [Default=False] -m, --manga-style Manga style (Right-to-left reading and splitting) [Default=False]
-c, --cbz-output Outputs a CBZ archive and does not generate EPUB
--nopanelviewhq Disable high quality Panel View [Default=False] --nopanelviewhq Disable high quality Panel View [Default=False]
--noprocessing Do not apply image preprocessing (Page splitting and optimizations) [Default=True] --noprocessing Do not apply image preprocessing (Page splitting and optimizations) [Default=True]
--forcepng Create PNG files instead JPEG (For non-Kindle devices) [Default=False] --forcepng Create PNG files instead JPEG (For non-Kindle devices) [Default=False]
@@ -62,7 +74,7 @@ Options:
--nosplitrotate Disable splitting and rotation [Default=False] --nosplitrotate Disable splitting and rotation [Default=False]
--nocutpagenumbers Do not try to cut page numbering on images [Default=True] --nocutpagenumbers Do not try to cut page numbering on images [Default=True]
-o OUTPUT, --output=OUTPUT -o OUTPUT, --output=OUTPUT
Output generated EPUB to specified directory or file Output generated file (EPUB or CBZ) to specified directory or file
-v, --verbose Verbose output [Default=False] -v, --verbose Verbose output [Default=False]
``` ```
@@ -81,50 +93,95 @@ The app relies and includes the following scripts/binaries:
- `magic.py` from [python-magic](https://github.com/ahupp/python-magic) library - `magic.py` from [python-magic](https://github.com/ahupp/python-magic) library
## CHANGELOG ## CHANGELOG
- 1.00: Initial version ####1.00
- 1.10: Added support for CBZ/CBR files in comic2ebook.py * Initial version
- 1.11: Added support for CBZ/CBR files in KindleComicConverter
- 1.20: Comic optimizations! Split pages not target-oriented (landscape with portrait target or portrait ####1.10
with landscape target), add palette and other image optimizations from Mangle. * Added support for CBZ/CBR files in comic2ebook.py
WARNING: PIL is required for all image mangling!
- 1.30: Fixed an issue in OPF generation for device resolution ####1.11
Reworked options system (call with -h option to get the inline help) * Added support for CBZ/CBR files in KindleComicConverter
- 1.40: Added some options for controlling image optimization
Further optimization (ImageOps, page numbering cut, autocontrast) ####1.20
- 1.41: Fixed a serious bug on resizing when img ratio was bigger than device one * Comic optimizations! Split pages not target-oriented (landscape with portrait target or portrait with landscape target), add palette and other image optimizations from Mangle. WARNING: PIL is required for all image mangling!
- 1.50: Added subfolder support for multiple chapters.
- 2.0: GUI! AppleScript is gone and Tk is used to provide cross-platform GUI support. ####1.30
- 2.1: Added basic error reporting * Fixed an issue in OPF generation for device resolution
- 2.2: Added (valid!) ePub 2.0 output * Reworked options system (call with -h option to get the inline help)
Rename .zip files to .cbz to avoid overwriting
- 2.3: Fixed win32 ePub generation, folder handling, filenames with spaces and subfolders ####1.40
- 2.4: Use temporary directory as workdir (fixes converting from external volumes and zipfiles renaming) * Added some options for controlling image optimization
Fixed "add folders" from GUI. * Further optimization (ImageOps, page numbering cut, autocontrast)
- 2.5: Added --black-borders option to set added borders black when page's ratio is not the device's one (#11).
Fixes epub containing zipped itself (#10) ####1.41
- 2.6: Added --rotate option to rotate landscape images instead of splitting them (#16, #24) * Fixed a serious bug on resizing when img ratio was bigger than device one
Added --output option to customize ePub output dir/file (#22)
Add rendition:layout and rendition:orientation ePub meta tags (supported by new kindlegen 2.8) ####1.50
Fixed natural sorting for files (#18) * Added subfolder support for multiple chapters.
- 2.7: Lots of GUI improvements (#27, #13)
Added gamma support within --gamma option (defaults to profile-specified gamma) (#26, #27) ####2.0
Added --nodithering option to prevent dithering optimizations (#27) * GUI! AppleScript is gone and Tk is used to provide cross-platform GUI support.
Epub margins support (#30)
Fixed no file added if file has no spaces on Windows (#25) ####2.1
Gracefully exit if unrar missing (#15) * Added basic error reporting
Do not call kindlegen if source epub is bigger than 320MB (#17)
Get filetype from magic number (#14) #### 2.2:
PDF conversion works again * Added (valid!) ePub 2.0 output
- 2.8: updated rarfile library * Rename .zip files to .cbz to avoid overwriting
Panel View support + HQ support (#36) - new option: --nopanelviewhq
Split profiles for K4NT and K4T ####2.3
Rewrite of Landscape Mode support (huge readability improvement for KPW) * Fixed win32 ePub generation, folder handling, filenames with spaces and subfolders
Upscale use now BILINEAR method
Added generic CSS file ####2.4
Optimized archive extraction for zip/rar files (#40) * Use temporary directory as workdir (fixes converting from external volumes and zipfiles renaming)
* Fixed "add folders" from GUI.
####2.5
* Added --black-borders option to set added borders black when page's ratio is not the device's one (#11).
* Fixes epub containing zipped itself (#10)
####2.6
* Added --rotate option to rotate landscape images instead of splitting them (#16, #24)
* Added --output option to customize ePub output dir/file (#22)
* Add rendition:layout and rendition:orientation ePub meta tags (supported by new kindlegen 2.8)
* Fixed natural sorting for files (#18)
####2.7
* Lots of GUI improvements (#27, #13)
* Added gamma support within --gamma option (defaults to profile-specified gamma) (#26, #27)
* Added --nodithering option to prevent dithering optimizations (#27)
* Epub margins support (#30)
* Fixed no file added if file has no spaces on Windows (#25)
* Gracefully exit if unrar missing (#15)
* Do not call kindlegen if source epub is bigger than 320MB (#17)
* Get filetype from magic number (#14)
* PDF conversion works again
####2.8
* Updated rarfile library
* Panel View support + HQ support (#36) - new option: --nopanelviewhq
* Split profiles for K4NT and K4T
* Rewrite of Landscape Mode support (huge readability improvement for KPW)
* Upscale use now BILINEAR method
* Added generic CSS file
* Optimized archive extraction for zip/rar files (#40)
####2.9
* Added support for generating a plain CBZ (skipping all the EPUB/Mobi generation) (#45)
* Prevent output file overwriting the source one: if a duplicate name is detected, append _kcc to the name
* Rarfile library updated to 2.6
* Added GIF, TIFF and BMP to supported formats (#42)
* Filenames slugifications (#28, #31, #9, #8)
####2.10:
* Multiprocessing support
* Kindle Fire support (color ePub/Mobi)
* Panel View support for horizontal content
* Fixed panel order for horizontal pages when --rotate is enabled
* Disabled cropping and page number cutting for blank pages
* Fixed some slugify issues with specific file naming conventions (#50, #51)
## COPYRIGHT ## COPYRIGHT
Copyright (c) 2012-2013 Ciro Mattia Gonano with further contributions by Paweł Jastrzębski. Copyright (c) 2012-2013 Ciro Mattia Gonano and Paweł Jastrzębski.
KCC is released under ISC LICENSE; see LICENSE.txt for further details. KCC is released under ISC LICENSE; see LICENSE.txt for further details.

4
kcc.py
View File

@@ -16,7 +16,7 @@
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE. # PERFORMANCE OF THIS SOFTWARE.
# #
__version__ = '2.8' __version__ = '2.10'
__license__ = 'ISC' __license__ = 'ISC'
__copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>' __copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@@ -24,8 +24,10 @@ __docformat__ = 'restructuredtext en'
from Tkinter import * from Tkinter import *
from kcc import gui from kcc import gui
from sys import platform from sys import platform
from multiprocessing import freeze_support
import os import os
freeze_support()
root = Tk() root = Tk()
root.resizable(width=False, height=False) root.resizable(width=False, height=False)
root.config(padx=5, pady=5, takefocus=True) root.config(padx=5, pady=5, takefocus=True)

View File

@@ -1,4 +1,4 @@
__version__ = '2.0' __version__ = '2.10'
__license__ = 'ISC' __license__ = 'ISC'
__copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>' __copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
# #
# Copyright (c) 2012 Ciro Mattia Gonano <ciromattia@gmail.com> # Copyright (c) 2012 Ciro Mattia Gonano <ciromattia@gmail.com>
# #
@@ -16,7 +17,7 @@
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE. # PERFORMANCE OF THIS SOFTWARE.
# #
__version__ = '2.8' __version__ = '2.10'
__license__ = 'ISC' __license__ = 'ISC'
__copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>' __copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@@ -31,6 +32,7 @@ from shutil import copytree
from shutil import rmtree from shutil import rmtree
from shutil import make_archive from shutil import make_archive
from optparse import OptionParser from optparse import OptionParser
from multiprocessing import Pool, freeze_support
import image import image
import cbxarchive import cbxarchive
import pdfjpgextract import pdfjpgextract
@@ -39,6 +41,11 @@ import pdfjpgextract
def buildHTML(path, imgfile): def buildHTML(path, imgfile):
filename = getImageFileName(imgfile) filename = getImageFileName(imgfile)
if filename is not None: if filename is not None:
# All files marked with this sufix need horizontal Panel View.
if "_rotated" in str(filename):
rotate = True
else:
rotate = False
htmlpath = '' htmlpath = ''
postfix = '' postfix = ''
backref = 1 backref = 1
@@ -69,26 +76,49 @@ def buildHTML(path, imgfile):
imgfile, "\" class=\"singlePage\"/></div>\n" imgfile, "\" class=\"singlePage\"/></div>\n"
]) ])
if options.panelview: if options.panelview:
if options.righttoleft: if rotate:
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", if options.righttoleft:
"BoxTL-Panel-Parent\", \"ordinal\":2}'></a></div>\n", f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
"BoxTR-Panel-Parent\", \"ordinal\":1}'></a></div>\n", "<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":3}'></a></div>\n",
"BoxBL-Panel-Parent\", \"ordinal\":4}'></a></div>\n", "<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
"BoxBR-Panel-Parent\", \"ordinal\":3}'></a></div>\n" "<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
]) "'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":4}'></a></div>\n"
])
else:
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":4}'></a></div>\n",
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
"'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":3}'></a></div>\n"
])
else: else:
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", if options.righttoleft:
"BoxTL-Panel-Parent\", \"ordinal\":1}'></a></div>\n", f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
"BoxTR-Panel-Parent\", \"ordinal\":2}'></a></div>\n", "<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
"BoxBL-Panel-Parent\", \"ordinal\":3}'></a></div>\n", "<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"", "'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":4}'></a></div>\n",
"BoxBR-Panel-Parent\", \"ordinal\":4}'></a></div>\n" "<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
]) "'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":3}'></a></div>\n"
])
else:
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
"'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":3}'></a></div>\n",
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
"'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":4}'></a></div>\n"
])
f.writelines(["<div id=\"BoxTL-Panel-Parent\" class=\"target-mag-parent\"><div id=\"BoxTL-Panel\" class=\"", f.writelines(["<div id=\"BoxTL-Panel-Parent\" class=\"target-mag-parent\"><div id=\"BoxTL-Panel\" class=\"",
"target-mag\"><img src=\"", "../" * backref, "Images/", postfix, imgfile, "\" alt=\"", "target-mag\"><img src=\"", "../" * backref, "Images/", postfix, imgfile, "\" alt=\"",
imgfile, "\"/></div></div>\n", imgfile, "\"/></div></div>\n",
@@ -128,7 +158,7 @@ def buildNCX(dstdir, title, chapters):
f = open(ncxfile, "w") f = open(ncxfile, "w")
f.writelines(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", f.writelines(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
"<!DOCTYPE ncx PUBLIC \"-//NISO//DTD ncx 2005-1//EN\" ", "<!DOCTYPE ncx PUBLIC \"-//NISO//DTD ncx 2005-1//EN\" ",
"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd\">\n", "\"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd\">\n",
"<ncx version=\"2005-1\" xml:lang=\"en-US\" xmlns=\"http://www.daisy.org/z3986/2005/ncx/\">\n", "<ncx version=\"2005-1\" xml:lang=\"en-US\" xmlns=\"http://www.daisy.org/z3986/2005/ncx/\">\n",
"<head>\n", "<head>\n",
"<meta name=\"dtb:uid\" content=\"015ffaec-9340-42f8-b163-a0c5ab7d0611\"/>\n", "<meta name=\"dtb:uid\" content=\"015ffaec-9340-42f8-b163-a0c5ab7d0611\"/>\n",
@@ -226,7 +256,7 @@ def buildOPF(profile, dstdir, title, filelist, cover=None):
f.write("</manifest>\n<spine toc=\"ncx\">\n") f.write("</manifest>\n<spine toc=\"ncx\">\n")
splitCountUsed = 1 splitCountUsed = 1
for entry in reflist: for entry in reflist:
if entry.endswith("-1"): if entry.endswith("-kcca"):
# noinspection PyRedundantParentheses # noinspection PyRedundantParentheses
if ((options.righttoleft and facing == 'left') or (not options.righttoleft and facing == 'right')) and\ if ((options.righttoleft and facing == 'left') or (not options.righttoleft and facing == 'right')) and\
options.landscapemode: options.landscapemode:
@@ -236,7 +266,7 @@ def buildOPF(profile, dstdir, title, filelist, cover=None):
f.write("<itemref idref=\"page_" + entry + "\" properties=\"page-spread-" + facing1 + "\"/>\n") f.write("<itemref idref=\"page_" + entry + "\" properties=\"page-spread-" + facing1 + "\"/>\n")
else: else:
f.write("<itemref idref=\"page_" + entry + "\"/>\n") f.write("<itemref idref=\"page_" + entry + "\"/>\n")
elif entry.endswith("-2"): elif entry.endswith("-kccb"):
if options.landscapemode: if options.landscapemode:
f.write("<itemref idref=\"page_" + entry + "\" properties=\"page-spread-" + facing2 + "\"/>\n") f.write("<itemref idref=\"page_" + entry + "\" properties=\"page-spread-" + facing2 + "\"/>\n")
else: else:
@@ -276,21 +306,16 @@ def getImageFileName(imgfile):
if filename[0].startswith('.') or\ if filename[0].startswith('.') or\
(filename[1].lower() != '.png' and (filename[1].lower() != '.png' and
filename[1].lower() != '.jpg' and filename[1].lower() != '.jpg' and
filename[1].lower() != '.gif' and
filename[1].lower() != '.tif' and
filename[1].lower() != '.tiff' and
filename[1].lower() != '.bmp' and
filename[1].lower() != '.jpeg'): filename[1].lower() != '.jpeg'):
return None return None
return filename return filename
def isInFilelist(filename, filelist): def applyImgOptimization(img, isSplit, toRight, options):
filename = os.path.splitext(filename)
seen = False
for item in filelist:
if filename[0] == item[0]:
seen = True
return seen
def applyImgOptimization(img, isSplit=False, toRight=False):
img.cropWhiteSpace(10.0) img.cropWhiteSpace(10.0)
if options.cutpagenumbers: if options.cutpagenumbers:
img.cutPageNumber() img.cutPageNumber()
@@ -303,51 +328,62 @@ def applyImgOptimization(img, isSplit=False, toRight=False):
def dirImgProcess(path): def dirImgProcess(path):
global options, splitCount global options, splitCount
if options.righttoleft: work = []
facing = "right" pagenumber = 0
else: pagenumbermodifier = 0
facing = "left" pool = Pool()
for (dirpath, dirnames, filenames) in os.walk(path): for (dirpath, dirnames, filenames) in os.walk(path):
for afile in filenames: for afile in filenames:
if getImageFileName(afile) is not None: if getImageFileName(afile) is not None:
if options.verbose: pagenumber += 1
print "Optimizing " + afile + " for " + options.profile work.append([afile, dirpath, pagenumber, options])
else: splitpages = pool.map(fileImgProcess, work)
print ".", pool.close()
img = image.ComicPage(os.path.join(dirpath, afile), options.profile) pool.join()
if options.nosplitrotate: splitpages = filter(None, splitpages)
split = None splitpages.sort()
else: for page in splitpages:
split = img.splitPage(dirpath, options.righttoleft, options.rotate) if (page + pagenumbermodifier) % 2 == 0:
if split is not None: splitCount += 1
if options.verbose: pagenumbermodifier += 1
print "Splitted " + afile pagenumbermodifier += 1
if options.righttoleft:
toRight1 = False
toRight2 = True def fileImgProcess(work):
if facing == "left": afile = work[0]
splitCount += 1 dirpath = work[1]
facing = "right" pagenumber = work[2]
else: options = work[3]
toRight1 = True output = None
toRight2 = False if options.verbose:
if facing == "right": print "Optimizing " + afile + " for " + options.profile
splitCount += 1 else:
facing = "left" print ".",
img0 = image.ComicPage(split[0], options.profile) img = image.ComicPage(os.path.join(dirpath, afile), options.profile)
applyImgOptimization(img0, True, toRight1) if options.nosplitrotate:
img0.saveToDir(dirpath, options.forcepng) split = None
img1 = image.ComicPage(split[1], options.profile) else:
applyImgOptimization(img1, True, toRight2) split = img.splitPage(dirpath, options.righttoleft, options.rotate)
img1.saveToDir(dirpath, options.forcepng) if split is not None and split is not "R":
else: if options.verbose:
if facing == "right": print "Splitted " + afile
facing = "left" if options.righttoleft:
else: toRight1 = False
facing = "right" toRight2 = True
applyImgOptimization(img) else:
img.saveToDir(dirpath, options.forcepng) toRight1 = True
toRight2 = False
output = pagenumber
img0 = image.ComicPage(split[0], options.profile)
applyImgOptimization(img0, True, toRight1, options)
img0.saveToDir(dirpath, options.forcepng, options.forcecolor)
img1 = image.ComicPage(split[1], options.profile)
applyImgOptimization(img1, True, toRight2, options)
img1.saveToDir(dirpath, options.forcepng, options.forcecolor)
else:
applyImgOptimization(img, False, False, options)
img.saveToDir(dirpath, options.forcepng, options.forcecolor, split)
return output
def genEpubStruct(path): def genEpubStruct(path):
@@ -356,10 +392,11 @@ def genEpubStruct(path):
chapterlist = [] chapterlist = []
cover = None cover = None
_, deviceres, _, _, panelviewsize = image.ProfileData.Profiles[options.profile] _, deviceres, _, _, panelviewsize = image.ProfileData.Profiles[options.profile]
sanitizeTree(os.path.join(path, 'OEBPS', 'Images'))
os.mkdir(os.path.join(path, 'OEBPS', 'Text')) os.mkdir(os.path.join(path, 'OEBPS', 'Text'))
f = open(os.path.join(path, 'OEBPS', 'Text', 'style.css'), 'w') f = open(os.path.join(path, 'OEBPS', 'Text', 'style.css'), 'w')
#DON'T COMPRESS CSS. KINDLE WILL FAIL TO PARSE IT. # DON'T COMPRESS CSS. KINDLE WILL FAIL TO PARSE IT.
#Generic Panel View support + Margins fix for Non-Kindle devices. # Generic Panel View support + Margins fix for Non-Kindle devices.
f.writelines(["@page {\n", f.writelines(["@page {\n",
"margin-bottom: 0;\n", "margin-bottom: 0;\n",
"margin-top: 0\n", "margin-top: 0\n",
@@ -482,13 +519,6 @@ def genEpubStruct(path):
for afile in filenames: for afile in filenames:
filename = getImageFileName(afile) filename = getImageFileName(afile)
if filename is not None: if filename is not None:
if "credit" in afile.lower():
os.rename(os.path.join(dirpath, afile), os.path.join(dirpath, 'ZZZ999_' + afile))
afile = 'ZZZ999_' + afile
if "+" in afile.lower() or "#" in afile.lower():
newfilename = afile.replace('+', '_').replace('#', '_')
os.rename(os.path.join(dirpath, afile), os.path.join(dirpath, newfilename))
afile = newfilename
filelist.append(buildHTML(dirpath, afile)) filelist.append(buildHTML(dirpath, afile))
if not chapter: if not chapter:
chapterlist.append((dirpath.replace('Images', 'Text'), filelist[-1][1])) chapterlist.append((dirpath.replace('Images', 'Text'), filelist[-1][1]))
@@ -535,14 +565,45 @@ def getWorkFolder(afile):
return path return path
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', unicode(value, 'latin1')).encode('ascii', 'ignore')
value = re.sub('[^\w\s\.-]', '', value).strip().lower()
value = re.sub('[-\.\s]+', '-', value)
value = re.sub(r'([0-9]+)', r'00000\1', value)
value = re.sub(r'0*([0-9]{6,})', r'\1', value)
return value
def sanitizeTree(filetree):
for root, dirs, files in os.walk(filetree, False):
for name in files:
if name.startswith('.') or name.lower() == 'thumbs.db':
os.remove(os.path.join(root, name))
else:
splitname = os.path.splitext(name)
slugified = slugify(splitname[0])
while os.path.exists(os.path.join(root, slugified + splitname[1])):
slugified += "1"
os.rename(os.path.join(root, name), os.path.join(root, slugified + splitname[1]))
for name in dirs:
if name.startswith('.'):
os.remove(os.path.join(root, name))
else:
os.rename(os.path.join(root, name), os.path.join(root, slugify(name)))
def Copyright(): def Copyright():
print ('comic2ebook v%(__version__)s. ' print ('comic2ebook v%(__version__)s. '
'Written 2012 by Ciro Mattia Gonano.' % globals()) 'Written 2013 by Ciro Mattia Gonano and Pawel Jastrzebski.' % globals())
def Usage(): def Usage():
print "Generates HTML, NCX and OPF for a Comic ebook from a bunch of images." print "Generates EPUB/CBZ comic ebook from a bunch of images."
print "Optimized for creating MOBI files to be read on Kindle Paperwhite."
parser.print_help() parser.print_help()
@@ -551,11 +612,14 @@ def main(argv=None):
usage = "Usage: %prog [options] comic_file|comic_folder" usage = "Usage: %prog [options] comic_file|comic_folder"
parser = OptionParser(usage=usage, version=__version__) parser = OptionParser(usage=usage, version=__version__)
parser.add_option("-p", "--profile", action="store", dest="profile", default="KHD", parser.add_option("-p", "--profile", action="store", dest="profile", default="KHD",
help="Device profile (Choose one among K1, K2, K3, K4NT, K4T, KDX, KDXG or KHD) [Default=KHD]") help="Device profile (Choose one among K1, K2, K3, K4NT, K4T, KDX, KDXG, KHD, KF, KFHD, KFHD8) "
"[Default=KHD]")
parser.add_option("-t", "--title", action="store", dest="title", default="defaulttitle", parser.add_option("-t", "--title", action="store", dest="title", default="defaulttitle",
help="Comic title [Default=filename]") help="Comic title [Default=filename]")
parser.add_option("-m", "--manga-style", action="store_true", dest="righttoleft", default=False, parser.add_option("-m", "--manga-style", action="store_true", dest="righttoleft", default=False,
help="Manga style (Right-to-left reading and splitting) [Default=False]") help="Manga style (Right-to-left reading and splitting) [Default=False]")
parser.add_option("-c", "--cbz-output", action="store_true", dest="cbzoutput", default=False,
help="Outputs a CBZ archive and does not generate EPUB")
parser.add_option("--nopanelviewhq", action="store_true", dest="nopanelviewhq", default=False, parser.add_option("--nopanelviewhq", action="store_true", dest="nopanelviewhq", default=False,
help="Disable high quality Panel View [Default=False]") help="Disable high quality Panel View [Default=False]")
parser.add_option("--noprocessing", action="store_false", dest="imgproc", default=True, parser.add_option("--noprocessing", action="store_false", dest="imgproc", default=True,
@@ -578,7 +642,7 @@ def main(argv=None):
parser.add_option("--nocutpagenumbers", action="store_false", dest="cutpagenumbers", default=True, parser.add_option("--nocutpagenumbers", action="store_false", dest="cutpagenumbers", default=True,
help="Do not try to cut page numbering on images [Default=True]") help="Do not try to cut page numbering on images [Default=True]")
parser.add_option("-o", "--output", action="store", dest="output", default=None, parser.add_option("-o", "--output", action="store", dest="output", default=None,
help="Output generated EPUB to specified directory or file") help="Output generated file (EPUB or CBZ) to specified directory or file")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
help="Verbose output [Default=False]") help="Verbose output [Default=False]")
options, args = parser.parse_args(argv) options, args = parser.parse_args(argv)
@@ -593,48 +657,82 @@ def main(argv=None):
if options.imgproc: if options.imgproc:
print "Processing images..." print "Processing images..."
dirImgProcess(path + "/OEBPS/Images/") dirImgProcess(path + "/OEBPS/Images/")
print "\nCreating ePub structure..." if options.cbzoutput:
genEpubStruct(path) # if CBZ output wanted, compress all images and return filepath
# actually zip the ePub print "\nCreating CBZ file..."
if options.output is not None: filepath = getOutputFilename(args[0], options.output, '.cbz')
if options.output.endswith('.epub'): make_archive(path + '_comic', 'zip', path + '/OEBPS/Images')
epubpath = os.path.abspath(options.output)
elif os.path.isdir(args[0]):
epubpath = os.path.abspath(options.output) + "/" + os.path.basename(args[0]) + '.epub'
else:
epubpath = os.path.abspath(options.output) + "/" \
+ os.path.basename(os.path.splitext(args[0])[0]) + '.epub'
elif os.path.isdir(args[0]):
epubpath = args[0] + '.epub'
else: else:
epubpath = os.path.splitext(args[0])[0] + '.epub' print "\nCreating ePub structure..."
make_archive(path + '_comic', 'zip', path) genEpubStruct(path)
move(path + '_comic.zip', epubpath) # actually zip the ePub
filepath = getOutputFilename(args[0], options.output, '.epub')
make_archive(path + '_comic', 'zip', path)
move(path + '_comic.zip', filepath)
rmtree(path) rmtree(path)
return epubpath return filepath
def getOutputFilename(srcpath, wantedname, ext):
if not ext.startswith('.'):
ext = '.' + ext
if wantedname is not None:
if wantedname.endswith(ext):
filename = os.path.abspath(wantedname)
elif os.path.isdir(srcpath):
filename = os.path.abspath(options.output) + "/" + os.path.basename(srcpath) + ext
else:
filename = os.path.abspath(options.output) + "/" \
+ os.path.basename(os.path.splitext(srcpath)[0]) + ext
elif os.path.isdir(srcpath):
filename = srcpath + ext
else:
filename = os.path.splitext(srcpath)[0] + ext
if os.path.isfile(filename):
filename = os.path.splitext(filename)[0] + '_kcc' + ext
return filename
def checkOptions(): def checkOptions():
global options global options
# Landscape mode is only supported by Kindle Touch and Paperwhite.
if options.profile == 'K4T' or options.profile == 'KHD': if options.profile == 'K4T' or options.profile == 'KHD':
options.landscapemode = True options.landscapemode = True
else: else:
options.landscapemode = False options.landscapemode = False
# Older Kindle don't support Virtual Panel View. We providing them configuration that will fake that feature.
if options.profile == 'K3' or options.profile == 'K4NT': if options.profile == 'K3' or options.profile == 'K4NT':
#Real Panel View # Real Panel View
options.panelview = True options.panelview = True
else: else:
#Virtual Panel View # Virtual Panel View
options.panelview = False options.panelview = False
if options.profile == 'K1' or options.profile == 'K2' or options.profile == 'KDX' or options.profile == 'KDXG': # Older Kindle don't need higher resolution files due lack of Panel View.
# Kindle Fire family have very high resolution. Bigger images are not needed.
if options.profile == 'K1' or options.profile == 'K2' or options.profile == 'KDX' or options.profile == 'KDXG'\
or options.profile == 'KF' or options.profile == 'KFHD' or options.profile == 'KFHD8':
options.nopanelviewhq = True options.nopanelviewhq = True
# Disabling grayscale conversion for Kindle Fire family.
# Forcing JPEG output. For now code can't provide color PNG files.
if options.profile == 'KF' or options.profile == 'KFHD' or options.profile == 'KFHD8':
options.forcecolor = True
options.forcepng = False
else:
options.forcecolor = False
# Mixing vertical and horizontal pages require real Panel View.
# Landscape mode don't work correcly without Virtual Panel View.
if options.rotate:
options.panelview = True
options.landscapemode = False
def getEpubPath(): def getEpubPath():
global epub_path global epub_path
return epub_path return epub_path
if __name__ == "__main__": if __name__ == "__main__":
freeze_support()
Copyright() Copyright()
main(sys.argv[1:]) main(sys.argv[1:])
sys.exit(0) sys.exit(0)

View File

@@ -93,31 +93,33 @@ class MainWindow:
self.options = { self.options = {
'Aepub_only': IntVar(None, 0), 'Aepub_only': IntVar(None, 0),
'Bmangastyle': IntVar(None, 0), 'Bcbz_only': IntVar(None, 0),
'Cnopanelviewhq': IntVar(None, 0), 'Cmangastyle': IntVar(None, 0),
'Dimage_preprocess': IntVar(None, 0), 'Dnopanelviewhq': IntVar(None, 0),
'Eforcepng': IntVar(None, 0), 'Eimage_preprocess': IntVar(None, 0),
'Fimage_gamma': DoubleVar(None, 0.0), 'Fforcepng': IntVar(None, 0),
'Gimage_upscale': IntVar(None, 0), 'Gimage_gamma': DoubleVar(None, 0.0),
'Himage_stretch': IntVar(None, 0), 'Himage_upscale': IntVar(None, 0),
'Iblack_borders': IntVar(None, 0), 'Iimage_stretch': IntVar(None, 0),
'Jrotate': IntVar(None, 0), 'Jblack_borders': IntVar(None, 0),
'Knosplitrotate': IntVar(None, 0), 'Krotate': IntVar(None, 0),
'Lcut_page_numbers': IntVar(None, 0) 'Lnosplitrotate': IntVar(None, 0),
'Mcut_page_numbers': IntVar(None, 0)
} }
self.optionlabels = { self.optionlabels = {
'Aepub_only': "Generate EPUB only", 'Aepub_only': "Generate EPUB only",
'Bmangastyle': "Manga mode", 'Bcbz_only': "Generate CBZ only (skip EPUB/Mobi generation)",
'Cnopanelviewhq': "Disable high quality Panel View", 'Cmangastyle': "Manga mode",
'Dimage_preprocess': "Disable image optimizations", 'Dnopanelviewhq': "Disable high quality Panel View",
'Eforcepng': "Create PNG files instead JPEG", 'Eimage_preprocess': "Disable image optimizations",
'Fimage_gamma': "Custom gamma correction", 'Fforcepng': "Create PNG files instead of JPEG",
'Gimage_upscale': "Allow image upscaling", 'Gimage_gamma': "Custom gamma correction",
'Himage_stretch': "Stretch images", 'Himage_upscale': "Allow image upscaling",
'Iblack_borders': "Use black borders", 'Iimage_stretch': "Stretch images",
'Jrotate': "Rotate images instead splitting them", 'Jblack_borders': "Use black borders (instead of white ones)",
'Knosplitrotate': "Disable splitting and rotation", 'Krotate': "Rotate images (instead of splitting them)",
'Lcut_page_numbers': "Disable page numbers cutting" 'Lnosplitrotate': "Disable both splitting and rotation",
'Mcut_page_numbers': "Disable page numbers cutting"
} }
self.optionsButtons = {} self.optionsButtons = {}
for key in sorted(self.options): for key in sorted(self.options):
@@ -162,28 +164,30 @@ class MainWindow:
return return
profilekey = ProfileData.ProfileLabels[self.profile.get()] profilekey = ProfileData.ProfileLabels[self.profile.get()]
argv = ["-p", profilekey] argv = ["-p", profilekey]
if self.options['Bmangastyle'].get() == 1: if self.options['Bcbz_only'].get() == 1:
argv.append("-c")
if self.options['Cmangastyle'].get() == 1:
argv.append("-m") argv.append("-m")
if self.options['Cnopanelviewhq'].get() == 1: if self.options['Dnopanelviewhq'].get() == 1:
argv.append("--nopanelviewhq") argv.append("--nopanelviewhq")
if self.options['Dimage_preprocess'].get() == 1: if self.options['Eimage_preprocess'].get() == 1:
argv.append("--noprocessing") argv.append("--noprocessing")
if self.options['Eforcepng'].get() == 1: if self.options['Fforcepng'].get() == 1:
argv.append("--forcepng") argv.append("--forcepng")
if self.options['Fimage_gamma'].get() != 0.0: if self.options['Gimage_gamma'].get() != 0.0:
argv.append("--gamma") argv.append("--gamma")
argv.append(self.options['Fimage_gamma'].get()) argv.append(self.options['Gimage_gamma'].get())
if self.options['Gimage_upscale'].get() == 1: if self.options['Himage_upscale'].get() == 1:
argv.append("--upscale") argv.append("--upscale")
if self.options['Himage_stretch'].get() == 1: if self.options['Iimage_stretch'].get() == 1:
argv.append("--stretch") argv.append("--stretch")
if self.options['Iblack_borders'].get() == 1: if self.options['Jblack_borders'].get() == 1:
argv.append("--blackborders") argv.append("--blackborders")
if self.options['Jrotate'].get() == 1: if self.options['Krotate'].get() == 1:
argv.append("--rotate") argv.append("--rotate")
if self.options['Knosplitrotate'].get() == 1: if self.options['Lnosplitrotate'].get() == 1:
argv.append("--nosplitrotate") argv.append("--nosplitrotate")
if self.options['Lcut_page_numbers'].get() == 1: if self.options['Mcut_page_numbers'].get() == 1:
argv.append("--nocutpagenumbers") argv.append("--nocutpagenumbers")
errors = False errors = False
left_files = len(self.filelist) left_files = len(self.filelist)
@@ -207,7 +211,7 @@ class MainWindow:
(subargv[-1], str(err), traceback.format_tb(traceback_))) (subargv[-1], str(err), traceback.format_tb(traceback_)))
errors = True errors = True
continue continue
if self.options['Aepub_only'].get() == 0: if self.options['Aepub_only'].get() == 0 and self.options['Bcbz_only'].get() == 0:
try: try:
if os.path.getsize(epub_path) > 314572800: if os.path.getsize(epub_path) > 314572800:
# do not call kindlegen if source is bigger than 300MB # do not call kindlegen if source is bigger than 300MB

View File

@@ -20,7 +20,7 @@ __copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os import os
from PIL import Image, ImageOps, ImageStat from PIL import Image, ImageOps, ImageStat, ImageChops
class ImageFlags: class ImageFlags:
@@ -84,7 +84,10 @@ class ProfileData:
'K4T': ("Kindle Touch", (600, 800), Palette16, 1.8, (900, 1200)), 'K4T': ("Kindle Touch", (600, 800), Palette16, 1.8, (900, 1200)),
'KHD': ("Kindle Paperwhite", (758, 1024), Palette16, 1.8, (1137, 1536)), 'KHD': ("Kindle Paperwhite", (758, 1024), Palette16, 1.8, (1137, 1536)),
'KDX': ("Kindle DX", (824, 1200), Palette15, 1.8, (1236, 1800)), 'KDX': ("Kindle DX", (824, 1200), Palette15, 1.8, (1236, 1800)),
'KDXG': ("Kindle DXG", (824, 1200), Palette16, 1.8, (1236, 1800)) 'KDXG': ("Kindle DXG", (824, 1200), Palette16, 1.8, (1236, 1800)),
'KF': ("Kindle Fire", (600, 1024), Palette16, 1.0, (900, 1536)),
'KFHD': ("Kindle Fire HD 7\"", (800, 1280), Palette16, 1.0, (1200, 1920)),
'KFHD8': ("Kindle Fire HD 8.9\"", (1200, 1920), Palette16, 1.0, (1800, 2880))
} }
ProfileLabels = { ProfileLabels = {
@@ -95,7 +98,10 @@ class ProfileData:
"Kindle 4/Touch": 'K4T', "Kindle 4/Touch": 'K4T',
"Kindle Paperwhite": 'KHD', "Kindle Paperwhite": 'KHD',
"Kindle DX": 'KDX', "Kindle DX": 'KDX',
"Kindle DXG": 'KDXG' "Kindle DXG": 'KDXG',
"Kindle Fire": 'KF',
"Kindle Fire HD 7\"": 'KFHD',
"Kindle Fire HD 8.9\"": 'KFHD8'
} }
@@ -113,15 +119,21 @@ class ComicPage:
raise RuntimeError('Cannot read image file %s' % source) raise RuntimeError('Cannot read image file %s' % source)
self.image = self.image.convert('RGB') self.image = self.image.convert('RGB')
def saveToDir(self, targetdir, forcepng): def saveToDir(self, targetdir, forcepng, color, sufix=None):
filename = os.path.basename(self.origFileName) filename = os.path.basename(self.origFileName)
try: try:
self.image = self.image.convert('L') # convert to grayscale if not color:
self.image = self.image.convert('L') # convert to grayscale
# Sufix is used to recognise which files need horizontal Panel View.
if sufix == "R":
sufix = "_rotated"
else:
sufix = ""
os.remove(os.path.join(targetdir, filename)) os.remove(os.path.join(targetdir, filename))
if forcepng: if forcepng:
self.image.save(os.path.join(targetdir, os.path.splitext(filename)[0] + ".png"), "PNG") self.image.save(os.path.join(targetdir, os.path.splitext(filename)[0] + sufix + ".png"), "PNG")
else: else:
self.image.save(os.path.join(targetdir, os.path.splitext(filename)[0] + ".jpg"), "JPEG") self.image.save(os.path.join(targetdir, os.path.splitext(filename)[0] + sufix + ".jpg"), "JPEG")
except IOError as e: except IOError as e:
raise RuntimeError('Cannot write image in directory %s: %s' % (targetdir, e)) raise RuntimeError('Cannot write image in directory %s: %s' % (targetdir, e))
@@ -195,7 +207,7 @@ class ComicPage:
if (width > height) != (dstwidth > dstheight): if (width > height) != (dstwidth > dstheight):
if rotate: if rotate:
self.image = self.image.rotate(90) self.image = self.image.rotate(90)
return None return "R"
else: else:
if width > height: if width > height:
# source is landscape, so split by the width # source is landscape, so split by the width
@@ -206,8 +218,8 @@ class ComicPage:
leftbox = (0, 0, width, height / 2) leftbox = (0, 0, width, height / 2)
rightbox = (0, height / 2, width, height) rightbox = (0, height / 2, width, height)
filename = os.path.splitext(os.path.basename(self.origFileName)) filename = os.path.splitext(os.path.basename(self.origFileName))
fileone = targetdir + '/' + filename[0] + '-1' + filename[1] fileone = targetdir + '/' + filename[0] + '-kcca' + filename[1]
filetwo = targetdir + '/' + filename[0] + '-2' + filename[1] filetwo = targetdir + '/' + filename[0] + '-kccb' + filename[1]
try: try:
if righttoleft: if righttoleft:
pageone = self.image.crop(rightbox) pageone = self.image.crop(rightbox)
@@ -225,95 +237,97 @@ class ComicPage:
return None return None
def cutPageNumber(self): def cutPageNumber(self):
widthImg, heightImg = self.image.size if ImageChops.invert(self.image).getbbox() is not None:
delta = 2 widthImg, heightImg = self.image.size
diff = delta delta = 2
fixedThreshold = 5
if ImageStat.Stat(self.image).var[0] < 2 * fixedThreshold:
return self.image
while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] < fixedThreshold\
and diff < heightImg:
diff += delta
diff -= delta
pageNumberCut1 = diff
if diff < delta:
diff = delta diff = delta
oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] fixedThreshold = 5
diff += delta if ImageStat.Stat(self.image).var[0] < 2 * fixedThreshold:
while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] - oldStat > 0\ return self.image
and diff < heightImg / 4: while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] < fixedThreshold\
and diff < heightImg:
diff += delta
diff -= delta
pageNumberCut1 = diff
if diff < delta:
diff = delta
oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0]
diff += delta diff += delta
diff -= delta while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] - oldStat > 0\
pageNumberCut2 = diff and diff < heightImg / 4:
diff += delta oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0]
oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0] diff += delta
while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0]\ diff -= delta
< fixedThreshold + oldStat and diff < heightImg / 4: pageNumberCut2 = diff
diff += delta diff += delta
diff -= delta oldStat = ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0]
pageNumberCut3 = diff while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg - pageNumberCut2))).var[0]\
delta = 5 < fixedThreshold + oldStat and diff < heightImg / 4:
diff = delta diff += delta
while ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut2, diff, heightImg))).var[0] < fixedThreshold\ diff -= delta
and diff < widthImg: pageNumberCut3 = diff
diff += delta delta = 5
diff -= delta diff = delta
pageNumberX1 = diff while ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut2, diff, heightImg))).var[0] < fixedThreshold\
diff = delta and diff < widthImg:
while ImageStat.Stat(self.image.crop((widthImg - diff, heightImg - pageNumberCut2, diff += delta
widthImg, heightImg))).var[0] < fixedThreshold and diff < widthImg: diff -= delta
diff += delta pageNumberX1 = diff
diff -= delta diff = delta
pageNumberX2 = widthImg - diff while ImageStat.Stat(self.image.crop((widthImg - diff, heightImg - pageNumberCut2,
if pageNumberCut3 - pageNumberCut1 > 2 * delta\ widthImg, heightImg))).var[0] < fixedThreshold and diff < widthImg:
and float(pageNumberX2 - pageNumberX1) / float(pageNumberCut2 - pageNumberCut1) <= 9.0\ diff += delta
and ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut3, widthImg, heightImg))).var[0]\ diff -= delta
/ ImageStat.Stat(self.image).var[0] < 0.1\ pageNumberX2 = widthImg - diff
and pageNumberCut3 < heightImg / 4 - delta: if pageNumberCut3 - pageNumberCut1 > 2 * delta\
diff = pageNumberCut3 and float(pageNumberX2 - pageNumberX1) / float(pageNumberCut2 - pageNumberCut1) <= 9.0\
else: and ImageStat.Stat(self.image.crop((0, heightImg - pageNumberCut3, widthImg, heightImg))).var[0]\
diff = pageNumberCut1 / ImageStat.Stat(self.image).var[0] < 0.1\
self.image = self.image.crop((0, 0, widthImg, heightImg - diff)) and pageNumberCut3 < heightImg / 4 - delta:
diff = pageNumberCut3
else:
diff = pageNumberCut1
self.image = self.image.crop((0, 0, widthImg, heightImg - diff))
return self.image return self.image
def cropWhiteSpace(self, threshold): def cropWhiteSpace(self, threshold):
widthImg, heightImg = self.image.size if ImageChops.invert(self.image).getbbox() is not None:
delta = 10 widthImg, heightImg = self.image.size
diff = delta delta = 10
# top diff = delta
while ImageStat.Stat(self.image.crop((0, 0, widthImg, diff))).var[0] < threshold and diff < heightImg: # top
diff += delta while ImageStat.Stat(self.image.crop((0, 0, widthImg, diff))).var[0] < threshold and diff < heightImg:
diff -= delta diff += delta
# print "Top crop: %s"%diff diff -= delta
self.image = self.image.crop((0, diff, widthImg, heightImg)) # print "Top crop: %s"%diff
widthImg, heightImg = self.image.size self.image = self.image.crop((0, diff, widthImg, heightImg))
diff = delta widthImg, heightImg = self.image.size
# left diff = delta
while ImageStat.Stat(self.image.crop((0, 0, diff, heightImg))).var[0] < threshold and diff < widthImg: # left
diff += delta while ImageStat.Stat(self.image.crop((0, 0, diff, heightImg))).var[0] < threshold and diff < widthImg:
diff -= delta diff += delta
# print "Left crop: %s"%diff diff -= delta
self.image = self.image.crop((diff, 0, widthImg, heightImg)) # print "Left crop: %s"%diff
widthImg, heightImg = self.image.size self.image = self.image.crop((diff, 0, widthImg, heightImg))
diff = delta widthImg, heightImg = self.image.size
# down diff = delta
while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] < threshold\ # down
and diff < heightImg: while ImageStat.Stat(self.image.crop((0, heightImg - diff, widthImg, heightImg))).var[0] < threshold\
diff += delta and diff < heightImg:
diff -= delta diff += delta
# print "Down crop: %s"%diff diff -= delta
self.image = self.image.crop((0, 0, widthImg, heightImg - diff)) # print "Down crop: %s"%diff
widthImg, heightImg = self.image.size self.image = self.image.crop((0, 0, widthImg, heightImg - diff))
diff = delta widthImg, heightImg = self.image.size
# right diff = delta
while ImageStat.Stat(self.image.crop((widthImg - diff, 0, widthImg, heightImg))).var[0] < threshold\ # right
and diff < widthImg: while ImageStat.Stat(self.image.crop((widthImg - diff, 0, widthImg, heightImg))).var[0] < threshold\
diff += delta and diff < widthImg:
diff -= delta diff += delta
# print "Right crop: %s"%diff diff -= delta
self.image = self.image.crop((0, 0, widthImg - diff, heightImg)) # print "Right crop: %s"%diff
# print "New size: %sx%s"%(self.image.size[0],self.image.size[1]) self.image = self.image.crop((0, 0, widthImg - diff, heightImg))
# print "New size: %sx%s"%(self.image.size[0],self.image.size[1])
return self.image return self.image
# def addProgressbar(self, file_number, files_totalnumber, size, howoften): # def addProgressbar(self, file_number, files_totalnumber, size, howoften):

View File

@@ -1,6 +1,6 @@
# rarfile.py # rarfile.py
# #
# Copyright (c) 2005-2012 Marko Kreen <markokr@gmail.com> # Copyright (c) 2005-2013 Marko Kreen <markokr@gmail.com>
# #
# Permission to use, copy, modify, and/or distribute this software for any # Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above # purpose with or without fee is hereby granted, provided that the above
@@ -17,7 +17,7 @@
r"""RAR archive reader. r"""RAR archive reader.
This is Python module for Rar archive reading. The interface This is Python module for Rar archive reading. The interface
is made as zipfile like as possible. is made as :mod:`zipfile`-like as possible.
Basic logic: Basic logic:
- Parse archive structure with Python. - Parse archive structure with Python.
@@ -34,7 +34,17 @@ Example::
for f in rf.infolist(): for f in rf.infolist():
print f.filename, f.file_size print f.filename, f.file_size
if f.filename == 'README': if f.filename == 'README':
print rf.read(f) print(rf.read(f))
Archive files can also be accessed via file-like object returned
by :meth:`RarFile.open`::
import rarfile
with rarfile.RarFile('archive.rar') as rf:
with rf.open('README') as f:
for ln in f:
print(ln.strip())
There are few module-level parameters to tune behaviour, There are few module-level parameters to tune behaviour,
here they are with defaults, and reason to change it:: here they are with defaults, and reason to change it::
@@ -64,7 +74,7 @@ For more details, refer to source.
""" """
__version__ = '2.5' __version__ = '2.6'
# export only interesting items # export only interesting items
__all__ = ['is_rarfile', 'RarInfo', 'RarFile', 'RarExtFile'] __all__ = ['is_rarfile', 'RarInfo', 'RarFile', 'RarExtFile']
@@ -148,45 +158,45 @@ except ImportError:
## Module configuration. Can be tuned after importing. ## Module configuration. Can be tuned after importing.
## ##
# default fallback charset #: default fallback charset
DEFAULT_CHARSET = "windows-1252" DEFAULT_CHARSET = "windows-1252"
# list of encodings to try, with fallback to DEFAULT_CHARSET if none succeed #: list of encodings to try, with fallback to DEFAULT_CHARSET if none succeed
TRY_ENCODINGS = ('utf8', 'utf-16le') TRY_ENCODINGS = ('utf8', 'utf-16le')
# 'unrar', 'rar' or full path to either one #: 'unrar', 'rar' or full path to either one
UNRAR_TOOL = "unrar" UNRAR_TOOL = "unrar"
# Command line args to use for opening file for reading. #: Command line args to use for opening file for reading.
OPEN_ARGS = ('p', '-inul') OPEN_ARGS = ('p', '-inul')
# Command line args to use for extracting file to disk. #: Command line args to use for extracting file to disk.
EXTRACT_ARGS = ('x', '-y', '-idq') EXTRACT_ARGS = ('x', '-y', '-idq')
# args for testrar() #: args for testrar()
TEST_ARGS = ('t', '-idq') TEST_ARGS = ('t', '-idq')
# whether to speed up decompression by using tmp archive #: whether to speed up decompression by using tmp archive
USE_EXTRACT_HACK = 1 USE_EXTRACT_HACK = 1
# limit the filesize for tmp archive usage #: limit the filesize for tmp archive usage
HACK_SIZE_LIMIT = 20*1024*1024 HACK_SIZE_LIMIT = 20*1024*1024
# whether to parse file/archive comments. #: whether to parse file/archive comments.
NEED_COMMENTS = 1 NEED_COMMENTS = 1
# whether to convert comments to unicode strings #: whether to convert comments to unicode strings
UNICODE_COMMENTS = 0 UNICODE_COMMENTS = 0
# When RAR is corrupt, stopping on bad header is better #: When RAR is corrupt, stopping on bad header is better
# On unknown/misparsed RAR headers reporting is better #: On unknown/misparsed RAR headers reporting is better
REPORT_BAD_HEADER = 0 REPORT_BAD_HEADER = 0
# Convert RAR time tuple into datetime() object #: Convert RAR time tuple into datetime() object
USE_DATETIME = 0 USE_DATETIME = 0
# Separator for path name components. RAR internally uses '\\'. #: Separator for path name components. RAR internally uses '\\'.
# Use '/' to be similar with zipfile. #: Use '/' to be similar with zipfile.
PATH_SEP = '\\' PATH_SEP = '\\'
## ##
@@ -337,49 +347,57 @@ def is_rarfile(fn):
class RarInfo(object): class RarInfo(object):
'''An entry in rar archive. r'''An entry in rar archive.
@ivar filename:
File name with relative path.
Default path separator is '/', to change set rarfile.PATH_SEP.
Always unicode string.
@ivar date_time:
Modification time, tuple of (year, month, day, hour, minute, second).
Or datetime() object if USE_DATETIME is set.
@ivar file_size:
Uncompressed size.
@ivar compress_size:
Compressed size.
@ivar compress_type:
Compression method: 0x30 - 0x35.
@ivar extract_version:
Minimal Rar version needed for decompressing.
@ivar host_os:
Host OS type, one of RAR_OS_* constants.
@ivar mode:
File attributes. May be either dos-style or unix-style, depending on host_os.
@ivar CRC:
CRC-32 of uncompressed file, unsigned int.
@ivar volume:
Volume nr, starting from 0.
@ivar volume_file:
Volume file name, where file starts.
@ivar type:
One of RAR_BLOCK_* types. Only entries with type==RAR_BLOCK_FILE are shown in .infolist().
@ivar flags:
For files, RAR_FILE_* bits.
@ivar comment:
File comment (unicode string or None).
@ivar mtime: :mod:`zipfile`-compatible fields:
Optional time field: Modification time, with float seconds.
Same as .date_time but with more precision. filename
@ivar ctime: File name with relative path.
Optional time field: creation time, with float seconds. Default path separator is '\\', to change set rarfile.PATH_SEP.
@ivar atime: Always unicode string.
Optional time field: last access time, with float seconds. date_time
@ivar arctime: Modification time, tuple of (year, month, day, hour, minute, second).
Optional time field: archival time, with float seconds. Or datetime() object if USE_DATETIME is set.
file_size
Uncompressed size.
compress_size
Compressed size.
CRC
CRC-32 of uncompressed file, unsigned int.
comment
File comment. Byte string or None. Use UNICODE_COMMENTS
to get automatic decoding to unicode.
volume
Volume nr, starting from 0.
RAR-specific fields:
compress_type
Compression method: 0x30 - 0x35.
extract_version
Minimal Rar version needed for decompressing.
host_os
Host OS type, one of RAR_OS_* constants.
mode
File attributes. May be either dos-style or unix-style, depending on host_os.
volume_file
Volume file name, where file starts.
mtime
Optional time field: Modification time, with float seconds.
Same as .date_time but with more precision.
ctime
Optional time field: creation time, with float seconds.
atime
Optional time field: last access time, with float seconds.
arctime
Optional time field: archival time, with float seconds.
Internal fields:
type
One of RAR_BLOCK_* types. Only entries with type==RAR_BLOCK_FILE are shown in .infolist().
flags
For files, RAR_FILE_* bits.
''' '''
__slots__ = ( __slots__ = (
@@ -433,19 +451,27 @@ class RarInfo(object):
class RarFile(object): class RarFile(object):
'''Parse RAR structure, provide access to files in archive. '''Parse RAR structure, provide access to files in archive.
@ivar comment:
Archive comment (unicode string or None).
''' '''
#: Archive comment. Byte string or None. Use UNICODE_COMMENTS
#: to get automatic decoding to unicode.
comment = None
def __init__(self, rarfile, mode="r", charset=None, info_callback=None, crc_check = True): def __init__(self, rarfile, mode="r", charset=None, info_callback=None, crc_check = True):
"""Open and parse a RAR archive. """Open and parse a RAR archive.
@param rarfile: archive file name Parameters:
@param mode: only 'r' is supported.
@param charset: fallback charset to use, if filenames are not already Unicode-enabled. rarfile
@param info_callback: debug callback, gets to see all archive entries. archive file name
@param crc_check: set to False to disable CRC checks mode
only 'r' is supported.
charset
fallback charset to use, if filenames are not already Unicode-enabled.
info_callback
debug callback, gets to see all archive entries.
crc_check
set to False to disable CRC checks
""" """
self.rarfile = rarfile self.rarfile = rarfile
self.comment = None self.comment = None
@@ -457,6 +483,7 @@ class RarFile(object):
self._needs_password = False self._needs_password = False
self._password = None self._password = None
self._crc_check = crc_check self._crc_check = crc_check
self._vol_list = []
self._main = None self._main = None
@@ -489,6 +516,14 @@ class RarFile(object):
'''Return RarInfo objects for all files/directories in archive.''' '''Return RarInfo objects for all files/directories in archive.'''
return self._info_list return self._info_list
def volumelist(self):
'''Returns filenames of archive volumes.
In case of single-volume archive, the list contains
just the name of main archive file.
'''
return self._vol_list
def getinfo(self, fname): def getinfo(self, fname):
'''Return RarInfo for file.''' '''Return RarInfo for file.'''
@@ -510,7 +545,8 @@ class RarFile(object):
raise NoRarEntry("No such file: "+fname) raise NoRarEntry("No such file: "+fname)
def open(self, fname, mode = 'r', psw = None): def open(self, fname, mode = 'r', psw = None):
'''Return open file object, where the data can be read. '''Returns file-like object (:class:`RarExtFile`),
from where the data can be read.
The object implements io.RawIOBase interface, so it can The object implements io.RawIOBase interface, so it can
be further wrapped with io.BufferedReader and io.TextIOWrapper. be further wrapped with io.BufferedReader and io.TextIOWrapper.
@@ -522,9 +558,14 @@ class RarFile(object):
uncompressed files, on compressed files the seeking is implemented uncompressed files, on compressed files the seeking is implemented
by reading ahead and/or restarting the decompression. by reading ahead and/or restarting the decompression.
@param fname: file name or RarInfo instance. Parameters:
@param mode: must be 'r'
@param psw: password to use for extracting. fname
file name or RarInfo instance.
mode
must be 'r'
psw
password to use for extracting.
''' '''
if mode != 'r': if mode != 'r':
@@ -571,8 +612,12 @@ class RarFile(object):
For longer files using .open() may be better idea. For longer files using .open() may be better idea.
@param fname: filename or RarInfo instance Parameters:
@param psw: password to use for extracting.
fname
filename or RarInfo instance
psw
password to use for extracting.
""" """
f = self.open(fname, 'r', psw) f = self.open(fname, 'r', psw)
@@ -593,9 +638,14 @@ class RarFile(object):
def extract(self, member, path=None, pwd=None): def extract(self, member, path=None, pwd=None):
"""Extract single file into current directory. """Extract single file into current directory.
@param member: filename or RarInfo instance Parameters:
@param path: optional destination path
@param pwd: optional password to use member
filename or RarInfo instance
path
optional destination path
pwd
optional password to use
""" """
if isinstance(member, RarInfo): if isinstance(member, RarInfo):
fname = member.filename fname = member.filename
@@ -606,9 +656,14 @@ class RarFile(object):
def extractall(self, path=None, members=None, pwd=None): def extractall(self, path=None, members=None, pwd=None):
"""Extract all files into current directory. """Extract all files into current directory.
@param path: optional destination path Parameters:
@param members: optional filename or RarInfo instance list to extract
@param pwd: optional password to use path
optional destination path
members
optional filename or RarInfo instance list to extract
pwd
optional password to use
""" """
fnlist = [] fnlist = []
if members is not None: if members is not None:
@@ -693,6 +748,7 @@ class RarFile(object):
more_vols = 0 more_vols = 0
endarc = 0 endarc = 0
volfile = self.rarfile volfile = self.rarfile
self._vol_list = [self.rarfile]
while 1: while 1:
if endarc: if endarc:
h = None # don't read past ENDARC h = None # don't read past ENDARC
@@ -707,6 +763,7 @@ class RarFile(object):
self._fd = fd self._fd = fd
more_vols = 0 more_vols = 0
endarc = 0 endarc = 0
self._vol_list.append(volfile)
continue continue
break break
h.volume = volume h.volume = volume
@@ -1210,7 +1267,7 @@ class UnicodeFilename:
class RarExtFile(RawIOBase): class RarExtFile(RawIOBase):
"""Base class for 'file-like' object that RarFile.open() returns. """Base class for file-like object that :meth:`RarFile.open` returns.
Provides public methods and common crc checking. Provides public methods and common crc checking.
@@ -1218,13 +1275,15 @@ class RarExtFile(RawIOBase):
- no short reads - .read() and .readinfo() read as much as requested. - no short reads - .read() and .readinfo() read as much as requested.
- no internal buffer, use io.BufferedReader for that. - no internal buffer, use io.BufferedReader for that.
@ivar name: If :mod:`io` module is available (Python 2.6+, 3.x), then this calls
filename of the archive entry. will inherit from :class:`io.RawIOBase` class. This makes line-based
access available: :meth:`RarExtFile.readline` and ``for ln in f``.
""" """
def __init__(self, rf, inf): #: Filename of the archive entry
"""Fill common fields""" name = None
def __init__(self, rf, inf):
RawIOBase.__init__(self) RawIOBase.__init__(self)
# standard io.* properties # standard io.* properties
@@ -1325,7 +1384,13 @@ class RarExtFile(RawIOBase):
return self.inf.file_size - self.remain return self.inf.file_size - self.remain
def seek(self, ofs, whence = 0): def seek(self, ofs, whence = 0):
"""Seek in data.""" """Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compresses files its slow
- forward seeking happends by reading ahead,
backwards by re-opening and decompressing from the start.
"""
# disable crc check when seeking # disable crc check when seeking
self.crc_check = 0 self.crc_check = 0
@@ -1374,8 +1439,17 @@ class RarExtFile(RawIOBase):
"""Returns True""" """Returns True"""
return True return True
def writable(self):
"""Returns False.
Writing is not supported."""
return False
def seekable(self): def seekable(self):
"""Returns True""" """Returns True.
Seeking is supported, although it's slow on compressed files.
"""
return True return True
def readall(self): def readall(self):

View File

@@ -15,7 +15,7 @@ use_setuptools()
import sys import sys
NAME = "KindleComicConverter" NAME = "KindleComicConverter"
VERSION = "2.8" VERSION = "2.10"
MAIN = "kcc.py" MAIN = "kcc.py"
includefiles = ['README.md', 'MANIFEST.in', 'LICENSE.txt', 'comic2ebook.ico', 'comic2ebook.icns'] includefiles = ['README.md', 'MANIFEST.in', 'LICENSE.txt', 'comic2ebook.ico', 'comic2ebook.icns']

View File

@@ -10,7 +10,7 @@ sys.path.insert(0, 'kcc')
setup( setup(
name = "KindleComicConverter", name = "KindleComicConverter",
version = "2.8", version = "2.10",
author = "Ciro Mattia Gonano", author = "Ciro Mattia Gonano",
author_email = "ciromattia@gmail.com", author_email = "ciromattia@gmail.com",
description = "A tool to convert comics (CBR/CBZ/PDFs/image folders) to MOBI.", description = "A tool to convert comics (CBR/CBZ/PDFs/image folders) to MOBI.",