<commit_before>"""
Formatters take a License instance and a dictionary of work metadata about
the licensed work. The keys of this work_dict are as follows:

 - format (Audio:Sound, Video:MovingImage, Image:StillImage,
           Text:Text, Interactive:InteractiveResource)
          Either this mapping above or the actual dctype
 - worktitle
 - attribution_name
 - attribution_url
 - source_work
 - more_permissions_url
"""

from urlparse import urlparse

import zope.interface

from cc.license._lib.interfaces import ILicenseFormatter
from cc.license import util
from cc.i18n.gettext_i18n import ugettext_for_locale
from cc.i18n.gettext_i18n import fake_ugettext as _
from cc.i18n.util import locale_to_lower_lower
from cc.i18n import mappers

import jinja2


TEMPLATE_LOADER = jinja2.PackageLoader('cc.license.formatters', 'templates')
TEMPLATE_ENV = jinja2.Environment(
    loader=TEMPLATE_LOADER, autoescape=False,
    extensions=['jinja2.ext.i18n'])


### --------------------------
### HTMLFormatter support functions
### --------------------------

IMAGE_HEADER_TEMPLATE = (
    '<a rel="license" href="%(license_url)s">'
    '<img alt="%(util.Creative_Commons_License)s" style="border-width:0"'
    ' src="%(license_logo)s" /></a><br />')


def get_dctype_url(dctype):
    return "http://purl.org/dc/dcmitype/%s" % dctype


WORK_TYPE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(dctype_url)s"'
    ' rel="dct:type">%(work)s</span>')

def process_work_type(gettext, dctype):
    work_word = gettext('work')
    if dctype:
        return WORK_TYPE_TEMPLATE % (
            {'dctype_url': get_dctype_url(dctype),
             'work': util.escape(work_word)})
    else:
        return util.escape(work_word)


DCTYPE_WORK_TITLE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(dctype_url)s"'
    ' property="dct:title"'
    ' rel="dct:type">%(worktitle)s</span>')
NO_DCTYPE_WORK_TITLE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' property="dct:title">%(worktitle)s</span>')

def process_work_title(dctype, worktitle):
    if dctype:
        return DCTYPE_WORK_TITLE_TEMPLATE % {
            'dctype_url': get_dctype_url(dctype),
            'worktitle': util.escape(worktitle)}
    else:
        return NO_DCTYPE_WORK_TITLE_TEMPLATE % {
            'worktitle': util.escape(worktitle)}


WORK_AUTHOR_TEMPLATE = (
    '<a xmlns:cc="http://creativecommons.org/ns#"'
    ' href="%(attribution_url)s" property="cc:attributionName"'
    ' rel="cc:attributionURL">%(attribution_name)s</a>')
WORK_AUTHOR_TEMPLATE_NO_URL = (
    '<span xmlns:cc="http://creativecommons.org/ns#"'
    ' property="cc:attributionName">%(attribution_name)s</span>')

def process_work_author(attribution_url, attribution_name):
    if attribution_url:
        return WORK_AUTHOR_TEMPLATE % {
            'attribution_name': util.escape(
                attribution_name or attribution_url),
            'attribution_url': util.escape(attribution_url)}
    else:
        return WORK_AUTHOR_TEMPLATE_NO_URL % {
            'attribution_name': util.escape(attribution_name)}


SOURCE_LINK_TEMPLATE = (
    '<a xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(source_work)s" rel="dct:source">%(source_domain)s</a>')

MORE_PERMS_LINK_TEMPATE = (
    '<a xmlns:cc="http://creativecommons.org/ns#"'
    ' href="%(more_permissions_url)s"'
    ' rel="cc:morePermissions">%(more_permissions_url)s</a>')


def _translate_dctype(format):
    # NOTE:
    #
    # So it's not clear if this function is needed or not.  Do we need
    # to support the Audio:Sound style mapping?  The current API and
    # Engine don't require it, but maybe an older version did.  Since
    # we're not sure we're keeping it here as legacy. :\
    try:
        return {
                 None : None,
                 'audio' : 'Sound',
                 'video' : 'MovingImage',
                 'image' : 'StillImage',
                 'text' : 'Text',
                 'interactive' : 'InteractiveResource',

                 # Original DCTYPES
                 # XXX: This is silly, but then again maybe this whole
                 #   function is silly.  Regardless, we already get the
                 #   format type from cc.engine in the correct form; no need
                 #   to translate.
                 'sound': 'Sound',
                 'movingimage': 'MovingImage',
                 'stillimage': 'StillImage',
                 'text': 'Text',
                 'interactiveresource': 'InteractiveResource',
                 'dataset': 'Dataset',
               }[format]
    except KeyError: # if we dont understand it, pretend its not there
        return None

