Substitute Template For Each Project

Update: Please, download scripts from the dedicated SF.net project page where they are maintained. Scripts at the links below might be obsolete (though most likely still working).

Here I have a script that reads a tab-separated file (any number of tabs between items), each line of which contains the patterns to be found in the first position, and what it should be replaced with in the second. This file MUST be named subst_template.txt (well, it can be changed in the script, so maybe such a loud “must” isn’t really needed). The first pair should start on the first line, no empty lines between the pairs, and after the final pair there should be exactly one empty line. Below you’ll find an example of such file.
The file ought to be placed in OmegaT project’s root. That is made intentionally so that one can have a unique set of substitute patterns for each project. For example, I had an English to Ukrainian Christian project where names of the Bible books needed to be translated using one particular Ukrainian Bible version (Khomenko Bible), while for another project they needed to be taken from another version (Ohiyenko Bible). While English abbreviations remained the same, Ukrainian needed to be quite different (for instance, “Jn.” was “Йо.” in one, and “Ів.” in the other). So having a separate substitute pattern file in each projects I could use just one script to get Bible references with proper abbreviations in each of them. Continue reading

Simple QA with OmegaT GUI scripts

Here I want to share several groovy scripts that bring up a window showing a clickable segment # button to skip to the respective segment, and source and target segments that meet certain criteria. I’m not a scripting master, so I share them in hope that they can be helpful to some and improved by many (reverse the pronouns if needed).
Here’s but one screenshot to give you an idea what this is all about.
Window showing a simple QA check

Following is a list of scripts with links (click on titles) to download them, and short descriptions of what each one does.

Update: Please, download scripts from the dedicated SF.net project page where they are maintained. Scripts at the links below might be obsolete (though most likely still working).

  • Check QA rules script
  • This one is a simple QA check. Originally it was included in OmegaT scripts bundle, but I expanded it to show a window with clickable buttons. Currently checks for leading and trailing spaces, double words, and unproportionally longer or shorter target segments. If anyone knows how to add more rules to check, please share.
    Update: No need to download this script from here, it’s now included in the OmegaT bundle.

  • Show Source = Target
  • This one was originally included in the bundle as well, and I just added the GUI part. It brings up a window that lets you navigate through segments where target is the same as source.

  • Show Untranslated
  • This script brings up a window with all the untranslated segments, so you get only segment # buttons and source segments. Beside that, in the scripting console (lower part of the right side of the Scripting window) you get the count of all and unique untranslated segments. I don’t see a big practical value of this script, but a friend of mine and a fellow OmegaT user felt really blessed to get it. This one originally isn’t mine either, I used Yu Tang’s idea that he shared on OmegaT Yahoo! Group.

Testing scripts

You know, of course, about the Scripting Plugin for OmegaT. If you’re a member of OmegaT Yahoo user group, you may know Yu Tang who provided a bunch of nice scripts to open various files and folders of the currently active OmegaT project. His scripts have been included in the most recent version of the Scripting Plugin. The only problem with them was that one needed to edit them if they were used on OS’es other than MS Windows. Generally not a problem, as many OmegaT users are quite computer savvy, but it would be nicer if they could work everywhere “out of box”.

Yu Tang has updated the scripts so now they check which OS they are running on. If you’re willing to test them out and report any possible problems, please do.

