Курсы машинного перевода для языков России/Раздел 6

From Apertium
Jump to navigation Jump to search

Система базового структурного переноса, описанного в session 5 достаточно для работы с большинством расхождений, которые имеются в родственных языках (например, башкирский и татарский, финский и квен), при работе с языками, которые имеют больше морфологических и синтаксических расхождений, необходимо использовать более мощную систему структурного переноса. В данном разделе мы познакомим вас с системой уровня Apertium 3+, которая была разработана для работы с более длинными шаблонами и языками, которые сильнее отличаются друг от друга.

Теория

Передача путем разбивки на блоки Chunking-based transfer

Традиционное применение данного метода состоит из трех модулей: блок a chunker, между блоками и послеan interchunk and a postchunk. При необходимости данная модель может быть расширена до двух и более модулей intertchunk.

Chunker

Идея chunker - расширить существующие правила переноса чтобы было возможно сгруппировать лексические единицы. Эти группы называются блоки . Блок может объединять имена, делать согласование, вставлять и удалять слова, и выполнять перестановку слов, например,

Входной шаблон набор Input pattern Пример Блок на выходе Пример
nom ҫурт SN{nom} дом
adj nom хитре ҫурт SN{nom adj} красивый дом
nom ҫуртӑм SN{det nom} мой дом
det nom манăн ҫурт SN{det nom} мой дом
det nom манăн ҫуртӑм SN{det nom} мой дом
num nom икĕ ҫурт SN{num nom} два дома
num nom пилĕ ҫурт SN{num nom} пять домов
adj nom хитре ҫуртсем SN{adj nom} красивые домы
adv adj nom питĕ хитре ҫурт SN{adv adj nom} очень красивый дом
num adv adj nom пилĕ питĕ хитре ҫурт SN{num adv adj nom} пять очень красивых домов

Где nom = существительное, adj = прилагательное, num = числительное, det = артикль, SN = именная конструкция.

Такой же процесс и для формирования глагольных блоков chunks:

Входной шаблон Пример Блок на выходе Output chunk Пример
verb вулать V{verb} читает
verb вуламасть V{neg_adv verb} не читает
verb вуларĕ V{verb} читал
verb вуламĕ V{aux inf} будет читать
verb вуламарĕ V{neg_adv aux inf} не будет читать
verb вуласшăн V{aux part inf} хотел бы говорить
verb вулӑттӑм V{verb part} говорил бы
adv verb ан вула ! V{adv verb} не читай !
ger verb вулама пуçлать V{verb inf} начинает читать.

Таким образом, если мы хотим согласовать именное словосочетание с основным глаголом, мы только можем использовать одно правило (для SN V) во втором модуле передачи (the interchunk) вместо отдельных правил для nom verb, adj nom verb, det adj nom verb, и тд.

Очень важно помнить о том, что блоки (chunks) не могут быть вложенными (т.е. блок сhunk не может содержать другой блок chunk). В определенных обстоятельствах, и при определенном усилии они могут быть сведены к интерблоку interchunk — например, можно присоединить одну или несколько однородных именных словосочетаний, но не вложить их друг в друга but not nested.

Важно отметить, что лексические формы переводятся на язык перевода в первом модуле; последующие модули уже работают с лексическими формами уже на языке перевода.

Interchunk

Как только созданы эти блоки, следующий модуль interchunk помогает проводить операции между блоками так, как будто они являются лексическими единицами: блоки используются на уровне абстракции, таким образом подобные слова и фразы также могут переводиться с использованием таких же правил so that equivalent words and phrases can be translated using the same rules.

Этот модуль позволяет распознавать лицо, а также проводить согласование в роде, и определении порядка слов — например, согласовывать глагол прошедшего времени с местоимением в предложении на чувашском языке. В русском предложении Я вчера читалa, разделитель на блоки привел бы к следующему результату the chunker would give the following output:

^pron<SN><p1><mf><sg><nom>{^Эпĕ<prn><pers><2><3><4><5>$}$ 
^adv<ADV>{^ĕнер<adv>$}$
^verb<SV><imperf><tv><evid><PD><f><sg>{^вула<v><3><4><5><7>$}$ 

