diff --git a/plugins/python/comics_project_management_tools/comics_exporter.py b/plugins/python/comics_project_management_tools/comics_exporter.py index 9d9856f9b4..a75d4cbf3f 100644 --- a/plugins/python/comics_project_management_tools/comics_exporter.py +++ b/plugins/python/comics_project_management_tools/comics_exporter.py @@ -1,647 +1,647 @@ """ Copyright (c) 2017 Wolthera van Hövell tot Westerflier This file is part of the Comics Project Management Tools(CPMT). CPMT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CPMT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the CPMT. If not, see . """ """ An exporter that take the comicsConfig and uses it to generate several files. """ import sys from pathlib import Path import zipfile from xml.dom import minidom from xml.etree import ElementTree as ET import types import re from PyQt5.QtWidgets import QLabel, QProgressDialog, QMessageBox, qApp # For the progress dialog. from PyQt5.QtCore import QElapsedTimer, QLocale, Qt, QRectF, QPointF from PyQt5.QtGui import QImage, QTransform, QPainterPath, QFontMetrics, QFont from krita import * from . import exporters """ The sizesCalculator is a convenience class for interpretting the resize configuration from the export settings dialog. It is also used for batch resize. """ class sizesCalculator(): def __init__(self): pass def get_scale_from_resize_config(self, config, listSizes): listScaleTo = listSizes oldWidth = listSizes[0] oldHeight = listSizes[1] oldXDPI = listSizes[2] oldYDPI = listSizes[3] if "Method" in config.keys(): method = config["Method"] if method is 0: # percentage percentage = config["Percentage"] / 100 listScaleTo[0] = round(oldWidth * percentage) listScaleTo[1] = round(oldHeight * percentage) if method is 1: # dpi DPI = config["DPI"] listScaleTo[0] = round((oldWidth / oldXDPI) * DPI) listScaleTo[1] = round((oldHeight / oldYDPI) * DPI) listScaleTo[2] = DPI listScaleTo[3] = DPI if method is 2: # maximum width width = config["Width"] listScaleTo[0] = width listScaleTo[1] = round((oldHeight / oldWidth) * width) if method is 3: # maximum height height = config["Height"] listScaleTo[1] = height listScaleTo[0] = round((oldWidth / oldHeight) * height) return listScaleTo """ The comicsExporter is a class that batch exports to all the requested formats. Make it, set_config with the right data, and then call up "export". The majority of the functions are meta-data encoding functions. """ class comicsExporter(): acbfLocation = str() acbfPageData = [] cometLocation = str() comicRackInfo = str() pagesLocationList = {} # set of keys used to define specific export behaviour for this page. pageKeys = ["acbf_title", "acbf_none", "acbf_fade", "acbf_blend", "acbf_horizontal", "acbf_vertical"] def __init__(self): pass """ The the configuration of the exporter. @param config: A dictionary containing all the config. @param projectUrl: the main location of the project folder. """ def set_config(self, config, projectURL): self.configDictionary = config self.projectURL = projectURL self.pagesLocationList = {} self.acbfLocation = str() self.acbfPageData = [] self.cometLocation = str() self.comicRackInfo = str() """ Export everything according to config and get yourself a coffee. This won't work if the config hasn't been set. """ def export(self): export_success = False path = Path(self.projectURL) if path.exists(): # Make a meta-data folder so we keep the export folder nice and clean. exportPath = path / self.configDictionary["exportLocation"] if Path(exportPath / "metadata").exists() is False: Path(exportPath / "metadata").mkdir() # Get to which formats to export, and set the sizeslist. lengthProcess = len(self.configDictionary["pages"]) sizesList = {} if "CBZ" in self.configDictionary.keys(): if self.configDictionary["CBZactive"]: lengthProcess += 5 sizesList["CBZ"] = self.configDictionary["CBZ"] if "EPUB" in self.configDictionary.keys(): if self.configDictionary["EPUBactive"]: lengthProcess += 1 sizesList["EPUB"] = self.configDictionary["EPUB"] if "TIFF" in self.configDictionary.keys(): if self.configDictionary["TIFFactive"]: sizesList["TIFF"] = self.configDictionary["TIFF"] # Export the pngs according to the sizeslist. # Create a progress dialog. self.progress = QProgressDialog(i18n("Preparing export."), str(), 0, lengthProcess) self.progress.setWindowTitle(i18n("Exporting Comic...")) self.progress.setCancelButton(None) self.timer = QElapsedTimer() self.timer.start() self.progress.show() qApp.processEvents() export_success = self.save_out_pngs(sizesList) # Export acbf metadata. if export_success: if "CBZ" in sizesList.keys(): title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): - title = self.configDictionary["title"] + title = str(self.configDictionary["title"]).replace(" ", "_") self.acbfLocation = str(exportPath / "metadata" / str(title + ".acbf")) locationStandAlone = str(exportPath / str(title + ".acbf")) self.progress.setLabelText(i18n("Saving out ACBF and\nACBF standalone")) self.progress.setValue(self.progress.value()+2) export_success = exporters.ACBF.write_xml(self.configDictionary, self.acbfPageData, self.pagesLocationList["CBZ"], self.acbfLocation, locationStandAlone, self.projectURL) print("CPMT: Exported to ACBF", export_success) # Export and package CBZ and Epub. if export_success: if "CBZ" in sizesList.keys(): export_success = self.export_to_cbz(exportPath) print("CPMT: Exported to CBZ", export_success) if "EPUB" in sizesList.keys(): self.progress.setLabelText(i18n("Saving out EPUB")) self.progress.setValue(self.progress.value()+1) export_success = exporters.EPUB.export(self.configDictionary, self.projectURL, self.pagesLocationList["EPUB"]) print("CPMT: Exported to EPUB", export_success) else: QMessageBox.warning(self, i18n("Export not Possible"), i18n("Nothing to export, URL not set."), QMessageBox.Ok) print("CPMT: Nothing to export, url not set.") return export_success """ This calls up all the functions necessary for making a cbz. """ def export_to_cbz(self, exportPath): title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): - title = self.configDictionary["title"] + title = str(self.configDictionary["title"]).replace(" ", "_") self.progress.setLabelText(i18n("Saving out CoMet\nmetadata file")) self.progress.setValue(self.progress.value()+1) self.cometLocation = str(exportPath / "metadata" / str(title + " CoMet.xml")) export_success = exporters.CoMet.write_xml(self.configDictionary, self.pagesLocationList["CBZ"], self.cometLocation) self.comicRackInfo = str(exportPath / "metadata" / "ComicInfo.xml") self.progress.setLabelText(i18n("Saving out Comicrack\nmetadata file")) self.progress.setValue(self.progress.value()+1) export_success = exporters.comic_rack_xml.write_xml(self.configDictionary, self.pagesLocationList["CBZ"], self.comicRackInfo) self.package_cbz(exportPath) return export_success def save_out_pngs(self, sizesList): # A small fix to ensure crop to guides is set. if "cropToGuides" not in self.configDictionary.keys(): self.configDictionary["cropToGuides"] = False # Check if we have pages at all... if "pages" in self.configDictionary.keys(): # Check if there's export methods, and if so make sure the appropriate dictionaries are initialised. if len(sizesList.keys()) < 1: print("CPMT: Export failed because there's no export methods set.") return False else: for key in sizesList.keys(): self.pagesLocationList[key] = [] # Get the appropriate paths. path = Path(self.projectURL) exportPath = path / self.configDictionary["exportLocation"] pagesList = self.configDictionary["pages"] fileName = str(exportPath) """ Mini function to handle the setup of this string. """ def timeString(timePassed, timeEstimated): return str(i18n("Time passed: {passedString}\n Estimated: {estimated}")).format(passedString=timePassed, estimated=timeEstimated) for p in range(0, len(pagesList)): pagesDone = str(i18n("{pages} of {pagesTotal} done.")).format(pages=p, pagesTotal=len(pagesList)) # Update the label in the progress dialog. self.progress.setValue(p) timePassed = self.timer.elapsed() if p > 0: timeEstimated = (len(pagesList) - p) * (timePassed / p) estimatedString = self.parseTime(timeEstimated) else: estimatedString = str(u"\u221E") passedString = self.parseTime(timePassed) self.progress.setLabelText("\n".join([pagesDone, timeString(passedString, estimatedString), i18n("Opening next page")])) qApp.processEvents() # Get the appropriate url and open the page. url = str(Path(self.projectURL) / pagesList[p]) page = Application.openDocument(url) page.waitForDone() # Update the progress bar a little self.progress.setLabelText("\n".join([pagesDone, timeString(self.parseTime(self.timer.elapsed()), estimatedString), i18n("Cleaning up page")])) # remove layers and flatten. labelList = self.configDictionary["labelsToRemove"] panelsAndText = [] # These three lines are what is causing the page not to close. root = page.rootNode() self.getPanelsAndText(root, panelsAndText) self.removeLayers(labelList, root) page.refreshProjection() # We'll need the offset and scale for aligning the panels and text correctly. We're getting this from the CBZ pageData = {} pageData["vector"] = panelsAndText tree = ET.fromstring(page.documentInfo()) pageData["title"] = page.name() calligra = "{http://www.calligra.org/DTD/document-info}" about = tree.find(calligra + "about") keywords = about.find(calligra + "keyword") keys = str(keywords.text).split(",") pKeys = [] for key in keys: if key in self.pageKeys: pKeys.append(key) pageData["keys"] = pKeys page.flatten() page.waitForDone() batchsave = Application.batchmode() Application.setBatchmode(True) # Start making the format specific copy. for key in sizesList.keys(): # Update the progress bar a little self.progress.setLabelText("\n".join([pagesDone, timeString(self.parseTime(self.timer.elapsed()), estimatedString), str(i18n("Exporting for {key}")).format(key=key)])) w = sizesList[key] # copy over data projection = page.clone() projection.setBatchmode(True) # Crop. Cropping per guide only happens if said guides have been found. if w["Crop"] is True: listHGuides = [] listHGuides = page.horizontalGuides() listHGuides.sort() for i in range(len(listHGuides) - 1, 0, -1): if listHGuides[i] < 0 or listHGuides[i] > page.height(): listHGuides.pop(i) listVGuides = page.verticalGuides() listVGuides.sort() for i in range(len(listVGuides) - 1, 0, -1): if listVGuides[i] < 0 or listVGuides[i] > page.width(): listVGuides.pop(i) if self.configDictionary["cropToGuides"] and len(listVGuides) > 1: cropx = listVGuides[0] cropw = listVGuides[-1] - cropx else: cropx = self.configDictionary["cropLeft"] cropw = page.width() - self.configDictionary["cropRight"] - cropx if self.configDictionary["cropToGuides"] and len(listHGuides) > 1: cropy = listHGuides[0] croph = listHGuides[-1] - cropy else: cropy = self.configDictionary["cropTop"] croph = page.height() - self.configDictionary["cropBottom"] - cropy projection.crop(cropx, cropy, cropw, croph) projection.waitForDone() qApp.processEvents() # resize appropriately else: cropx = 0 cropy = 0 res = page.resolution() listScales = [projection.width(), projection.height(), res, res] projectionOldSize = [projection.width(), projection.height()] sizesCalc = sizesCalculator() listScales = sizesCalc.get_scale_from_resize_config(config=w, listSizes=listScales) projection.unlock() projection.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic") projection.waitForDone() qApp.processEvents() # png, gif and other webformats should probably be in 8bit srgb at maximum. if key != "TIFF": if (projection.colorModel() != "RGBA" and projection.colorModel() != "GRAYA") or projection.colorDepth() != "U8": projection.setColorSpace("RGBA", "U8", "sRGB built-in") else: # Tiff on the other hand can handle all the colormodels, but can only handle integer bit depths. # Tiff is intended for print output, and 16 bit integer will be sufficient. if projection.colorDepth() != "U8" or projection.colorDepth() != "U16": projection.setColorSpace(page.colorModel(), "U16", page.colorProfile()) # save # Make sure the folder name for this export exists. It'll allow us to keep the # export folders nice and clean. folderName = str(key + "-" + w["FileType"]) if Path(exportPath / folderName).exists() is False: Path.mkdir(exportPath / folderName) # Get a nice and descriptive fle name. fn = str(Path(exportPath / folderName) / str("page_" + format(p, "03d") + "_" + str(listScales[0]) + "x" + str(listScales[1]) + "." + w["FileType"])) # Finally save and add the page to a list of pages. This will make it easy for the packaging function to # find the pages and store them. projection.exportImage(fn, InfoObject()) projection.waitForDone() qApp.processEvents() if key == "CBZ": transform = {} transform["offsetX"] = cropx transform["offsetY"] = cropy transform["resDiff"] = page.resolution() / 72 transform["scaleWidth"] = projection.width() / projectionOldSize[0] transform["scaleHeight"] = projection.height() / projectionOldSize[1] pageData["transform"] = transform self.pagesLocationList[key].append(fn) projection.close() self.acbfPageData.append(pageData) page.close() self.progress.setValue(len(pagesList)) Application.setBatchmode(batchsave) # TODO: Check what or whether memory leaks are still caused and otherwise remove the entry below. print("CPMT: Export has finished. If there are memory leaks, they are caused by file layers.") return True print("CPMT: Export not happening because there aren't any pages.") QMessageBox.warning(self, i18n("Export not Possible"), i18n("Export not happening because there are no pages."), QMessageBox.Ok) return False """ Function to get the panel and text data. """ def getPanelsAndText(self, node, list): textLayersToSearch = ["text"] panelLayersToSearch = ["panels"] if "textLayerNames" in self.configDictionary.keys(): textLayersToSearch = self.configDictionary["textLayerNames"] if "panelLayerNames" in self.configDictionary.keys(): panelLayersToSearch = self.configDictionary["panelLayerNames"] if node.type() == "vectorlayer": for name in panelLayersToSearch: if str(name).lower() in str(node.name()).lower(): for shape in node.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list) else: self.handleShapeDescription(shape, list) for name in textLayersToSearch: if str(name).lower() in str(node.name()).lower(): for shape in node.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list, True) else: self.handleShapeDescription(shape, list, True) else: if node.childNodes(): for child in node.childNodes(): self.getPanelsAndText(node=child, list=list) def parseTime(self, time = 0): timeList = [] timeList.append(str(int(time / 60000))) timeList.append(format(int((time%60000) / 1000), "02d")) timeList.append(format(int(time % 1000), "03d")) return ":".join(timeList) """ Function to get the panel and text data from a group shape """ def getPanelsAndTextVector(self, group, list, textOnly=False): for shape in group.shapes(): if (shape.type() == "groupshape"): self.getPanelsAndTextVector(shape, list, textOnly) else: self.handleShapeDescription(shape, list, textOnly) """ Function to get text and panels in a format that acbf will accept """ def handleShapeDescription(self, shape, list, textOnly=False): if (shape.type() != "KoSvgTextShapeID" and textOnly is True): return shapeDesc = {} shapeDesc["name"] = shape.name() rect = shape.boundingBox() listOfPoints = [rect.topLeft(), rect.topRight(), rect.bottomRight(), rect.bottomLeft()] shapeDoc = minidom.parseString(shape.toSvg()) docElem = shapeDoc.documentElement svgRegExp = re.compile('[MLCSQHVATmlzcqshva]\d+\.?\d* \d+\.?\d*') transform = docElem.getAttribute("transform") coord = [] adjust = QTransform() # TODO: If we get global transform api, use that instead of parsing manually. if "translate" in transform: transform = transform.replace('translate(', '') for c in transform[:-1].split(" "): coord.append(float(c)) if len(coord) < 2: coord.append(coord[0]) adjust = QTransform(1, 0, 0, 1, coord[0], coord[1]) if "matrix" in transform: transform = transform.replace('matrix(', '') for c in transform[:-1].split(" "): coord.append(float(c)) adjust = QTransform(coord[0], coord[1], coord[2], coord[3], coord[4], coord[5]) path = QPainterPath() if docElem.localName == "path": dVal = docElem.getAttribute("d") listOfSvgStrings = [" "] listOfSvgStrings = svgRegExp.findall(dVal) if listOfSvgStrings: listOfPoints = [] for l in listOfSvgStrings: line = l[1:] coordinates = line.split(" ") if len(coordinates) < 2: coordinates.append(coordinates[0]) x = float(coordinates[-2]) y = float(coordinates[-1]) offset = QPointF() if l.islower(): offset = listOfPoints[0] if l.lower().startswith("m"): path.moveTo(QPointF(x, y) + offset) elif l.lower().startswith("h"): y = listOfPoints[-1].y() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("v"): x = listOfPoints[-1].x() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("c"): path.cubicTo(coordinates[0], coordinates[1], coordinates[2], coordinates[3], x, y) else: path.lineTo(QPointF(x, y) + offset) path.setFillRule(Qt.WindingFill) for polygon in path.simplified().toSubpathPolygons(adjust): for point in polygon: listOfPoints.append(point) elif docElem.localName == "rect": listOfPoints = [] if (docElem.hasAttribute("x")): x = float(docElem.getAttribute("x")) else: x = 0 if (docElem.hasAttribute("y")): y = float(docElem.getAttribute("y")) else: y = 0 w = float(docElem.getAttribute("width")) h = float(docElem.getAttribute("height")) path.addRect(QRectF(x, y, w, h)) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "ellipse": listOfPoints = [] if (docElem.hasAttribute("cx")): x = float(docElem.getAttribute("cx")) else: x = 0 if (docElem.hasAttribute("cy")): y = float(docElem.getAttribute("cy")) else: y = 0 ry = float(docElem.getAttribute("ry")) rx = float(docElem.getAttribute("rx")) path.addEllipse(QPointF(x, y), rx, ry) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "text": # NOTE: This only works for horizontal preformated text. Vertical text needs a different # ordering of the rects, and wraparound should try to take the shape it is wrapped in. family = "sans-serif" if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") size = "11" if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") multilineText = True for el in docElem.childNodes: if el.nodeType == minidom.Node.TEXT_NODE: multilineText = False if multilineText: listOfPoints = [] listOfRects = [] # First we collect all the possible line-rects. for el in docElem.childNodes: if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") fontsize = int(size) font = QFont(family, fontsize) string = el.toxml() string = re.sub("\<.*?\>", " ", string) string = string.replace(" ", " ") width = min(QFontMetrics(font).width(string.strip()), rect.width()) height = QFontMetrics(font).height() anchor = "start" if docElem.hasAttribute("text-anchor"): anchor = docElem.getAttribute("text-anchor") top = rect.top() if len(listOfRects)>0: top = listOfRects[-1].bottom() if anchor == "start": spanRect = QRectF(rect.left(), top, width, height) listOfRects.append(spanRect) elif anchor == "end": spanRect = QRectF(rect.right()-width, top, width, height) listOfRects.append(spanRect) else: # Middle spanRect = QRectF(rect.center().x()-(width*0.5), top, width, height) listOfRects.append(spanRect) # Now we have all the rects, we can check each and draw a # polygon around them. heightAdjust = (rect.height()-(listOfRects[-1].bottom()-rect.top()))/len(listOfRects) for i in range(len(listOfRects)): span = listOfRects[i] addtionalHeight = i*heightAdjust if i == 0: listOfPoints.append(span.topLeft()) listOfPoints.append(span.topRight()) else: if listOfRects[i-1].width()< span.width(): listOfPoints.append(QPointF(span.right(), span.top()+addtionalHeight)) listOfPoints.insert(0, QPointF(span.left(), span.top()+addtionalHeight)) else: bottom = listOfRects[i-1].bottom()+addtionalHeight-heightAdjust listOfPoints.append(QPointF(listOfRects[i-1].right(), bottom)) listOfPoints.insert(0, QPointF(listOfRects[i-1].left(), bottom)) listOfPoints.append(QPointF(span.right(), rect.bottom())) listOfPoints.insert(0, QPointF(span.left(), rect.bottom())) path = QPainterPath() path.moveTo(listOfPoints[0]) for p in range(1, len(listOfPoints)): path.lineTo(listOfPoints[p]) path.closeSubpath() listOfPoints = [] for point in path.toFillPolygon(adjust): listOfPoints.append(point) shapeDesc["boundingBox"] = listOfPoints if (shape.type() == "KoSvgTextShapeID" and textOnly is True): shapeDesc["text"] = shape.toSvg() list.append(shapeDesc) """ Function to remove layers when they have the given labels. If not, but the node does have children, check those too. """ def removeLayers(self, labels, node): if node.colorLabel() in labels: node.remove() else: if node.childNodes(): for child in node.childNodes(): self.removeLayers(labels, node=child) """ package cbz puts all the meta-data and relevant files into an zip file ending with ".cbz" """ def package_cbz(self, exportPath): # Use the project name if there's no title to avoid sillyness with unnamed zipfiles. title = self.configDictionary["projectName"] if "title" in self.configDictionary.keys(): - title = self.configDictionary["title"] + title = str(self.configDictionary["title"]).replace(" ", "_") # Get the appropriate path. url = str(exportPath / str(title + ".cbz")) # Create a zip file. cbzArchive = zipfile.ZipFile(url, mode="w", compression=zipfile.ZIP_STORED) # Add all the meta data files. cbzArchive.write(self.acbfLocation, Path(self.acbfLocation).name) cbzArchive.write(self.cometLocation, Path(self.cometLocation).name) cbzArchive.write(self.comicRackInfo, Path(self.comicRackInfo).name) comic_book_info_json_dump = str() self.progress.setLabelText(i18n("Saving out Comicbook\ninfo metadata file")) self.progress.setValue(self.progress.value()+1) comic_book_info_json_dump = exporters.comic_book_info.writeJson(self.configDictionary) cbzArchive.comment = comic_book_info_json_dump.encode("utf-8") # Add the pages. if "CBZ" in self.pagesLocationList.keys(): for page in self.pagesLocationList["CBZ"]: if (Path(page).exists()): cbzArchive.write(page, Path(page).name) self.progress.setLabelText(i18n("Packaging CBZ")) self.progress.setValue(self.progress.value()+1) # Close the zip file when done. cbzArchive.close() diff --git a/plugins/python/comics_project_management_tools/exporters/CPMT_ACBF_XML_Exporter.py b/plugins/python/comics_project_management_tools/exporters/CPMT_ACBF_XML_Exporter.py index 625650e7db..2c9b3dd78c 100644 --- a/plugins/python/comics_project_management_tools/exporters/CPMT_ACBF_XML_Exporter.py +++ b/plugins/python/comics_project_management_tools/exporters/CPMT_ACBF_XML_Exporter.py @@ -1,797 +1,802 @@ """ Copyright (c) 2018 Wolthera van Hövell tot Westerflier This file is part of the Comics Project Management Tools(CPMT). CPMT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CPMT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the CPMT. If not, see . """ """ Write the Advanced Comic Book Data xml file. http://acbf.wikia.com/wiki/ACBF_Specifications """ import os import re from PyQt5.QtCore import QDate, Qt, QPointF, QByteArray, QBuffer from PyQt5.QtGui import QImage, QColor, QFont, QRawFont from PyQt5.QtXml import QDomDocument, QDomElement, QDomText, QDomNodeList from . import CPMT_po_parser as po_parser def write_xml(configDictionary = {}, pageData = [], pagesLocationList = [], locationBasic = str(), locationStandAlone = str(), projectUrl = str()): acbfGenreList = ["science_fiction", "fantasy", "adventure", "horror", "mystery", "crime", "military", "real_life", "superhero", "humor", "western", "manga", "politics", "caricature", "sports", "history", "biography", "education", "computer", "religion", "romance", "children", "non-fiction", "adult", "alternative", "other", "artbook"] acbfAuthorRolesList = ["Writer", "Adapter", "Artist", "Penciller", "Inker", "Colorist", "Letterer", "Cover Artist", "Photographer", "Editor", "Assistant Editor", "Translator", "Other", "Designer"] document = QDomDocument() root = document.createElement("ACBF") - root.setAttribute("xmlns", "http://www.fictionbook-lib.org/xml/acbf/1.0") + root.setAttribute("xmlns", "http://www.acbf.info/xml/acbf/1.1") document.appendChild(root) emphasisStyle = {} strongStyle = {} if "acbfStyles" in configDictionary.keys(): stylesDictionary = configDictionary.get("acbfStyles", {}) emphasisStyle = stylesDictionary.get("emphasis", {}) strongStyle = stylesDictionary.get("strong", {}) styleString = "\n" tabs = " " for key in sorted(stylesDictionary.keys()): style = stylesDictionary.get(key, {}) if key == "emphasis" or key == "strong": styleClass = key+" {\n" elif key == "speech": styleClass = "text-area {\n" elif key == "general": styleClass = "* {\n" elif key == "inverted": - styleClass = "text-area[inverted=\"True\"] {\n" + styleClass = "text-area[inverted=\"true\"] {\n" else: styleClass = "text-area[type=\""+key+"\"] {\n" styleString += tabs+styleClass if "color" in style.keys(): styleString += tabs+tabs+"color:"+style["color"]+";\n" if "font" in style.keys(): fonts = style["font"] genericfont = style.get("genericfont", "sans-serif") if isinstance(fonts, list): styleString += tabs+tabs+"font-family:\""+str("\", \"").join(fonts)+"\", "+genericfont+";\n" else: styleString += tabs+tabs+"font-family:\""+fonts+"\", "+genericfont+";\n" if "bold" in style.keys(): if style["bold"]: styleString += tabs+tabs+"font-weight: bold;\n" if "ital" in style.keys(): if style["ital"]: styleString += tabs+tabs+"font-style: italic;\n" else: styleString += tabs+tabs+"font-style: normal;\n" styleString += tabs+"}\n" style = document.createElement("style") style.setAttribute("type", "text/css") style.appendChild(document.createTextNode(styleString)) root.appendChild(style) meta = document.createElement("meta-data") translationFolder = configDictionary.get("translationLocation", "translations") fullTranslationPath = os.path.join(projectUrl, translationFolder) poParser = po_parser.po_file_parser(fullTranslationPath, True) bookInfo = document.createElement("book-info") if "authorList" in configDictionary.keys(): for authorE in range(len(configDictionary["authorList"])): author = document.createElement("author") authorDict = configDictionary["authorList"][authorE] if "first-name" in authorDict.keys(): authorN = document.createElement("first-name") authorN.appendChild(document.createTextNode(str(authorDict["first-name"]))) author.appendChild(authorN) if "last-name" in authorDict.keys(): authorN = document.createElement("last-name") authorN.appendChild(document.createTextNode(str(authorDict["last-name"]))) author.appendChild(authorN) if "initials" in authorDict.keys(): authorN = document.createElement("middle-name") authorN.appendChild(document.createTextNode(str(authorDict["initials"]))) author.appendChild(authorN) if "nickname" in authorDict.keys(): authorN = document.createElement("nickname") authorN.appendChild(document.createTextNode(str(authorDict["nickname"]))) author.appendChild(authorN) if "homepage" in authorDict.keys(): authorN = document.createElement("home-page") authorN.appendChild(document.createTextNode(str(authorDict["homepage"]))) author.appendChild(authorN) if "email" in authorDict.keys(): authorN = document.createElement("email") authorN.appendChild(document.createTextNode(str(authorDict["email"]))) author.appendChild(authorN) if "role" in authorDict.keys(): if str(authorDict["role"]).title() in acbfAuthorRolesList: author.setAttribute("activity", str(authorDict["role"])) if "language" in authorDict.keys(): - author.setAttribute("lang", str(authorDict["language"])) + author.setAttribute("lang", str(authorDict["language"]).replace("_", "-")) bookInfo.appendChild(author) bookTitle = document.createElement("book-title") if "title" in configDictionary.keys(): bookTitle.appendChild(document.createTextNode(str(configDictionary["title"]))) else: bookTitle.appendChild(document.createTextNode(str("Comic with no Name"))) bookInfo.appendChild(bookTitle) extraGenres = [] if "genre" in configDictionary.keys(): genreListConf = configDictionary["genre"] if isinstance(configDictionary["genre"], dict): genreListConf = configDictionary["genre"].keys() for genre in genreListConf: genreModified = str(genre).lower() genreModified.replace(" ", "_") if genreModified in acbfGenreList: bookGenre = document.createElement("genre") bookGenre.appendChild(document.createTextNode(str(genreModified))) if isinstance(configDictionary["genre"], dict): genreMatch = configDictionary["genre"][genreModified] if genreMatch>0: bookGenre.setAttribute("match", str(genreMatch)) bookInfo.appendChild(bookGenre) else: extraGenres.append(genre) + + if "characters" in configDictionary.keys(): + character = document.createElement("characters") + for name in configDictionary["characters"]: + char = document.createElement("name") + char.appendChild(document.createTextNode(str(name))) + character.appendChild(char) + bookInfo.appendChild(character) + annotation = document.createElement("annotation") if "summary" in configDictionary.keys(): paragraphList = str(configDictionary["summary"]).split("\n") for para in paragraphList: p = document.createElement("p") p.appendChild(document.createTextNode(str(para))) annotation.appendChild(p) else: p = document.createElement("p") p.appendChild(document.createTextNode(str("There was no summary upon generation of this file."))) annotation.appendChild(p) bookInfo.appendChild(annotation) - if "characters" in configDictionary.keys(): - character = document.createElement("characters") - for name in configDictionary["characters"]: - char = document.createElement("name") - char.appendChild(document.createTextNode(str(name))) - character.appendChild(char) - bookInfo.appendChild(character) - keywords = document.createElement("keywords") stringKeywordsList = [] for key in extraGenres: stringKeywordsList.append(str(key)) if "otherKeywords" in configDictionary.keys(): for key in configDictionary["otherKeywords"]: stringKeywordsList.append(str(key)) if "format" in configDictionary.keys(): for key in configDictionary["format"]: stringKeywordsList.append(str(key)) keywords.appendChild(document.createTextNode(", ".join(stringKeywordsList))) bookInfo.appendChild(keywords) coverpageurl = "" coverpage = document.createElement("coverpage") if "pages" in configDictionary.keys(): if "cover" in configDictionary.keys(): pageList = [] pageList = configDictionary["pages"] coverNumber = max([pageList.index(configDictionary["cover"]), 0]) image = document.createElement("image") if len(pagesLocationList) >= coverNumber: coverpageurl = pagesLocationList[coverNumber] image.setAttribute("href", os.path.basename(coverpageurl)) coverpage.appendChild(image) bookInfo.appendChild(coverpage) if "language" in configDictionary.keys(): language = document.createElement("languages") textlayer = document.createElement("text-layer") - textlayer.setAttribute("lang", configDictionary["language"]) - textlayer.setAttribute("show", "False") + textlayer.setAttribute("lang", str(configDictionary["language"]).replace("_", "-")) + textlayer.setAttribute("show", "false") textlayerNative = document.createElement("text-layer") - textlayerNative.setAttribute("lang", configDictionary["language"]) - textlayerNative.setAttribute("show", "True") + textlayerNative.setAttribute("lang", str(configDictionary["language"]).replace("_", "-")) + textlayerNative.setAttribute("show", "true") language.appendChild(textlayer) language.appendChild(textlayerNative) translationComments = {} for lang in poParser.get_translation_list(): textlayer = document.createElement("text-layer") textlayer.setAttribute("lang", lang) - textlayer.setAttribute("show", "True") + textlayer.setAttribute("show", "true") language.appendChild(textlayer) translationComments[lang] = [] translation = poParser.get_entry_for_key("@meta-title "+configDictionary["title"], lang).get("trans", None) if translation is not None: bookTitleTr = document.createElement("book-title") bookTitleTr.setAttribute("lang", lang) bookTitleTr.appendChild(document.createTextNode(translation)) - bookInfo.appendChild(bookTitleTr) + bookInfo.insertAfter(bookTitleTr, bookTitle) translation = poParser.get_entry_for_key("@meta-summary "+configDictionary["summary"], lang).get("trans", None) if translation is not None: annotationTr = document.createElement("annotation") annotationTr.setAttribute("lang", lang) - annotationTr.appendChild(document.createTextNode(translation)) - bookInfo.appendChild(annotationTr) + paragraph = document.createElement("p") + paragraph.appendChild(document.createTextNode(translation)) + annotationTr.appendChild(paragraph) + bookInfo.insertAfter(annotationTr, annotation) translation = poParser.get_entry_for_key("@meta-keywords "+", ".join(configDictionary["otherKeywords"]), lang).get("trans", None) if translation is not None: keywordsTr = document.createElement("keywords") keywordsTr.setAttribute("lang", lang) keywordsTr.appendChild(document.createTextNode(translation)) - bookInfo.appendChild(keywordsTr) + bookInfo.insertAfter(keywordsTr, keywords) bookInfo.appendChild(language) - bookTitle.setAttribute("lang", configDictionary["language"]) - annotation.setAttribute("lang", configDictionary["language"]) - keywords.setAttribute("lang", configDictionary["language"]) + bookTitle.setAttribute("lang", str(configDictionary["language"]).replace("_", "-")) + annotation.setAttribute("lang", str(configDictionary["language"]).replace("_", "-")) + keywords.setAttribute("lang", str(configDictionary["language"]).replace("_", "-")) if "databaseReference" in configDictionary.keys(): database = document.createElement("databaseref") dbRef = configDictionary["databaseReference"] database.setAttribute("dbname", dbRef.get("name", "")) if "type" in dbRef.keys(): database.setAttribute("type", dbRef["type"]) database.appendChild(document.createTextNode(dbRef.get("entry", ""))) bookInfo.appendChild(database) if "seriesName" in configDictionary.keys(): sequence = document.createElement("sequence") sequence.setAttribute("title", configDictionary["seriesName"]) if "seriesVolume" in configDictionary.keys(): sequence.setAttribute("volume", str(configDictionary["seriesVolume"])) if "seriesNumber" in configDictionary.keys(): sequence.appendChild(document.createTextNode(str(configDictionary["seriesNumber"]))) else: sequence.appendChild(document.createTextNode(str(0))) bookInfo.appendChild(sequence) contentrating = document.createElement("content-rating") if "rating" in configDictionary.keys(): contentrating.appendChild(document.createTextNode(str(configDictionary["rating"]))) else: contentrating.appendChild(document.createTextNode(str("Unrated."))) if "ratingSystem" in configDictionary.keys(): contentrating.setAttribute("type", configDictionary["ratingSystem"]) bookInfo.appendChild(contentrating) if "readingDirection" in configDictionary.keys(): readingDirection = document.createElement("reading-direction") if configDictionary["readingDirection"] is "rightToLeft": readingDirection.appendChild(document.createTextNode(str("RTL"))) else: readingDirection.appendChild(document.createTextNode(str("LTR"))) bookInfo.appendChild(readingDirection) meta.appendChild(bookInfo) publisherInfo = document.createElement("publish-info") if "publisherName" in configDictionary.keys(): publisherName = document.createElement("publisher") publisherName.appendChild(document.createTextNode(str(configDictionary["publisherName"]))) publisherInfo.appendChild(publisherName) if "publishingDate" in configDictionary.keys(): publishingDate = document.createElement("publish-date") publishingDate.setAttribute("value", configDictionary["publishingDate"]) publishingDate.appendChild(document.createTextNode(QDate.fromString(configDictionary["publishingDate"], Qt.ISODate).toString(Qt.SystemLocaleLongDate))) publisherInfo.appendChild(publishingDate) if "publisherCity" in configDictionary.keys(): publishCity = document.createElement("city") publishCity.appendChild(document.createTextNode(str(configDictionary["publisherCity"]))) publisherInfo.appendChild(publishCity) if "isbn-number" in configDictionary.keys(): publishISBN = document.createElement("isbn") publishISBN.appendChild(document.createTextNode(str(configDictionary["isbn-number"]))) publisherInfo.appendChild(publishISBN) license = str(configDictionary.get("license", "")) if license.isspace() is False and len(license) > 0: publishLicense = document.createElement("license") publishLicense.appendChild(document.createTextNode(license)) publisherInfo.appendChild(publishLicense) meta.appendChild(publisherInfo) documentInfo = document.createElement("document-info") # TODO: ACBF apparently uses first/middle/last/nick/email/homepage for the document author too... # The following code compensates for me not understanding this initially. if "acbfAuthor" in configDictionary.keys(): if isinstance(configDictionary["acbfAuthor"], list): for e in configDictionary["acbfAuthor"]: acbfAuthor = document.createElement("author") authorDict = e if "first-name" in authorDict.keys(): authorN = document.createElement("first-name") authorN.appendChild(document.createTextNode(str(authorDict["first-name"]))) acbfAuthor.appendChild(authorN) if "last-name" in authorDict.keys(): authorN = document.createElement("last-name") authorN.appendChild(document.createTextNode(str(authorDict["last-name"]))) acbfAuthor.appendChild(authorN) if "initials" in authorDict.keys(): authorN = document.createElement("middle-name") authorN.appendChild(document.createTextNode(str(authorDict["initials"]))) acbfAuthor.appendChild(authorN) if "nickname" in authorDict.keys(): authorN = document.createElement("nickname") authorN.appendChild(document.createTextNode(str(authorDict["nickname"]))) acbfAuthor.appendChild(authorN) if "homepage" in authorDict.keys(): authorN = document.createElement("home-page") authorN.appendChild(document.createTextNode(str(authorDict["homepage"]))) acbfAuthor.appendChild(authorN) if "email" in authorDict.keys(): authorN = document.createElement("email") authorN.appendChild(document.createTextNode(str(authorDict["email"]))) acbfAuthor.appendChild(authorN) if "language" in authorDict.keys(): - acbfAuthor.setAttribute("lang", str(authorDict["language"])) + acbfAuthor.setAttribute("lang", str(authorDict["language"]).replace("_", "-")) documentInfo.appendChild(acbfAuthor) else: acbfAuthor = document.createElement("author") acbfAuthorNick = document.createElement("nickname") acbfAuthorNick.appendChild(document.createTextNode(str(configDictionary["acbfAuthor"]))) acbfAuthor.appendChild(acbfAuthorNick) documentInfo.appendChild(acbfAuthor) else: acbfAuthor = document.createElement("author") acbfAuthorNick = document.createElement("nickname") acbfAuthorNick.appendChild(document.createTextNode(str("Anon"))) acbfAuthor.appendChild(acbfAuthorNick) documentInfo.appendChild(acbfAuthor) acbfDate = document.createElement("creation-date") now = QDate.currentDate() acbfDate.setAttribute("value", now.toString(Qt.ISODate)) acbfDate.appendChild(document.createTextNode(str(now.toString(Qt.SystemLocaleLongDate)))) documentInfo.appendChild(acbfDate) if "acbfSource" in configDictionary.keys(): acbfSource = document.createElement("source") acbfSourceP = document.createElement("p") acbfSourceP.appendChild(document.createTextNode(str(configDictionary["acbfSource"]))) acbfSource.appendChild(acbfSourceP) documentInfo.appendChild(acbfSource) if "acbfID" in configDictionary.keys(): acbfID = document.createElement("id") acbfID.appendChild(document.createTextNode(str(configDictionary["acbfID"]))) documentInfo.appendChild(acbfID) if "acbfVersion" in configDictionary.keys(): acbfVersion = document.createElement("version") acbfVersion.appendChild(document.createTextNode(str(configDictionary["acbfVersion"]))) documentInfo.appendChild(acbfVersion) if "acbfHistory" in configDictionary.keys(): - acbfHistory = document.createElement("history") - for h in configDictionary["acbfHistory"]: - p = document.createElement("p") - p.appendChild(document.createTextNode(str(h))) - acbfHistory.appendChild(p) - documentInfo.appendChild(acbfHistory) + if len(configDictionary["acbfHistory"])>0: + acbfHistory = document.createElement("history") + for h in configDictionary["acbfHistory"]: + p = document.createElement("p") + p.appendChild(document.createTextNode(str(h))) + acbfHistory.appendChild(p) + documentInfo.appendChild(acbfHistory) meta.appendChild(documentInfo) root.appendChild(meta) body = document.createElement("body") references = document.createElement("references") def figure_out_type(svg = QDomElement()): type = None skipList = ["speech", "emphasis", "strong", "inverted", "general"] if svg.attribute("text-anchor") == "middle" or svg.attribute("text-align") == "center": if "acbfStyles" in configDictionary.keys(): stylesDictionary = configDictionary.get("acbfStyles", {}) for key in stylesDictionary.keys(): if key not in skipList: style = stylesDictionary.get(key, {}) font = style.get("font", "") if isinstance(fonts, list): if svg.attribute("family") in font: type = key elif svg.attribute("family") == font: type = key else: type = None elif svg.attribute("text-align") == "justified": type = "formal" else: type = "commentary" inverted = None #Figure out whether this is inverted colored text. if svg.hasAttribute("fill"): stylesDictionary = configDictionary.get("acbfStyles", {}) key = stylesDictionary.get("general", {}) regular = QColor(key.get("color", "#000000")) key = stylesDictionary.get("inverted", {}) invertedColor = QColor(key.get("color", "#FFFFFF")) textColor = QColor(svg.attribute("fill")) # Proceed to get luma for the three colors. lightnessR = (0.21 * regular.redF()) + (0.72 * regular.greenF()) + (0.07 * regular.blueF()) lightnessI = (0.21 * invertedColor.redF()) + (0.72 * invertedColor.greenF()) + (0.07 * invertedColor.blueF()) lightnessT = (0.21 * textColor.redF()) + (0.72 * textColor.greenF()) + (0.07 * textColor.blueF()) if lightnessI > lightnessR: if lightnessT > (lightnessI+lightnessR)*0.5: - inverted = "True" + inverted = "true" else: if lightnessT < (lightnessI+lightnessR)*0.5: - inverted = "True" + inverted = "true" return [type, inverted] listOfPageColors = [] for p in range(0, len(pagesLocationList)): page = pagesLocationList[p] imageFile = QImage() imageFile.load(page) imageRect = imageFile.rect().adjusted(0, 0, -1, -1) pageColor = findDominantColor([imageFile.pixelColor(imageRect.topLeft()), imageFile.pixelColor(imageRect.topRight()), imageFile.pixelColor(imageRect.bottomRight()), imageFile.pixelColor(imageRect.bottomLeft())]) listOfPageColors.append(pageColor) language = "en" if "language" in configDictionary.keys(): - language = configDictionary["language"] + language = str(configDictionary["language"]).replace("_", "-") textLayer = document.createElement("text-layer") textLayer.setAttribute("lang", language) data = pageData[p] transform = data["transform"] frameList = [] listOfTextColors = [] for v in data["vector"]: boundingBoxText = [] listOfBoundaryColors = [] for point in v["boundingBox"]: offset = QPointF(transform["offsetX"], transform["offsetY"]) pixelPoint = QPointF(point.x() * transform["resDiff"], point.y() * transform["resDiff"]) newPoint = pixelPoint - offset x = max(0, min(imageRect.width(), int(newPoint.x() * transform["scaleWidth"]))) y = max(0, min(imageRect.height(), int(newPoint.y() * transform["scaleHeight"]))) listOfBoundaryColors.append(imageFile.pixelColor(x, y)) pointText = str(x) + "," + str(y) boundingBoxText.append(pointText) mainColor = findDominantColor(listOfBoundaryColors) if "text" in v.keys(): textArea = document.createElement("text-area") textArea.setAttribute("points", " ".join(boundingBoxText)) # TODO: Rotate will require proper global transform api as transform info is not written intotext. #textArea.setAttribute("text-rotation", str(v["rotate"])) svg = QDomDocument() svg.setContent(v["text"]) figureOut = figure_out_type(svg.documentElement()) type = figureOut[0] inverted = figureOut[1] paragraph = QDomDocument() paragraph.appendChild(paragraph.createElement("p")) parseTextChildren(paragraph, svg.documentElement(), paragraph.documentElement(), emphasisStyle, strongStyle) textArea.appendChild(paragraph.documentElement()) textArea.setAttribute("bgcolor", mainColor.name()) if type is not None: textArea.setAttribute("type", type) if inverted is not None: textArea.setAttribute("inverted", inverted) textLayer.appendChild(textArea) else: f = {} f["points"] = " ".join(boundingBoxText) frameList.append(f) listOfTextColors.append(mainColor) textLayer.setAttribute("bgcolor", findDominantColor(listOfTextColors).name()) textLayerList = document.createElement("trlist") for lang in poParser.get_translation_list(): textLayerTr = document.createElement("text-layer") textLayerTr.setAttribute("lang", lang) for i in range(len(data["vector"])): d = data["vector"] v = d[i] boundingBoxText = [] for point in v["boundingBox"]: offset = QPointF(transform["offsetX"], transform["offsetY"]) pixelPoint = QPointF(point.x() * transform["resDiff"], point.y() * transform["resDiff"]) newPoint = pixelPoint - offset x = int(newPoint.x() * transform["scaleWidth"]) y = int(newPoint.y() * transform["scaleHeight"]) pointText = str(x) + "," + str(y) boundingBoxText.append(pointText) if "text" in v.keys(): textArea = document.createElement("text-area") textArea.setAttribute("points", " ".join(boundingBoxText)) # TODO: Rotate will require proper global transform api as transform info is not written intotext. #textArea.setAttribute("text-rotation", str(v["rotate"])) svg = QDomDocument() svg.setContent(v["text"]) figureOut = figure_out_type(svg.documentElement()) type = figureOut[0] inverted = figureOut[1] string = re.sub("\<\/*?text.*?\>",'', str(v["text"])) string = re.sub("\s+?", " ", string) translationEntry = poParser.get_entry_for_key(string, lang) string = translationEntry.get("trans", string) svg.setContent(""+string+"") paragraph = QDomDocument() paragraph.appendChild(paragraph.createElement("p")) parseTextChildren(paragraph, svg.documentElement(), paragraph.documentElement(), emphasisStyle, strongStyle) if "translComment" in translationEntry.keys(): key = translationEntry["translComment"] listOfComments = [] listOfComments = translationComments[lang] index = 0 if key in listOfComments: index = listOfComments.index(key)+1 else: listOfComments.append(key) index = len(listOfComments) translationComments[lang] = listOfComments refID = "-".join(["tn", lang, str(index)]) anchor = document.createElement("a") anchor.setAttribute("href", "#"+refID) anchor.appendChild(document.createTextNode("*")) paragraph.documentElement().appendChild(anchor) textArea.appendChild(paragraph.documentElement()) textLayerTr.appendChild(textArea) if type is not None: textArea.setAttribute("type", type) if inverted is not None: textArea.setAttribute("inverted", inverted) textArea.setAttribute("bgcolor", listOfTextColors[i].name()) - textLayerTr.setAttribute("bgcolor", findDominantColor(listOfTextColors).name()) - textLayerList.appendChild(textLayerTr) + if textLayerTr.hasChildNodes(): + textLayerTr.setAttribute("bgcolor", findDominantColor(listOfTextColors).name()) + textLayerList.appendChild(textLayerTr) if page is not coverpageurl: pg = document.createElement("page") image = document.createElement("image") image.setAttribute("href", os.path.basename(page)) pg.appendChild(image) if "acbf_title" in data["keys"]: title = document.createElement("title") title.setAttribute("lang", language) title.appendChild(document.createTextNode(str(data["title"]))) pg.appendChild(title) for lang in poParser.get_translation_list(): titleTrans = " " titlekey = "@page-title "+str(data["title"]) translationEntry = poParser.get_entry_for_key(titlekey, lang) titleTrans = translationEntry.get("trans", titleTrans) if titleTrans.isspace() is False: titleT = document.createElement("title") titleT.setAttribute("lang", lang) titleT.appendChild(document.createTextNode(titleTrans)) pg.appendChild(titleT) if "acbf_none" in data["keys"]: pg.setAttribute("transition", "none") if "acbf_blend" in data["keys"]: pg.setAttribute("transition", "blend") if "acbf_fade" in data["keys"]: pg.setAttribute("transition", "fade") if "acbf_horizontal" in data["keys"]: pg.setAttribute("transition", "scroll_right") if "acbf_vertical" in data["keys"]: pg.setAttribute("transition", "scroll_down") - for f in frameList: - frame = document.createElement("frame") - frame.setAttribute("points", f["points"]) - pg.appendChild(frame) - pg.appendChild(textLayer) + if textLayer.hasChildNodes(): + pg.appendChild(textLayer) pg.setAttribute("bgcolor", pageColor.name()) for n in range(0, textLayerList.childNodes().size()): node = textLayerList.childNodes().at(n) pg.appendChild(node) + for f in frameList: + frame = document.createElement("frame") + frame.setAttribute("points", f["points"]) + pg.appendChild(frame) body.appendChild(pg) else: for f in frameList: frame = document.createElement("frame") frame.setAttribute("points", f["points"]) coverpage.appendChild(frame) coverpage.appendChild(textLayer) - coverpage.setAttribute("bgcolor", pageColor.name()) for n in range(0, textLayerList.childNodes().size()): node = textLayerList.childNodes().at(n) coverpage.appendChild(node) bodyColor = findDominantColor(listOfPageColors) body.setAttribute("bgcolor", bodyColor.name()) if configDictionary.get("includeTranslComment", False): for lang in translationComments.keys(): for key in translationComments[lang]: index = translationComments[lang].index(key)+1 refID = "-".join(["tn", lang, str(index)]) ref = document.createElement("reference") ref.setAttribute("lang", lang) ref.setAttribute("id", refID) transHeaderStr = configDictionary.get("translatorHeader", "Translator's Notes") transHeaderStr = poParser.get_entry_for_key("@meta-translator "+transHeaderStr, lang).get("trans", transHeaderStr) translatorHeader = document.createElement("p") translatorHeader.appendChild(document.createTextNode(transHeaderStr+":")) ref.appendChild(translatorHeader) refPara = document.createElement("p") refPara.appendChild(document.createTextNode(key)) ref.appendChild(refPara) references.appendChild(ref) root.appendChild(body) if references.childNodes().size(): root.appendChild(references) f = open(locationBasic, 'w', newline="", encoding="utf-8") f.write(document.toString(indent=2)) f.close() success = True success = createStandAloneACBF(configDictionary, document, locationStandAlone, pagesLocationList) return success def createStandAloneACBF(configDictionary, document = QDomDocument(), location = str(), pagesLocationList = []): title = configDictionary["projectName"] if "title" in configDictionary.keys(): title = configDictionary["title"] root = document.firstChildElement("ACBF") meta = root.firstChildElement("meta-data") bookInfo = meta.firstChildElement("book-info") cover = bookInfo.firstChildElement("coverpage") body = root.firstChildElement("body") pages = [] for p in range(0, len(body.elementsByTagName("page"))): pages.append(body.elementsByTagName("page").item(p).toElement()) if (cover): pages.append(cover) data = document.createElement("data") root.appendChild(data) # Covert pages to base64 strings. for i in range(0, len(pages)): image = pages[i].firstChildElement("image") href = image.attribute("href") for p in pagesLocationList: if href in p: binary = document.createElement("binary") binary.setAttribute("id", href) imageFile = QImage() imageFile.load(p) imageData = QByteArray() buffer = QBuffer(imageData) imageFile.save(buffer, "PNG") # For now always embed as png. contentType = "image/png" binary.setAttribute("content-type", contentType) binary.appendChild(document.createTextNode(str(bytearray(imageData.toBase64()).decode("ascii")))) image.setAttribute("href", "#" + href) data.appendChild(binary) f = open(location, 'w', newline="", encoding="utf-8") f.write(document.toString(indent=2)) f.close() return True """ Function to parse svg text to acbf ready text """ def parseTextChildren(document = QDomDocument(), elRead = QDomElement(), elWrite = QDomElement(), emphasisStyle = {}, strongStyle = {}): for n in range(0, elRead.childNodes().size()): childNode = elRead.childNodes().item(n) if childNode.isText(): if elWrite.hasChildNodes() and str(childNode.nodeValue()).startswith(" ") is False: elWrite.appendChild(document.createTextNode(" ")) elWrite.appendChild(document.createTextNode(str(childNode.nodeValue()))) elif childNode.hasChildNodes(): childNode = childNode.toElement() fontFamily = str(childNode.attribute("font-family")) fontWeight = str(childNode.attribute("font-weight", "400")) fontItalic = str(childNode.attribute("font-style")) fontStrikeThrough = str(childNode.attribute("text-decoration")) fontBaseLine = str(childNode.attribute("baseline-shift")) newElementMade = False emphasis = False strong = False if len(emphasisStyle.keys()) > 0: emphasis = compare_styles(emphasisStyle, fontFamily, fontWeight, fontItalic) else: if fontItalic == "italic": emphasis = True if len(strongStyle.keys()) > 0: strong = compare_styles(strongStyle, fontFamily, fontWeight, fontItalic) else: if fontWeight == "bold" or int(fontWeight) > 400: strong = True if strong: newElement = document.createElement("strong") newElementMade = True elif emphasis: newElement = document.createElement("emphasis") newElementMade = True elif fontStrikeThrough == "line-through": newElement = document.createElement("strikethrough") newElementMade = True elif fontBaseLine.isalnum(): if (fontBaseLine == "super"): newElement = document.createElement("sup") newElementMade = True elif (fontBaseLine == "sub"): newElement = document.createElement("sub") newElementMade = True if newElementMade is True: parseTextChildren(document, childNode, newElement, emphasisStyle, strongStyle) elWrite.appendChild(newElement) else: parseTextChildren(document, childNode, elWrite, emphasisStyle, strongStyle) # If it is not a text node, nor does it have children(which could be textnodes), # we should assume it's empty and ignore it. elWrite.normalize() for e in range(0, elWrite.childNodes().size()): el = elWrite.childNodes().item(e) if el.isText(): eb = el.nodeValue() el.setNodeValue(eb.replace(" ", " ")) def compare_styles(style = {}, fontFamily = str(), fontWeight = str(), fontStyle = str()): compare = [] if "font" in style.keys(): font = style.get("font") if isinstance(font, list): compare.append(fontFamily in font) else: compare.append((fontFamily == font)) if "bold" in style.keys(): compare.append(fontWeight == "bold" or int(fontWeight) > 400) if "ital" in style.keys(): compare.append(fontStyle == "italic") countTrue = 0 for i in compare: if i is True: countTrue +=1 if countTrue > 1: return True else: return False """ This function tries to determine if there's a dominant color, and if not, it'll mix all of them. """ def findDominantColor(listOfColors = [QColor()]): dominantColor = QColor() listOfColorNames = {} for color in listOfColors: count = listOfColorNames.get(color.name(), 0) listOfColorNames[color.name()] = count+1 # Check if there's a sense of dominant color: clear_dominant = False if len(listOfColorNames) == 2 and len(listOfColors) == 1: clear_dominant = True elif len(listOfColorNames) == 3 and len(listOfColors) == 2: clear_dominant = True elif len(listOfColorNames.keys()) < (len(listOfColors)*0.5): clear_dominant = True if clear_dominant: namesSorted = sorted(listOfColorNames, key=listOfColorNames.get, reverse=True) dominantColor = QColor(namesSorted[0]) else: for color in listOfColors: dominantColor.setRedF(0.5*(dominantColor.redF()+color.redF())) dominantColor.setGreenF(0.5*(dominantColor.greenF()+color.greenF())) dominantColor.setBlueF(0.5*(dominantColor.blueF()+color.blueF())) return dominantColor diff --git a/plugins/python/comics_project_management_tools/exporters/CPMT_EPUB_exporter.py b/plugins/python/comics_project_management_tools/exporters/CPMT_EPUB_exporter.py index ecf6866df6..1dcf2692b8 100644 --- a/plugins/python/comics_project_management_tools/exporters/CPMT_EPUB_exporter.py +++ b/plugins/python/comics_project_management_tools/exporters/CPMT_EPUB_exporter.py @@ -1,326 +1,326 @@ """ Copyright (c) 2018 Wolthera van Hövell tot Westerflier This file is part of the Comics Project Management Tools(CPMT). CPMT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CPMT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the CPMT. If not, see . """ """ Create an epub folder, finally, package to a epubzip. """ import shutil import os from pathlib import Path import xml.etree.ElementTree as ET def export(configDictionary = {}, projectURL = str(), pagesLocationList = []): path = Path(os.path.join(projectURL, configDictionary["exportLocation"])) exportPath = path / "EPUB-files" metaInf = exportPath / "META-INF" oebps = exportPath / "OEBPS" imagePath = oebps / "Images" stylesPath = oebps / "Styles" textPath = oebps / "Text" if exportPath.exists() is False: exportPath.mkdir() metaInf.mkdir() oebps.mkdir() imagePath.mkdir() stylesPath.mkdir() textPath.mkdir() mimetype = open(str(Path(exportPath / "mimetype")), mode="w") mimetype.write("application/epub+zip") mimetype.close() container = ET.ElementTree() cRoot = ET.Element("container") cRoot.set("version", "1.0") cRoot.set("xmlns", "urn:oasis:names:tc:opendocument:xmlns:container") container._setroot(cRoot) rootFiles = ET.Element("rootfiles") rootfile = ET.Element("rootfile") rootfile.set("full-path", "OEBPS/content.opf") rootfile.set("media-type", "application/oebps-package+xml") rootFiles.append(rootfile) cRoot.append(rootFiles) container.write(str(Path(metaInf / "container.xml")), encoding="utf-8", xml_declaration=True) # copyimages to images pagesList = [] if len(pagesLocationList)>0: if "cover" in configDictionary.keys(): coverNumber = configDictionary["pages"].index(configDictionary["cover"]) else: coverNumber = 0 for p in pagesLocationList: if os.path.exists(p): shutil.copy2(p, str(imagePath)) pagesList.append(str(Path(imagePath / os.path.basename(p)))) if len(pagesLocationList) >= coverNumber: coverpageurl = pagesList[coverNumber] else: print("CPMT: Couldn't find the location for the epub files.") return False # for each image, make an xml file htmlFiles = [] for i in range(len(pagesList)): pageName = "Page" + str(i) + ".xhtml" doc = ET.ElementTree() html = ET.Element("html") doc._setroot(html) html.set("xmlns", "http://www.w3.org/1999/xhtml") html.set("xmlns:epub", "http://www.idpf.org/2007/ops") head = ET.Element("head") html.append(head) body = ET.Element("body") img = ET.Element("img") img.set("src", os.path.relpath(pagesList[i], str(textPath))) body.append(img) if pagesList[i] != coverpageurl: pagenumber = ET.Element("p") pagenumber.text = "Page " + str(i) body.append(pagenumber) html.append(body) filename = str(Path(textPath / pageName)) doc.write(filename, encoding="utf-8", xml_declaration=True) if pagesList[i] == coverpageurl: coverpagehtml = os.path.relpath(filename, str(oebps)) htmlFiles.append(filename) # opf file opfFile = ET.ElementTree() opfRoot = ET.Element("package") opfRoot.set("version", "3.0") opfRoot.set("unique-identifier", "BookId") opfRoot.set("xmlns", "http://www.idpf.org/2007/opf") opfFile._setroot(opfRoot) # metadata opfMeta = ET.Element("metadata") opfMeta.set("xmlns:dc", "http://purl.org/dc/elements/1.1/") if "language" in configDictionary.keys(): bookLang = ET.Element("dc:language") bookLang.text = configDictionary["language"] opfMeta.append(bookLang) bookTitle = ET.Element("dc:title") if "title" in configDictionary.keys(): bookTitle.text = str(configDictionary["title"]) else: bookTitle.text = "Comic with no Name" opfMeta.append(bookTitle) if "authorList" in configDictionary.keys(): for authorE in range(len(configDictionary["authorList"])): authorDict = configDictionary["authorList"][authorE] authorType = "dc:creator" if "role" in authorDict.keys(): if str(authorDict["role"]).lower() in ["editor", "assistant editor", "proofreader", "beta"]: authorType = "dc:contributor" author = ET.Element(authorType) authorName = [] if "last-name" in authorDict.keys(): authorName.append(authorDict["last-name"]) if "first-name" in authorDict.keys(): authorName.append(authorDict["first-name"]) if "initials" in authorDict.keys(): authorName.append(authorDict["initials"]) if "nickname" in authorDict.keys(): authorName.append("(" + authorDict["nickname"] + ")") author.text = ", ".join(authorName) opfMeta.append(author) if "role" in authorDict.keys(): author.set("id", "cre" + str(authorE)) role = ET.Element("meta") role.set("refines", "cre" + str(authorE)) role.set("scheme", "marc:relators") role.set("property", "role") role.text = str(authorDict["role"]) opfMeta.append(role) if "publishingDate" in configDictionary.keys(): date = ET.Element("dc:date") date.text = configDictionary["publishingDate"] opfMeta.append(date) description = ET.Element("dc:description") if "summary" in configDictionary.keys(): description.text = configDictionary["summary"] else: description.text = "There was no summary upon generation of this file." opfMeta.append(description) type = ET.Element("dc:type") type.text = "Comic" opfMeta.append(type) if "publisherName" in configDictionary.keys(): publisher = ET.Element("dc:publisher") publisher.text = configDictionary["publisherName"] opfMeta.append(publisher) if "isbn-number" in configDictionary.keys(): publishISBN = ET.Element("dc:identifier") publishISBN.text = str("urn:isbn:") + configDictionary["isbn-number"] opfMeta.append(publishISBN) if "license" in configDictionary.keys(): rights = ET.Element("dc:rights") rights.text = configDictionary["license"] opfMeta.append(rights) if "genre" in configDictionary.keys(): genreListConf = configDictionary["genre"] if isinstance(configDictionary["genre"], dict): genreListConf = configDictionary["genre"].keys() for g in genreListConf: subject = ET.Element("dc:subject") subject.text = g opfMeta.append(subject) if "characters" in configDictionary.keys(): for name in configDictionary["characters"]: char = ET.Element("dc:subject") char.text = name opfMeta.append(char) if "format" in configDictionary.keys(): for format in configDictionary["format"]: f = ET.Element("dc:subject") f.text = format opfMeta.append(f) if "otherKeywords" in configDictionary.keys(): for key in configDictionary["otherKeywords"]: word = ET.Element("dc:subject") word.text = key opfMeta.append(word) opfRoot.append(opfMeta) opfManifest = ET.Element("manifest") toc = ET.Element("item") toc.set("id", "ncx") toc.set("href", "toc.ncx") toc.set("media-type", "application/x-dtbncx+xml") opfManifest.append(toc) for p in htmlFiles: item = ET.Element("item") item.set("id", os.path.basename(p)) item.set("href", os.path.relpath(p, str(oebps))) item.set("media-type", "application/xhtml+xml") opfManifest.append(item) for p in pagesList: item = ET.Element("item") item.set("id", os.path.basename(p)) item.set("href", os.path.relpath(p, str(oebps))) item.set("media-type", "image/png") if os.path.basename(p) == os.path.basename(coverpageurl): item.set("properties", "cover-image") opfManifest.append(item) opfRoot.append(opfManifest) opfSpine = ET.Element("spine") opfSpine.set("toc", "ncx") for p in htmlFiles: item = ET.Element("itemref") item.set("idref", os.path.basename(p)) opfSpine.append(item) opfRoot.append(opfSpine) opfGuide = ET.Element("guide") if coverpagehtml is not None and coverpagehtml.isspace() is False and len(coverpagehtml) > 0: item = ET.Element("reference") item.set("type", "cover") item.set("title", "Cover") item.set("href", coverpagehtml) opfRoot.append(opfGuide) opfFile.write(str(Path(oebps / "content.opf")), encoding="utf-8", xml_declaration=True) # toc tocDoc = ET.ElementTree() ncx = ET.Element("ncx") ncx.set("version", "2005-1") ncx.set("xmlns", "http://www.daisy.org/z3986/2005/ncx/") tocDoc._setroot(ncx) tocHead = ET.Element("head") metaID = ET.Element("meta") metaID.set("content", "ID_UNKNOWN") metaID.set("name", "dtb:uid") tocHead.append(metaID) metaDepth = ET.Element("meta") metaDepth.set("content", str(0)) metaDepth.set("name", "dtb:depth") tocHead.append(metaDepth) metaTotal = ET.Element("meta") metaTotal.set("content", str(0)) metaTotal.set("name", "dtb:totalPageCount") tocHead.append(metaTotal) metaMax = ET.Element("meta") metaMax.set("content", str(0)) metaMax.set("name", "dtb:maxPageNumber") tocHead.append(metaDepth) ncx.append(tocHead) docTitle = ET.Element("docTitle") text = ET.Element("text") if "title" in configDictionary.keys(): text.text = str(configDictionary["title"]) else: text.text = "Comic with no Name" docTitle.append(text) ncx.append(docTitle) navmap = ET.Element("navMap") navPoint = ET.Element("navPoint") navPoint.set("id", "navPoint-1") navPoint.set("playOrder", "1") navLabel = ET.Element("navLabel") navLabelText = ET.Element("text") navLabelText.text = "Start" navLabel.append(navLabelText) navContent = ET.Element("content") navContent.set("src", os.path.relpath(htmlFiles[0], str(oebps))) navPoint.append(navLabel) navPoint.append(navContent) navmap.append(navPoint) ncx.append(navmap) tocDoc.write(str(Path(oebps / "toc.ncx")), encoding="utf-8", xml_declaration=True) package_epub(configDictionary, projectURL) return True """ package epub packages the whole epub folder and renames the zip file to .epub. """ def package_epub(configDictionary = {}, projectURL = str()): # Use the project name if there's no title to avoid sillyness with unnamed zipfiles. title = configDictionary["projectName"] if "title" in configDictionary.keys(): - title = configDictionary["title"] + title = str(configDictionary["title"]).replace(" ", "_") # Get the appropriate paths. url = os.path.join(projectURL, configDictionary["exportLocation"], title) epub = os.path.join(projectURL, configDictionary["exportLocation"], "EPUB-files") # Make the archive. shutil.make_archive(base_name=url, format="zip", root_dir=epub) # Rename the archive to epub. shutil.move(src=str(url + ".zip"), dst=str(url + ".epub"))