The scripts are listed here and posted on the Pastebin.com with the link to each individual script right before the respective listing.

  1. open_current_file.groovy
    /*
    * Open current file
    *
    * @author Yu Tang
    * @date 2013-05-23
    * @version 0.2
    */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
    final def title = 'open current file'
    final def msg = 'Please try again after you open a project.'
    showMessageDialog null, msg, title, INFORMATION_MESSAGE
    return
    }
    
    // get command GString to open a file
    def file = prop.sourceRoot + editor.currentFile
    def command
    switch (osType) {
    case [OsType.WIN64, OsType.WIN32]:
    command = "cmd /c start \"\" \"$file\"" // for WinNT
    // command = "command /c start \"\" \"$file\"" // for Win9x or WinME
    break
    case [OsType.MAC64, OsType.MAC32]:
    command = "open \"$file\""
    break
    default: // for Linux or others
    command = ['xdg-open', file]
    break
    }
    
    // open it
    command.execute()
    
  2. open_folder.groovy
    /*
     *  Open project folder
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open project folder'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString to open a folder
    def folder = prop.projectRoot
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "explorer.exe \"$folder\""
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$folder\""
        break
      default:  // for Linux or others
        command = ['xdg-open', folder]
        break
    }
    
    // open it
    command.execute()
    
  3. open_glossary.groovy
    /*
     *  Open the writeable glossary in an editor
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    /**
     * Uncomment the next line if you want to set a default text editor
     * that will open glossary file
     */
    // def textEditor = /path to your editor/
    // E.g., /TextMate/
    // /C:\Program Files (x86)\editor\editor.exe/
    // ['x-terminal-emulator', '-e', 'vi']
    
    // make a Closure to show message dialog
    def showMessage = { msg -> showMessageDialog null, msg, 'Open glossary', INFORMATION_MESSAGE }
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      showMessage 'Please try again after you open a project.'
      return
    }
    
    // exit if file not found
    def file = prop.writeableGlossary
    if (! new File(file).exists()) {
      showMessage 'Glossary file not found.'
      return
    }
    
    // get command GString list to open a file
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "cmd /c start \"\" \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "\"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "open -a \"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      default:  // for Linux or others
        command = ['xdg-open', file] // default
        try { command = textEditor instanceof List ? [*textEditor, file] : [textEditor, file] } catch (ignore) {}
        break
    }
    
    // open it
    console.println "command: $command"
    command.execute()
    
  4. open_project_save.groovy
    /*
     *  Open project_save.tmx in an editor
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    /**
     * Uncomment the next line if you want to set a default text editor
     * that will open project_save.tmx
     */
    // def textEditor = /path to your editor/
    // E.g., /TextMate/
    // /C:\Program Files (x86)\editor\editor.exe/
    // ['x-terminal-emulator', '-e', 'vi']
    // "x-terminal-emulator -e vi".split()
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open project_save.tmx'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString list to open a file
    def file = "${prop.projectInternal}project_save.tmx" 
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "cmd /c start \"\" \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "\"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "open -a \"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      default:  // for Linux or others
        command = ['xdg-open', file] // default
        try { command = textEditor instanceof List ? [*textEditor, file] : [textEditor, file] } catch (ignore) {}
        break
    }
    
    // open it
    console.println "command: $command"
    command.execute()
    
  5. open_tm_folder.groovy
    /*
     *  Open the /tm folder
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open TM folder'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString to open a folder
    def folder = prop.TMRoot
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "explorer.exe \"$folder\""
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$folder\""
        break
      default:  // for Linux or others
        command = ['xdg-open', folder]
        break
    }
    
    // open it
    command.execute()
    

To test, put the scripts to other scripts that come with the Scripting Plugin and run them on a real or testing OmegaT projects. Among the things to check are: ability to run at all, ability to run when the filenames or path to the projects contain spaces and “special” characters.
You can post your findings in comments, or, if you’re so inclined, here (clickable)


UPDATE

Thanks to all who participated in testing, now shiny new scripts got included in a new release of the Scripting Plugin for OmegaT 2.6, and as an integral part of new OmegaT 3.0. Pretty cool, yeah?

Новая версия OmegaT 3.0.0

Уважаемое сообщество!
Состоялся выпуск последней версии (3.0.0) программы OmegaT. Для работы программы требуется Java версии 6 или выше, при этом требованием для стандартной версии 2.6.3 является Java 5 или выше.

В новой версии была изменена лицензия. Ранее OmegaT выпускалась под лицензией GPLv2, однако OmegaT 3 выпущена под лицензией GPLv3: http://www.gnu.org/licenses/gpl-3.0.en.html
По сравнению с версией 2.6.3 в версии 3.0.0 содержится 27 улучшений и 5 исправлений ошибок.

Благодаря переходу на новую лицензию непосредственно в саму программу были включены токенайзеры (с автоматическим определением необходимых анализаторов для загруженного проекта — теперь не нужно указывать токенайзеры в параметрах запуска) и LanguageTool (средство для проверки грамматики). В предыдущих версиях OmegaT этот функционал был реализован только в виде плагинов. Данное изменение позволило включить эти две функции и в версию Java WebStart.

Для работы OmegaT 3 ранее установленные плагины токенайзеров и LanguageTool должны быть удалены.

Улучшения коснулись трех важных аспектов работы OmegaT.

Улучшенная работа с тегами.
Теги теперь защищены от изменений (такое поведение можно отключить). Кроме того, OmegaT теперь умеет правильно работать с защищенными тегами (которые обычно не могут быть изменены) в фильтре XLIFF.

Теги обрабатываются так же, как слова, благодаря чему их стало легче выделять и перемещать.

Новые параметры позволяют вставлять недостающие теги в текущем сегменте. В окне проверки тегов более четко показываются проблемы, появилась возможность автоматического исправления ошибок тегов. Помимо этого, проверка тегов может производиться после каждого сегмента. Есть возможность запретить создание переведенных документов при наличии ошибок тегов.

Для фильтров XML OmegaT появляется всплывающая подсказка, в которой отображается полное содержание тега при наведении на него указателя мыши.

Улучшения взаимного соответствия между XLIFF и TMX

Для обеспечения лучшего соответствия между XLIFF и TMX был полностью изменен способ вычисления тегов в фильтре XLIFF. Содержимое с тегами теперь должно давать теперь одинаковые сокращение тегов как в файле XLIFF, так и в файле TMX. Поскольку фильтр XLIFF был значительно переработан, то в него был добавлен параметр «совместимость с версией 2.6», которая позволяет использовать новую версию без необходимости проверки тегов в существующих переводах.

Помимо упомянутого выше, несколько глобальных параметров файловых фильтров позволяют добиться большего соответствия: теперь появилась возможность выбрать, будут ли удаляться начальные и конечные теги, будут ли удалятся начальные и конечные пробелы в несегментированных проектах (удобно при работе с предварительно сегментированным содержанием), а также будут ли сохраняться пробелы во всех тегах. Эти параметры применимы и к фильтрам OmegaT для файлов XML и HTML.

Новые параметры поиска
Теперь есть возможность искать в памяти, в файлах памяти переводов и в глоссариях одновременно или по отдельности, а также производить поиск только в переведенных сегментах

OmegaT теперь может работать с системой машинного перевода MyMemory.

Список последних изменений сейчас можно прочитать непосредственно в OmegaT, в меню Помощь > Последние изменения

Для версии 3.0.0 былы обновлены локализации на баскском, португальском (Бразилия), голландском, русском и турецком языках.

Новую версию программы можно загрузить, следуя инструкциям относительно последней версии по адресу: http://www.omegat.org/en/downloads.html.

Пожертвования приветствуются: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9UB6Y2BBF99LL
С наилучшими пожеланиями

Didier Briel
перевод Кос(ть) Иванцов

 

File Renamer (Bash from within OmegaT)

Situation

You have a client who loves to give his files very descriptive names. That’s understandable as mostly the files you get to translate from him are lessons, lectures, howtos, manuals and so on. It makes sense to distribute them digitally with localized filenames.

Problem

What you need is a way to translate filenames in OmegaT thus keeping consistency with the contents of the translated files and past/future files from the same client.
Continue reading

OmegaT match insert/replace without tags

Situation

After having translated a complete user manual that you converted from PDF to ODT to be able to work on it in OmegaT, you receive another manual from the same client, but this time it’s a DOCX file. Great! You can start right away, without converting anything. That should be a peace of cake — half of the manual looks almost the same as the one you have just done.

Problem

After starting to work with it you find out that getting a lot of 95-97% would be really awesome, if it wasn’t for all those nasty tags that are very different in the source and in the match. And there is no “Insert match without tags” menu item in OmegaT (yet).

Continue reading

Bash (Perl, Python, Tcl/Tk and what not) Scripting from within OmegaT

Situation

So, right now you’re using quite a few scripts while working in OmegaT. Some of them are the ones included in the Scripting Plugin, others are taken from the Internet, several of them were written on your own, and a couple are still cooking in your head, promising to be something that will save you a couple hours of work everyday in future and now hindering you from concentrating on what is at hand. To run them from with a key shortcut you had to assign global key combinations, as from withing OmegaT you can run only 5 custom scripts with a key combo, and those are not just any scripts but the ones that the Scripting Plugin can run.

Problem

Now, with many other scripts and actions used elsewhere for your work/leisure you’re running out of available key combinations, plus you get more and more questions like, “Dad, what you just did doesn’t work on my computer. Do I press it wrong or what’s the matter?” from your elementary-school-aged son.
What you want is an ability to run any script from within OmegaT, not just the ones that the Scripting Plugin can run, as you don’t want to be limited to Java-like languages, but you look for a way to use anything that you’re comfortable with. Besides, these custom scripts should be aware of your current OmegaT project’s variables and settings (like project folders, language pairs etc.) Then at least you’ll be able to say to your son, “Boy, you don’t use OmegaT yet. Let me better show you this combo that you can use on your computer.”
Continue reading

Dummy OmegaT tags

Situation

Now you’re working on a nice text with very few tags. The recipe with nice navigation between tags is quite good, but somewhat cumbersome for just two or three tags you have to insert here and there.

Problem

Minimizing the number of keystrokes to insert tags and staying mouse-free while doing that.
Continue reading

OmegaT’s speed on big files

Situation

Now you are working on a huge file with over a thousand segments where each segment is a complex sentence with numerous clauses and clarifying statements, and thus takes three or four lines in the editor pane. Using OmegaT for this work is a blessing in itself, as you get only this much at a time,  and, not getting lost too easily, can concentrate on your work much better.

Problem

When this particular file is open, you experience some latency in OmegaT’s response to your keystrokes or mouse clicks. Not a huge problem, but considering the size of each segment and the level of mental concentration this slowdown is rather annoying.
Continue reading

Target Document Preview

Situation

So, now you’re working on a fancy formatted file and would like to have a preview of what your translation looks like. To do that, you save in OmegaT (Ctrl+S), create translated document (Ctrl+D), and open it in LibreOffice or OpenOffice.org. A bit awkward, and you wish there were a preview button in OmegaT, but oh well, as long as it gets things done, you’ll bare with it.

Problem

But oops, the document was already open, and opening it again doesn’t automatically update the view in Office. Luckily, there is File → Reload functionality now both in LibreOffice and in OpenOffice.org, so you don’t have to close the document and reopen it again.
Continue reading