Skip to content

Any ways to generate translation tables ? #89

Closed

Description

@geekyme

hello, is there an automated way to generate translation tables in multiple languages when we write our components?

So when we are done writing our components with formatJS syntax, we can type a command to generate some JSON / .pot files to upload to a translation software.

Flask-Babel does this quite elegantly with its

$ pybabel init -i messages.pot -d translations -l de

Activity

  1. ericf commented on Mar 10, 2015

    @ericf
    Collaborator

    This is what we're shooting towards. I've began developing a POC of an idea I have to statically analyze an app's React components looking for string messages that need to be translated.

    Once I get something working to talk about I'll be happy to share it.

  2. caridy commented on Mar 10, 2015

    @caridy
    Collaborator

    lets also loop other people with experience on this field like @tinganho, creator of l10ns.

  3. tinganho commented on Mar 10, 2015

    @tinganho

    I'm happy to help. For starters, my biggest pain for the static code analyzation was misses in message id extractions and a miss means a deleted message in l10ns. I'm using a combination of regex and some logic right now. In my initial plan—I was considering using a JS parser like esprima to make the message id extraction bullet proof. I have kept using regex in L10ns, because I might make it available to other programming languages and I don't think people want to write their own parser for these languages.

    I guess for react-intl, the best would be to hook into some JSX/JS parser and get the relevant AST nodes from there.

  4. tinganho commented on Mar 10, 2015

    @tinganho

    Btw, @caridy @ericf I'm landing an article on AlistApart next week in an effort to mainstream ICU's MessageFormat in the JS community. It will be about pluralization in JavaScript and I'm mentioning formatjs.

  5. ericf commented on Mar 10, 2015

    @ericf
    Collaborator

    @tinganho cool! Send us email if you need anything from us.

  6. ericf commented on Mar 10, 2015

    @ericf
    Collaborator

    Here's the train of thought I followed to arrive at my rough idea:

    It sucks to have to maintain a separate strings file and keep it in sync with UI components where those strings are used. Doing it this way leads to over translations (which costs real money) and cruft over time.

    Authoring messages inside the components where they are used is ideal for encapsulation and creating [potentially disposable] components. But doing that would go against traditional internationalization practices and potentially lead to duplicate messages.

    Message translation is a [long] async process done by humans, and in many cases the job is contracted out to professional translators. This means we always need some default or fallback message available if we want true CI/CD.

    Messages can become complex if they use plural/select arguments, so its ideal to author them in a context where multi-line strings are supported.

    The process of finding messages in code can happen via static analysis because all messages should be gathered, de-duplicated, and sent off for translation. An ideal static analysis process would be as unambiguous and deterministic as possible.

    These thoughts lead me to coming up with the idea of using ES6 Module exports + ES6 Tagged Template Strings as the hooks for the static analyzer. The default/fallback messages would be written as tagged template strings (multi-line support). The static analyzer would look for these tagged template strings and generate a hash using the literal string as both the key and value to create the default strings external file. This allows for the messages to be de-duplicated throughout all of the source.

    I'm imagining something like this:

    import React from 'react';
    import {
        translated,
        IntlMixin,
        FormattedMessage
    } from 'react-intl';
    
    var Component = React.createClass({
        mixins: [IntlMixin],
    
        render() {
            var hello = translated`Hello, {name}`;
    
            return (
                <FormattedMessage
                    message={this.getIntlMessage(hello)}
                    name={this.props.name}
                />
            );
        }
    });
    
    export default Component;

    And the static analyzer would produce a default.json messages file:

    {
        "Hello, {name}": "Hello, {name}"
    }

    And a translator would create say the fr.json message file:

    {
        "Hello, {name}": "Bonjour, {name}"
    }

    For the runtime side of things I was thinking this:

    The the template string tag translated would be inert and simply return the literal string value which is the key to lookup the translated message. If the translation was missing, then the key — which is the default/fallback message — would be formatted.

    Again, this are my rough ideas and I still haven't built a POC with working code.

  7. tinganho commented on Mar 10, 2015

    @tinganho

    @ericf I've had problem using text as message ids. Maybe it is just my translators, but I dealt with apps where the word "Cancel" can be rendered differently depending on context in some languages. It's a known problem in Gettext where they solves this by defining the property msgctxt. https://www.gnu.org/software/gettext/manual/html_node/Contexts.html

  8. geekyme commented on Mar 10, 2015

    @geekyme
    Author

    Looks great @ericf . In python flask, I litter html templates with bunch of

    {{ gettext('some string') }}
    

    PyBabel will read each gettext static analyzer will deduplicate and produce files with the string as key too.

    Would we be able to achieve the same effect by analyzing and grabbing the string contents between each getIntlMessage ? http://formatjs.io/react/#getIntlMessage

    Then the generated json files can be required:

    var messages = require('en-US.json')
    
    var intlData = {
        "locales": "en-US",
        "messages": messages
    };
    
  9. caridy commented on Mar 10, 2015

    @caridy
    Collaborator

    @geekyme we can't do that because getIntlMessage will be overloaded, and you can call it with virtually anything, while translated is easy to identify and is declarative, which makes it even easier.

    @tinganho the cancel use case is interesting, we haven't thought about it, I guess a quick solution will be to extract some extra metadata from the file to signal what part of the app, or component does the string belongs to, so the translation tool (and the output json file with the default strings) can signal what type of translation is needed.

  10. sebmarkbage commented on Mar 11, 2015

    @sebmarkbage

    We've been doing this for years now and it has been very successful. In fact, we've completely removed our previous system that used external strings.

    I'd recommend that you also have support for embedding strings in your JSX. This makes it even more collocated and is easier to manage for complex content.

    You don't need to write it in a standardized format, as long as you can extract it into a standardized format.

    We do something like this:

    <FormattedMessage>
      Hello, <Param key="name">{this.props.name}</Param>
    </FormattedMessage>

    You can even fit pluralization in there, you just use an JSX like syntax for it. IMO, the sweet spot is when you can reuse the React keys as param names and embed components:

    <FormattedMessage>
      Hello, <strong key="name">{this.props.name}</strong>
    </FormattedMessage>

    You can even have pluralization etc:

    <FormattedMessage>
      You have
      <strong key="itemCount">{this.props.items}</strong>
      <Pluralize count={this.props.items}>
        item
      </Pluralize>
      in your cart.
    </FormattedMessage>

    We also annotate files with additional information (jsdoc blocks) that relate to all messages in a file, e.g. what project they belong to.

    cc @jrwats

  11. jbrantly commented on Mar 11, 2015

    @jbrantly

    I spoke briefly to @ericf about this at React.js Conf. Static analysis is really the way to go. We built something at AssureSign which uses esprima and pofile to extract and package strings based on gettext, with overloads for context and plural forms. The nice thing about using function calls instead of tagged template strings is the overloads.

    For integrating with JSX we simply escape to JS:

    <span>{tr('Some translatable string')}</span>
    

    The downside to this is that it's harder to work with multiple plural words in the same string, and it's hard to do things like formatting.

  12. caridy commented on Mar 11, 2015

    @caridy
    Collaborator

    @sebmarkbage my only concern about using react props directly in messages is that translations have a long life, they normally transcend multiple rewrites/evolutions of the product (at least in my experience), so having the props in the messages mean a refactor hazard since messages will tend to force the implementation in the long run.

  13. ericf commented on Mar 11, 2015

    @ericf
    Collaborator

    The nice thing about using function calls instead of tagged template strings is the overloads.

    @jbrantly Can you explain this more? The tagged template strings are function calls and allow for multi-line strings which is a huge benefit for more complex messages.

  14. 9 remaining items

  15. drd commented on May 11, 2015

    @drd

    I think it's interesting what you're trying to do here, seems similar to what the FB folks are doing.

    I think I'm predisposed to think along those same lines… we are rewriting a Python application that uses Genshi templates, which have a very nice message extraction interface, which is the conceptual basis for this work in a lot of ways.

    This generates the message, "You have{ itemCount, plural, =0 { no items } one { one item } other { {itemCount} items } }in your cart."

    Is the idea that whatever this string gets translated into, you'll take the translated string and stick it as a child to the element in the code-gen'd function?

    Yes, the translated string will be re-formulated into React components in the code-gen'd function, expanding any MessageFormat transforms into the corresponding ReactIntl component.

    I could see the message string getting very large with all the React syntax in it, and that could both confuse the translator (especially for deep sub-trees) and cost you much more money since translators are usually paid by word. It's unlikely that translation systems will be smart enough to understand JSX and not count words in angle-brackets.

    That's a valid concern in the general case and I'm very curious to see how that plays out, but in my experience I have found that most units of translation are small and contain few embedded tags/elements.

    In Genshi, nested tags are extracted in a way that hides them entirely from translators, and represents them as numerical references. The fragment <p i18n:msg="foo">Your name is <span id="foo">${this.foo}</span>, right?</p> is extracted as "Your name is [1:%(foo)s], right?". It would be possible to do something similar here, but one of the benefits of our approach is to allow translators to alter whitelisted attributes of the HTML. (See our original goals, updated somewhat to correspond with this proposal)

    The trick with this approach is that the original component may reference external dependencies which are in lexical scope, which will not be available in the translated module. So, I plan to transform the render function into a closure which will invoke the translated renderer with all of the free variables as arguments.

    I agree this will be a problem. It also sounds like a lot of added complexity for something I'm not sold on being a benefit — that is defining the messages as JSX instead of using the ICU Message syntax.

    Seeing where you ended up with this, makes me think that declaratively defining strings using ICU Message syntax, then declaratively formatting those strings using will be a better approach, all things considered.

    It does seem like a lot of added complexity, but I strongly feel that it's worth it for two reasons:

    1. As an author, I am able to write components more or less like I normally do, seeing the natural hierarchy of the components that I'm creating. (It sounds though that we both agree that co-locating the message and the component logic is a good thing.)
    2. Automated extraction of strings :) We're a small team and not having to maintain synchronization between the messages and the code is a big win for us. Of course, we do still have to define what fuzzy-matching is in this space…

    The thing missing from my original proposal in this thread is having a way to define metadata for an ICU Message string that gives it a label, context, and potentially a note for the translator. If you want to continuing going with defining strings in JSX, I'd recommend add that too — probably on your component.

    I agree — <I18N comment="An obscure string" context="nav-menu"> ... </I18N> would be a very useful interface. (I even made a patch to genshi to add gettext's msgctxt property to it. :)

  16. necolas commented on May 15, 2015

    @necolas

    Following from @sebmarkbage's example. Google Closure Templates have a msg command that is similar, and it has a really useful feature which is a desc param to provide translators with additional context needed to accurately translate the text (important given the ambiguity of language, particularly when phrases are short). It could look something like this:

    <FormattedMessage desc="Indicates how many items are in the shopping cart">
      You have
      <strong key="itemCount">{this.props.items}</strong>
      <Pluralize count={this.props.items}>item</Pluralize>
      in your cart.
    </FormattedMessage>
  17. SlexAxton commented on May 21, 2015

    @SlexAxton

    Just in case it's helpful, I used to do something very similar at Bazaarvoice inside of Handlebars with Messageformat.js - I had initially begun to implement it publicly, but never fully completed: https://github.com/slexaxton/mfbars

    My two pain points (which perhaps you fine folks could resolve) were:

    • Not every string was inside of a template. Our error messages, for instance were a mapping of error codes to strings that we'd then stick into an error popup. So we still ended up needing to have some messages outside of templates. The way we solved this was just generating the translation file from our templates, but also allowing an external file with a subset of the keys, and then merging them together. This worked alright, but I think you'd want to know about this ahead of time. We also had the idea of "message packs" - which could live directly next to the files for components that had the strings for those components that couldn't be declarative. button.js and button.mf.json - and the relevant strings lived there. We could "automatically" resolve and precompile all those files into our final output as well (with nicely scoped keys based on the file system).
    • More importantly: we needed a lot more than just an ID and a message to get back high quality translations. By the time we were done, we'd send our translators an ID, the message, a developer written description of when/how the message would be used, an optional screenshot of the message in context, a list of possible/example values for the variables, and probably a few other things. If you try to smash all of that in a template, it becomes pretty cumbersome.
    {{! forgive my handlebars }}
    
    <button class="foo">
    {{#_ "a.key.here" . description="This is a button you'd click to get a discount on a product" screenshot="https://screenshot.org" vars="{price: ['$10.99', '$49.99'], item: ['vacuums', 'guitars']}"}}
      Click here to save {price} on {item}!
    {{/_}}
    </button>

    That kind of ruins the whole point of nice, inline messages for context. We eventually switched to using a comment node with just raw json in it (similar to the jsdoc block that seb mentioned), since it was easier to type, but that was a hack. Many of our developers preferred to just write it in the external files because of all the extra information they needed to provide. There are plenty of messages that don't have this much data, so maybe it doesn't matter as much, but I think this type of metadata really does make a vast difference for the quality of translations.

    Feel free to ignore entirely, and forgive the lack of react specifics, but I figured I'd let you guys know where we ran into trouble so you can try to avoid from the outset.

  18. jenseng commented on May 24, 2015

    @jenseng

    +1 for something like the Facebook approach, where strings are as inline as possible. Typically most strings in an application don't have pluralization or gender concerns. So the more you can optimize the API for the common case, the better it is for developers IMO.

    I've been working on something similar for react (albeit built on a much weaker backend, i18n-js), and it's working well in the first app I've added it to. The API is ridiculously simple, just translate="yes" on any component 😮, e.g.

    <p translate="yes">
      Hey {this.props.user.name}!
      Although I am <Link to="route">linking to something</Link> and
      have some <strong>bold text</strong>, the translators will see
      <strong><em>absolutely no markup</em></strong> and will only have a
      single string to translate :o
    </p>

    Nested components/markup get converted into wrappers (increasing pairs of asterisks, e.g. "Although I am *linking to something* ..."), which keeps the translations clean and solves some of the problems with @drb's approach.

    We've had a lot of success with this strategy in handlebars and ERB over the years in canvas-lms and a couple other apps @ instructure (via i18nliner(rb) and i18nliner-handlebars).

    That said, MessageFormat/FormatJS is a much more robust backend ... i18n.rb and i18n-js fall apart when you have multiple plurals in the string, and they have no concept of gender. IMO the ideal solution would be i18nliner (or something like it) with MessageFormat/FormatJS as the backend... a dead simple API for the common case, but the ability to opt in to powerful features when you need them. And as others have commented, the ability to provide context/description to translators is super important.

    While I do eventually want to make i18nliner support other backends, it's not at the top of my priority list ATM (but I will happily accept reasonable PRs). So you may find some ideas from it useful for wherever this ticket ends up going 😄

  19. tinganho commented on May 24, 2015

    @tinganho

    From personal experience, I have just found the problem with that the same English text can be translated differently in two or more locations. I don't know if there is a need of a thorough description if there is just one problem? I could be wrong on this.

    One thing to consider then, instead of having a thorough description describing the text that is going to be translated – just use the view context as the information? I think the view context and the English translation is the only info the translator needs? Writing thorough description is cumbersome.

    In L10ns, I recommend people to set message id:s using a view hierarchy.
    http://l10ns.org/docs.html#namingkeys

    As an example:

    This Github issue has a label with a message id:
    ISSUES->THREAD->COMMENT_AND_CLOSE_BUTTON_TEXT with the value Comment and close. This is enough information to translate it on any language. If Comment and close is too long to be translated in one place but not another in some other language. The translator will know it because she knows which view it belongs to.

  20. SlexAxton commented on May 24, 2015

    @SlexAxton

    I agree that that would be enough information for me, or another person on my team to translate the string. But we worked with some of the biggest vendors (ended up with SDL, longer term), and the quality of translation increased by double when we sent them a handwritten description of the context. All of our keys were named in more or less the same way you list there (using dots instead of arrows, and maybe less capital letters). It's certainly the case that for very obvious things we could skip.

    Even if translators were able to find context for the easy strings via the keys, which wasn't my experience, it certainly made a big difference to send in 'example variable values' so we could render sentences as whole coherent strings to translate, rather than expect that our translators would fully learn the complexities of messageformat syntax.

    (Trust me, I'd be the first person jumping up and down with joy if I could just send a key and a messageformat string and get back high quality translations. It is cumbersome to provide the extra context and help to translators, but I haven't experienced a case when it hans't increased the quality by a huge margin)

  21. drd commented on Jun 23, 2015

    @drd

    For anyone interested in automatic message extraction, I have some initial work available at drd/jsxlate. It's not 100% ready for public consumption, but I would appreciate any feedback you have to offer.

    @ericf @caridy I'm particularly interested in sharing locale information, such as the plural function, between FormatJS and jsxlate — however currently I don't see a great way to do that. Suggestions?

    I would like to explore ways to converge jsxlate with React Intl, since you have done a ton of great work here, I just need, essentially, a different implementation of FormattedMessage and intend to use all the rest of your components.

  22. caridy commented on Jun 23, 2015

    @caridy
    Collaborator

    @drd we tried to keep things as dry as possible, using a bunch of small, re-usable, packages, you just need to figure what are those that you need. As for the CLDR, the same applies, here is what you need: https://github.com/yahoo/grunt-extract-cldr-data, and here is how we use it in this project: https://github.com/yahoo/react-intl/blob/master/Gruntfile.js#L35-L78

  23. geekyme commented on Jun 27, 2015

    @geekyme
    Author

    @ericf @caridy I'm not too sure about the progress but it seems this issue has been around for really long with no real solution yet. Are you guys coming up with one?

  24. caridy commented on Jun 29, 2015

    @caridy
    Collaborator

    I was on sabbatical for few months, and @ericf was working on other stuff, but we are determined to work on this at some point, let's keep this open.

  25. mAiNiNfEcTiOn commented on Jul 3, 2015

    @mAiNiNfEcTiOn

    Hi guys, I'm currently choosing a translation library for my team to start implementing it, so I will give you my 2 cents talking a little bit about my experience.

    I started by implementing gettext on our project, which was enough until we got texts being used in several pages and have different translations and/or purposes.

    Besides that, the ICU format seemed much better because it targeted localization points that gettext didn't, specially DateFormat, CurrencyFormat, etc...

    But regarding the creation of the texts (and their keys), I noticed that there were some aspects to take into consideration:

    1. We, as developers, don't maintain the texts... We create them in the page, but others maintain them and translate them. And - at least in my company - we normally take those texts and then pass them to third-parties that are responsible for translating them. The context is truly important for both the Content Managers (yes, persons) and the third-parties with whom we work and rely in.
    2. The texts are constantly changing. The text that originally was Hello, {name} can quickly become Welcome {name}, your last login was {last_login, date, short}. And you can have worse, like sentences that in the beginning were welcome messages, but then become nothing related.

    I agree with @tinganho that defining keys using a view hierarchy would be ideal. It would provide the necessary context to the editor, while maintaining the specificity and usability.

    I am currently seeing both l10ns and FormatJs as alternatives to use. However FormatJS has something that I can't seem to find in L10ns, which is integration with Handlebars.

    Nevertheless I am still analyzing the libs, maybe I'll come up with that integration to it :)

    Hope I was of any help.

  26. ericf commented on Sep 11, 2015

    @ericf
    Collaborator

    See: #162

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions