Difference between revisions of "Курсы машинного перевода для языков России/Раздел 5"
Line 70: | Line 70: | ||
===Left-to-right longest match (LRLM)=== |
===Left-to-right longest match (LRLM)=== |
||
==Transfer structure== |
==Структура переноса Transfer structure== |
||
Папки, которые содержат правила переноса в Apertium выглядят следующим образом: |
|||
Files containing structural transfer rules in Apertium are laid out in the following fashion: |
|||
<pre> |
<pre> |
||
Line 100: | Line 100: | ||
</pre> |
</pre> |
||
This is the minimal layout. The four sections are: |
Это минимальный план. Вот четыре раздела This is the minimal layout. The four sections are: |
||
* {{tag|section-def-cats}}: Contains one or more {{tag|def-cat}} entries. These specify patterns that can be matched by the transfer rules, and may match either tag sequences, or lemmas. The {{tag|def-cat}} entry above for <code>adj_or_pp</code> matches any lexical unit in which the tags start with {{tag|adj}} or {{tag|vblex><pp}}. This might be useful where two categories behave similarly (for example adjectives and past particiles in Spanish). |
* {{tag|section-def-cats}}: Contains one or more {{tag|def-cat}} entries. These specify patterns that can be matched by the transfer rules, and may match either tag sequences, or lemmas. The {{tag|def-cat}} entry above for <code>adj_or_pp</code> matches any lexical unit in which the tags start with {{tag|adj}} or {{tag|vblex><pp}}. This might be useful where two categories behave similarly (for example adjectives and past particiles in Spanish). |
||
Line 107: | Line 107: | ||
* {{tag|section-rules}}: Contains the rules. |
* {{tag|section-rules}}: Contains the rules. |
||
===Default parts=== |
===Стандартные части Default parts=== |
||
In addition to the parts that are defined in <code>section-def-attrs</code>, the transfer module predefines a number of default parts of each lexical unit. |
In addition to the parts that are defined in <code>section-def-attrs</code>, the transfer module predefines a number of default parts of each lexical unit. |
||
Line 123: | Line 123: | ||
* <code>lemq</code>: the lemma ''queue''; the rest of a multiword (the <code><nowiki><g></g></nowiki></code> part in the dictionaries): <tt># по безопасности</tt> |
* <code>lemq</code>: the lemma ''queue''; the rest of a multiword (the <code><nowiki><g></g></nowiki></code> part in the dictionaries): <tt># по безопасности</tt> |
||
==Practice== |
==Практика Practice== |
||
For this practical, we're going to use the Turkish--Chuvash language pair in Apertium, you could also choose another pair with single-level transfer (such as Tatar--Bashkir). So, go to the directory <code>apertium-cv-tr</code> and open the file of transfer rules for Turkish to Chuvash <code>apertium-cv-tr.tr-cv.t1x</code>, in other pairs this might be a <code>.t1x</code> file. |
For this practical, we're going to use the Turkish--Chuvash language pair in Apertium, you could also choose another pair with single-level transfer (such as Tatar--Bashkir). So, go to the directory <code>apertium-cv-tr</code> and open the file of transfer rules for Turkish to Chuvash <code>apertium-cv-tr.tr-cv.t1x</code>, in other pairs this might be a <code>.t1x</code> file. |
||
===Описание правила переноса=== |
|||
===Describe a transfer rule=== |
|||
The objective of this exercise is to describe the behaviour of an existing transfer rule given the input sentence in Turkish: ''Yeme!''. First we're going to give some preliminaries for how transfer rules are structured, then we're going to look at an actual rule and describe it. |
The objective of this exercise is to describe the behaviour of an existing transfer rule given the input sentence in Turkish: ''Yeme!''. First we're going to give some preliminaries for how transfer rules are structured, then we're going to look at an actual rule and describe it. |
||
Line 270: | Line 270: | ||
</pre> |
</pre> |
||
===Описание нового правила переноса=== |
|||
===Describe a new transfer rule=== |
|||
The objective of this part of the practical is to describe a new transfer rule. Run some text through the translator of your choice, and describe a new rule in natural language, as was done in the previous subsection. If you have time after defining the rule, try and write it out in XML format. |
The objective of this part of the practical is to describe a new transfer rule. Run some text through the translator of your choice, and describe a new rule in natural language, as was done in the previous subsection. If you have time after defining the rule, try and write it out in XML format. |
||
==Для дальнейшего чтения== |
|||
==Further reading== |
|||
* Ginestí i Rosell, M. (ed.) (2007) [https://wiki.apertium.org/w/images/d/d0/Apertium2-documentation.pdf Documentation of the Open-Source Shallow-Transfer Machine Translation Platform ''Apertium''] |
* Ginestí i Rosell, M. (ed.) (2007) [https://wiki.apertium.org/w/images/d/d0/Apertium2-documentation.pdf Documentation of the Open-Source Shallow-Transfer Machine Translation Platform ''Apertium''] |
Revision as of 18:31, 12 January 2012
Цель данного раздела познакомить с понятием сопоставительного морфологического и синтаксического анализов, и показать как основные (т.е. that is, single level) правила морфологической и синтаксической передачи могут быть созданы в Apertium.
Теория
Сопоставительный анализ
Сопоставительный анализ подразумевает анализ и сравнение двух языков с целью обнаружения какие они имеют общие и отличительные характеристики. При работе над неглубоким машинным переводом мы можем рассмотреть, например, как морфологические так и синтаксические различия When working on shallow-transfer machine translation, we can consider for example, both morphological contrasts and syntactic contrasts.
Морфологические различия сопоставления Morphological contrasts
Морфологические различия - это различия между морфологическими характеристикам двух языков. Например, если в одном языке категория определенности выражено морфологически, а в другом нет, или одни язык имеет категорию падежа и рода, а другой нет. Или когда инструменты выражения падежа/рода отличаются между языками. Примеры: Morphological contrasts are differences in which morphological features are expressed in each language, and how they differ. For example, if one language expresses definiteness morphologically, and another doesn't, or one language has case or gender while the other doesn't. Or if the case/gender inventories differ between the languages. Examples:
- В казахском языке нет грамматического рода, а в русском их три (мужской, женский, средний). Род в русском языке играет роль при согласовании внутри словосочетания с существительным
- В русском языке два вида числа (единственное и множественное), а в мансийском три (единственное, двойственное и множественное).
- Венгерский содержит огромное количество падежей, которых нет в финском (например, временный падеж -kor, который на финский может быть переведен творительным аблативом, адессивом или эссив изобразительный палеж ablative, adessive, or essive). В венгерском и финском языках падеж не играет роли при согласовании в словосочетании с существительным Case in Hungarian and Finnish does not play a rôle in noun-phrase agreement.
Синтаксические различия Syntactic contrasts
Синтаксические различия наблюдается в том как устроена синтаксическая система разных языков, например, наличие или отсутствие артиклей, ordering of clitic pronouns, обозначение падежей, аналитические временные формы глаголов, употребление личных местоимений и тд. case inventories, analytic verb tenses, usage of subject pronouns, etc.
- Например в абхазском языке есть a postfixed неопределенный артикль, и prefixed определенный артикль, а в русском нет.
- В русском языке обязательно употребление личного местоимения в качестве подлежащего, а в венгерском нет,
- В чувашском используется аблятив ablative case, а в русском используется предлог и другой падеж.
Передача Transfer
Transfer is the process of altering the intermediate representation of a source language into that of the target language. In Apertium, transfer works on an intermediate representation of lemmas and tags specifying morphological features (lexical forms).
Базовые операции
Когда вы начинаете думать о применении правил передачи, стоит разложить их на самые базовые действия.
- A) Вставка
Вставка - это добавление нового tag или слова, например, при перевод существительного с дунганского на русский язык, необходимо вставить tag указывающий падеж (именительный, винительный, ...), так как в дунганском языке отсутствует категория падежа. Очень часто в переводе требуется вставить слово. Например при переводе повелительного наклонения с турецкого на чувашский, необходимо в начале добавить наречие ан: Yeme! → Ан çи!.
- B) Удаление
Удаление - это операция, противоположная вставке, когда необходимо удалить слово или tag, например, как в предыдущем примере, как только мы добавили наречие, необходимо убрать отрицание от последующего глагола, так как наречие передает отрицательное значение.
- C) Замена Substitution
Замена происходит, когда один tag заменяется другим, например, когда изменяется род слова. Это часто применяется при лексическом переносе, о чем мы читали в первом разделе, но также часто происходит при передаче transfer. Например, при переводе с русского на башкирский, мои брюки, слово брюки будем помечено специальным tag ND
(которое указывает в каком числе употребляется существительное) при лексическом переносе, и потом, согласно правилам переноса, при переводе число будет изменено.
- D) Изменение порядка слов Reordering
Изменение порядка слов или tags. Например, изменение порядка следования числа и принадлежности при переводе с турецкого на чувашский kitap·lar·ım → кӗнеке·м·сем.
- E) Комбинированные операции
Очень часто, для создания правила переноса требуется набор из всех вышеуказанных операций, например, при переводе с одного языке слова, стоящее в определенном падеже на язык, в котором, для передачи такого же значения требуется предлог и падеж, необходимо провести две операции, во-первых, слово,выражающее предлог должно быть вставлено перед существительным, и затем необходимо изменить черту, влияющую на определение падежа for example when translating from language with a case for a given meaning into a language with a preposition and a case for the same meaning, two operations are required, first the word for preposition needs to be inserted before the noun, and secondly the feature denoting case on the noun needs to be changed.
Left-to-right longest match (LRLM)
Структура переноса Transfer structure
Папки, которые содержат правила переноса в Apertium выглядят следующим образом:
<transfer default="chunk"> <section-def-cats> <def-cat n="adj_or_pp"> <cat-item tags="adj.*"> <cat-item tags="vblex.pp.*"> </def-cat> ... </section-def-cats> <section-def-attrs> <def-attr n="nbr"> <attr-item n="sg"/> <attr-item n="pl"/> </def-attr> ... </section-def-attrs> <section-def-vars> <def-var n="number"/> ... </section-def-vars> <section-rules> ... </section-rules> </transfer>
Это минимальный план. Вот четыре раздела This is the minimal layout. The four sections are:
<section-def-cats>
: Contains one or more<def-cat>
entries. These specify patterns that can be matched by the transfer rules, and may match either tag sequences, or lemmas. The<def-cat>
entry above foradj_or_pp
matches any lexical unit in which the tags start with<adj>
or<vblex><pp>
. This might be useful where two categories behave similarly (for example adjectives and past particiles in Spanish).<section-def-attrs>
: Contains one or more<def-attr>
entries. These list possible tags corresponding to a feature. For example, in this case the feature ofnbr
"number" may be one of two tags<sg>
"singular" or<pl>
"plural". When we use the<clip>
tag, to extract apart
, this allows us to define our own parts, in addition to the default parts.<section-def-vars>
: Contains variable definitions. Variables are used to pass information between rules. For example we might want to keep track of the last gender or number that we have seen, or the lemma of the last finite verb.<section-rules>
: Contains the rules.
Стандартные части Default parts
In addition to the parts that are defined in section-def-attrs
, the transfer module predefines a number of default parts of each lexical unit.
To more easily demonstrate the default parts that are available, we'll use the follow example:
^правило# по безопасности<n><nt><nn><pl>$
whole
: as the name suggests, this provides the whole content of the lexical unit.lem
: the lemma: in this case, правило# по безопасностиtags
: all of the tags, in one unit: <n><nt><nn><pl>lemh
: the lemma head; the part of the multiword which inflects: правилоlemq
: the lemma queue; the rest of a multiword (the<g></g>
part in the dictionaries): # по безопасности
Практика Practice
For this practical, we're going to use the Turkish--Chuvash language pair in Apertium, you could also choose another pair with single-level transfer (such as Tatar--Bashkir). So, go to the directory apertium-cv-tr
and open the file of transfer rules for Turkish to Chuvash apertium-cv-tr.tr-cv.t1x
, in other pairs this might be a .t1x
file.
Описание правила переноса
The objective of this exercise is to describe the behaviour of an existing transfer rule given the input sentence in Turkish: Yeme!. First we're going to give some preliminaries for how transfer rules are structured, then we're going to look at an actual rule and describe it.
Transfer rules in Apertium are made up of two principle parts. A pattern — that is a sequence of categories which will be matched, and an action, which contains operations that are carried out on the patterns matched. An overall schema for a rule might look like the following:
<rule> <pattern> ... </pattern> <action> ... </action> </rule>
An overview of the meanings of the tags which are used in the example below are given here, along with references to the page of the documentation where a full description can be found.
Name | Doc. ref. | Description |
---|---|---|
<rule> |
§3.5.4.18 | Starts a new rule, it contains at the highest level a pattern and an action. |
<pattern> |
§3.5.4.19 | Contains one or more pattern-item tags that define the pattern of lexical forms to be matched.
|
<pattern-item> |
§3.5.4.20 | Contains references to patterns of lexical forms defined in the section-def-cats part of the rule file.
|
<action> |
§3.5.4.21 | Contains tags defining the actions that should take place when a sequence of lexical units matching pattern is matched.
|
<choose> |
§3.5.4.24 | Contains one or more when statements which define different actions depending on different conditions, and optionally an otherwise statement, which defines a default action if none of the when s are matched.
|
<when> |
§3.5.4.25 | Specifies a condition and an action to take if that condition is fulfilled. The condition is in a test tag, and the action comes after.
|
<otherwise> |
§3.5.4.26 | A default condition, which contains actions that are run if none of the when conditions in a choose block are matched.
|
<test> |
§3.5.4.27 | Describes a condition. For example "test if the number of the first pattern matched is singular". |
<or> |
§3.5.4.28 | A tag allowing more than one condition to be matched. This tag is a Boolean operator, other Boolean operators available are: <and> and <not>
|
<equal> |
§3.5.4.28 | Tests if two strings or tags are equal. |
<clip> |
§3.5.4.29 | Extracts the part of a lexical unit corresponding to an attribute as defined in the section-def-attrs section of the transfer file. The part to be extracted is specified in the part attribute.
|
<lit-tag> |
§3.5.4.31 | Generates a string enclosed in < > , that is to say, a tag.
|
<lit> |
§3.5.4.30 | Generates a string. |
<out> |
§3.5.4.40 | Contains everything that will be output by the rule. |
<lu> |
§3.5.4.41 | Encloses the contents in ^ and $ , that is defines the contents as a lexical unit.
|
<b> |
§3.5.4.46 | Outputs a space, or the formatting contained at the given position. |
<get-case-from> |
§3.5.4.34 | Converts the case (e.g. upper, lower) of whatever is enclosed in it to the case of the word marked by the pos attribute.
|
The rule we're going to describe is regla: v_neg_imp
, so search for it in the file. Here is what the rule looks like:
<rule comment="regla: v_neg_imp (yeme! → ан ҫи!)"> <pattern> <pattern-item n="v_neg_imp"/> </pattern> <action> <let> <clip pos="1" side="tl" part="a_neg"/> <lit v=""/> </let> <out> <lu> <lit v="ан"/> <lit-tag v="adv"/> </lu> <b/> <lu> <clip pos="1" side="tl" part="whole"/> </lu> </out> </action> </rule>
For reference, the pattern being matched are defined as:
<section-def-cats> ... <def-cat n="v_neg_imp"> <cat-item tags="v.*.neg.imp.*"/> </def-cat> ... </section-def-cats>
Description
So, given the description of the tags, and the contents of the rule, we could describe the rule as follows:
- This rule matches a sequence of "vb_neg_imp"
- The lexical form pattern "vb_neg_imp" is defined, in the
<section-def-cats>
of the file, as the tag<v>
followed by any tag (e.g.<iv>
or<tv>
followed by the tags<neg><imp>
and then any other tags. - The rule then sets the value of the part of the lexical unit which matches the attribute
a_neg
to nothing (meaning it "deletes" it) - The rule outputs the lemma "ан", followed by the tag
<adv>
in a single lexical unit (between^
and$
). - The rule then outputs a blank space
- The rule then outputs the a lexical unit with the information from the verb matched by the original pattern.
Example output
- Input text
$ echo 'yeme!' | hfst-proc tr-cv.automorf.hfst | cg-proc tr-cv.rlx.bin | apertium-tagger -g tr-cv.prob ^ye<v><tv><neg><imp><p2><sg>$^!<sent>$^.<sent>$
- Output from transfer
$ echo 'yeme!' | hfst-proc tr-cv.automorf.hfst | cg-proc tr-cv.rlx.bin | apertium-tagger -g tr-cv.prob |\ apertium-pretransfer | lt-proc -b tr-cv.autobil.bin | apertium-lrx-proc tr-cv.lrx.bin |\ apertium-transfer -b apertium-cv-tr.tr-cv.t1x tr-cv.t1x.bin ^ан<adv>$ ^ҫи<v><tv><imp><p2><sg>$^!<sent>$
If you want to trace which rules are matched, add the -t option to the apertium-transfer:
- Output from transfer
$ echo 'yeme!' | hfst-proc tr-cv.automorf.hfst | cg-proc tr-cv.rlx.bin | apertium-tagger -g tr-cv.prob |\ apertium-pretransfer | lt-proc -b tr-cv.autobil.bin | apertium-lrx-proc tr-cv.lrx.bin |\ apertium-transfer -t -b apertium-cv-tr.tr-cv.t1x tr-cv.t1x.bin apertium-transfer: Rule 3 ye<v><tv><neg><imp><p2><sg>/ҫи<v><tv><neg><imp><p2><sg> ^ан<adv>$ ^ҫи<v><tv><imp><p2><sg>$^!<sent>$
Описание нового правила переноса
The objective of this part of the practical is to describe a new transfer rule. Run some text through the translator of your choice, and describe a new rule in natural language, as was done in the previous subsection. If you have time after defining the rule, try and write it out in XML format.
Для дальнейшего чтения
- Ginestí i Rosell, M. (ed.) (2007) Documentation of the Open-Source Shallow-Transfer Machine Translation Platform Apertium