<commit_before># -*- coding:utf-8 -*-

# This file is part of agora-results.
# Copyright (C) 2016-2021  <NAME> <<EMAIL>>

# agora-results is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# agora-results  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 Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with agora-results.  If not, see <http://www.gnu.org/licenses/>. 

import os
import re
import subprocess
import json
import requests
from reportlab.lib import colors
from reportlab.platypus import (
  SimpleDocTemplate, 
  Paragraph, 
  Spacer, 
  Table, 
  TableStyle, 
  Image
)
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.enums import TA_RIGHT, TA_LEFT, TA_CENTER
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
import gettext
import os
from datetime import datetime
import pytz

def configure_pdf(
    data_list, 
    title=None, 
    first_description_paragraph=None,
    last_description_paragraph=None,
    languages=None,
    timezone=None,
    date_format=None
):
    data = data_list[0]
    data['pdf'] = {}
    if title:
        assert(isinstance(title, str))
        data['pdf']['title'] = title
    if first_description_paragraph:
        assert(isinstance(first_description_paragraph, str))
        data['pdf']['first_description_paragraph'] = first_description_paragraph
    if last_description_paragraph:
        assert(isinstance(last_description_paragraph, str))
        data['pdf']['last_description_paragraph'] = last_description_paragraph
    if languages:
        assert(isinstance(languages, list))
        for language in languages:
            assert(isinstance(language, str))
        data['pdf']['languages'] = languages
    if timezone:
        assert(isinstance(timezone, str))
        data['pdf']['timezone'] = timezone
    if date_format:
        assert(isinstance(date_format, str))
        data['pdf']['date_format'] = date_format

def remove_html(text):
    return re.sub(r"<[^>]+>", " ", text)

def parse_date(date_str, input_date_format, timezone_str, output_date_format):
    date = datetime.strptime(date_str, input_date_format)
    timezone = pytz.timezone(timezone_str)
    date_timezoned = date.astimezone(timezone)
    return date_timezoned.strftime(output_date_format)

def gen_text(
    text,
    size=None, 
    bold=False, 
    align=None, 
    color='black', 
    fontName=None
):
    if not isinstance(text, str):
        text = text.__str__()
    p = ParagraphStyle('test')
    if fontName:
        p.fontName = fontName
    if size:
        p.fontSize = size
        p.leading = size * 1.2
    if bold:
        text = '<b>%s</b>' % text
    p.textColor = color
    if align:
        p.alignment = align
    return Paragraph(text, p)

