Skip to content

Instantly share code, notes, and snippets.

@masterdje
Last active December 23, 2015 13:39
Show Gist options
  • Save masterdje/6643474 to your computer and use it in GitHub Desktop.
Save masterdje/6643474 to your computer and use it in GitHub Desktop.
Main Objective : Better graphical ebook reading on strict vertical-reading device, like the Kobo Touch and Kobo Glo
# Open any graphical ebook file ( cbr / cbz),
# and check every pic inside for anything in landscape mode, to cut it in half.
# Then reorder everything, and save the cbr/z as if nothing happened (huh huh)
#
# There are un bunch of more switchs (force b&w render, reverse order (manga anyone ?), jump to page X etc) to play with.
#
# Mangasplit.py is still really -rough to the edge-
# Feel free to improve...
#!/usr/bin/python
from PIL import Image
from subprocess import call
import re
import sys
import string
import random
import os
import zipfile
import shutil
import getopt
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
def verboseprint (level,cvl,text):
#currentverboselevel
if ( cvl >= level ) : print text
return
def conversionbw(filename, convertbw):
if convertbw:
img=Image.open(filename)
img=img.convert('L')
img.save(filename)
return "+ Conversion NB de %s" % filename
else:
return "+ pas de conversion de %s" % filename
def help():
return "mangasplit.py -i <inputfile> -s <startpage> -v <verboselevel> -r <reversemode> -c <convert>"
def main(argv):
inputfile=""
startpage=0
reversemode=False
convertbw=False
cvl=1
try:
opts,args= getopt.getopt(argv,"hi:s:v:rc",["help", "ifile=","startpage=","verboselevel="])
except getopt.GetoptError:
verboseprint(0,cvl, help())
for opt, arg in opts:
if opt in ('-h','--help'):
verboseprint(0,cvl, help())
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-s","--startpage"):
startpage = int(arg)
elif opt in ("-v","--verboselevel"):
cvl = int(arg)
elif opt in ("-r","--reversemode"):
reversemode = True
elif opt in ("-c","--convert"):
convertbw = True
else:
verboseprint(0,cvl, help())
sys.exit(2)
#check du fichier source
if not os.path.isfile(inputfile):
verboseprint(0,cvl,"<!> Fichier non trouve : %s" % inputfile) ;
verboseprint(0,cvl, help())
sys.exit(2)
#check du fichier zip/cbz
fullpathfile = os.path.abspath(inputfile)
if zipfile.is_zipfile(fullpathfile):
z = zipfile.ZipFile(fullpathfile)
else:
verboseprint(0,cvl,"<!> Fichier cbz non valide : %s" % inputfile) ;
verboseprint(0,cvl,"<!> Essai de unrar : %s" % inputfile) ;
os.system("unrar x %s" %inputfile)
#variable = "CF_tome_03_017_scanddl.com.jpg"
#regex re.compile('[0-9]{2,5}')
#regex = re.search('[0-9]{3sud,5}',variable)
#if regex:
# print "variable : " , variable
# print "donc : ", regex.group()
sys.exit(2)
#print inputfile[:-4]
[a,b]=[1,2]
if reversemode:[a,b]=[b,a]
prefix= inputfile[:5]
verboseprint(1,cvl, "! Start")
verboseprint(2,cvl, "+ Creation du dossier temp - %s" % rndfolder)
makemydir(rndfolder)
verboseprint(2,cvl, "+->Creation ok")
verboseprint(2,cvl, "+ Extraction de %s" % inputfile)
z.extractall(rndfolder)
verboseprint(2,cvl, "+-> Extraction de ok")
os.chdir(rndfolder)
for dirname, dirnames, filenames in os.walk('.'):
for filename in filenames:
verboseprint(1,cvl, "+ Traitement - %s" % os.path.join(dirname, filename))
#test du convertbw
verboseprint(1,cvl,conversionbw(os.path.join(dirname, filename),convertbw))
#test du startpage
#a attraper si y a pas de compteur !
try:
#mega test de la mort
obvious_string = int(filename[-7:-4])
if (int(filename[-7:-4]) <= startpage):
verboseprint(2,cvl, "+--Image non decoupee")
ficname = prefix+str(filename[-7:-4]) +"0" +".jpg"
os.rename(os.path.join(dirname, filename), ficname)
verboseprint(2,cvl, "+->Sauvegarde - %s" % ficname)
verboseprint(1,cvl, "+ Rajout a l'archive - %s" % ficname)
with zipfile.ZipFile(racine + rndarchive, 'a') as myzip:
myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep +os.path.join(ficname),zipfile.ZIP_DEFLATED)
#myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep +os.path.join(ficname),zipfile.ZIP_DEFLATED)
verboseprint(2,cvl, "+->Rajout ok")
else:
img = Image.open(os.path.join(dirname, filename))
width, height = img.size
if (width > height) :
verboseprint(2,cvl, "+--Infos : Paysage | W : %i px H : %i px" %( width , height))
box = (0, 0, width/2, height)
area = img.crop(box)
ficname = prefix+str(filename[-7:-4]) +str(a)+ ".jpg"
area.save(ficname, 'jpeg')
verboseprint(2,cvl, "+->Sauvegarde - %s" % ficname)
verboseprint(1,cvl, "+ Rajout a l'archive - %s" % ficname)
with zipfile.ZipFile(racine + rndarchive, 'a') as myzip:
myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep +os.path.join(ficname),zipfile.ZIP_DEFLATED)
verboseprint(2,cvl, "+->Rajout ok")
box = (width/2, 0, width, height)
area = img.crop(box)
ficname = prefix+str(filename[-7:-4]) +str(b) + ".jpg"
area.save(ficname, 'jpeg')
verboseprint(2,cvl, "+->Sauvegarde - %s" % ficname)
verboseprint(1,cvl, "+ Rajout a l'archive - %s" % ficname)
with zipfile.ZipFile(racine + rndarchive, 'a') as myzip:
#myzip.write(os.path.join(ficname))
myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep +os.path.join(ficname),zipfile.ZIP_DEFLATED)
verboseprint(2,cvl, "+->Rajout ok")
else:
verboseprint(2,cvl, "+--Infos : Portrait | W : %i px H : %i px" %( width , height))
ficname = prefix+str(filename[-7:-4]) +"0" +".jpg"
os.rename(os.path.join(dirname, filename), ficname)
verboseprint(2,cvl, "+->Sauvegarde - %s" % ficname)
verboseprint(1,cvl, "+ Rajout a l'archive - %s" % ficname)
with zipfile.ZipFile(racine + rndarchive, 'a') as myzip:
#myzip.write(os.path.join(ficname))
myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep + os.path.join(ficname),zipfile.ZIP_DEFLATED)
verboseprint(2,cvl, "+->Rajout ok")
except ValueError:
verboseprint(2,cvl, "+->Sauvegarde - %s" % filename)
verboseprint(1,cvl, "+ Rajout a l'archive - %s" % filename)
with zipfile.ZipFile(racine + rndarchive, 'a') as myzip:
myzip.write(os.path.join(dirname, filename),inputfile[:-4] + os.path.sep + os.path.join(filename),zipfile.ZIP_DEFLATED)
#myzip.write(os.path.join(ficname),inputfile[:-4] + os.path.sep +os.path.join(ficname),zipfile.ZIP_DEFLATED)
verboseprint(2,cvl, "+->Rajout ok")
#renommer le fichier d'orgine
os.rename(fullpathfile,racine + "old_"+inputfile)
#renommer l'archive en fichier d'origine
os.rename(racine + rndarchive,fullpathfile[:-4]+".cbz")
#regex re.compile('[0-9]{2,5}')
#re.search(variable)
os.chdir(racine)
verboseprint(2,cvl, "+ Suppression du dossier temp - %s" % rndfolder)
shutil.rmtree(rndfolder)
verboseprint(2,cvl, "+->Suppression ok")
verboseprint(1,cvl, "! End")
racine= os.getcwd() + "/"
rndfolder = os.getcwd() + "/" + id_generator()
rndarchive = id_generator()
retval = os.getcwd()
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment