Beispiel #1
0
def translate(key, location, **kwargs):
    lid = None
    if location is not None:
        if hasattr(location, "guild"):
            location = location.guild
        if location is not None and hasattr(location, "id"):
            lid = location.id
        else:
            lid = location

    if lid is None:
        lang_key = "en_US"
    else:
        lang_key = Configuration.get_var(lid, "GENERAL", "LANG")
    translated = key
    if key not in LANGS[lang_key]:
        if key not in untranlatable:
            BOT.loop.create_task(tranlator_log('WARNING', f'Untranslatable string detected: {key}\n'))
            untranlatable.add(key)
        return key if key not in LANGS["en_US"] else format(LANGS['en_US'][key], kwargs, 'en_US')
    try:
        translated = format(LANGS[lang_key][key], kwargs, lang_key)
    except (KeyError, ValueError, ParseError, VisitationError) as ex:
        BOT.loop.create_task(tranlator_log('NO', f'Corrupt translation detected!\n**Lang code:** {lang_key}\n**Translation key:** {key}\n```\n{LANGS[lang_key][key]}```'))
        GearbotLogging.exception("Corrupt translation", ex)
        if key in LANGS["en_US"].keys():
            try:
                translated = format(LANGS['en_US'][key], kwargs, 'en_US')
            except (KeyError, ValueError, ParseError, VisitationError) as ex:
                BOT.loop.create_task(tranlator_log('NO', f'Corrupt English source string detected!\n**Translation key:** {key}\n```\n{LANGS["en_US"][key]}```'))
                GearbotLogging.exception('Corrupt translation', ex)
    return translated
Beispiel #2
0
def test_format():
    select = format('{WHO, select, male {He} female {She} other {They}}.',
                    {'WHO': 'male'}, 'en')

    assert select == 'He.'

    plural = format(
        '{NUM_TICKETS, plural, one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {'NUM_TICKETS': 1}, 'en')

    assert plural == '1 ticket.'

    select_plural = format(
        '{GENDER, select, male {He wants} female {She wants} other {They want}} {NUM_TICKETS, plural, one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {
            'GENDER': 'male',
            'NUM_TICKETS': 5
        }, 'en')

    assert select_plural == 'He wants 5 tickets.'

    select_plural_offset = format(
        '{GENDER, select, male {He wants} female {She wants} other {They want}} {NUM_TICKETS, plural, offset:2 one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {
            'GENDER': 'female',
            'NUM_TICKETS': '44'
        }, 'en')

    assert select_plural_offset == 'She wants 42 ticketerinos.'
Beispiel #3
0
    def render(
        cls,
        source_string,
        string_to_render,
        language_code,
        escape,
        missing_policy,
        params=None,
    ):
        """Render the given ICU string.

        Takes into account the given language code (for the plurals)
        as well as the given parameters.

        If the given `string_to_render` is None, it returns a rendered
        string based on the given `missing_policy`.

        :param unicode source_string: the full ICU string in the source
            language
        :param unicode string_to_render: the full ICU string to render as a
            string_to_render
        :param str language_code: the language code to use
        :param bool escape: if True, the returned string will be HTML-escaped,
            otherwise it won't
        :param AbstractRenderingPolicy missing_policy: the policy to use for
            returning strings when `string_to_render` is missing. If `None`,
            don't use a missing policy. In that case, if `string_to_render`
            does not exist, a `RenderingError` will be raised.
        :return: the final rendered string
        :rtype: unicode
        """

        if params is None:
            params = {}

        try:
            if not string_to_render and not missing_policy:
                raise Exception(
                    "No string to render and no missing policy defined!"
                    " (Source String: `{}`)".format(source_string))

            # `string_to_render` doesn't exist, fallback to the missing policy
            if not string_to_render and missing_policy:
                if escape:
                    source_string = html_escape(source_string)
                return missing_policy.get(
                    format(source_string, params, language_code))

            if escape:
                string_to_render = html_escape(string_to_render)

            rendered = format(string_to_render, params, language_code)
            return rendered
        except Exception as e:
            logger.error(
                "RenderingError: Could not render string `%s` in language `%s` "
                "with parameters `%s` (Error: %s, Source String: %s)",
                string_to_render, language_code, str(params), str(e),
                source_string)
            raise e
