{ "cells": [ { "cell_type": "markdown", "id": "marine-termination", "metadata": {}, "source": [ "![Logo 1](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech1.jpg)\n", "
\n", "

Komputerowe wspomaganie tłumaczenia

\n", "

15. Korekta gramatyczna [laboratoria]

\n", "

Rafał Jaworski (2021)

\n", "
\n", "\n", "![Logo 2](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech2.jpg)" ] }, { "cell_type": "markdown", "id": "featured-afghanistan", "metadata": {}, "source": [ "Ostatnią z omawianych przez nas technik stosowaną podczas wspomagania tłumaczenia jest korekta gramatyczna. Automatyczna korekta gramatyczna tekstu to ambitne zadanie odnalezienia możliwych błędów niezwiązanych bezpośrednio z pisownią. Są to między innymi:\n", "* błędy gramatyczne\n", "* źle użyte słowa\n", "* złe połączenia wyrazowe\n", "* błędy interpunkcyjne\n", "* kolokwializmy\n", "* redundancja (np. \"tylko i wyłącznie\")" ] }, { "cell_type": "markdown", "id": "peaceful-kingston", "metadata": {}, "source": [ "Warto zwrócić uwagę, iż systemy do korekcji gramatycznej można traktować jako klasyfikatory binarne. Przyjmijmy, że odpowiedź pozytywna korektora to wykrycie błędu w tekście, natomiast negatywna - brak błędu. Wówczas rozróżniamy dwa typy pomyłek: false positive oraz false negative. False positive to tzw. \"fałszywy alarm\" - zbyt duża ich ilość spowoduje wydłużenie czasu pracy użytkownika przez konieczność analizowania zgłoszeń, które w istocie błędami nie są. Co jednak jeszcze gorsze, zbyt duża ilość false positives powoduje spadek zaufania użytkownika do systemu oraz drastyczny spadek satysfakcji z używania systemu. Te drugie błędy - false negatives - to z kolei faktyczne błędy w tekście, które nie zostały wyłapane przez system korekty. Stare polskie porzekadło głosi, że \"czego oko nie widzi, tego sercu nie żal\". Niestety jednak problem pojawia się, kiedy dostrzeże to jakieś inne oko... Wysoka liczba false negatives wprawdzie skraca czas korekty (sic!), ale odbywa się to kosztem jakości całego procesu. Idealnie zatem byłoby zminimalizować zarówno liczbę false positives, jak i false negatives. Jak jednak łatwo się domyślić, nie jest to zawsze możliwe. Korektor gramatyczny, który jest bardzo restrykcyjny i raportuje wiele błędów, będzie miał tendencję do popełniania false positives. Natomiast korektor bardziej pobłażliwy niechybnie popełni wiele false negatives. Co zatem jest ważniejsze? Praktyka wskazuje, że oba parametry mają podobną wagę, ale jednak odrobinę ważniejsze jest powstrzymanie się od false positives." ] }, { "cell_type": "markdown", "id": "soviet-highland", "metadata": {}, "source": [ "Do najbardziej popularnych narzędzi wspomagających korektę gramatyczną tekstu należą Grammarly oraz LanguageTool. Na dzisiejszych zajęciach zajmiemy się tym drugim. LanguageTool został pierwotnie napisany jako praca dyplomowa Daniela Nabera, a następnie intensywnie rozwijany wspólnie z Marcinem Miłkowskim. Aż do dziś projekt jest ciągle rozwijany, zwiększana jest liczba obsługiwanych języków oraz dokładność działania." ] }, { "cell_type": "markdown", "id": "arbitrary-reconstruction", "metadata": {}, "source": [ "LanguageTool jest systemem opartym na regułach. W dobie wszechobecnej sztucznej inteligencji opartej na uczeniu maszynowym rozwiązanie to wydaje się nieco przestarzałe. Jednak to właśnie reguły stanowią o sile LanguageToola - pozwalają one na zwiększenie precyzji korektora poprzez minimalizację false positives. Warto wspomnieć, iż liczne reguły LanguageToola dotyczą również korekty pisowni. Czyni to z LanguageToola kompletne narzędzie do korekty tekstu. Polecam przejrzenie zestawu reguł LanguageToola dla języka angielskiego: https://community.languagetool.org/rule/list?lang=en" ] }, { "cell_type": "markdown", "id": "piano-satellite", "metadata": {}, "source": [ "Czas uruchomić to narzędzie. Skorzystajmy z Pythona." ] }, { "cell_type": "markdown", "id": "academic-crest", "metadata": { "vscode": { "languageId": "raw" } }, "source": [] }, { "cell_type": "code", "execution_count": 1, "id": "9020428a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting language_tool_python\n", " Downloading language_tool_python-2.8-py3-none-any.whl (35 kB)\n", "Requirement already satisfied: pip in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from language_tool_python) (22.0.2)\n", "Requirement already satisfied: tqdm in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from language_tool_python) (4.66.4)\n", "Requirement already satisfied: requests in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from language_tool_python) (2.31.0)\n", "Requirement already satisfied: wheel in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from language_tool_python) (0.37.1)\n", "Requirement already satisfied: idna<4,>=2.5 in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from requests->language_tool_python) (3.7)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from requests->language_tool_python) (2.2.1)\n", "Requirement already satisfied: certifi>=2017.4.17 in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from requests->language_tool_python) (2024.2.2)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /home/potato/.virtualenvs/praca/lib/python3.11/site-packages (from requests->language_tool_python) (3.3.2)\n", "Installing collected packages: language_tool_python\n", "Successfully installed language_tool_python-2.8\n" ] } ], "source": [ "!pip install language_tool_python" ] }, { "cell_type": "markdown", "id": "italian-cheese", "metadata": {}, "source": [ "Następnie możemy użyć LanguageToola w programie Pythonowym: (przykład zaczerpnięty z oficjalnego tutoriala: https://pypi.org/project/language-tool-python/)" ] }, { "cell_type": "code", "execution_count": 2, "id": "relative-anaheim", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Downloading LanguageTool 6.4: 100%|██████████| 246M/246M [00:07<00:00, 34.5MB/s] \n", "Unzipping /tmp/tmp2yjlywpj.zip to /home/potato/.cache/language_tool_python.\n", "Downloaded https://www.languagetool.org/download/LanguageTool-6.4.zip to /home/potato/.cache/language_tool_python.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[Match({'ruleId': 'EN_A_VS_AN', 'message': 'Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.', 'replacements': ['an'], 'offsetInContext': 16, 'context': 'A sentence with a error in the Hitchhiker’s Guide tot he ...', 'offset': 16, 'errorLength': 1, 'category': 'MISC', 'ruleIssueType': 'misspelling', 'sentence': \"A sentence with a error in the Hitchhiker's Guide tot he Galaxy\"}),\n", " Match({'ruleId': 'TOT_HE', 'message': 'Did you mean “to the”?', 'replacements': ['to the'], 'offsetInContext': 43, 'context': '... with a error in the Hitchhiker’s Guide tot he Galaxy', 'offset': 50, 'errorLength': 6, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': \"A sentence with a error in the Hitchhiker's Guide tot he Galaxy\"})]\n" ] } ], "source": [ "import language_tool_python\n", "import pprint\n", "tool = language_tool_python.LanguageTool('en-US') \n", "\n", "text = 'A sentence with a error in the Hitchhiker’s Guide tot he Galaxy'\n", "\n", "pp = pprint.PrettyPrinter(depth=2)\n", "errors = tool.check(text)\n", "pp.pprint(errors)" ] }, { "cell_type": "markdown", "id": "gorgeous-million", "metadata": {}, "source": [ "Przeanalizujmy format zwracanego wyniku. Otrzymujemy listę obiektów Match - zawiadomień o potencjalnym błędzie. Razem z każdym błędem otrzymujemy m.in. identyfikator użytej reguły, opis błędu, rekomendancję poprawy, kontekst." ] }, { "cell_type": "markdown", "id": "reasonable-cornwall", "metadata": {}, "source": [ "### Ćwiczenie 1: Użyj LanguageTool do znalezienia jak największej liczby prawdziwych błędów na swoim ulubionym portalu internetowym. Skorzystaj z poznanych wcześniej technik web scrapingu. Uwaga - LanguageTool najprawdopodobniej oznaczy nazwy własne jako literówki - ten typ błędu nie powinien być brany pod uwagę." ] }, { "cell_type": "code", "execution_count": 5, "id": "sound-teaching", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' The'], 'offsetInContext': 43, 'context': '...h mana, reverence, strength and bravery.The Meaning of the TokiTraditionally, a Tok...', 'offset': 219, 'errorLength': 3, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'The Meaning of the TokiTraditionally, a Toki (Adze) was an everyday tool used by Māori for different woodworking tasks, such as felling trees, hollowing out waka (canoes), and constructing houses and wharenui (Māori communal houses).'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Māori'], 'offsetInContext': 43, 'context': '...t was then swung powerfully to cut wood.Māori were skilful woodworkers, and as they d...', 'offset': 654, 'errorLength': 5, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Māori were skilful woodworkers, and as they did not have metal, pounamu served well as a woodcutting tool because of its exceptional toughness and ability to retain a hard, sharp cutting edge.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' DiscoverToki'], 'offsetInContext': 43, 'context': '...a powerful symbol of strength and power.DiscoverToki (Adze) NecklacesShop All TokiA Toki Pou...', 'offset': 970, 'errorLength': 12, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'DiscoverToki (Adze) NecklacesShop All TokiA Toki Poutangata is an adze worked from pounamu and lashed to an elaborately carved wooden handle, and adorned with the feathers of significant native birds.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Shop'], 'offsetInContext': 43, 'context': '... steeped in Māori tradition and meaning.Shop All TokiWatch how we carve TokiMorepoun...', 'offset': 2076, 'errorLength': 4, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Shop All TokiWatch how we carve TokiMorepounamu meanings & designsTwist (Pikorua)Koru (spiral)Hei Matau (hook)HeartManaiaHei TikiFollow usStay in the know on new releases, special offers, and more.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Your'], 'offsetInContext': 43, 'context': '... new releases, special offers, and more.Your email addressSupportContactFAQsShipping...', 'offset': 2273, 'errorLength': 4, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Your email addressSupportContactFAQsShippingGift WrappingReturnsCarePrivacy PolicyTerms & ConditionsWarrantyGift CardsReviewsAboutOur StorySustainabilityLearn about JadeNewsletterAuckland StoreRotorua StoreOur ToursTen Reasons to GiftNeed Help?+64 7 349 3968customercare@mountainjade.co.nz1288 Fenton Street, RotoruaNew ZealandSupportAboutNeed Help?'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Website'], 'offsetInContext': 43, 'context': '...RotoruaNew ZealandSupportAboutNeed Help?Website byWe Ship WorldwidePremium Gift Wrappin...', 'offset': 2622, 'errorLength': 7, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Website byWe Ship WorldwidePremium Gift WrappingFree Shipping*We Ship WorldwidePremium Gift WrappingFree Shipping*ShopLearnToursFind Us$NZD$AUD£GBP$CAD$USD€EUR¥JPY'})]\n" ] }, { "data": { "text/plain": [ "[Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' The'], 'offsetInContext': 43, 'context': '...h mana, reverence, strength and bravery.The Meaning of the TokiTraditionally, a Tok...', 'offset': 219, 'errorLength': 3, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'The Meaning of the TokiTraditionally, a Toki (Adze) was an everyday tool used by Māori for different woodworking tasks, such as felling trees, hollowing out waka (canoes), and constructing houses and wharenui (Māori communal houses).'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Māori'], 'offsetInContext': 43, 'context': '...t was then swung powerfully to cut wood.Māori were skilful woodworkers, and as they d...', 'offset': 654, 'errorLength': 5, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Māori were skilful woodworkers, and as they did not have metal, pounamu served well as a woodcutting tool because of its exceptional toughness and ability to retain a hard, sharp cutting edge.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' DiscoverToki'], 'offsetInContext': 43, 'context': '...a powerful symbol of strength and power.DiscoverToki (Adze) NecklacesShop All TokiA Toki Pou...', 'offset': 970, 'errorLength': 12, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'DiscoverToki (Adze) NecklacesShop All TokiA Toki Poutangata is an adze worked from pounamu and lashed to an elaborately carved wooden handle, and adorned with the feathers of significant native birds.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Shop'], 'offsetInContext': 43, 'context': '... steeped in Māori tradition and meaning.Shop All TokiWatch how we carve TokiMorepoun...', 'offset': 2076, 'errorLength': 4, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Shop All TokiWatch how we carve TokiMorepounamu meanings & designsTwist (Pikorua)Koru (spiral)Hei Matau (hook)HeartManaiaHei TikiFollow usStay in the know on new releases, special offers, and more.'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Your'], 'offsetInContext': 43, 'context': '... new releases, special offers, and more.Your email addressSupportContactFAQsShipping...', 'offset': 2273, 'errorLength': 4, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Your email addressSupportContactFAQsShippingGift WrappingReturnsCarePrivacy PolicyTerms & ConditionsWarrantyGift CardsReviewsAboutOur StorySustainabilityLearn about JadeNewsletterAuckland StoreRotorua StoreOur ToursTen Reasons to GiftNeed Help?+64 7 349 3968customercare@mountainjade.co.nz1288 Fenton Street, RotoruaNew ZealandSupportAboutNeed Help?'}),\n", " Match({'ruleId': 'SENTENCE_WHITESPACE', 'message': 'Add a space between sentences.', 'replacements': [' Website'], 'offsetInContext': 43, 'context': '...RotoruaNew ZealandSupportAboutNeed Help?Website byWe Ship WorldwidePremium Gift Wrappin...', 'offset': 2622, 'errorLength': 7, 'category': 'TYPOGRAPHY', 'ruleIssueType': 'whitespace', 'sentence': 'Website byWe Ship WorldwidePremium Gift WrappingFree Shipping*We Ship WorldwidePremium Gift WrappingFree Shipping*ShopLearnToursFind Us$NZD$AUD£GBP$CAD$USD€EUR¥JPY'})]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import re\n", "import requests\n", "from bs4 import BeautifulSoup\n", "import language_tool_python\n", "import pprint\n", "\n", "\n", "def fetch_page_content(url):\n", " response = requests.get(url)\n", " soup = BeautifulSoup(response.content, 'html.parser')\n", "\n", " for unwanted in soup([\"script\", \"style\"]):\n", " unwanted.decompose()\n", "\n", " page_text = soup.get_text()\n", "\n", " clean_text = re.sub(r\"\\s+\", \" \", page_text)\n", " return clean_text\n", "\n", "\n", "def identify_language_errors(site_url):\n", " issues = []\n", " page_content = fetch_page_content(site_url)\n", " language_tool = language_tool_python.LanguageTool('en-NZ')\n", " matches = language_tool.check(page_content)\n", " for match in matches:\n", " if match.ruleId != 'MORFOLOGIK_RULE_EN_NZ':\n", " issues.append(match)\n", "\n", " pprint.pprint(issues)\n", " return issues\n", "\n", "identify_language_errors('https://www.mountainjade.co.nz/pages/greenstone-meanings-and-designs/toki-adze')\n" ] }, { "cell_type": "markdown", "id": "coupled-extra", "metadata": {}, "source": [ "### Ćwiczenie 2: Napisz skrypt, który poszuka błędów w komentarzach klasy Javowej (zwykłych // oraz w javadocach). Uruchom ten skrypt na źródłach wybranego opensourcowego projektu w Javie." ] }, { "cell_type": "code", "execution_count": 3, "id": "settled-armor", "metadata": {}, "outputs": [], "source": [ "def correct_java_grammar(java_file_path):\n", " return []" ] } ], "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", "version": "3.11.9" }, "subtitle": "15. Korekta gramatyczna", "title": "Komputerowe wspomaganie tłumaczenia", "year": "2021" }, "nbformat": 4, "nbformat_minor": 5 }