<commit_before>from django.conf import settings
from ..models import BadgePermission

from tempfile import mkdtemp, mkstemp
import os
import subprocess
import shutil


class BadgeCreatorError(Exception):
    def __init__(self, value, latex_output=None):
        self.value = value
        self.latex_output = latex_output

    def is_latex_output(self):
        return self.latex_output is not None

    def get_latex_output(self):
        return self.latex_output

    def __str__(self):
        return repr(self.value)


class BadgeCreator:
    def __init__(self, settings):
        self.settings = settings

        self.columns = self.settings.columns
        self.rows = self.settings.rows

        # list of helpers (dict with attributes)
        self.helpers = []

        # create temporary files
        self.dir = mkdtemp()
        self.latex_file, self.latex_filename = mkstemp(suffix='.tex',
                                                       dir=self.dir)

    def add_helper(self, helper):
        tmp = {'prename': helper.badge.prename or helper.prename,
               'surname': helper.badge.surname or helper.surname,
               'shift': helper.badge.shift}

        job = helper.badge.get_job()

        # job
        if helper.badge.job:
            tmp['job'] = helper.badge.job
        elif job:
            tmp['job'] = job.name
        else:
            tmp['job'] = ''

        # role
        if helper.badge.role:
            tmp['role'] = helper.badge.role
        elif helper.is_coordinator:
            tmp['role'] = self.settings.coordinator_title
        else:
            tmp['role'] = self.settings.helper_title

        # photo
        if helper.badge.photo:
            tmp['photo'] = helper.badge.photo.path
        else:
            tmp['photo'] = ''

        # design
        design = helper.badge.get_design()
        tmp['bgfront'] = design.bg_front.path
        tmp['bgback'] = design.bg_back.path
        tmp['fontcolor'] = self._latex_color(design.font_color)

        # role
        role = helper.badge.get_role()
        tmp['roleid'] = role.latex_name

        # permissions
        all_permissions = BadgePermission.objects.filter(
            badge_settings=self.settings).all()
        selected_permissions = role.permissions
        for perm in all_permissions:
            if selected_permissions.filter(pk=perm.pk).exists():
                tmp['perm-%s' % perm.latex_name] = 'true'
            else:
                tmp['perm-%s' % perm.latex_name] = 'false'

        self.helpers.append(tmp)

    def generate(self):
        latex_code = self._get_latex()

        # read template
        try:
            f = self.settings.latex_template
            f.open('r')
            template = f.read().decode('utf-8')
            f.close()
        except IOError as e:
            raise BadgeCreatorError("Cannot open file \"%s\": %s" %
                                    (self.settings.latex_template.path,
                                     str(e)))

        # replace '%BADGEDATA%'
        latex = template.replace('%BADGEDATA%', latex_code)

        # write code
        try:
            f = open(self.latex_file, 'w')
            f.write(latex)
            f.close()
        except IOError as e:
            raise BadgeCreatorError("Cannot write to file \"%s\": %s" %
                                    (self.latex_filename, str(e)))

        # debug
        if settings.BADGE_TEMPLATE_DEBUG_FILE:
            shutil.copyfile(self.latex_filename,
                            settings.BADGE_TEMPLATE_DEBUG_FILE)

        # call pdflatex
        try:
            subprocess.check_output(["pdflatex", "-halt-on-error",
                                     "-output-directory", self.dir,
                                     self.latex_filename])
        except subprocess.CalledProcessError as e:
            raise BadgeCreatorError("PDF generation failed", e.output)

        # return path to pdf
        return "%s.pdf" % os.path.splitext(self.latex_filename)[0]

    def finish(self):
        shutil.rmtree(self.dir)<commit_msg>fixed bug for python2 compatibility<commit_after>from django.conf import settings
from ..models import BadgePermission

from tempfile import mkdtemp, mkstemp
import os
import subprocess
import shutil


class BadgeCreatorError(Exception):
    def __init__(self, value, latex_output=None):
        self.value = value
        self.latex_output = latex_output

    def is_latex_output(self):
        return self.latex_output is not None

    def get_latex_output(self):
        return self.latex_output

    def __str__(self):
        return repr(self.value)


class BadgeCreator:
    def __init__(self, settings):
        self.settings = settings

        self.columns = self.settings.columns
        self.rows = self.settings.rows

        # list of helpers (dict with attributes)
        self.helpers = []

        # create temporary files
        self.dir = mkdtemp()
        self.latex_file, self.latex_filename = mkstemp(suffix='.tex',
                                                       dir=self.dir)

    def add_helper(self, helper):
        tmp = {'prename': helper.badge.prename or helper.prename,
               'surname': helper.badge.surname or helper.surname,
               'shift': helper.badge.shift}

        job = helper.badge.get_job()

        # job
        if helper.badge.job:
            tmp['job'] = helper.badge.job
        elif job:
            tmp['job'] = job.name
        else:
            tmp['job'] = ''

        # role
        if helper.badge.role:
            tmp['role'] = helper.badge.role
        elif helper.is_coordinator:
            tmp['role'] = self.settings.coordinator_title
        else:
            tmp['role'] = self.settings.helper_title

        # photo
        if helper.badge.photo:
            tmp['photo'] = helper.badge.photo.path
        else:
            tmp['photo'] = ''

        # design
        design = helper.badge.get_design()
        tmp['bgfront'] = design.bg_front.path
        tmp['bgback'] = design.bg_back.path
        tmp['fontcolor'] = self._latex_color(design.font_color)

        # role
        role = helper.badge.get_role()
        tmp['roleid'] = role.latex_name

        # permissions
        all_permissions = BadgePermission.objects.filter(
            badge_settings=self.settings).all()
        selected_permissions = role.permissions
        for perm in all_permissions:
            if selected_permissions.filter(pk=perm.pk).exists():
                tmp['perm-%s' % perm.latex_name] = 'true'
            else:
                tmp['perm-%s' % perm.latex_name] = 'false'

        self.helpers.append(tmp)

    def generate(self):
        latex_code = self._get_latex()

        # read template
        try:
            f = self.settings.latex_template
            f.open('r')
            template = f.read().decode('utf-8')
            f.close()
        except IOError as e:
            raise BadgeCreatorError("Cannot open file \"%s\": %s" %
                                    (self.settings.latex_template.path,
                                     str(e)))

        # replace '%BADGEDATA%'
        latex = template.replace('%BADGEDATA%', latex_code)

        # write code
        try:
            f = os.fdopen(self.latex_file, 'w')
            f.write(latex)
            f.close()
        except IOError as e:
            raise BadgeCreatorError("Cannot write to file \"%s\": %s" %
                                    (self.latex_filename, str(e)))

        # debug
        if settings.BADGE_TEMPLATE_DEBUG_FILE:
            shutil.copyfile(self.latex_filename,
                            settings.BADGE_TEMPLATE_DEBUG_FILE)

        # call pdflatex
        try:
            subprocess.check_output(["pdflatex", "-halt-on-error",
                                     "-output-directory", self.dir,
                                     self.latex_filename])
        except subprocess.CalledProcessError as e:
            raise BadgeCreatorError("PDF generation failed", e.output)

        # return path to pdf
        return "%s.pdf" % os.path.splitext(self.latex_filename)[0]

    def finish(self):
        shutil.rmtree(self.dir)
{'fraction_non_alphanumeric': 0.10485933503836317, 'fraction_numerical': 0.000608939227865059, 'mean_word_length': 1.704874835309618, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5425163', 'n_tokens_mistral': 2401, 'n_tokens_neox': 2329, 'n_words': 471}