Skip to content

Commit

Permalink
Python 3 compatibility and migration to config.conf
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaszgo1 committed Mar 15, 2020
1 parent d1fe551 commit 0fb2df0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 22 deletions.
35 changes: 13 additions & 22 deletions addon/globalPlugins/ocr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
import subprocess
from xml.parsers import expat
from collections import namedtuple
from io import StringIO
import configobj
import validate
import wx
import config
import globalPluginHandler
Expand All @@ -32,8 +29,12 @@
PLUGIN_DIR = os.path.dirname(__file__)
TESSERACT_EXE = os.path.join(PLUGIN_DIR, "tesseract", "tesseract.exe")

# Pillow requires pathlib which is not bundled with NVDA
# Therefore place it in the plugin directory and add it temporarily to PYTHONPATH
sys.path.append(PLUGIN_DIR)
from .PIL import ImageGrab
from .PIL import Image
del sys.path[-1]

IMAGE_RESIZE_FACTOR = 2

Expand Down Expand Up @@ -150,7 +151,7 @@ def terminate(self):
def onOCRSettings(self, event):
# Pop a dialog with available OCR languages to set
langs = sorted(getAvailableTesseractLanguages())
curlang = getConfig()['language']
curlang = config.conf["ocr"]["language"]
try:
select = langs.index(curlang)
except ValueError:
Expand All @@ -164,11 +165,8 @@ def onOCRSettings(self, event):
gui.mainFrame.postPopup()
if ret == wx.ID_OK:
lang = langs[dialog.GetSelection()]
getConfig()['language'] = lang
try:
getConfig().write()
except IOError:
log.error("Error writing ocr configuration", exc_info=True)
config.conf["ocr"]["language"] = lang

def script_ocrNavigatorObject(self, gesture):
nav = api.getNavigatorObject()
left, top, width, height = nav.location
Expand All @@ -183,7 +181,7 @@ def script_ocrNavigatorObject(self, gesture):
img.save(imgFile)

ui.message(_("Running OCR"))
lang = getConfig()['language']
lang = config.conf["ocr"]["language"]
# Hide the Tesseract window.
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESHOWWINDOW
Expand Down Expand Up @@ -262,15 +260,8 @@ def getDefaultLanguage():
lang = lang.split("_")[0]
return localesToTesseractLangs.get(lang, "eng")

_config = None
configspec = StringIO("""
language=string(default={defaultLanguage})
""".format(defaultLanguage=getDefaultLanguage()))
def getConfig():
global _config
if not _config:
path = os.path.join(config.getUserDefaultConfigPath(), "ocr.ini")
_config = configobj.ConfigObj(path, configspec=configspec)
val = validate.Validator()
_config.validate(val)
return _config
configspec = {
"language" : f"string(default={getDefaultLanguage()})"
}

config.conf.spec["ocr"] = configspec
20 changes: 20 additions & 0 deletions addon/installTasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import re
import os
import config
import globalVars

def onInstall():
oldOCRConfig = os.path.join(globalVars.appArgs.configPath, "ocr.ini")
try:
with open(oldOCRConfig, "r", encoding = "utf-8") as f:
configContent = f.read()
langFinder = r'^language \= (.+)$'
if re.match(langFinder, configContent):
OCRLang = re.match(langFinder, configContent)[1]
# Ensure that language is written to the default configuration
if "ocr" not in config.conf.profiles[0]:
config.conf.profiles[0]["ocr"] = {}
config.conf.profiles[0]["ocr"]["language"] = OCRLang
os.remove(oldOCRConfig)
except FileNotFoundError:
pass

0 comments on commit 0fb2df0

Please sign in to comment.