Skip to content

Commit

Permalink
Add support for localization API of npf-renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
syeopite committed Jan 2, 2025
1 parent 3dac874 commit e79ca25
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 7 deletions.
84 changes: 84 additions & 0 deletions locales/en_US/LC_MESSAGES/npf_renderer.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Copyright (C) 2023 Syeopite
# This file is distributed under the same license as the Priviblur project.
# syeopite <[email protected]>, 2023
#
msgid ""
msgstr ""
"Project-Id-Version: Priviblur v0.3.0-dev\n"
"Report-Msgid-Bugs-To: https://github.com/syeopite/priviblur/issues\n"
"POT-Creation-Date: 2023-11-16 00:07-0800\n"
"PO-Revision-Date: 2024-06-29 04:09+0000\n"
"Last-Translator: syeopite <[email protected]>\n"
"Language-Team: English <https://hosted.weblate.org/projects/priviblur/"
"translations/en/>\n"
"Language: en\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 5.7-dev\n"

msgid "asker_with_no_attribution"
msgstr "Anonymous"

msgid "asker_and_ask_verb"
msgstr "{name} asked"

msgid "unsupported_block_header"
msgstr "Unsupported NPF block"

msgid "unsupported_block_description"
msgstr "Placeholder for the unsupported \"{block}\" type NPF block Please report me over at https://github.com/syeopite/npf-renderer"

msgid "generic_image_alt_text"
msgstr "image"

msgid "link_block_poster_alt_text"
msgstr "Preview image for \"{site}\""

msgid "link_block_fallback_embeds_are_disabled"
msgstr "Embeds are disabled"

msgid "error_video_link_block_fallback_heading"
msgstr "Error: unable to render video block"

msgid "video_link_block_fallback_description"
msgstr "Please click me to watch on the original site"

msgid "error_link_block_fallback_native_video_player_non_tumblr_source"
msgstr "Error: non-tumblr source for video player"

msgid "fallback_audio_block_thumbnail_alt_text"
msgstr "Album art"

msgid "error_audio_link_block_fallback_heading"
msgstr "Error: unable to render audio block"

msgid "audio_link_block_fallback_description"
msgstr "Please click me to listen on the original site"

msgid "error_link_block_fallback_native_audio_player_non_tumblr_source"
msgstr "Error: non-tumblr source for audio player"

msgid "poll_total_votes"
msgid_plural "poll_total_votes_plural"
msgstr[0] "{votes} vote"
msgstr[1] "{votes} votes"

msgid "poll_remaining_time"
msgstr "{duration} remaining"

msgid "poll_ended_on"
msgstr "Ended on: {ended_date}"

msgid "post_attribution"
msgstr "From {0}"

msgid "blog_attribution"
msgstr "Created by {0}"

msgid "app_attribution"
msgstr "View on {0}"

msgid "unsupported_attribution"
msgstr "Attributed via an unsupported (\"{0}\") attribution type. Please report this over at https://github.com/syeopite/npf-renderer"
1 change: 1 addition & 0 deletions src/helpers/ext_npf_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ def __init__(
if request:
# Asking to expand a post is the reverse of asking to truncate a post
initialization_arguments["truncate"] = not request.ctx.preferences.expand_posts
initialization_arguments["localizer"] = request.app.ctx.LANGUAGES[request.ctx.language].npf_renderer_localizer

super().__init__(**initialization_arguments)

Expand Down
63 changes: 57 additions & 6 deletions src/i18n/i18n.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,58 @@
import sys
import gettext
import typing
import functools

import sanic
import babel
import babel.dates
import npf_renderer

from .i18n_data import LOCALE_DATA


class NPFRendererGettextFallback(gettext.NullTranslations):
def gettext(self, message):
return npf_renderer.DEFAULT_LOCALIZATION[message]

def ngettext(self, msgid1: str, msgid2: str, n: int) -> str:
return npf_renderer.DEFAULT_LOCALIZATION[msgid1]


class NPFRendererLocalizer:
def __init__(self, language, locale):
self.language = language
self.locale = locale

self.format_functions = {
"format_duration_func": functools.partial(babel.dates.format_timedelta, threshold=1.1, locale=language),
"format_datetime_func": functools.partial(babel.dates.format_datetime, format=f"short", locale=language),
}

def __getitem__(self, key : str):
# Starts with format_
if key[:7] == "format_":
return self.format_functions[key]
# Starts with plural_
elif key[:7] == "plural_":
return lambda number : translate(self.language, key[7:], number, priviblur_translations=False)

translate("en_US", "poll_remaining_time", priviblur_translations=False)

return translate(self.language, key, priviblur_translations=False)


class Language:
"""Stores metadata about supported translations"""
def __init__(self, locale, gettext_instance,) -> None:
def __init__(self, locale, priviblur_gettext, npf_renderer_gettext) -> None:
self.locale = locale

self.priviblur_translations = gettext_instance
self.babel_locale = babel.Locale.parse(locale)

self.priviblur_translations = priviblur_gettext

self.npf_renderer_translations = npf_renderer_gettext
self.npf_renderer_localizer = NPFRendererLocalizer(locale, self.babel_locale)

self.name, self.translation_percentage = LOCALE_DATA[locale]

Expand All @@ -30,8 +70,11 @@ def initialize_locales() -> typing.Mapping[str, Language]:

priviblur_english_instance = gettext.translation("priviblur", localedir="locales", languages=("en_US",))

npf_renderer_english_instance = gettext.translation("npf_renderer", localedir="locales", languages=("en_US",))
npf_renderer_english_instance.add_fallback(NPFRendererGettextFallback())

languages = {
"en_US": Language("en_US", priviblur_english_instance)
"en_US": Language("en_US", priviblur_english_instance, npf_renderer_english_instance)
}

for locale in SUPPORTED_LANGUAGES:
Expand All @@ -41,7 +84,12 @@ def initialize_locales() -> typing.Mapping[str, Language]:
instance = gettext.translation("priviblur", localedir="locales", languages=(locale,))
instance.add_fallback(priviblur_english_instance)

languages[locale] = Language(locale, instance)
try:
npf_renderer_instance = gettext.translation("npf_renderer", localedir="locales", languages=(locale,))
except FileNotFoundError:
npf_renderer_instance = npf_renderer_english_instance

languages[locale] = Language(locale, instance, npf_renderer_instance)
except FileNotFoundError as e:
print(
'Error: Unable to find locale files. '
Expand All @@ -56,10 +104,13 @@ def initialize_locales() -> typing.Mapping[str, Language]:


def translate(language : str, id : str, number : int | float | None = None,
substitution : str | dict | None = None) -> str:
substitution : str | dict | None = None, priviblur_translations : bool = True) -> str:
app = sanic.Sanic.get_app("Priviblur")

gettext_instance = app.ctx.LANGUAGES[language].priviblur_translations
if priviblur_translations:
gettext_instance = app.ctx.LANGUAGES[language].priviblur_translations
else:
gettext_instance = app.ctx.LANGUAGES[language].npf_renderer_translations

if number is not None:
translated = gettext_instance.ngettext(id, f"{id}_plural", number)
Expand Down
2 changes: 1 addition & 1 deletion src/preferences.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import dataclasses
import urllib.parse

from .helpers.i18n import SUPPORTED_LANGUAGES
from .i18n import SUPPORTED_LANGUAGES

VERSION = 1

Expand Down

0 comments on commit e79ca25

Please sign in to comment.