Esempio n. 1
0
def t_import(filename, source, target):
    if filename:
        from_tron = json.loads(open(filename, 'r', encoding='utf-8').read())
    else:
        from_tron = json.loads(
            open(app_path + '/json_strings/strings.json',
                 'r',
                 encoding='utf-8').read())

    template_str = StringIO(open('messages.pot', 'r', encoding='utf-8').read())

    if not target:
        for locale in current_app.config.get('LANGUAGES').keys():
            new_catalog = Catalog()
            for id in from_tron:
                if locale in from_tron[id].keys():
                    new_catalog.add(id, from_tron[id][locale])
            new_catalog.update(template)
            write_po(
                open(
                    TRANSLATIONS_FOLDER + '/' + locale +
                    '/LC_MESSAGES/messages.po', 'wb'), new_catalog)

    else:
        new_catalog = Catalog()
        for id in from_tron:
            if target in from_tron[id].keys():
                new_catalog.add(id, from_tron[id][target])
        new_catalog.update(template)
        write_po(
            open(
                TRANSLATIONS_FOLDER + '/' + target +
                '/LC_MESSAGES/messages.po', 'wb'), new_catalog)
Esempio n. 2
0
    def po_catalog_export(self):
        """
        Export a catalog from a project into a PO file
        """
        toast_path = "/home/django/Emencia/po_headquarter/dummy_po/"

        project = Project.objects.get(slug='dummy')
        catalog = Catalog.objects.get(project=project, locale='fr')

        #mime_dict = json.loads(catalog.mime_headers)

        forged_catalog = BabelCatalog(locale=catalog.locale,
                                      header_comment=catalog.header_comment,
                                      project=project.name,
                                      version="0.2.0")

        print("before add:", len(forged_catalog))

        for entry in catalog.translationmsg_set.all().order_by('id'):
            locations = [
                tuple(item) for item in json.loads(entry.template.locations)
            ]
            forged_catalog.add(entry.template.message,
                               string=entry.message,
                               locations=locations,
                               flags=entry.template.flags)

        print("after add:", len(forged_catalog))
        print("errors:", [item for item in forged_catalog.check()])

        print()
        print("---------------- Original")
        fpw = StringIO()
        write_po(fpw,
                 forged_catalog,
                 sort_by_file=False,
                 ignore_obsolete=True,
                 include_previous=False)
        print(fpw.getvalue())
        fpw.close()

        print()
        print("---------------- Updated")
        fp3 = open(os.path.join(toast_path, '0-3-0.pot'), 'r')
        template_catalog_3 = read_po(fp3)
        forged_catalog.update(template_catalog_3)

        fpw = StringIO()
        write_po(fpw,
                 forged_catalog,
                 sort_by_file=False,
                 ignore_obsolete=True,
                 include_previous=False)
        print(fpw.getvalue())
        fpw.close()
Esempio n. 3
0
 def po_catalog_export(self):
     """
     Export a catalog from a project into a PO file
     """
     toast_path = "/home/django/Emencia/po_headquarter/dummy_po/"
     
     project = Project.objects.get(slug='dummy')
     catalog = Catalog.objects.get(project=project, locale='fr')
     
     #mime_dict = json.loads(catalog.mime_headers)
     
     forged_catalog = BabelCatalog(
         locale=catalog.locale, 
         header_comment=catalog.header_comment,
         project=project.name,
         version="0.2.0"
     )
     
     print "before add:", len(forged_catalog)
     
     for entry in catalog.translationmsg_set.all().order_by('id'):
         locations = [tuple(item) for item in json.loads(entry.template.locations)]
         forged_catalog.add(entry.template.message, string=entry.message, locations=locations, flags=entry.template.flags)
     
     print "after add:", len(forged_catalog)
     print "errors:", [item for item in forged_catalog.check()]
     
     print
     print "---------------- Original"
     fpw = StringIO()
     write_po(fpw, forged_catalog, sort_by_file=False, ignore_obsolete=True, include_previous=False)
     print fpw.getvalue()
     fpw.close()
     
     print
     print "---------------- Updated"
     fp3 = open(os.path.join(toast_path, '0-3-0.pot'), 'r')
     template_catalog_3 = read_po(fp3)
     forged_catalog.update(template_catalog_3)
     
     fpw = StringIO()
     write_po(fpw, forged_catalog, sort_by_file=False, ignore_obsolete=True, include_previous=False)
     print fpw.getvalue()
     fpw.close()
