mirror of
https://github.com/ciromattia/kcc
synced 2026-04-25 10:28:58 +00:00
Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b068d82ccf | ||
|
|
43ca5ac5b9 | ||
|
|
18c3ab2340 | ||
|
|
87eaba184e | ||
|
|
97b5d8a2ee | ||
|
|
7c3a762107 | ||
|
|
0b90af77da | ||
|
|
28dcab8ee8 | ||
|
|
6c468a5291 | ||
|
|
d090d8c2e8 | ||
|
|
aba315866e | ||
|
|
e981aa4520 | ||
|
|
e603622021 | ||
|
|
3e007965b2 | ||
|
|
c0610360a3 | ||
|
|
ff8f6e073f | ||
|
|
aadb5407d2 | ||
|
|
2e4d5eb958 | ||
|
|
33fb13a66e | ||
|
|
4dc69aa1c4 | ||
|
|
b3681a3ceb | ||
|
|
348dcc4275 | ||
|
|
39e69119ac | ||
|
|
8c57926978 | ||
|
|
8b1965054f | ||
|
|
18993069e3 | ||
|
|
7e6c8cc768 | ||
|
|
3ae44d2fcb | ||
|
|
a6eb3936e4 | ||
|
|
bb24d3ca30 | ||
|
|
7e191c0be5 | ||
|
|
d9ea165bbb | ||
|
|
148211a5c7 | ||
|
|
23e07f47f0 | ||
|
|
724156c554 | ||
|
|
b972e4c746 | ||
|
|
f0afa1fff2 | ||
|
|
a36c05f0c5 | ||
|
|
4f3a66b4eb | ||
|
|
6369c7ea44 | ||
|
|
f1b8aff8d4 | ||
|
|
be270aa797 | ||
|
|
f33d355024 | ||
|
|
6f913b026e | ||
|
|
220b4e0954 | ||
|
|
bac4a4fd86 |
155
README.md
155
README.md
@@ -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
|
||||||
|