### END HTMLFormatter support functions

class HTMLFormatter(object):
    zope.interface.implements(ILicenseFormatter)

    def __repr__(self):
        return "<LicenseFormatter object '%s'>" % self.id

    def __str__(self):
        return '(%s)' % self.title

    @property
    def id(self):
        return 'html+rdfa'

    @property
    def title(self):
        return "HTML + RDFa formatter"

    def format(self, license, work_dict=None, locale='en'):
        """Return an HTML + RDFa string serialization for the license,
            optionally incorporating the work metadata and locale."""
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        localized_deed = license.uri
        if locale!='en':
            localized_deed += "deed." + locale

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url': localized_deed,
            'util.Creative_Commons_License': util.escape(
                gettext(u'Creative Commons License')),
            'license_logo': license.logo}

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        body_vars = {
            'license_url': localized_deed,
            'license_name': util.escape(
                license.title(locale_to_lower_lower(locale)))}

        if ((work_dict.get('attribution_url')
             or work_dict.get('attribution_name'))
                and work_dict.get('worktitle')):
            body_template = gettext(
                    u'%(work_title)s by %(work_author)s is licensed under a '
                    u'<a rel="license" href="%(license_url)s">Creative Commons '
                    u'%(license_name)s License</a>.')
            body_vars.update(
                {'work_title': process_work_title(<commit_msg>HTMLFormatter now normalizes deed uri's language correctly.<commit_after>"""
Formatters take a License instance and a dictionary of work metadata about
the licensed work. The keys of this work_dict are as follows:

 - format (Audio:Sound, Video:MovingImage, Image:StillImage,
           Text:Text, Interactive:InteractiveResource)
          Either this mapping above or the actual dctype
 - worktitle
 - attribution_name
 - attribution_url
 - source_work
 - more_permissions_url
"""

from urlparse import urlparse

import zope.interface

from cc.license._lib.interfaces import ILicenseFormatter
from cc.license import util
from cc.i18n.gettext_i18n import ugettext_for_locale
from cc.i18n.gettext_i18n import fake_ugettext as _
from cc.i18n.util import locale_to_lower_lower
from cc.i18n import mappers

import jinja2


TEMPLATE_LOADER = jinja2.PackageLoader('cc.license.formatters', 'templates')
TEMPLATE_ENV = jinja2.Environment(
    loader=TEMPLATE_LOADER, autoescape=False,
    extensions=['jinja2.ext.i18n'])


### --------------------------
### HTMLFormatter support functions
### --------------------------

IMAGE_HEADER_TEMPLATE = (
    '<a rel="license" href="%(license_url)s">'
    '<img alt="%(util.Creative_Commons_License)s" style="border-width:0"'
    ' src="%(license_logo)s" /></a><br />')


def get_dctype_url(dctype):
    return "http://purl.org/dc/dcmitype/%s" % dctype


WORK_TYPE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(dctype_url)s"'
    ' rel="dct:type">%(work)s</span>')

def process_work_type(gettext, dctype):
    work_word = gettext('work')
    if dctype:
        return WORK_TYPE_TEMPLATE % (
            {'dctype_url': get_dctype_url(dctype),
             'work': util.escape(work_word)})
    else:
        return util.escape(work_word)


DCTYPE_WORK_TITLE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(dctype_url)s"'
    ' property="dct:title"'
    ' rel="dct:type">%(worktitle)s</span>')
NO_DCTYPE_WORK_TITLE_TEMPLATE = (
    '<span xmlns:dct="http://purl.org/dc/terms/"'
    ' property="dct:title">%(worktitle)s</span>')

def process_work_title(dctype, worktitle):
    if dctype:
        return DCTYPE_WORK_TITLE_TEMPLATE % {
            'dctype_url': get_dctype_url(dctype),
            'worktitle': util.escape(worktitle)}
    else:
        return NO_DCTYPE_WORK_TITLE_TEMPLATE % {
            'worktitle': util.escape(worktitle)}


WORK_AUTHOR_TEMPLATE = (
    '<a xmlns:cc="http://creativecommons.org/ns#"'
    ' href="%(attribution_url)s" property="cc:attributionName"'
    ' rel="cc:attributionURL">%(attribution_name)s</a>')
WORK_AUTHOR_TEMPLATE_NO_URL = (
    '<span xmlns:cc="http://creativecommons.org/ns#"'
    ' property="cc:attributionName">%(attribution_name)s</span>')

def process_work_author(attribution_url, attribution_name):
    if attribution_url:
        return WORK_AUTHOR_TEMPLATE % {
            'attribution_name': util.escape(
                attribution_name or attribution_url),
            'attribution_url': util.escape(attribution_url)}
    else:
        return WORK_AUTHOR_TEMPLATE_NO_URL % {
            'attribution_name': util.escape(attribution_name)}


SOURCE_LINK_TEMPLATE = (
    '<a xmlns:dct="http://purl.org/dc/terms/"'
    ' href="%(source_work)s" rel="dct:source">%(source_domain)s</a>')

MORE_PERMS_LINK_TEMPATE = (
    '<a xmlns:cc="http://creativecommons.org/ns#"'
    ' href="%(more_permissions_url)s"'
    ' rel="cc:morePermissions">%(more_permissions_url)s</a>')


def _translate_dctype(format):
    # NOTE:
    #
    # So it's not clear if this function is needed or not.  Do we need
    # to support the Audio:Sound style mapping?  The current API and
    # Engine don't require it, but maybe an older version did.  Since
    # we're not sure we're keeping it here as legacy. :\
    try:
        return {
                 None : None,
                 'audio' : 'Sound',
                 'video' : 'MovingImage',
                 'image' : 'StillImage',
                 'text' : 'Text',
                 'interactive' : 'InteractiveResource',

                 # Original DCTYPES
                 # XXX: This is silly, but then again maybe this whole
                 #   function is silly.  Regardless, we already get the
                 #   format type from cc.engine in the correct form; no need
                 #   to translate.
                 'sound': 'Sound',
                 'movingimage': 'MovingImage',
                 'stillimage': 'StillImage',
                 'text': 'Text',
                 'interactiveresource': 'InteractiveResource',
                 'dataset': 'Dataset',
               }[format]
    except KeyError: # if we dont understand it, pretend its not there
        return None

### END HTMLFormatter support functions

class HTMLFormatter(object):
    zope.interface.implements(ILicenseFormatter)

    def __repr__(self):
        return "<LicenseFormatter object '%s'>" % self.id

    def __str__(self):
        return '(%s)' % self.title

    @property
    def id(self):
        return 'html+rdfa'

    @property
    def title(self):
        return "HTML + RDFa formatter"

    def format(self, license, work_dict=None, locale='en'):
        """Return an HTML + RDFa string serialization for the license,
            optionally incorporating the work metadata and locale."""
        gettext = ugettext_for_locale(locale)

        work_dict = work_dict or {}

        localized_deed = license.uri
        default_lang = license.jurisdiction.default_language
        if not default_lang:
            default_lang = "en"
        if locale != default_lang:
            localized_deed += "deed." + locale

        image_header = IMAGE_HEADER_TEMPLATE % {
            'license_url': localized_deed,
            'util.Creative_Commons_License': util.escape(
                gettext(u'Creative Commons License')),
            'license_logo': license.logo}

        dctype = None
        if work_dict.get('format'):
            dctype = _translate_dctype(work_dict['format'].lower())

        body_vars = {
            'license_url': localized_deed,
            'license_name': util.escape(
                license.title(locale_to_lower_lower(locale)))}

        if ((work_dict.get('attribution_url')
             or work_dict.get('attribution_name'))
                and work_dict.get('worktitle')):
            body_template = gettext(
                    u'%(work_title)s by %(work_author)s is licensed under a '
                    u'<a rel="license" href="%(license_url)s">Creative Commons '
                    u'%(license_name)s License</a>.')
            body_vars.update(
                {'work_title': process_work_title(
{'fraction_non_alphanumeric': 0.12854770531400966, 'fraction_numerical': 0.0028683574879227055, 'mean_word_length': 2.6348422496570643, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 14}, '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': '905567', 'n_tokens_mistral': 4328, 'n_tokens_neox': 4050, 'n_words': 847}