Skip to content

Commit

Permalink
Fix errors, add option Capitalize first letter
Browse files Browse the repository at this point in the history
  • Loading branch information
alekssamos committed Feb 3, 2021
1 parent 83718c6 commit 5a72d68
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 74 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Дополнение Text Normalizer для NVDA

[Скачать версию 2021.02.03](https://github.com/alekssamos/textnormalizer_for_nvda/releases/latest/download/textnormalizer-2021.02.03.nvda-addon)
[Скачать версию 2021.02.04](https://github.com/alekssamos/textnormalizer_for_nvda/releases/latest/download/textnormalizer-2021.02.04.nvda-addon)

### Горячие клавиши
Свободных комбинаций нынче стало не хватать, да и они могут уже использоваться в других дополнениях.
Expand Down
22 changes: 16 additions & 6 deletions addon/globalPlugins/textnormalizer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
if "TextNormalizer" not in config.conf: config.conf["TextNormalizer"]={}
default_conf = {
"copyToClipBoard": True,
"autoNormalize": True
"autoNormalize": True,
"change_case": True
}

for t in default_conf:
Expand All @@ -50,6 +51,10 @@ def makeSettings(self, sizer):
self.autoNormalize.SetValue(tobool(config.conf["TextNormalizer"]["autoNormalize"]))
settingsSizerHelper.addItem(self.autoNormalize)

self.change_case_checkbox = wx.CheckBox(self, label=_("&Capitalize first letter"))
self.change_case_checkbox.SetValue(tobool(config.conf["TextNormalizer"]["change_case"]))
settingsSizerHelper.addItem(self.change_case_checkbox)

self.source_text = settingsSizerHelper.addLabeledControl(_("&Source text:"), wx.TextCtrl, value="")
settingsSizerHelper.addItem(self.source_text)
self.normalize_text = wx.Button(self, label=_("&Normalize entered text"))
Expand All @@ -63,7 +68,9 @@ def postInit(self):
self.source_text.SetFocus()

def onNormalize_text(self, event):
self.normalized_text.Value = tn.CheckText(self.source_text.Value)
config.conf["TextNormalizer"]["change_case"] = self.change_case_checkbox.Value
change_case = config.conf["TextNormalizer"]["change_case"]
self.normalized_text.Value = tn.CheckText(self.source_text.Value, change_case)
self.normalized_text.SetFocus()

def _save_settings(self):
Expand All @@ -81,6 +88,7 @@ def onReset(self, event):
def onOk(self, event):
config.conf["TextNormalizer"]["copyToClipBoard"] = self.copyToClipBoard.Value
config.conf["TextNormalizer"]["autoNormalize"] = self.autoNormalize.Value
config.conf["TextNormalizer"]["change_case"] = self.change_case_checkbox.Value
# self._save_settings()
super(TextNormalizerSettingsDialog, self).onOk(event)

Expand All @@ -93,10 +101,11 @@ def __init__(self, callback, **kwargs):
self.start()

def run(self):
change_case = config.conf["TextNormalizer"]["change_case"]
if isinstance(self._kwargs["text"], str):
self._kwargs["text"] = tn.CheckText(self._kwargs["text"])
self._kwargs["text"] = tn.CheckText(self._kwargs["text"], change_case)
else:
self._kwargs["text"] = [tn.CheckText(txt) for txt in self._kwargs["text"]]
self._kwargs["text"] = [tn.CheckText(txt, change_case) for txt in self._kwargs["text"]]

wx.CallAfter(self._callback, self._kwargs["text"])

Expand All @@ -117,7 +126,7 @@ def __init__(self):

def speakDecorator(self, speak):
def my_speak(speechSequence, *args, **kwargs):
try: braille.handler.message(" ".join(speechSequence))
try: braille.handler.message(txt)
except: pass
return speak(speechSequence, *args, **kwargs)
def wrapper(speechSequence, *args, **kwargs):
Expand All @@ -128,7 +137,8 @@ def checkByCharacters(ss):
return False
if not tobool(config.conf["TextNormalizer"]["autoNormalize"]) or checkByCharacters(speechSequence):
return speak(speechSequence, *args, **kwargs)
text=" ".join([tn.CheckText(i) for i in speechSequence if isinstance(i, str)])
change_case = config.conf["TextNormalizer"]["change_case"]
text=" ".join([tn.CheckText(i, change_case) for i in speechSequence if isinstance(i, str)])
return speak([text], *args, **kwargs)
return wrapper

Expand Down
33 changes: 20 additions & 13 deletions addon/globalPlugins/textnormalizer/textnormalizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@

import re

def replace(old, new, str, caseinsentive = False):
if caseinsentive:
return str.replace(old, new)
else:
return re.sub(re.escape(old), new, str, flags=re.IGNORECASE)

class TextNormalizer():
"""Translates the letters of the alphabet mixed in normal"""

lang = "?"
Changes = False
def CheckWord(self, word):

def replace(self, old, new, str, caseinsentive = False):
if caseinsentive:
return str.replace(old, new)
else:
return re.sub(re.escape(old), new, str, flags=re.IGNORECASE)

def CheckWord(self, word, change_case = True):
"""Check the word
Args:
Expand All @@ -30,7 +31,10 @@ def CheckWord(self, word):

newword = word
# если есть цифры - не меняем
if re.match("[24579]", newword):
if re.search("[24579]", newword):
return newword
# если в конце русского слова цифра - не меняем
if re.search("^[а-яё]+[0-9]$", newword):
return newword
OnlyRu = "БбвГгДдЁёЖжЗзИиЙйЛлмнПптУФфЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"
OnlyEn = "DdFfGghIiJjLlNQqRrSstUVvWwYZz"
Expand Down Expand Up @@ -73,9 +77,10 @@ def CheckWord(self, word):
# Были ли замены?
self.Changes = newword != word
newword = newword.lower()
if self.Changes and change_case: newword = newword.capitalize()
return newword

def CheckText(self, text):
def CheckText(self, text, change_case = True):
"""Normalize the text
Args:
Expand All @@ -87,28 +92,30 @@ def CheckText(self, text):

newText = text
for word in re.findall("[\\w\\@]+", text, re.DOTALL + re.IGNORECASE):
newWord = self.CheckWord(word)
newWord = self.CheckWord(word, change_case)
if self.Changes:
newText = newText.replace(word, newWord)
Rus = ["с", "у", "нет", "ее"]
Eng = ["c", "y", "heт", "ee"]
if text != newText:
newText = newText.replace("B", "В").replace("H", "Н")
for i in range(0, len(Rus)):
newText = replace(Eng[i], Rus[i], newText, False)
newText = self.replace(Eng[i], Rus[i], newText, False)
patterns = [
"[cс][kк][oо][pр][еe]",
"[kк][yу][pр][сc]",
"[kк][yу][pр][сc][eе]",
"[s][kк][yу][pр][eе]",
r"[a]([a-zа-яё\s,:.?!]+)"
r"[a]([^dfgjmnqrsvwz]+)",
"[Hн][eе][tт]"
]
replaces = [
"скорее",
"курс",
"курсе",
"skype",
r"а\1"
r"а\1",
"нет"
]
for i in range(0, len(patterns)):
newText = re.sub(patterns[i], replaces[i], newText, flags=re.IGNORECASE)
Expand Down
61 changes: 33 additions & 28 deletions addon/locale/ru/LC_MESSAGES/nvda.po
Original file line number Diff line number Diff line change
Expand Up @@ -7,97 +7,102 @@ msgid ""
msgstr ""
"Project-Id-Version: 'textnormalizer' '2021.02.01'\n"
"Report-Msgid-Bugs-To: 'nvda-translations@groups.io'\n"
"POT-Creation-Date: 2021-02-01 23:48+0300\n"
"PO-Revision-Date: 2021-02-02 01:03+0300\n"
"POT-Creation-Date: 2021-02-03 11:26+0300\n"
"PO-Revision-Date: 2021-02-03 11:27+0300\n"
"Last-Translator: Alex <aleks-samos@yandex.ru>\n"
"Language-Team: \n"
"Language: ru\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.4.2\n"
"Last-Translator: Alex <aleks-samos@yandex.ru>\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);\n"
"Language: ru\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
"%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);\n"

#: addon\globalPlugins\textnormalizer\__init__.py:41
#: addon\globalPlugins\textnormalizer\__init__.py:42
msgid "Text Normalizer Settings"
msgstr "Настройки Text Normalizer"

#: addon\globalPlugins\textnormalizer\__init__.py:44
#: addon\globalPlugins\textnormalizer\__init__.py:46
msgid "&Copy text to clipboard"
msgstr "&Копировать текст в буфер обмена"

#: addon\globalPlugins\textnormalizer\__init__.py:48
#: addon\globalPlugins\textnormalizer\__init__.py:50
msgid "&Instant normalizing"
msgstr "&Мгновенная нормализация"

#: addon\globalPlugins\textnormalizer\__init__.py:52
#: addon\globalPlugins\textnormalizer\__init__.py:54
msgid "&Capitalize first letter"
msgstr "&Первая буква заглавная"

#: addon\globalPlugins\textnormalizer\__init__.py:58
msgid "&Source text:"
msgstr "&Исходный текст:"

#: addon\globalPlugins\textnormalizer\__init__.py:54
#: addon\globalPlugins\textnormalizer\__init__.py:60
msgid "&Normalize entered text"
msgstr "&Нормализовать введенный текст"

#: addon\globalPlugins\textnormalizer\__init__.py:57
#: addon\globalPlugins\textnormalizer\__init__.py:63
msgid "N&ormalized text:"
msgstr "Н&ормализованный текст"

#: addon\globalPlugins\textnormalizer\__init__.py:73
#: addon\globalPlugins\textnormalizer\__init__.py:81
msgid "Error saving settings"
msgstr "Ошибка сохранения настроек"

#: addon\globalPlugins\textnormalizer\__init__.py:87
#: addon\globalPlugins\textnormalizer\__init__.py:98
#: addon\globalPlugins\textnormalizer\__init__.py:113
#: addon\globalPlugins\textnormalizer\__init__.py:125
msgid "Text Normalizer"
msgstr ""

#: addon\globalPlugins\textnormalizer\__init__.py:130
#: addon\globalPlugins\textnormalizer\__init__.py:163
msgid "Normalize text from the clipboard"
msgstr "Нормализовать текст из буфера обмена"

#: addon\globalPlugins\textnormalizer\__init__.py:136
#: addon\globalPlugins\textnormalizer\__init__.py:147
#: addon\globalPlugins\textnormalizer\__init__.py:172
#: addon\globalPlugins\textnormalizer\__init__.py:169
#: addon\globalPlugins\textnormalizer\__init__.py:180
#: addon\globalPlugins\textnormalizer\__init__.py:205
msgid "No text to normalize"
msgstr "Нет текста для нормализации"

#: addon\globalPlugins\textnormalizer\__init__.py:142
#: addon\globalPlugins\textnormalizer\__init__.py:175
msgid "Normalizes the selected text."
msgstr "Нормализовать выделенный текст"

#: addon\globalPlugins\textnormalizer\__init__.py:153
#: addon\globalPlugins\textnormalizer\__init__.py:186
msgid "Normalizes the last spoken phrase"
msgstr "Нормализовать последнюю сказанную фразу"

#: addon\globalPlugins\textnormalizer\__init__.py:161
#: addon\globalPlugins\textnormalizer\__init__.py:194
msgid "Normalizes text from navigator object"
msgstr "Нормализовать текст под объектом навигатора"

#: addon\globalPlugins\textnormalizer\__init__.py:180
#: addon\globalPlugins\textnormalizer\__init__.py:213
msgid "Copy to clipboard"
msgstr "Копировать в буфер обмена"

#: addon\globalPlugins\textnormalizer\__init__.py:182
#: addon\globalPlugins\textnormalizer\__init__.py:215
msgid "No normalization to copy"
msgstr "Нет текста для копирования"

#: addon\globalPlugins\textnormalizer\__init__.py:183
#: addon\globalPlugins\textnormalizer\__init__.py:216
msgid "Copy last normalization to clipboard"
msgstr "Копировать последний текст в буфер обмена"

#: addon\globalPlugins\textnormalizer\__init__.py:187
#: addon\globalPlugins\textnormalizer\__init__.py:220
msgid "Shows the settings dialog"
msgstr "Показать диалог настроек"

#: addon\globalPlugins\textnormalizer\__init__.py:190
#: addon\globalPlugins\textnormalizer\__init__.py:223
msgid "Switches the function of automatic normalization"
msgstr "Переключает функцию автоматической нормализации"

#: addon\globalPlugins\textnormalizer\__init__.py:194
#: addon\globalPlugins\textnormalizer\__init__.py:227
msgid "Automatic normalization enabled"
msgstr "Автоматическая нормализация включена"

#: addon\globalPlugins\textnormalizer\__init__.py:198
#: addon\globalPlugins\textnormalizer\__init__.py:231
msgid "Automatic normalization disabled"
msgstr "Автоматическая нормализация отключена"

Expand Down
2 changes: 1 addition & 1 deletion buildVars.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# Translators: Long description to be shown for this add-on on add-on information from add-ons manager
"addon_description": _("""Translates the letters of the alphabet mixed in normal."""),
# version
"addon_version": "2021.02.03",
"addon_version": "2021.02.04",
# Author(s)
"addon_author": u"alekssamos <aleks-samos@yandex.ru>",
# URL for the add-on documentation support
Expand Down
Loading

0 comments on commit 5a72d68

Please sign in to comment.