def get_election_cfg(election_id):
    headers = {'content-type': 'application/json'}
    base_url = 'http://localhost:9000/api'

    url = '%s/election/%d' % (base_url, election_id)

    try:
        r = requests.get(url, headers=headers, timeout=5)
    except requests.exceptions.Timeout:
        raise Exception(
            'Timeout when requesting election_id = %s' % election_id
        )

    if r.status_code != 200:
        print(r.status_code, r.text)
        raise Exception(
            'Invalid status code: %d for election_id = %s' % (
                r.status_code,
                election_id
            )
        )

    return r.json()

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        canvas.Canvas.__init__(self, *args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        """add page info to each page (page x of y)"""
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self.draw_page_number(num_pages)
            canvas.Canvas.showPage(self)
        canvas.Canvas.save(self)

    def draw_page_number(self, page_count):
        self.setFont("Helvetica", 7)
        self.drawRightString(200*mm, 20*mm,
            "Page %d of %d" % (self._pageNumber, page_count))


def _header_footer(canvas, doc):
    # Save the state of our canvas so we can draw on it
    canvas.saveState()
    styles = getSampleStyleSheet()

    # Header
    header = Image(
        '/home/agoraelections/agora-results/img/nvotes_logo.jpg',
        height=20,
        width=80
    )
    header.hAlign = 'RIGHT'
    w, h = header.wrap(doc.width, doc.topMargin)
    header.drawOn(
        canvas, 
        doc.width - w + doc.rightMargin, 
        doc.height + h + doc.bottomMargin - doc.topMargin
    )

    # Release the canvas
    canvas.restoreState()

def pdf_print(election_results, config_folder, election_id):

    localedir = os.path.join(
      os.path.abspath(os.path.dirname(__file__)), 
      'locale'
    )
    translate = gettext.translation(
      'pipes', 
      localedir, 
      languages=election_results.get('pdf', dict()).get('languages', None), 
      fallback=True
    )
    _ = translate.gettext
    try:
        jsonconfig = get_election_cfg(election_id)
        election_title = remove_html(jsonconfig['payload']['configuration']['title'])
    except:
        election_title = ""

    tx_description = _(
        'Detailed and question by question results of the election ' +
        '{election_id} titled <u>"{election_title}"</u>.'
    ).format(
        election_id=election_id,
        election_title=election_title
    )
    tx_title = _(
        'Results of the election tally {election_id} - {election_title}'<commit_msg>ensure unneded dependencies don't import when calling configure_pdf (#75)<commit_after># -*- coding:utf-8 -*-

# This file is part of agora-results.
# Copyright (C) 2016-2021  <NAME> <<EMAIL>>

# agora-results is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# agora-results  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 Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with agora-results.  If not, see <http://www.gnu.org/licenses/>. 

import os
import re
import gettext
import os
from datetime import datetime

def configure_pdf(
    data_list, 
    title=None, 
    first_description_paragraph=None,
    last_description_paragraph=None,
    languages=None,
    timezone=None,
    date_format=None
):
    data = data_list[0]
    data['pdf'] = {}
    if title:
        assert(isinstance(title, str))
        data['pdf']['title'] = title
    if first_description_paragraph:
        assert(isinstance(first_description_paragraph, str))
        data['pdf']['first_description_paragraph'] = first_description_paragraph
    if last_description_paragraph:
        assert(isinstance(last_description_paragraph, str))
        data['pdf']['last_description_paragraph'] = last_description_paragraph
    if languages:
        assert(isinstance(languages, list))
        for language in languages:
            assert(isinstance(language, str))
        data['pdf']['languages'] = languages
    if timezone:
        assert(isinstance(timezone, str))
        data['pdf']['timezone'] = timezone
    if date_format:
        assert(isinstance(date_format, str))
        data['pdf']['date_format'] = date_format

def remove_html(text):
    return re.sub(r"<[^>]+>", " ", text)

def parse_date(date_str, input_date_format, timezone_str, output_date_format):
    import pytz
    date = datetime.strptime(date_str, input_date_format)
    timezone = pytz.timezone(timezone_str)
    date_timezoned = date.astimezone(timezone)
    return date_timezoned.strftime(output_date_format)

def gen_text(
    text,
    size=None, 
    bold=False, 
    align=None, 
    color='black', 
    fontName=None
):
    from reportlab.platypus import Paragraph
    from reportlab.lib.styles import ParagraphStyle

    if not isinstance(text, str):
        text = text.__str__()
    p = ParagraphStyle('test')
    if fontName:
        p.fontName = fontName
    if size:
        p.fontSize = size
        p.leading = size * 1.2
    if bold:
        text = '<b>%s</b>' % text
    p.textColor = color
    if align:
        p.alignment = align
    return Paragraph(text, p)

def get_election_cfg(election_id):
    import requests
    headers = {'content-type': 'application/json'}
    base_url = 'http://localhost:9000/api'

    url = '%s/election/%d' % (base_url, election_id)

    try:
        r = requests.get(url, headers=headers, timeout=5)
    except requests.exceptions.Timeout:
        raise Exception(
            'Timeout when requesting election_id = %s' % election_id
        )

    if r.status_code != 200:
        print(r.status_code, r.text)
        raise Exception(
            'Invalid status code: %d for election_id = %s' % (
                r.status_code,
                election_id
            )
        )

    return r.json()

def _header_footer(canvas, doc):
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.platypus import Image

    # Save the state of our canvas so we can draw on it
    canvas.saveState()
    styles = getSampleStyleSheet()

    # Header
    header = Image(
        '/home/agoraelections/agora-results/img/nvotes_logo.jpg',
        height=20,
        width=80
    )
    header.hAlign = 'RIGHT'
    w, h = header.wrap(doc.width, doc.topMargin)
    header.drawOn(
        canvas, 
        doc.width - w + doc.rightMargin, 
        doc.height + h + doc.bottomMargin - doc.topMargin
    )

    # Release the canvas
    canvas.restoreState()

def pdf_print(election_results, config_folder, election_id):
    from reportlab.lib import colors
    from reportlab.platypus import (
        SimpleDocTemplate,
        Spacer,
        Table,
        TableStyle,
    )
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.enums import TA_RIGHT, TA_LEFT, TA_CENTER
    from reportlab.pdfgen import canvas
    from reportlab.lib.units import mm

    class NumberedCanvas(canvas.Canvas):
        def __init__(self, *args, **kwargs):
            canvas.Canvas.__init__(self, *args, **kwargs)
            self._saved_page_states = []

        def showPage(self):
            self._saved_page_states.append(dict(self.__dict__))
            self._startPage()

        def save(self):
            """add page info to each page (page x of y)"""
            num_pages = len(self._saved_page_states)
            for state in self._saved_page_states:
                self.__dict__.update(state)
                self.draw_page_number(num_pages)
                canvas.Canvas.showPage(self)
            canvas.Canvas.save(self)

        def draw_page_number(self, page_count):
            self.setFont("Helvetica", 7)
            self.drawRightString(200*mm, 20*mm,
                "Page %d of %d" % (self._pageNumber, page_count))

    localedir = os.path.join(
      os.path.abspath(os.path.dirname(__file__)), 
      'locale'
    )
    translate = gettext.translation(
      'pipes', 
      localedir, 
      languages=election_results.get('pdf', dict()).get('languages', None), 
      fallback=True
    )
    _ = translate.gettext
    try:
        jsonconfig = get_election_cfg(election_id)
        election_title = remove_html(jsonconfig['payload']['configuration']['title'])
    except:
        election_title = ""

    tx_description = _(
        'Detailed and question by question results of the election ' +
        '{election_id} titled <u>"{election_title}"</u>.'
    ).format(
        election_id=election_id,
        election_title=election_title
    )
    tx_title = _(
        'Results of the election tally {election_id} - {election_title}'
{'fraction_non_alphanumeric': 0.10263030498628369, 'fraction_numerical': 0.005163788930127481, 'mean_word_length': 2.7998160637645615, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2852926', 'n_tokens_mistral': 3792, 'n_tokens_neox': 3680, 'n_words': 926}