KWT-2024/lab/lab_06-07.ipynb

545 lines
19 KiB
Plaintext
Raw Permalink Normal View History

2024-04-13 08:20:53 +02:00
{
"cells": [
{
"cell_type": "markdown",
"id": "described-terrain",
"metadata": {},
"source": [
"![Logo 1](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech1.jpg)\n",
"<div class=\"alert alert-block alert-info\">\n",
"<h1> Komputerowe wspomaganie tłumaczenia </h1>\n",
"<h2> 6,7. <i>Preprocessing i postprocessing</i> [laboratoria]</h2> \n",
"<h3>Rafał Jaworski (2021)</h3>\n",
"</div>\n",
"\n",
"![Logo 2](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech2.jpg)"
]
},
{
"cell_type": "markdown",
"id": "colored-nothing",
"metadata": {},
"source": [
"Na dzisiejszych zajęciach zajmiemy się niezwykle przydatnymi narzędziami wspomagającymi pracę tłumacza. W odróżnieniu od dotychczas poznanych, nie są one oparte na pamięci tłumaczeń, ani na słownikach. Chodzi o techniki preprocessingu i postprocessingu."
]
},
{
"cell_type": "markdown",
"id": "atomic-rubber",
"metadata": {},
"source": [
"Proces tłumaczenia przeprowadzony w pełni profesjonalnie składa się z wielu faz, które angażują nie tylko tłumaczy, ale także kierowników projektu, analityków, czy korektorów. Każda z tych osób do swojej pracy może wykorzystywać system informatyczny, do którego na początku całego procesu trafiają pliki do tłumaczenia. Oznacza to, że zanim tekst źródłowy trafi do tłumacza, system ma jeszcze szansę coś w nim zmienić. A kiedy tłumacz wykona już swoją pracę, można uruchomić kolejny mechanizm, który zmodyfikuje tłumaczenie przed oddaniem go do zamawiającego. Jak się domyślamy, modyfikacje tekstu przed przekazaniem go do tłumacza nazywamy **preprocessingiem**, natomiast te dokonywane po wykonaniu tłumaczenia (ale przed zwróceniem go do klienta) nazywamy **postprocessingiem**. Terminy te, będące mało zgrabnymi kalkami z języka angielskiego, mają wersje prawdziwie polskie: przetwarzanie wstępne i końcowe. Wersje te są jednak stosowane na tyle rzadko, że mogą jedynie wprowadzić zamieszanie (co w gruncie rzeczy jest dość smutne)."
]
},
{
"cell_type": "markdown",
"id": "mature-republic",
"metadata": {},
"source": [
"Typowe operacje w fazie preprocessingu obejmują:\n",
"* identyfikację tagów xmlowych (które często są później wyświetlane w interfejsie CAT-a jako jeden niepodzielny znak)\n",
"* identyfikację segmentów, których nie należy tłumaczyć (na przykład składających się z samych liczb)\n",
"\n",
"* identyfikację dat i jednostek miary w tekście źródłowym\n",
"\n",
"We wszystkich tych operacjach niezwykle przydatne okazują się wyrażenia regularne."
]
},
{
"cell_type": "markdown",
"id": "southern-applicant",
"metadata": {},
"source": [
"### Ćwiczenie 1: Używając wyrażeń regularnych napisz funkcję do znajdowania wszystkich tagów XML w tekście. Funkcja powinna zwracać pozycje, na których znalazła tagi."
]
},
{
"cell_type": "code",
2024-04-14 19:33:04 +02:00
"execution_count": 7,
2024-04-13 08:20:53 +02:00
"id": "documented-hacker",
"metadata": {},
2024-04-14 19:33:04 +02:00
"outputs": [
{
"data": {
"text/plain": [
"[(10, 13), (17, 21)]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
2024-04-13 08:20:53 +02:00
"source": [
2024-04-14 19:33:04 +02:00
"import re\n",
"\n",
2024-04-13 08:20:53 +02:00
"def find_tags(text):\n",
2024-04-14 19:33:04 +02:00
" tags = re.finditer(r'<[^>]+>', text)\n",
" return [tag.span() for tag in tags]\n",
"\n",
"# Test the function\n",
"text = 'This is a <b>bold</b> text'\n",
"find_tags(text)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "1781331d",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('<b>', '</b>')"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text[10:13], text[17:21]"
2024-04-13 08:20:53 +02:00
]
},
{
"cell_type": "markdown",
"id": "determined-utilization",
"metadata": {},
"source": [
"### Ćwiczenie 2: Używając wyrażeń regularnych napisz funkcję do identyfikacji segmentów, których nie należy tłumaczyć. Zastosuj wymyślone przez siebie kryteria. Funkcja is_translatable powinna zwracać True, jeśli segment powinien być przetłumaczony przez tłumacza (zwykłe zdanie). False powinno być zwrócone, kiedy segment jest nieprzetłumaczalny i powinien zostać skopiowany (np. 4.2.1.)"
]
},
{
"cell_type": "code",
2024-04-14 19:33:04 +02:00
"execution_count": 9,
2024-04-13 08:20:53 +02:00
"id": "unauthorized-study",
"metadata": {},
2024-04-14 19:33:04 +02:00
"outputs": [
{
"data": {
"text/plain": [
"(True, False, False)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
2024-04-13 08:20:53 +02:00
"source": [
"def is_translatable(text):\n",
2024-04-14 19:33:04 +02:00
" # Text is translatable if it contains only letters, spaces, and punctuation\n",
" return re.fullmatch(r'[a-zA-Z .,!?]+', text) is not None\n",
"\n",
"# Test the function\n",
"is_translatable('Hello, world!'), is_translatable('Hello, 123!'), is_translatable('你好,世界!')"
2024-04-13 08:20:53 +02:00
]
},
{
"cell_type": "markdown",
"id": "plastic-crown",
"metadata": {},
"source": [
"### Ćwiczenie 3: Używając wyrażeń regularnych napisz funkcję do identyfikacji i interpretacji 5 wybranych przez siebie formatów daty. Funkcja powinna zwracać pozycje, na których odnalazła daty oraz dzień, miesiąc i rok, które ta data reprezentuje."
]
},
{
"cell_type": "code",
2024-04-14 19:33:04 +02:00
"execution_count": 12,
2024-04-13 08:20:53 +02:00
"id": "beautiful-mathematics",
"metadata": {},
2024-04-14 19:33:04 +02:00
"outputs": [
{
"data": {
"text/plain": [
"[(12, 22), (28, 38), (42, 52), (56, 66), (70, 85)]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
2024-04-13 08:20:53 +02:00
"source": [
"def find_dates(text):\n",
2024-04-14 19:33:04 +02:00
" # Find all dates in 5 formats: yyyy-mm-dd, yyyy/mm/dd, dd-mm-yyyy, dd/mm/yyyy, dd month yyyy\n",
" # yyyy-mm-dd\n",
" dates = [date.span() for date in re.finditer(r'\\b\\d{4}-\\d{2}-\\d{2}\\b', text)]\n",
" # yyyy/mm/dd\n",
" dates = dates + [date.span() for date in re.finditer(r'\\b\\d{4}/\\d{2}/\\d{2}\\b', text)]\n",
" # dd-mm-yyyy\n",
" dates = dates + [date.span() for date in re.finditer(r'\\b\\d{2}-\\d{2}-\\d{4}\\b', text)]\n",
" # dd/mm/yyyy\n",
" dates = dates + [date.span() for date in re.finditer(r'\\b\\d{2}/\\d{2}/\\d{4}\\b', text)]\n",
" # dd month yyyy\n",
" dates = dates + [date.span() for date in re.finditer(r'\\b\\d{2} [a-zA-Z]+ \\d{4}\\b', text)]\n",
" return dates\n",
"\n",
"# Test the function\n",
"text = 'The date is 2020-01-01, not 2020/01/01 or 01-01-2020 or 01/01/2020 or 01 January 2020'\n",
"find_dates(text)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "215a4cbd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2020-01-01\n",
"2020/01/01\n",
"01-01-2020\n",
"01/01/2020\n",
"01 January 2020\n"
]
}
],
"source": [
"print(text[12:22])\n",
"print(text[28:38])\n",
"print(text[42:52])\n",
"print(text[56:66])\n",
"print(text[70:85])"
2024-04-13 08:20:53 +02:00
]
},
{
"cell_type": "markdown",
"id": "hourly-incentive",
"metadata": {},
"source": [
"Po preprocessingu i tłumaczeniu czas na postprocessing. Ponieważ wykonywany jest on na przetłumaczonym tekście, jego głównym zadaniem jest eliminacja błędów popełnionych przez tłumacza w fazie tłumaczenia. Podczas postprocessingu najczęściej wykonuje się:\n",
"* korektę pisowni dla języka docelowego\n",
"* usuwanie błędów typograficznych z tekstu (np. wielokrotne spacje, brak spacji po przecinku)\n",
"Stanowi to bardzo ważne wsparcie dla edytorów i korektorów, czyli osób sprawdzających pracę tłumacza.\n",
"\n",
"Jednak nowoczesne CAT-y potrafią coś jeszcze. Są w stanie w sprytny sposób wykorzystać kombinację pre- i postprocessingu do wyręczenia tłumacza w żmudnych i technicznych czynnościach. Wykonajmy następujące ćwiczenie:"
]
},
{
"cell_type": "markdown",
"id": "dental-combination",
"metadata": {},
"source": [
"### Ćwiczenie 4: Wykorzystując funkcję find_dates napisz funkcję do obsługi dat w tłumaczeniu. Wejściem jest segment źródłowy oraz docelowy, które zawierają daty, przy czym daty te mogą być w różnych formatach. Dodatkowym parametrem wejściowym jest nazwa oczekiwanego formatu daty w tłumaczeniu (np. \"Europe\", \"US\", \"digit-dot\". Funkcja najpierw sprawdza, czy liczba dat w tłumaczeniu zgadza się z liczbą dat w segmencie źródłowym oraz czy odpowiadające sobie daty wskazują na ten sam dzień. Jeśli nie, wypisywane jest stosowne ostrzeżenie. Oczekiwanym wyjściem jest segment docelowy, w którym wszystkie daty są w żądanym formacie. "
]
},
{
"cell_type": "code",
2024-04-14 19:33:04 +02:00
"execution_count": 37,
"id": "e37a24ad",
2024-04-13 08:20:53 +02:00
"metadata": {},
"outputs": [],
2024-04-14 19:33:04 +02:00
"source": [
"text = 'The date is 2020-01-02, not 2020/01/02 or 02-01-2020 or 02/01/2020 or 02 January 2020'"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "4da1f53f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'The date is 01/02/2020, not 01/02/2020 or 02/01/2020 or 02/01/2020 or 01/02/2020'"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from dateutil.parser import parse\n",
"\n",
"def change_data_to_US_format(text):\n",
" dates = find_dates(text)\n",
"\n",
" for start, end in dates:\n",
" date = text[start:end]\n",
" try:\n",
" new_date = parse(date).strftime('%m/%d/%Y')\n",
" text = text[:start] + new_date + text[end:]\n",
" except:\n",
" pass\n",
" return text\n",
"\n",
"# Test the function\n",
"change_data_to_US_format(text)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"id": "8a2bf3a3",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'The date is 02/01/2020, not 02/01/2020 or 01/02/2020 or 01/02/2020 or 02/01/2020'"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from dateutil.parser import parse\n",
"\n",
"def change_data_to_EU_format(text):\n",
" dates = find_dates(text)\n",
"\n",
" for start, end in dates:\n",
" date = text[start:end]\n",
" try:\n",
" new_date = parse(date).strftime('%d/%m/%Y')\n",
" text = text[:start] + new_date + text[end:]\n",
" except:\n",
" pass\n",
" return text\n",
"\n",
"# Test the function\n",
"change_data_to_EU_format(text)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "e1c63075",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'The date is 2020.01.02, not 2020.01.02 or 2020.02.01 or 2020.02.01 or 2020.01.02'"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from dateutil.parser import parse\n",
"\n",
"def change_data_to_digit_dot_format(text):\n",
" dates = find_dates(text)\n",
"\n",
" for start, end in dates:\n",
" date = text[start:end]\n",
" try:\n",
" new_date = parse(date).strftime('%Y.%m.%d')\n",
" text = text[:start] + new_date + text[end:]\n",
" except:\n",
" pass\n",
" return text\n",
"\n",
"# Test the function\n",
"change_data_to_digit_dot_format(text)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "finished-essex",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Data jest 01/01/2020, a nie 01/01/2020 lub 01/01/2020 lub 01/01/2020'"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
2024-04-13 08:20:53 +02:00
"source": [
"def correct_dates(source_segment, target_segment, date_format):\n",
2024-04-14 19:33:04 +02:00
" # Check if number of dates in source and target segments are the same\n",
" assert len(find_dates(source_segment)) == len(find_dates(target_segment))\n",
"\n",
" # Check if all dates are the same (ignore the format)\n",
" source_dates = find_dates(source_segment)\n",
" target_dates = find_dates(target_segment)\n",
" for source_date, target_date in zip(source_dates, target_dates):\n",
" assert change_data_to_US_format(source_segment[source_date[0]:source_date[1]]) == change_data_to_US_format(target_segment[target_date[0]:target_date[1]]), f\"Dates are different: {source_segment[source_date[0]:source_date[1]]} and {target_segment[target_date[0]:target_date[1]]}\"\n",
"\n",
" # Change the format of dates in the target segment\n",
" if date_format == 'US':\n",
" target_segment = change_data_to_US_format(target_segment)\n",
" elif date_format == 'EU':\n",
" target_segment = change_data_to_EU_format(target_segment)\n",
" elif date_format == 'digit.dot':\n",
" target_segment = change_data_to_digit_dot_format(target_segment)\n",
"\n",
" return target_segment\n",
"\n",
"# Test the function\n",
"source_segment = 'The date is 2020-01-01, not 2020/01/01 or 01-01-2020 or 01/01/2020'\n",
"target_segment = \"Data jest 01/01/2020, a nie 2020-01-01 lub 01-01-2020 lub 01/01/2020\"\n",
"correct_dates(source_segment, target_segment, 'US')"
2024-04-13 08:20:53 +02:00
]
},
{
"cell_type": "markdown",
"id": "vertical-divide",
"metadata": {},
"source": [
"Co jeszcze można zrobić? Zajmijmy się tagami XML. Z punktu widzenia tłumacza najlepiej byłoby, gdyby mógł przetłumaczyć segment źródłowy zawierający tagi XML na język docelowy zupełnie ignorując te tagi. Ponieważ jednak tagi muszą jakoś znaleźć się w segmencie docelowym, przydałaby się jakaś \"magiczna różdżka\", która przeniosłaby wszystkie tagi ze źródła do tłumaczenia na mniej więcej dobre miejsca. Spełnijmy marzenie tłumacza!"
]
},
{
"cell_type": "markdown",
"id": "trained-trouble",
"metadata": {},
"source": [
"Rozważmy następujący algorytm: na wejściu mamy segment źródłowy zawierający tagi oraz segment docelowy bez tagów. Dokonujemy tokenizacji segmentu źródłowego tak, aby tagi były osobnymi tokenami. Następnie przeprowadźmy tokenizację segmentu docelowego. Gdy to jest gotowe, możemy zabrać się za przenoszenie (kopiowanie) tagów z segmentu źródłowego do docelowego."
]
},
{
"cell_type": "markdown",
"id": "damaged-simpson",
"metadata": {},
"source": [
"![Transfer tagów](img/tagtransfer.png)"
]
},
{
"cell_type": "markdown",
"id": "numerical-southeast",
"metadata": {},
"source": [
"Gdzie w segmencie docelowym powinien trafić tag? Przede wszystkim pomiędzy tokeny - nie chcemy rozbijać słów tagami. Pytanie tylko, pomiędzy które tokeny? Jeśli sytuacja jest taka, jak powyżej, kiedy segment źródłowy i docelowy mają taką samą liczbę słów nie będących tagami, przenosimy tagi na odpowiadające pozycje w tłumaczeniu. Natomiast jeśli długość tłumaczenia jest inna niż źródła, należy obliczać te pozycje w sposób proporcjonalny - jeśli np. mamy tag w źródle na pozycji 3, a tłumaczenie jest dwa razy dłuższe niż źródło, tag powinien być przeniesiony do tłumaczenia na pozycję 6. W przypadku niecałkowitych wartości proporcji stosujemy zaokrąglenia."
]
},
{
"cell_type": "markdown",
"id": "separated-socket",
"metadata": {},
"source": [
"### Ćwiczenie 5: Zaimplementuj opisany algorytm transferu tagów."
]
},
{
"cell_type": "code",
2024-04-14 19:33:04 +02:00
"execution_count": 60,
2024-04-13 08:20:53 +02:00
"id": "romance-judge",
"metadata": {},
"outputs": [],
"source": [
2024-04-14 19:33:04 +02:00
"import math\n",
"\n",
2024-04-13 08:20:53 +02:00
"def transfer_tags(source_segment, target_segment):\n",
2024-04-14 19:33:04 +02:00
" # Split the segments into tokens\n",
" source_tokens = source_segment.split()\n",
" target_tokens = target_segment.split()\n",
"\n",
" # Calculate the ratio of the number of tokens in the target to the number of tokens in the source\n",
" ratio = len(target_tokens) / len(source_tokens)\n",
"\n",
" # Assign tags to tokens in the target tokens - if the source token has a tag, assign it to the corresponding token in the target tokens\n",
" for i, source_token in enumerate(source_tokens):\n",
" if re.match(r'<[^>]+>', source_token):\n",
" target_index = math.ceil(i * ratio)\n",
"\n",
" if target_index >= len(target_tokens):\n",
" target_index = len(target_tokens) - 1\n",
"\n",
" # Assign start tag\n",
" target_tokens[target_index] = re.findall(r'<[^>]+>', source_token)[0] + target_tokens[target_index]\n",
"\n",
" # Assign end tag\n",
" target_tokens[target_index] = target_tokens[target_index] + re.findall(r'</[^>]+>', source_token)[0]\n",
"\n",
" return ' '.join(target_tokens)"
]
},
{
"cell_type": "code",
"execution_count": 61,
"id": "fd8858d8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'To jest <b>ważny</b> tekst'"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test the function (same number of tokens)\n",
"source_segment = 'This is <b>bold</b> text'\n",
"target_segment = 'To jest ważny tekst'\n",
"transfer_tags(source_segment, target_segment)"
]
},
{
"cell_type": "code",
"execution_count": 62,
"id": "de9e6298",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'To jest bardzo <b>ważny</b> tekst'"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Test the function (different number of tokens)\n",
"source_segment = 'This is <b>bold</b> text'\n",
"target_segment = 'To jest bardzo ważny tekst'\n",
"transfer_tags(source_segment, target_segment)"
2024-04-13 08:20:53 +02:00
]
}
],
"metadata": {
"author": "Rafał Jaworski",
"email": "rjawor@amu.edu.pl",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"lang": "pl",
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
2024-04-14 19:33:04 +02:00
"version": "3.10.14"
2024-04-13 08:20:53 +02:00
},
"subtitle": "6,7. Preprocessing i postprocessing",
"title": "Komputerowe wspomaganie tłumaczenia",
"year": "2021"
},
"nbformat": 4,
"nbformat_minor": 5
}