Commits

Jameel Haffejee  committed 7708486

Initial Checkin for the convertor and the Progress Bar add on

  • Participants

Comments (0)

Files changed (2)

File buildKindleComic.py

+#!/usr/bin/env python
+
+#The rar library used in this project can be found @ http://pypi.python.org/pypi/rarfile/2.2
+
+import os
+import sys
+import glob
+import shutil
+import time
+
+from rarfile import *
+from zipfile import *
+from pyPdf import PdfFileWriter, PdfFileReader
+import Image
+from progress_bar import ProgressBar
+
+def validateComicStructure(comic):
+	'''
+		Do a quick check to make sure we have a dir to work with
+		This prevents files from lying in the root folder
+	'''
+	files = comic.namelist()
+	files.sort()	
+	dirCheck = files[len(files) -1]
+	#This handles dir with a dir option that would otherwise be missed
+	if dirCheck.find('\\') != -1:
+		return True
+
+	for page in files:
+		if page.find(dirCheck) == -1:
+			return False
+
+	return True
+
+def extractFile(comicFileName,fileExtension):
+	''' Extracts all the images from a rar/cbr file '''
+	if comicFileName.endswith('.cbz'):
+		comic = ZipFile(comicFileName)
+	else:
+		comic = RarFile(comicFileName)
+
+	if not validateComicStructure(comic):
+		cleanComicName = comicFileName.replace(fileExtension,"")
+		os.mkdir(cleanComicName)
+		extractedFolder = cleanComicName
+		comic.extractall(path=extractedFolder)
+	else:
+		files = comic.namelist()
+		comic.extractall()
+		extractedFolder = files[len(files) -1]
+		if extractedFolder.find('\\') != -1:
+			extractedFolder = extractedFolder[:extractedFolder.find('\\')]
+			 
+
+	comic.close()
+	return extractedFolder
+
+def compilePdfFile(directory,originalFileName,fileExtension):
+	''' Compiles a directory containing kindle formated image files into a single pdf '''
+	#Need to add alot of error checking here , so much can go wrong , also remove extensions from the original files
+	filesToCompile = glob.glob('kindle*.pdf')
+	filesToCompile.sort()
+
+	output = PdfFileWriter()
+
+	for kindleFile in filesToCompile:
+		if kindleFile.startswith('kindle'):
+			input1 = PdfFileReader(file(kindleFile, "rb"))
+			output.addPage(input1.getPage(0))
+			os.remove(kindleFile)	
+
+	outputStream = file(originalFileName.replace(fileExtension,".pdf"), "wb")
+
+	output.write(outputStream)
+	try:
+		shutil.move(originalFileName.replace(fileExtension,".pdf"),'..')
+	except Exception:
+		print 'File Already Exists will not overwrite please remove manually ' + originalFileName.replace('.cbr',".pdf")
+
+def formatImageForKindle(fileName):
+	''' Formats a image for the kindle ,this mostly involes resizing the image '''
+	im1 = Image.open(fileName)
+	resizedImage = im1.resize((600, 800), Image.ANTIALIAS)
+	resizedImage.save("kindle_"+fileName+".pdf")
+
+def processComics(filterType,fileExtension):
+	''' Check that we have a dir to scan provided '''
+	dirList = glob.glob(filterType)
+	dirList.sort()
+	for comic in dirList:
+		extractedFolder = extractFile(comic,fileExtension)
+		os.chdir(extractedFolder)
+		comicPages = os.listdir('.') 
+		comicPages.sort()
+		
+		if len(comicPages) > 0:
+			comicName = comic.replace(fileExtension,".pdf")
+			print 'Compiling ' + comicName
+			pageCount = 1
+			p = ProgressBar(len(comicPages))
+			for page in comicPages:
+				#Make sure we end in a picture format or we have more problems
+				if page.endswith('jpg') or page.endswith('png'):
+					pageCount += 1
+					p.update_time(pageCount)
+					formatImageForKindle(page)
+					os.system('clear')
+					print 'Compiling '+ comicName
+					print p
+					#print 'Formated : ' + page
+			
+				
+			compilePdfFile(os.path.abspath('.'),comic,fileExtension)	
+			
+			print 'PDF File Compiled ' + comic.replace(fileExtension,".pdf")
+			os.chdir('..')
+			shutil.rmtree(extractedFolder)
+		else:
+			print 'Nothing Extracted'
+
+
+def main():
+	comics = glob.glob('*.cbr')
+	comics += glob.glob('*.cbz')
+	print 'The Following Comics Will be processed'
+	for comic in comics:
+		print comic
+
+	decision = raw_input('Do you want to continue ? (Y/n)')
+	if decision == 'y' or decision == '':
+		#First Handle CBR's then CBZ's
+		processComics('*.cbr','.cbr')	
+		processComics('*.cbz','.cbz')	
+
+if __name__ == "__main__":
+    main()
+

File progress_bar.py

+#!/usr/bin/env python
+#
+#  Corey Goldberg - 2010
+#  ascii command-line progress bar with percentage and elapsed time display
+# 
+
+
+"""
+example output:
+
+
+$ python progress_bar.py 
+
+static progress bar:
+[##########       25%                  ]  15s/60s
+
+static progress bar:
+[=================83%============      ]  25s/30s
+
+
+dynamic updating progress bar:
+
+please wait 10 seconds...
+
+[################100%##################]  10s/10s
+done
+
+"""
+
+class ProgressBar:
+    def __init__(self, duration):
+        self.duration = duration
+        self.prog_bar = '[]'
+        self.fill_char = '#'
+        self.width = 40
+        self.__update_amount(0)
+    
+    def __update_amount(self, new_amount):
+        percent_done = int(round((new_amount / 100.0) * 100.0))
+        all_full = self.width - 2
+        num_hashes = int(round((percent_done / 100.0) * all_full))
+        self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
+        pct_place = (len(self.prog_bar) / 2) - len(str(percent_done))
+        pct_string = '%d%%' % percent_done
+        self.prog_bar = self.prog_bar[0:pct_place] + \
+            (pct_string + self.prog_bar[pct_place + len(pct_string):])
+        
+    def update_time(self, elapsed_secs):
+        self.__update_amount((elapsed_secs / float(self.duration)) * 100.0)
+        self.prog_bar += '  %d/%s' % (elapsed_secs, self.duration)
+        
+    def __str__(self):
+        return str(self.prog_bar)
+        
+        
+        
+if __name__ == '__main__':
+    # example usage
+    
+    import sys
+    import time
+    
+    
+    # print a static progress bar
+    #  [##########       25%                  ]  15s/60s
+
+    p = ProgressBar(60)
+    p.update_time(15)
+    print '\nstatic progress bar:'
+    print p
+    
+    
+    # print a static progress bar
+    #  [=================83%============      ]  25s/30s
+
+    p = ProgressBar(30)
+    p.fill_char = '='
+    p.update_time(25)
+    print '\nstatic progress bar:'
+    print p
+    
+    
+    # print a dynamic updating progress bar on one line:
+    #
+    #  [################100%##################]  10s/10s
+    #  done
+    
+    secs = 10
+    p = ProgressBar(secs)
+    print '\n\ndynamic updating progress bar:'
+    print '\nplease wait %d seconds...\n' % secs
+    
+    # spawn threaded or multiprocessed code here that runs for secs
+    
+    for i in range(secs):
+        if sys.platform.startswith('win'):
+            print p, '\r',
+        else:
+            print p, chr(27) + '[A'
+        p.update_time(i + 1)
+        time.sleep(1) 
+    print p
+    print 'done'
+