Формат блоков chunks во многом похож на формат выделения лексических единиц, ^ указывает на начало, и $ на конец. Разница в том, что блок может содержать внутри себя другие лексические единицы { и }.

Лексические единицы, которые заключены внутри блока (между обозначениями { и }) не могут быть обработаны и изменены модулем interchunk; на данном этапе мы можете только работать и изменять элементы описания блока chunk, которые находятся после ^ и перед первым {. Описание блока содержит лемму блока (как pron в предыдущем примере) и морфологические тэги блока (для pron это <SN><p1><mf><sg><nom>).

Эти тэги могут быть связаны с лексическими формами внутри блока: этим объясняются цифры <5> и <7> в лексических формах блока verb: они связаны с пятым и седьмым тэгами блока (<PD> и <sg>) и будут заменены на них в модуле postchunk.

Interchunk имеет правило для разных блоков 'имя' 'прилагательное' 'глагол', которые копируют лицо из первого блока для имени в блок для глагола, заменяя тэг 'PD'; в данном примере присваивая тегу <p1> (первое лицо) значение:

^pron<SN><p1><mf><sg><nom>{^Эпĕ<prn><pers><2><3><4><5>$}$ 
^adv<ADV>{^ĕнер<adv>$}$
^verb<SV><imperf><tv><evid><p1><f><sg>{^вула<v><3><4><5><7>$}$ 

Модуль постфрагментирования припишет этот тег глаголу внутри блока.

Постфрагментирование Postchunk

Postchunk позволяет нам использовать результаты межчленения interchunk и еще раз поработать с контентом.

Изменения, которые блоки претерпели после прохождения модуля interchunk будут применены к контенту блока: тэги, содержащие число будут заменены на значение, соответствующее тэгу вне блока. Модуль postchunk удаляет блоки лемма и тэги, и оставляет в качестве итогового продукта ряд лексических единиц.

Postchunk operates on a single chunk at a time. In addition to the clip elements which refer to individual words contained in the chunk, there is also a clip numbered 0 (zero), which allows us to access information from the chunk lemma, which can be used to take information from "outside" the chunk (changed in interchunk) to the words inside. Also, because the number of words in a chunk may vary, there is an element, lu-count, which allows us to test how many words the chunk contains, and act accordingly.

Practice

For the practice section, we are going to look at how a transfer is performed in three stages by the Apertium Tatar—Kyrgyz pair, apertium-tt-ky, and then describe a transfer rule in terms of three or more levels. So change directory to apertium-tt-ky and make sure the pair is compiled.

Looking at three-stage transfer

We're going to translate the sentence Әхмәт тиз генә иске зур бер агачка йөгерә. from Tatar to Kyrgyz and follow the translation process through the three levels.

Input

Because we don't yet have a full translator for Tatar and Kyrgyz, we're going to use some preprepared input from the Tatar and Bashkir pair.

$ cat input 
^Әхмәт<np><ant><m><nom>$ ^тиз<adv>$ ^гына<postadv>$ ^иске<adj>$ ^зур<adj>$ ^бер<det><ind>$ 
^агач<n><dat>$ ^йөгер<v><iv><pres><p3><sg>$^..<sent>$

Chunker

Then output of the part-of-speech tagger is passed to the lexical transfer, and then the first level of transfer:

$ cat input | lt-proc -b tt-ky.autobil.bin | apertium-transfer -b apertium-tt-ky.tt-ky.t1x tt-ky.t1x.bin 

^ant<SN>{^Акмат<np><ant><m><nom>$}$ ^adv<ADV>{^катуу<adv>$ ^гана<postadv>$}$ 
^a_a_d_n<SN><dat>{^эски<adj><pst>$ ^чоң<adj><pst>$ ^бир<det><ind>$ ^дарак<n><2>$}$ 
^чурка<V>{^чурка<v><iv><prt_perf>$ ^бар<v><iv><prt_impf>$ ^жат<vaux><aor><p3><sg>$}$^sent<SENT>{^..<sent>$}$

There are four rules applied by the first-level transfer module:

  • ПРАВИЛО: NP-ANT: This rule matches an anthroponym (person's first name). It creates a new nominal <SN> chunk.
  • ПРАВИЛО: ADV POSTADV: This rule matches a sequence of adverb and postadverb, it outputs an adverbial chunk <ADV> containing the two lexical units.
  • ПРАВИЛО: ADJ ADJ DET NOM: This rule matches a sequence of two adjetives, a determiner and a noun. These are put inside a nominal chunk <SN> and the case of the chunk is set to the case of the noun. A pointer <2> is put on the noun so that when the case of the chunk is changed, it will be propagated inside.
  • ПРАВИЛО: V-PRES: This is the default present tense verb rule, it matches any verb in the present tense. It currently changes the synthetic present in Tatar into a progressive present tense with an auxiliary verb in Kyrgyz. WHY???

Note that after the first stage of transfer there are a couple of problems. The tense is correct, but the case of the noun is wrong, and the adverbial is in the wrong place. In Kyrgyz it should come before the verb.

Interchunk

$ cat input | lt-proc -b tt-ky.autobil.bin | apertium-transfer -b apertium-tt-ky.tt-ky.t1x tt-ky.t1x.bin |\
   apertium-interchunk apertium-tt-ky.tt-ky.t2x tt-ky.t2x.bin 

^ant<SN>{^Акмат<np><ant><m><nom>$}$ ^a_a_d_n<SN><acc>{^эски<adj><pst>$ ^чоң<adj><pst>$ ^бир<det><ind>$ ^дарак<n><2>$}$ 
^post<POST>{^көздөй<post>$}$ ^adv<ADV>{^катуу<adv>$ ^гана<postadv>$}$ 
^чурка<V>{^чурка<v><iv><prt_perf>$ ^бар<v><iv><prt_impf>$ ^жат<vaux><aor><p3><sg>$}$^sent<SENT>{^..<sent>$}$

One rule is applied in the interchunk module:

  • ПРАВИЛО: ADV SN V: The rule matches an adverbial chunk (ADV) followed by a nominal chunk (SN) and then a verbal chunk (V). It contains a macro conv_arg1 which adjusts the case of the nominal chunk, and outputs a postposition depending on the lemma of the verbal chunk. It also switches the position of the nominal chunk and the adverbial chunk, placing the adverbial before the verb.

We can see that in the output of interchunk, the adverbial has been moved and the nominal chunk is in the correct case with a postposition.

Postchunk

The final module of transfer takes the chunks output by the interchunk module, and replaces the linked tag (e.g. <2>) with its value from the chunk.

$ cat input | lt-proc -b tt-ky.autobil.bin | apertium-transfer -b apertium-tt-ky.tt-ky.t1x tt-ky.t1x.bin |\
  apertium-interchunk apertium-tt-ky.tt-ky.t2x tt-ky.t2x.bin | apertium-postchunk apertium-tt-ky.tt-ky.t3x tt-ky.t3x.bin 

^Акмат<np><ant><m><nom>$ ^эски<adj><pst>$ ^чоң<adj><pst>$ ^бир<det><ind>$ ^дарак<n><acc>$ ^көздөй<post>$ ^катуу<adv>$ 
^гана<postadv>$ ^чурка<v><iv><prt_perf>$ ^бар<v><iv><prt_impf>$ ^жат<vaux><aor><p3><sg>$^..<sent>$

Now the sentence is ready to be morphologically generated. The file tr-ky.autogen.hfst can be copied from the apertium-tr-ky pair in trunk/.

Output

$ cat input | lt-proc -b tt-ky.autobil.bin | apertium-transfer -b apertium-tt-ky.tt-ky.t1x tt-ky.t1x.bin |\
   apertium-interchunk apertium-tt-ky.tt-ky.t2x tt-ky.t2x.bin | apertium-postchunk apertium-tt-ky.tt-ky.t3x tt-ky.t3x.bin |\
   hfst-proc -g tr-ky.autogen.hfst 

Акмат эски чоң бир даракты көздөй катуу гана чуркап бара жатат.

Describing a multi-stage transfer rule

The important thing to work out when writing a multi-stage transfer rule is how to split the rule between the different parts of transfer. For example, local reorderings (at the level of 1—5 words) should probably be done in the first stage. The chunks should be in some way thematic, so for example, finite verbs should probably not be chunked with adjectives or nominals.

Further reading