How to use polib - 10 common examples

To help you get started, we’ve selected a few polib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github edx / i18n-tools / tests / test_extract.py View on Github external
def test_is_keystring(self):
        """
        Verifies is_keystring predicate
        """
        entry1 = polib.POEntry()
        entry2 = polib.POEntry()
        entry1.msgid = "_.lms.admin.warning.keystring"
        entry2.msgid = "This is not a keystring"
        self.assertTrue(extract.is_key_string(entry1.msgid))
        self.assertFalse(extract.is_key_string(entry2.msgid))
github edx / i18n-tools / tests / test_compiled_messages.py View on Github external
def test_translated_messages(self, locale):
        message_dir = LOCALE_DIR / locale / 'LC_MESSAGES'
        for pofile_name in self.PO_FILES:
            pofile_path = message_dir / pofile_name
            pofile = polib.pofile(pofile_path)
            mofile = polib.mofile(pofile_path.stripext() + '.mo')

            po_entries = {entry.msgid: entry for entry in pofile.translated_entries()}
            mo_entries = {entry.msgid: entry for entry in mofile.translated_entries()}

            # Check that there are no entries in po that aren't in mo, and vice-versa
            self.assertEquals(po_entries.viewkeys(), mo_entries.viewkeys())

            for entry_id, po_entry in po_entries.items():
                mo_entry = mo_entries[entry_id]
                for attr in ('msgstr', 'msgid_plural', 'msgstr_plural', 'msgctxt', 'obsolete', 'encoding'):
                    po_attr = getattr(po_entry, attr)
                    mo_attr = getattr(mo_entry, attr)

                    # The msgstr_plural in the mo_file is keyed on ints, but in the po_file it's
                    # keyed on strings. This normalizes them.
                    if attr == 'msgstr_plural':
github django / django-localflavor / scripts / port.py View on Github external
locale_locale_po_file = join(country_locale_subdir,
                                         'LC_MESSAGES', 'django.po')
            # get locale to update from dir name
            _, subdir_locale = split(country_locale_subdir)

            # build path to new destination locale po file, create dirs
            locale_subdir = join(locale_dir, subdir_locale, 'LC_MESSAGES')
            dest_po_path = join(locale_subdir, 'django.po')
            mkdir_p(locale_subdir)

            print 'merging', locale_locale_po_file, 'into', dest_po_path

            # either load existing file and add the entries of the current source file
            if exists(dest_po_path):
                dest_po = polib.pofile(dest_po_path, encoding='utf-8', check_for_duplicates=True)
                src_po = polib.pofile(locale_locale_po_file, encoding='utf-8')
                merge(src_po, dest_po)
            # or just load the source file directly
            else:
                dest_po = polib.pofile(locale_locale_po_file, encoding='utf-8')

            # update the project-id-version to be consistent
            dest_po.metadata['Project-Id-Version'] = 'django-localflavor'
            # save new po file
            dest_po.save(dest_po_path)
            # and compile it
            dest_po.save_as_mofile(join(locale_subdir, 'django.mo'))
            # print 'percent translated for', dest_po_path, po.percent_translated()

        # throw away the old locale subdir
        if exists(country_locale_dir):