Beispiel #4
0
def isICUvalid(valueToCheck, values, lang):
    try:
        result = format(valueToCheck, values, lang)
        return True

    except Exception:
        return False
Beispiel #5
0
def translate(key, location, **kwargs):
    lang_key = "en_US"
    translated = key
    if key not in LANGS[lang_key]:
        if key not in untranlatable:
            BOT.loop.create_task(tranlator_log('WARNING', f'Untranslatable string detected in {lang_key}: {key}\n'))
            untranlatable.add(key)
        return key
    try:
        translated = format(LANGS[lang_key][key], kwargs, lang_key)
    except (KeyError, ValueError, ParseError, VisitationError) as ex:
        BOT.loop.create_task(tranlator_log('NO', f'Corrupt translation detected!\n**Lang code:** {lang_key}\n**Translation key:** {key}\n```\n{LANGS[lang_key][key]}```'))
        GearbotLogging.exception("Corrupt translation", ex)
    return translated
Beispiel #6
0
def test_format():
    select = format(
        '{WHO, select, male {He} female {She} other {They}}.',
        {'WHO': 'male'}, 'en')

    assert select == 'He.'

    plural = format(
        '{NUM_TICKETS, plural, one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {'NUM_TICKETS': 1}, 'en')

    assert plural == '1 ticket.'

    select_plural = format(
        '{GENDER, select, male {He wants} female {She wants} other {They want}} {NUM_TICKETS, plural, one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {'GENDER': 'male', 'NUM_TICKETS': 5}, 'en')

    assert select_plural == 'He wants 5 tickets.'

    select_plural_offset = format(
        '{GENDER, select, male {He wants} female {She wants} other {They want}} {NUM_TICKETS, plural, offset:2 one {1 ticket} other {# tickets} =42 {42 ticketerinos}}.',
        {'GENDER': 'female', 'NUM_TICKETS': '44'}, 'en')

    assert select_plural_offset == 'She wants 42 ticketerinos.'
Beispiel #7
0
def translate_by_code(key, code, **kwargs):
    if key not in LANGS[code]:
        return key
    return format(LANGS[code][key], kwargs, code)
Beispiel #8
0
from pyseeyou import format
try:
    result = format(
        '''{GENDER, select,
                       male {He}
                     female {She}
                      other {They}
                   } found {NUM_RESULTS, plural,
                       one {1 result}}}}}
                     other {# results}
                   } in {NUM_CATEGORIES, plural,
                         one {1 category}
                       other {# categories}
                   }.''', {
            'GENDER': 'male',
            'NUM_RESULTS': 1,
            'NUM_CATEGORIES': '2'
        }, 'en')
    print(result)
except Exception:
    print("Error")


def isICUvalid(valueToCheck, values, lang):
    try:
        result = format(valueToCheck, values, lang)
        return True

    except Exception:
        return False
Beispiel #9
0
    @classmethod
    def translate(cls, query_string, context=None, **kwargs) -> str:
        current_lang = 'en_US'

        if context is not None:
            if hasattr(context, 'guild'):
                if context.guild is not None:
                    if (settings_cache :=
                            CacheManager.guilds.get(context.guild.id,
                                                    None)) is not None:
                        current_lang = settings_cache.language

            elif isinstance(context, int):
                if (settings_cache :=
                        CacheManager.guilds.get(context, None)) is not None:
                    current_lang = settings_cache.language

        try:
            translation = pyseeyou.format(
                cls.translations[current_lang][query_string], kwargs,
                current_lang)
        except KeyError:
            try:
                translation = pyseeyou.format(
                    cls.translations['en_US'][query_string], kwargs,
                    current_lang)
            except KeyError:
                translation = "..."

        return translation