Esempio n. 4
0
class Pot(object):
    """This class encapsulates file operations and update from sources
    for a po or pot file. It uses the public API of the `babel` package.

    :param file_path: if is not `None`, the catalog is read from this file.
                      the catalog in empty in other case. Default is `None`.
    :attribute catalog: the catalog with the messages of the po/pot object.
                        It is a `babel.messages.catalog.Catalog`
    :attribute path: contains the path of the file associated if any. It is
                     `None` in other case.
    """
    def __init__(self, file_path=None, **kwargs):
        self.path = file_path
        if self.path is not None:
            self.from_file(self.path, **kwargs)
        else:
            self.catalog = Catalog(**kwargs)

    def extract(self, src_path='.', charset='utf-8', locale=None, **kwargs):
        """Extracts translatable messages from sources. This function is based
        on the extract function of the `pybabel` command, which is not part of
        the public API of `babel`. Only the public API of `babel` is used here.

        :param src_path: base path of the source tree, default is the current
                         path.
        :param charset: see the `babel.messages.catalog.Catalog` docs. Default
                        is `utf-8`.
        :param locale: see the `babel.messages.catalog.Catalog` docs. Default
                        is `None`.

        Other optional keyword parameters are passed to
        `babel.messages.extract.extract_from_dir` see `babel` public API docs.
        """
        #: This is the babel.messages.catalog.Catalog to contain the
        #: extracted messages
        self.catalog = Catalog(charset=charset, locale=locale)

        if not pth.isdir(src_path):
            raise IOError('{} is not a directory'.format(src_path))

        #: Extracts the data from source in a low level format. This is
        #: the only way present in babel's public API.
        extracted = extract_from_dir(src_path, **kwargs)

        #: Constructs the catalog from the raw extracted data.
        #: Based on the source code of pybabel:
        #: babel.messages.frontend.extract_messages.run
        for filename, lineno, message, comments, context in extracted:
            self.catalog.add(message, None, [(filename, lineno)],
                             auto_comments=comments, context=context)

    def from_file(self, file_path, **kwargs):
        """Reads the message's catalog from a file

        :param file_path: a path to a po/pot file. A exception is raised if the
        file does not exist. The `path` attribute is updated with this value.

        Other optional keyword parameters are passed to
        `babel.messages.pofile.read_po()` see `babel` public API docs.
        """
        with open(file_path, 'rt') as f:
            self.catalog = read_po(f, **kwargs)
        self.path = file_path

    def to_file(self, file_path=None, backup=True, warn=False, **kwargs):
        """Writes the catalog to a file.

        :param file_path: if the `file_path` attribute is  `None`, `path` is
                          taken as the output file and `file_path` parameter is
                          discarded. If `file_path` is not `None`, the output
                          file is `file_path` and `path` is not updated.
                          Default is `None`.
        :param backup: if `True` and the output file exists, a backup is made
                       prior to overwrite the file. Further backups overwrite
                       the previous.
        :param warn: if `True` warnings about fuzzy, untranslated and obsolete
                     messages are issued.

        Other optional keyword parameters are passed to
        `babel.messages.pofile.write_po()` see `babel` public API docs.
        """
        if file_path is None:
            file_path = self.path
        if pth.isfile(file_path) and backup:
            shutil.copy(file_path, '{}~'.format(file_path))

        if warn:
            logging.basicConfig(level=logging.WARNING)
            fuzzy = 0
            untrans = 0
            obsolete = len(self.catalog.obsolete)
            for message in self.catalog:
                if message.fuzzy and message.id:
                    fuzzy += 1
                if not message.string:
                    untrans += 1
            if fuzzy:
                logging.warning('There are {} fuzzy messages in {}.\n'.format(
                    fuzzy, file_path))
            if untrans:
                logging.warning('There are {} untranslated messages '
                                'in {}.\n'.format(untrans, file_path))
            if obsolete:
                logging.warning('There are {} obsolete  messages '
                                'in {}.\n'.format(obsolete, file_path))
        else:
            logging.basicConfig(level=logging.INFO)

        with open(file_path, 'wb') as f:
            write_po(f, self.catalog, **kwargs)

    def update(self, template_po, *args, **kwargs):
        """updates the catalog from a pot.

        :param template_po: a pot with a message template catalog. See
        `babel.messages.catalog.Catalog()`
        """
        self.catalog.update(template_po.catalog, *args, **kwargs)