|
||||||
|
|
||||||
|
[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
|
|
||||||
with landscape target), add palette and other image optimizations from Mangle.
|
|
||||||
WARNING: PIL is required for all image mangling!
|
|
||||||
- 1.30: Fixed an issue in OPF generation for device resolution
|
|
||||||
Reworked options system (call with -h option to get the inline help)
|
|
||||||
- 1.40: Added some options for controlling image optimization
|
|
||||||
Further optimization (ImageOps, page numbering cut, autocontrast)
|
|
||||||
- 1.41: Fixed a serious bug on resizing when img ratio was bigger than device one
|
|
||||||
- 1.50: Added subfolder support for multiple chapters.
|
|
||||||
- 2.0: GUI! AppleScript is gone and Tk is used to provide cross-platform GUI support.
|
|
||||||
- 2.1: Added basic error reporting
|
|
||||||
- 2.2: Added (valid!) ePub 2.0 output
|
|
||||||
Rename .zip files to .cbz to avoid overwriting
|
|
||||||
- 2.3: Fixed win32 ePub generation, folder handling, filenames with spaces and subfolders
|
|
||||||
- 2.4: 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)
|
|
||||||
|
|
||||||
|
####1.10
|
||||||
|
* Added support for CBZ/CBR files in comic2ebook.py
|
||||||
|
|
||||||
|
####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 with landscape target), add palette and other image optimizations from Mangle. WARNING: PIL is required for all image mangling!
|
||||||
|
|
||||||
|
####1.30
|
||||||
|
* Fixed an issue in OPF generation for device resolution
|
||||||
|
* Reworked options system (call with -h option to get the inline help)
|
||||||
|
|
||||||
|
####1.40
|
||||||
|
* Added some options for controlling image optimization
|
||||||
|
* Further optimization (ImageOps, page numbering cut, autocontrast)
|
||||||
|
|
||||||
|
####1.41
|
||||||
|
* Fixed a serious bug on resizing when img ratio was bigger than device one
|
||||||
|
|
||||||
|
####1.50
|
||||||
|
* Added subfolder support for multiple chapters.
|
||||||
|
|
||||||
|
####2.0
|
||||||
|
* GUI! AppleScript is gone and Tk is used to provide cross-platform GUI support.
|
||||||
|
|
||||||
|
####2.1
|
||||||
|
* Added basic error reporting
|
||||||
|
|
||||||
|
#### 2.2:
|
||||||
|
* Added (valid!) ePub 2.0 output
|
||||||
|
* Rename .zip files to .cbz to avoid overwriting
|
||||||
|
|
||||||
|
####2.3
|
||||||
|
* Fixed win32 ePub generation, folder handling, filenames with spaces and subfolders
|
||||||
|
|
||||||
|
####2.4
|
||||||
|
* 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
4
kcc.py
@@ -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)
|
||||||
|
|||||||
@@ -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'
|
||||||
@@ -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 rotate:
|
||||||
if options.righttoleft:
|
if options.righttoleft:
|
||||||
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxTL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
|
"'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
|
||||||
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxTR-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
|
"'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":3}'></a></div>\n",
|
||||||
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxBL-Panel-Parent\", \"ordinal\":4}'></a></div>\n",
|
"'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
|
||||||
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
|
||||||
"BoxBR-Panel-Parent\", \"ordinal\":3}'></a></div>\n"
|
"'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":4}'></a></div>\n"
|
||||||
])
|
])
|
||||||
else:
|
else:
|
||||||
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
f.writelines(["<div id=\"BoxTL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxTL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
|
"'{\"targetId\":\"BoxTL-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
|
||||||
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxTR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxTR-Panel-Parent\", \"ordinal\":2}'></a></div>\n",
|
"'{\"targetId\":\"BoxTR-Panel-Parent\", \"ordinal\":4}'></a></div>\n",
|
||||||
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
"BoxBL-Panel-Parent\", \"ordinal\":3}'></a></div>\n",
|
"'{\"targetId\":\"BoxBL-Panel-Parent\", \"ordinal\":1}'></a></div>\n",
|
||||||
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify='{\"targetId\":\"",
|
"<div id=\"BoxBR\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify="
|
||||||
"BoxBR-Panel-Parent\", \"ordinal\":4}'></a></div>\n"
|
"'{\"targetId\":\"BoxBR-Panel-Parent\", \"ordinal\":3}'></a></div>\n"
|
||||||
])
|
])
|
||||||
|
else:
|
||||||
|
if options.righttoleft:
|
||||||
|
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\":1}'></a></div>\n",
|
||||||
|
"<div id=\"BoxBL\"><a class=\"app-amzn-magnify\" data-app-amzn-magnify=",
|
||||||
|
"'{\"targetId\":\"BoxBL-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,14 +328,33 @@ 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:
|
||||||
|
pagenumber += 1
|
||||||
|
work.append([afile, dirpath, pagenumber, options])
|
||||||
|
splitpages = pool.map(fileImgProcess, work)
|
||||||
|
pool.close()
|
||||||
|
pool.join()
|
||||||
|
splitpages = filter(None, splitpages)
|
||||||
|
splitpages.sort()
|
||||||
|
for page in splitpages:
|
||||||
|
if (page + pagenumbermodifier) % 2 == 0:
|
||||||
|
splitCount += 1
|
||||||
|
pagenumbermodifier += 1
|
||||||
|
pagenumbermodifier += 1
|
||||||
|
|
||||||
|
|
||||||
|
def fileImgProcess(work):
|
||||||
|
afile = work[0]
|
||||||
|
dirpath = work[1]
|
||||||
|
pagenumber = work[2]
|
||||||
|
options = work[3]
|
||||||
|
output = None
|
||||||
if options.verbose:
|
if options.verbose:
|
||||||
print "Optimizing " + afile + " for " + options.profile
|
print "Optimizing " + afile + " for " + options.profile
|
||||||
else:
|
else:
|
||||||
@@ -320,34 +364,26 @@ def dirImgProcess(path):
|
|||||||
split = None
|
split = None
|
||||||
else:
|
else:
|
||||||
split = img.splitPage(dirpath, options.righttoleft, options.rotate)
|
split = img.splitPage(dirpath, options.righttoleft, options.rotate)
|
||||||
if split is not None:
|
if split is not None and split is not "R":
|
||||||
if options.verbose:
|
if options.verbose:
|
||||||
print "Splitted " + afile
|
print "Splitted " + afile
|
||||||
if options.righttoleft:
|
if options.righttoleft:
|
||||||
toRight1 = False
|
toRight1 = False
|
||||||
toRight2 = True
|
toRight2 = True
|
||||||
if facing == "left":
|
|
||||||
splitCount += 1
|
|
||||||
facing = "right"
|
|
||||||
else:
|
else:
|
||||||
toRight1 = True
|
toRight1 = True
|
||||||
toRight2 = False
|
toRight2 = False
|
||||||
if facing == "right":
|
output = pagenumber
|
||||||
splitCount += 1
|
|
||||||
facing = "left"
|
|
||||||
img0 = image.ComicPage(split[0], options.profile)
|
img0 = image.ComicPage(split[0], options.profile)
|
||||||
applyImgOptimization(img0, True, toRight1)
|
applyImgOptimization(img0, True, toRight1, options)
|
||||||
img0.saveToDir(dirpath, options.forcepng)
|
img0.saveToDir(dirpath, options.forcepng, options.forcecolor)
|
||||||
img1 = image.ComicPage(split[1], options.profile)
|
img1 = image.ComicPage(split[1], options.profile)
|
||||||
applyImgOptimization(img1, True, toRight2)
|
applyImgOptimization(img1, True, toRight2, options)
|
||||||
img1.saveToDir(dirpath, options.forcepng)
|
img1.saveToDir(dirpath, options.forcepng, options.forcecolor)
|
||||||
else:
|
else:
|
||||||
if facing == "right":
|
applyImgOptimization(img, False, False, options)
|
||||||
facing = "left"
|
img.saveToDir(dirpath, options.forcepng, options.forcecolor, split)
|
||||||
else:
|
return output
|
||||||
facing = "right"
|
|
||||||
applyImgOptimization(img)
|
|
||||||
img.saveToDir(dirpath, options.forcepng)
|
|
||||||
|
|
||||||
|
|
||||||
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/")
|
||||||
|
if options.cbzoutput:
|
||||||
|
# if CBZ output wanted, compress all images and return filepath
|
||||||
|
print "\nCreating CBZ file..."
|
||||||
|
filepath = getOutputFilename(args[0], options.output, '.cbz')
|
||||||
|
make_archive(path + '_comic', 'zip', path + '/OEBPS/Images')
|
||||||
|
else:
|
||||||
print "\nCreating ePub structure..."
|
print "\nCreating ePub structure..."
|
||||||
genEpubStruct(path)
|
genEpubStruct(path)
|
||||||
# actually zip the ePub
|
# actually zip the ePub
|
||||||
if options.output is not None:
|
filepath = getOutputFilename(args[0], options.output, '.epub')
|
||||||
if options.output.endswith('.epub'):
|
|
||||||
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:
|
|
||||||
epubpath = os.path.splitext(args[0])[0] + '.epub'
|
|
||||||
make_archive(path + '_comic', 'zip', path)
|
make_archive(path + '_comic', 'zip', path)
|
||||||
move(path + '_comic.zip', epubpath)
|
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)
|
||||||
|
|||||||
74
kcc/gui.py
74
kcc/gui.py
@@ -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
|
||||||
|
|||||||
32
kcc/image.py
32
kcc/image.py
@@ -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:
|
||||||
|
if not color:
|
||||||
self.image = self.image.convert('L') # convert to grayscale
|
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,6 +237,7 @@ class ComicPage:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def cutPageNumber(self):
|
def cutPageNumber(self):
|
||||||
|
if ImageChops.invert(self.image).getbbox() is not None:
|
||||||
widthImg, heightImg = self.image.size
|
widthImg, heightImg = self.image.size
|
||||||
delta = 2
|
delta = 2
|
||||||
diff = delta
|
diff = delta
|
||||||
@@ -278,6 +291,7 @@ class ComicPage:
|
|||||||
return self.image
|
return self.image
|
||||||
|
|
||||||
def cropWhiteSpace(self, threshold):
|
def cropWhiteSpace(self, threshold):
|
||||||
|
if ImageChops.invert(self.image).getbbox() is not None:
|
||||||
widthImg, heightImg = self.image.size
|
widthImg, heightImg = self.image.size
|
||||||
delta = 10
|
delta = 10
|
||||||
diff = delta
|
diff = delta
|
||||||
|
|||||||
222
kcc/rarfile.py
222
kcc/rarfile.py
@@ -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:
|
:mod:`zipfile`-compatible fields:
|
||||||
|
|
||||||
|
filename
|
||||||
File name with relative path.
|
File name with relative path.
|
||||||
Default path separator is '/', to change set rarfile.PATH_SEP.
|
Default path separator is '\\', to change set rarfile.PATH_SEP.
|
||||||
Always unicode string.
|
Always unicode string.
|
||||||
@ivar date_time:
|
date_time
|
||||||
Modification time, tuple of (year, month, day, hour, minute, second).
|
Modification time, tuple of (year, month, day, hour, minute, second).
|
||||||
Or datetime() object if USE_DATETIME is set.
|
Or datetime() object if USE_DATETIME is set.
|
||||||
@ivar file_size:
|
file_size
|
||||||
Uncompressed size.
|
Uncompressed size.
|
||||||
@ivar compress_size:
|
compress_size
|
||||||
Compressed size.
|
Compressed size.
|
||||||
@ivar compress_type:
|
CRC
|
||||||
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.
|
CRC-32 of uncompressed file, unsigned int.
|
||||||
@ivar volume:
|
comment
|
||||||
|
File comment. Byte string or None. Use UNICODE_COMMENTS
|
||||||
|
to get automatic decoding to unicode.
|
||||||
|
volume
|
||||||
Volume nr, starting from 0.
|
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:
|
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.
|
Optional time field: Modification time, with float seconds.
|
||||||
Same as .date_time but with more precision.
|
Same as .date_time but with more precision.
|
||||||
@ivar ctime:
|
ctime
|
||||||
Optional time field: creation time, with float seconds.
|
Optional time field: creation time, with float seconds.
|
||||||
@ivar atime:
|
atime
|
||||||
Optional time field: last access time, with float seconds.
|
Optional time field: last access time, with float seconds.
|
||||||
@ivar arctime:
|
arctime
|
||||||
Optional time field: archival time, with float seconds.
|
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):
|
||||||
|
|||||||
2
setup.py
2
setup.py
@@ -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']
|
||||||
|
|||||||
@@ -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.",
|
||||||
|
|||||||
Reference in New Issue
Block a user