github mozilla / kitsune / scripts / l10n_completion.py View on Github external
def get_completion_data_for_file(fn):
    """Parses .po file and returns completion data for that .po file

    :returns: dict with keys total, translated and percent

    """
    app_to_translations = {}

    lang = get_language(fn)

    try:
        pofile = polib.pofile(fn)
    except IOError as ioe:
        print 'Error opening file: {fn}'.format(fn=fn)
        print ioe.message
        return 1

    for poentry in pofile:
        if poentry.obsolete:
            continue

        for occ in poentry.occurrences:
            path = occ[0].split(os.sep)
            if path[0] == 'kitsune':
                path = path[1]
            else:
                path = 'vendor/' + path[2]
            app_to_translations.setdefault(
github transifex / transifex / transifex / webtrans / views.py View on Github external
def transfile_edit(request, pofile_id):
    pofile = get_object_or_404(POFile, pk=pofile_id)
    po_entries = pofile.object.trans.get_po_entries(pofile.filename)
    filename = pofile.filename
    component = pofile.object
    lang_code = pofile.language_code

    if not webtrans_is_under_max(pofile.total):
        return permission_denied(request)

    if request.method == "POST":
        for fieldname, value in request.POST.items():
            if 'msgid_field_' in fieldname:
                nkey = fieldname.split('msgid_field_')[1]
                if request.POST.get('changed_field_%s' % nkey, None) == 'True':
                    entry = po_entries.find(unescape(value))

                    #TODO: Find out why it's needed to remove it first
                    po_entries.remove(entry)

                    try:
                        string = request.POST['msgstr_field_%s' % nkey]
                        entry.msgstr = unescape(string);
                    except MultiValueDictKeyError:
                        has_plurals = True
                        index=0
                        while has_plurals:
                            plural_field = 'msgstr_field_%s_%s' % (nkey, index)
                            string = request.POST.get(plural_field, None)
                            if string is not None:
                                entry.msgstr_plural['%s' % index]=unescape(string)
                            else:
github transifex / transifex / transifex / webtrans / wizards.py View on Github external
nkey = fieldname.split('msgid_field_')[1]
                msgstr_field = 'msgstr_field_%s' % nkey
                fuzzy_field = 'fuzzy_field_%s' % nkey

                if msgstr_field in form.changed_data or \
                    fuzzy_field in form.changed_data:

                    msgid_value = form.cleaned_data['msgid_field_%s' % nkey]
                    entry = self.po_entries.find(unescape(msgid_value))

                    msgstr_value = form.cleaned_data['msgstr_field_%s' % nkey]
                    try:
                        entry.msgstr = unescape(msgstr_value)
                    except AttributeError:
                        for i, value in enumerate(msgstr_value):
                            entry.msgstr_plural['%s' % i]=unescape(value)

                    # Taking care of fuzzies flags
                    if form.cleaned_data.get('fuzzy_field_%s' % nkey, None):
                        if 'fuzzy' not in entry.flags:
                            entry.flags.append('fuzzy')
                    else:
                        if 'fuzzy' in entry.flags:
                            entry.flags.remove('fuzzy')
github transifex / transifex / transifex / webtrans / wizards.py View on Github external
def update_po_entries(self, form):
        """
        Update po_entries, which is a polib.POFile object, with the changed 
        form data.
        """
        for fieldname in form.fields.keys():
            if 'msgid_field_' in fieldname:
                nkey = fieldname.split('msgid_field_')[1]
                msgstr_field = 'msgstr_field_%s' % nkey
                fuzzy_field = 'fuzzy_field_%s' % nkey

                if msgstr_field in form.changed_data or \
                    fuzzy_field in form.changed_data:

                    msgid_value = form.cleaned_data['msgid_field_%s' % nkey]
                    entry = self.po_entries.find(unescape(msgid_value))

                    msgstr_value = form.cleaned_data['msgstr_field_%s' % nkey]
                    try:
                        entry.msgstr = unescape(msgstr_value)
                    except AttributeError:
                        for i, value in enumerate(msgstr_value):
                            entry.msgstr_plural['%s' % i]=unescape(value)

                    # Taking care of fuzzies flags
                    if form.cleaned_data.get('fuzzy_field_%s' % nkey, None):
                        if 'fuzzy' not in entry.flags:
                            entry.flags.append('fuzzy')
                    else:
                        if 'fuzzy' in entry.flags:
                            entry.flags.remove('fuzzy')
github qooxdoo / qooxdoo / qooxdoo / tool / pylib / generator / action / Locale.py View on Github external
def pofileGetIdIndex(self):
    idIndex = {}
    for entry in self:
        idIndex[entry.msgid] = entry
    self.idIndex = idIndex
    return idIndex

##
# looks up a msgid in the POFile, using the .idIndex index generated by .getIdIndex()

def pofileIndexFind(self, msgid):
    return self.idIndex.get(msgid, None)

# Attach the new methods to the POFile class

polib.POFile.getIdIndex = pofileGetIdIndex
polib.POFile.indexFind  = pofileIndexFind

class Locale(object):
    def __init__(self, context, classesObj, translation, cache, console):
        self._context = context
        self._classesObj = classesObj
        self._translation = translation
        self._cache = cache
        self._console = console



    def getLocalizationData(self, classList, targetLocales, ):
        self._console.debug("Generating localization data...")
        data = {}
github qooxdoo / qooxdoo / tool / pylib / generator / action / Locale.py View on Github external
def pofileGetIdIndex(self):
    idIndex = {}
    for entry in self:
        idIndex[entry.msgid] = entry
    self.idIndex = idIndex
    return idIndex

##
# looks up a msgid in the POFile, using the .idIndex index generated by .getIdIndex()

def pofileIndexFind(self, msgid):
    return self.idIndex.get(msgid, None)

# Attach the new methods to the POFile class

polib.POFile.getIdIndex = pofileGetIdIndex
polib.POFile.indexFind  = pofileIndexFind

class Locale(object):
    def __init__(self, context, classesObj, translation, cache, console):
        self._context = context
        self._classesObj = classesObj
        self._translation = translation
        self._cache = cache
        self._console = console



    def getLocalizationData(self, classList, targetLocales, ):
        self._console.debug("Generating localization data...")
        data = {}
github transifex / transifex / transifex / webtrans / fields.py View on Github external
def _calculate_rows(entry):
    """Return the estimated number of rows for a textarea based on string size."""
    text = getattr(entry, 'msgid', entry)
    if isinstance(text, str):
        text = text.decode(getattr(entry, 'encoding', 'UTF-8'))
    replacement = polib.escape(text).replace(r'\n','<br>\n')
    lines = mark_safe(replacement).split(u'\n')
    return sum(len(line)/40 for k, line in enumerate(lines)) + 1