<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all
# copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
# OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

__version__ = '3.0'
__license__ = 'ISC'
__copyright__ = '2012-2013, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>'
__docformat__ = 'restructuredtext en'

import os
import sys
import shutil
import traceback
import urllib2
import comic2ebook
import kindlestrip
from image import ProfileData
from subprocess import call, Popen, STDOUT, PIPE
from PyQt4 import QtGui, QtCore
from xml.dom.minidom import parse
from HTMLParser import HTMLParser


class Icons:
    def __init__(self):
        self.deviceKindle = QtGui.QIcon()
        self.deviceKindle.addPixmap(QtGui.QPixmap(":/Devices/icons/Kindle.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.deviceOther = QtGui.QIcon()
        self.deviceOther.addPixmap(QtGui.QPixmap(":/Devices/icons/Other.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.MOBIFormat = QtGui.QIcon()
        self.MOBIFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/MOBI.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.CBZFormat = QtGui.QIcon()
        self.CBZFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/CBZ.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.EPUBFormat = QtGui.QIcon()
        self.EPUBFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/EPUB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.info = QtGui.QIcon()
        self.info.addPixmap(QtGui.QPixmap(":/Status/icons/info.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.warning = QtGui.QIcon()
        self.warning.addPixmap(QtGui.QPixmap(":/Status/icons/warning.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.error = QtGui.QIcon()
        self.error.addPixmap(QtGui.QPixmap(":/Status/icons/error.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)


class HTMLStripper(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)


# noinspection PyBroadException
class VersionThread(QtCore.QThread):
    def __init__(self, parent):
        QtCore.QThread.__init__(self)
        self.parent = parent

    def __del__(self):
        self.wait()

    def run(self):
        try:
            XML = urllib2.urlopen('http://kcc.vulturis.eu/Version.php')
            XML = parse(XML)
        except Exception:
            return
        latestVersion = XML.childNodes[0].getElementsByTagName('latest')[0].childNodes[0].toxml()
        if tuple(map(int, (latestVersion.split(".")))) > tuple(map(int, (__version__.split(".")))):
            self.emit(QtCore.SIGNAL("addMessage"), '<a href="http://kcc.vulturis.eu/">'
                                                   '<b>New version is available!</b></a>', 'warning')


# noinspection PyBroadException
class WorkerThread(QtCore.QThread):
    def __init__(self, parent):
        QtCore.QThread.__init__(self)
        self.parent = parent

    def __del__(self):
        self.wait()

    def run(self):
        self.emit(QtCore.SIGNAL("modeConvert"), False)
        profile = ProfileData.ProfileLabels[str(GUI.DeviceBox.currentText())]
        argv = ["--profile=" + profile]
        currentJobs = []
        if GUI.MangaBox.isChecked():
            argv.append("--manga-style")
        if GUI.RotateBox.isChecked():
            argv.append("--rotate")
        if GUI.QualityBox.checkState() == 1:
            argv.append("--quality=1")
        elif GUI.QualityBox.checkState() == 2:
            argv.append("--quality=2")
        if self.parent.currentMode > 1:
            if GUI.ProcessingBox.isChecked():
                argv.append("--noprocessing")
            if GUI.UpscaleBox.isChecked():
                argv.append("--upscale")
            if GUI.NoRotateBox.isChecked():
                argv.append("--nosplitrotate")
            if GUI.BorderBox.isChecked():
                argv.append("--blackborders")
            if GUI.StretchBox.isChecked():
                argv.append("--stretch")
            if GUI.NoDitheringBox.isChecked():
                argv.append("--forcepng")
            if float(self.parent.GammaValue) > 0.09:
                argv.append("--gamma=" + self.parent.GammaValue)
            if str(GUI.FormatBox.currentText()) == 'CBZ':
                argv.append("--cbz-output")
        if self.parent.currentMode > 2:
            argv.append("--customwidth=" + str(GUI.customWidth.text()))
            argv.append("--customheight=" + str(GUI.customHeight.text()))
            if GUI.ColorBox.isChecked():
                argv.append("--forcecolor")
        for i in range(GUI.JobList.count()):
            currentJobs.append(str(GUI.JobList.item(i).text()))
        GUI.JobList.clear()
        for job in currentJobs:
            self.errors = False
            self.emit(QtCore.SIGNAL("addMessage"), '<b>Source:</b> ' + job, 'info')
            if str(GUI.FormatBox.currentText()) == 'CBZ':
                self.emit(QtCore.SIGNAL("addMessage"), 'Creating CBZ file...', 'info')
            else:
                self.emit(QtCore.SIGNAL("addMessage"), 'Creating EPUB file...', 'info')
            jobargv = list(argv)
            jobargv.append(job)
            try:
                outputPath = comic2ebook.main(jobargv, self)
                self.emit(QtCore.SIGNAL("hideProgressBar"))
            except UserWarning as warn:
                self.errors = True
                self.emit(QtCore.SIGNAL("addMessage"), str(warn), 'warning')
                self.emit(QtCore.SIGNAL("addMessage"), 'KCC failed to create output file!', 'warning')
            except Exception as err:
                self.errors = True
                type_, value_, traceback_ = sys.exc_info()
                self.emit(QtCore.SIGNAL("showDialog"), "Error during conversion %s:\n\n%s\n\nTraceback:\n%s"
                                                       % (jobargv[-1], str(err), traceback.format_tb(traceback_)))
                self.emit(QtCore.SIGNAL("addMessage"), 'KCC failed to create EPUB!', 'error')
            if not self.errors:
                if str(GUI.FormatBox.currentText()) == 'CBZ':
                    self.emit(QtCore.SIGNAL("addMessage"), 'Creating CBZ file... Done!', 'info', True)
                else:
                    self.emit(QtCore.SIGNAL("addMessage"), 'Creating EPUB file... Done!', 'info', True)
                if str(GUI.FormatBox.currentText()) == 'MOBI':
                    if not os.path.getsize(outputPath) > 314572800:
                        self.emit(QtCore.SIGNAL("addMessage"), 'Creating MOBI file...', 'info')
                        self.emit(QtCore.SIGNAL("progressBarTick"), 1)
                        try:
                            retcode = call('kindlegen -verbose "' + outputPath + '"', shell=True)
                        except:
                            continue
                        if retcode == 0:
                            self.emit(QtCore.SIGNAL("addMessage"), 'Creating MOBI file... Done!', 'info', True)
                            self.emit(QtCore.SIGNAL("addMessage"), 'Removing SRCS header...', 'info')
                            os.remove(outputPath)
                            mobiPath = outputPath.replace('.epub', '.mobi')
                            shutil.move(mobiPath, mobiPath + '_tostrip')
                            try:
                                kindlestrip.main((mobiPath + '_tostrip', mobiPath))
                            except Exception:
                                self.errors = True
                            if not self.errors:
                                os.remove(mobiPath + '_tostrip')
                                self.emit(QtCore.SIGNAL("addMessage"), 'Removing SRCS header... Done!', 'info', True)<commit_msg>Don't stop conversion if KindleGen return only warnings<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all
# copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
# OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

__version__ = '3.0'
__license__ = 'ISC'
__copyright__ = '2012-2013, <NAME> <<EMAIL>>, <NAME> <<EMAIL>>'
__docformat__ = 'restructuredtext en'

import os
import sys
import shutil
import traceback
import urllib2
import comic2ebook
import kindlestrip
from image import ProfileData
from subprocess import call, Popen, STDOUT, PIPE
from PyQt4 import QtGui, QtCore
from xml.dom.minidom import parse
from HTMLParser import HTMLParser


class Icons:
    def __init__(self):
        self.deviceKindle = QtGui.QIcon()
        self.deviceKindle.addPixmap(QtGui.QPixmap(":/Devices/icons/Kindle.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.deviceOther = QtGui.QIcon()
        self.deviceOther.addPixmap(QtGui.QPixmap(":/Devices/icons/Other.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.MOBIFormat = QtGui.QIcon()
        self.MOBIFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/MOBI.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.CBZFormat = QtGui.QIcon()
        self.CBZFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/CBZ.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.EPUBFormat = QtGui.QIcon()
        self.EPUBFormat.addPixmap(QtGui.QPixmap(":/Formats/icons/EPUB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.info = QtGui.QIcon()
        self.info.addPixmap(QtGui.QPixmap(":/Status/icons/info.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.warning = QtGui.QIcon()
        self.warning.addPixmap(QtGui.QPixmap(":/Status/icons/warning.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.error = QtGui.QIcon()
        self.error.addPixmap(QtGui.QPixmap(":/Status/icons/error.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)


class HTMLStripper(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)


# noinspection PyBroadException
class VersionThread(QtCore.QThread):
    def __init__(self, parent):
        QtCore.QThread.__init__(self)
        self.parent = parent

    def __del__(self):
        self.wait()

    def run(self):
        try:
            XML = urllib2.urlopen('http://kcc.vulturis.eu/Version.php')
            XML = parse(XML)
        except Exception:
            return
        latestVersion = XML.childNodes[0].getElementsByTagName('latest')[0].childNodes[0].toxml()
        if tuple(map(int, (latestVersion.split(".")))) > tuple(map(int, (__version__.split(".")))):
            self.emit(QtCore.SIGNAL("addMessage"), '<a href="http://kcc.vulturis.eu/">'
                                                   '<b>New version is available!</b></a>', 'warning')


# noinspection PyBroadException
class WorkerThread(QtCore.QThread):
    def __init__(self, parent):
        QtCore.QThread.__init__(self)
        self.parent = parent

    def __del__(self):
        self.wait()

    def run(self):
        self.emit(QtCore.SIGNAL("modeConvert"), False)
        profile = ProfileData.ProfileLabels[str(GUI.DeviceBox.currentText())]
        argv = ["--profile=" + profile]
        currentJobs = []
        if GUI.MangaBox.isChecked():
            argv.append("--manga-style")
        if GUI.RotateBox.isChecked():
            argv.append("--rotate")
        if GUI.QualityBox.checkState() == 1:
            argv.append("--quality=1")
        elif GUI.QualityBox.checkState() == 2:
            argv.append("--quality=2")
        if self.parent.currentMode > 1:
            if GUI.ProcessingBox.isChecked():
                argv.append("--noprocessing")
            if GUI.UpscaleBox.isChecked():
                argv.append("--upscale")
            if GUI.NoRotateBox.isChecked():
                argv.append("--nosplitrotate")
            if GUI.BorderBox.isChecked():
                argv.append("--blackborders")
            if GUI.StretchBox.isChecked():
                argv.append("--stretch")
            if GUI.NoDitheringBox.isChecked():
                argv.append("--forcepng")
            if float(self.parent.GammaValue) > 0.09:
                argv.append("--gamma=" + self.parent.GammaValue)
            if str(GUI.FormatBox.currentText()) == 'CBZ':
                argv.append("--cbz-output")
        if self.parent.currentMode > 2:
            argv.append("--customwidth=" + str(GUI.customWidth.text()))
            argv.append("--customheight=" + str(GUI.customHeight.text()))
            if GUI.ColorBox.isChecked():
                argv.append("--forcecolor")
        for i in range(GUI.JobList.count()):
            currentJobs.append(str(GUI.JobList.item(i).text()))
        GUI.JobList.clear()
        for job in currentJobs:
            self.errors = False
            self.emit(QtCore.SIGNAL("addMessage"), '<b>Source:</b> ' + job, 'info')
            if str(GUI.FormatBox.currentText()) == 'CBZ':
                self.emit(QtCore.SIGNAL("addMessage"), 'Creating CBZ file...', 'info')
            else:
                self.emit(QtCore.SIGNAL("addMessage"), 'Creating EPUB file...', 'info')
            jobargv = list(argv)
            jobargv.append(job)
            try:
                outputPath = comic2ebook.main(jobargv, self)
                self.emit(QtCore.SIGNAL("hideProgressBar"))
            except UserWarning as warn:
                self.errors = True
                self.emit(QtCore.SIGNAL("addMessage"), str(warn), 'warning')
                self.emit(QtCore.SIGNAL("addMessage"), 'KCC failed to create output file!', 'warning')
            except Exception as err:
                self.errors = True
                type_, value_, traceback_ = sys.exc_info()
                self.emit(QtCore.SIGNAL("showDialog"), "Error during conversion %s:\n\n%s\n\nTraceback:\n%s"
                                                       % (jobargv[-1], str(err), traceback.format_tb(traceback_)))
                self.emit(QtCore.SIGNAL("addMessage"), 'KCC failed to create EPUB!', 'error')
            if not self.errors:
                if str(GUI.FormatBox.currentText()) == 'CBZ':
                    self.emit(QtCore.SIGNAL("addMessage"), 'Creating CBZ file... Done!', 'info', True)
                else:
                    self.emit(QtCore.SIGNAL("addMessage"), 'Creating EPUB file... Done!', 'info', True)
                if str(GUI.FormatBox.currentText()) == 'MOBI':
                    if not os.path.getsize(outputPath) > 314572800:
                        self.emit(QtCore.SIGNAL("addMessage"), 'Creating MOBI file...', 'info')
                        self.emit(QtCore.SIGNAL("progressBarTick"), 1)
                        try:
                            retcode = call('kindlegen -verbose "' + outputPath + '"', shell=True)
                        except:
                            continue
                        if retcode == 0 or retcode == 1:
                            self.emit(QtCore.SIGNAL("addMessage"), 'Creating MOBI file... Done!', 'info', True)
                            self.emit(QtCore.SIGNAL("addMessage"), 'Removing SRCS header...', 'info')
                            os.remove(outputPath)
                            mobiPath = outputPath.replace('.epub', '.mobi')
                            shutil.move(mobiPath, mobiPath + '_tostrip')
                            try:
                                kindlestrip.main((mobiPath + '_tostrip', mobiPath))
                            except Exception:
                                self.errors = True
                            if not self.errors:
                                os.remove(mobiPath + '_tostrip')
                                self.emit(QtCore.SIGNAL("addMessage"), 'Removing SRCS header... Done!', 'info', True)
{'fraction_non_alphanumeric': 0.13295507721104352, 'fraction_numerical': 0.005205896116050538, 'mean_word_length': 2.0827623512441398, 'pattern_counts': {'":': 16, '<': 33, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2794983', 'n_tokens_mistral': 5234, 'n_tokens_neox': 4971, 'n_words': 1029}