Esempio n. 5
0
class Pot(object):
    """This class encapsulates file operations and update from sources
    for a po or pot file. It uses the public API of the `babel` package.

    :param file_path: if is not `None`, the catalog is read from this file.
                      the catalog in empty in other case. Default is `None`.
    :attribute catalog: the catalog with the messages of the po/pot object.
                        It is a `babel.messages.catalog.Catalog`
    :attribute path: contains the path of the file associated if any. It is
                     `None` in other case.
    """
    def __init__(self, file_path=None, **kwargs):
        self.path = file_path
        if self.path is not None:
            self.from_file(self.path, **kwargs)
        else:
            self.catalog = Catalog(**kwargs)

    def extract(self, src_path='.', charset='utf-8', locale=None, **kwargs):
        """Extracts translatable messages from sources. This function is based
        on the extract function of the `pybabel` command, which is not part of
        the public API of `babel`. Only the public API of `babel` is used here.

        :param src_path: base path of the source tree, default is the current
                         path.
        :param charset: see the `babel.messages.catalog.Catalog` docs. Default
                        is `utf-8`.
        :param locale: see the `babel.messages.catalog.Catalog` docs. Default
                        is `None`.

        Other optional keyword parameters are passed to
        `babel.messages.extract.extract_from_dir` see `babel` public API docs.
        """
        #: This is the babel.messages.catalog.Catalog to contain the
        #: extracted messages
        self.catalog = Catalog(charset=charset, locale=locale)

        if not pth.isdir(src_path):
            raise IOError('{} is not a directory'.format(src_path))

        #: Extracts the data from source in a low level format. This is
        #: the only way present in babel's public API.
        extracted = extract_from_dir(src_path, **kwargs)

        #: Constructs the catalog from the raw extracted data.
        #: Based on the source code of pybabel:
        #: babel.messages.frontend.extract_messages.run
        for filename, lineno, message, comments, context in extracted:
            self.catalog.add(message, None, [(filename, lineno)],
                             auto_comments=comments, context=context)

    def from_file(self, file_path, **kwargs):
        """Reads the message's catalog from a file

        :param file_path: a path to a po/pot file. A exception is raised if the
        file does not exist. The `path` attribute is updated with this value.

        Other optional keyword parameters are passed to
        `babel.messages.pofile.read_po()` see `babel` public API docs.
        """
        with open(file_path, 'rt') as f:
            self.catalog = read_po(f, **kwargs)
        self.path = file_path

    def to_file(self, file_path=None, backup=True, warn=False, **kwargs):
        """Writes the catalog to a file.

        :param file_path: if the `file_path` attribute is  `None`, `path` is
                          taken as the output file and `file_path` parameter is
                          discarded. If `file_path` is not `None`, the output
                          file is `file_path` and `path` is not updated.
                          Default is `None`.
        :param backup: if `True` and the output file exists, a backup is made
                       prior to overwrite the file. Further backups overwrite
                       the previous.
        :param warn: if `True` warnings about fuzzy, untranslated and obsolete
                     messages are issued.

        Other optional keyword parameters are passed to
        `babel.messages.pofile.write_po()` see `babel` public API docs.
        """
        if file_path is None:
            file_path = self.path
        if pth.isfile(file_path) and backup:
            shutil.copy(file_path, '{}~'.format(file_path))

        if warn:
            logging.basicConfig(level=logging.WARNING)
            fuzzy = 0
            untrans = 0
            obsolete = len(self.catalog.obsolete)
            for message in self.catalog:
                if message.fuzzy and message.id:
                    fuzzy += 1
                if not message.string:
                    untrans += 1
            if fuzzy:
                logging.warning('There are {} fuzzy messages in {}.\n'.format(
                    fuzzy, file_path))
            if untrans:
                logging.warning('There are {} untranslated messages '
                                'in {}.\n'.format(untrans, file_path))
            if obsolete:
                logging.warning('There are {} obsolete  messages '
                                'in {}.\n'.format(obsolete, file_path))
        else:
            logging.basicConfig(level=logging.INFO)

        with open(file_path, 'wb') as f:
            write_po(f, self.catalog, **kwargs)

    def update(self, template_po, *args, **kwargs):
        """updates the catalog from a pot.

        :param template_po: a pot with a message template catalog. See
        `babel.messages.catalog.Catalog()`
        """
        self.catalog.update(template_po.catalog, *args, **kwargs)