Commits

Grzegorz Chrupała committed 9024097 Draft

Write a new file instead of overwriting input epub.

Comments (0)

Files changed (2)

+#!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
 import re
 def main():
 	'''Apply unit conversion to all html files found in a zip (i.e. epub) file'''
 	inp = sys.argv[1]
-	modifyzip.modifyZip(inp, lambda f: os.path.splitext(f)[1] == ".html", replaceUnits)
+	out = sys.argv[2]
+	convert = lambda x: replaceUnits(x, logger=sys.stderr)
+	modifyzip.modifyZip(inp, out, \
+		lambda f: os.path.splitext(f)[1] == ".html", convert)
 	
-def replaceUnits(text):
+def replaceUnits(text, logger=None):
 	'''Convert quantities in legacy units to SI units in a text string'''
 	def replace(match):
 		try:
 		sep  = match.group(2)
 		unit = match.group(3)	
 		unit_si, (a, b) = units[unit] 
-		return "%s%s%s" % (prettify(a * x + b), sep, unit_si)		
+		output = "%s%s%s" % (prettify(a * x + b), sep, unit_si)		
+		if logger:
+			logger.write("%s --> %s\n" % (match.group(0), output))
+		return output
 	return re.sub(number_unit, replace, text)
 
 def prettify(n):
 	if whole_pretty == "0": 
 		# Use complete decimal
 		return whole_pretty + "." + decimal
-	elif int(whole) > 1000:
+	elif int(whole) > 100:
 		# Skip the decimal
 		return whole_pretty
 	elif float("0." + decimal) 	== 0:
 import shutil
 import os.path
 
-def modifyZip(zipfname, match, modify):
+def modifyZip(zipfname, outzipfname, match, modify):
   '''Apply transformation _modify_ to all file whose name _match_'''
-    tempdir = tempfile.mkdtemp()
-    try:
-        tempname = os.path.join(tempdir, 'new.zip')
-        with zipfile.ZipFile(zipfname, 'r') as zipread:
-            with zipfile.ZipFile(tempname, 'w') as zipwrite:
-                for item in zipread.infolist():
-                    data = zipread.read(item.filename)                  
-                    if match(item.filename):
-                      f = modify
-                    else:
-                      f = lambda x: x
-                    zipwrite.writestr(item, f(data))
-        shutil.move(tempname, zipfname)
-    finally:
-        shutil.rmtree(tempdir)
+  tempdir = tempfile.mkdtemp()
+  try:
+    tempname = os.path.join(tempdir, 'new.zip')
+    with zipfile.ZipFile(zipfname, 'r') as zipread:
+      with zipfile.ZipFile(tempname, 'w') as zipwrite:
+        for item in zipread.infolist():
+          data = zipread.read(item.filename)                  
+          if match(item.filename):
+            f = modify
+          else:
+            f = lambda x: x
+          zipwrite.writestr(item, f(data))
+    shutil.move(tempname, outzipfname)
+  finally:
+    shutil.rmtree(tempdir)