/
__init__.py
299 lines (262 loc) · 11.1 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#contentRecog/__init__.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2017 NV Access Limited
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""Framework for recognition of content; OCR, image recognition, etc.
When authors don't provide sufficient information for a screen reader user to determine the content of something,
various tools can be used to attempt to recognize the content from an image.
Some examples are optical character recognition (OCR) to recognize text in an image
and the Microsoft Cognitive Services Computer Vision and Google Cloud Vision APIs to describe images.
Recognizers take an image and produce text.
They are implemented using the L{ContentRecognizer} class.
"""
from collections import namedtuple
import textInfos.offsets
from abc import ABCMeta, abstractmethod
from locationHelper import RectLTWH
class ContentRecognizer(object, metaclass=ABCMeta):
"""Implementation of a content recognizer.
"""
def getResizeFactor(self, width, height):
"""Return the factor by which an image must be resized
before it is passed to this recognizer.
@param width: The width of the image in pixels.
@type width: int
@param height: The height of the image in pixels.
@type height: int
@return: The resize factor, C{1} for no resizing.
@rtype: int or float
"""
return 1
@abstractmethod
def recognize(self, pixels, imageInfo, onResult):
"""Asynchronously recognize content from an image.
This method should not block.
Only one recognition can be performed at a time.
@param pixels: The pixels of the image as a two dimensional array of RGBQUADs.
For example, to get the red value for the coordinate (1, 2):
pixels[2][1].rgbRed
This can be treated as raw bytes in BGRA8 format;
i.e. four bytes per pixel in the order blue, green, red, alpha.
However, the alpha channel should be ignored.
@type pixels: Two dimensional array (y then x) of L{winGDI.RGBQUAD}
@param imageInfo: Information about the image for recognition.
@type imageInfo: L{RecogImageInfo}
@param onResult: A callable which takes a L{RecognitionResult} (or an exception on failure) as its only argument.
@type onResult: callable
"""
raise NotImplementedError
@abstractmethod
def cancel(self):
"""Cancel the recognition in progress (if any).
"""
raise NotImplementedError
class RecogImageInfo(object):
"""Encapsulates information about a recognized image and
provides functionality to convert coordinates.
An image captured for recognition can begin at any point on the screen.
However, the image must be cropped when passed to the recognizer.
Also, some recognizers need the image to be resized prior to recognition.
This class calculates the width and height of the image for recognition;
see the L{recogWidth} and L{recogHeight} attributes.
It can also convert coordinates in the recognized image
to screen coordinates suitable to be returned to NVDA;
e.g. in order to route the mouse.
This is done using the L{convertXToScreen} and L{convertYToScreen} methods.
"""
def __init__(self, screenLeft, screenTop, screenWidth, screenHeight, resizeFactor):
"""
@param screenLeft: The x screen coordinate of the upper-left corner of the image.
@type screenLeft: int
@param screenTop: The y screen coordinate of the upper-left corner of the image.
@type screenTop: int
@param screenWidth: The width of the image on the screen.
@type screenWidth: int
@param screenHeight: The height of the image on the screen.
@type screenHeight: int
@param resizeFactor: The factor by which the image must be resized for recognition.
@type resizeFactor: int or float
@raise ValueError: If the supplied screen coordinates indicate that
the image is not visible; e.g. width or height of 0.
"""
if screenLeft < 0 or screenTop < 0 or screenWidth <= 0 or screenHeight <= 0:
raise ValueError("Image not visible (invalid screen coordinates)")
self.screenLeft = screenLeft
self.screenTop = screenTop
self.screenWidth = screenWidth
self.screenHeight = screenHeight
self.resizeFactor = resizeFactor
#: The width of the recognized image.
self.recogWidth = int(screenWidth * resizeFactor)
#: The height of the recognized image.
self.recogHeight = int(screenHeight * resizeFactor)
@classmethod
def createFromRecognizer(cls, screenLeft, screenTop, screenWidth, screenHeight, recognizer):
"""Convenience method to construct an instance using a L{ContentRecognizer}.
The resize factor is obtained by calling L{ContentRecognizer.getResizeFactor}.
"""
resize = recognizer.getResizeFactor(screenWidth, screenHeight)
return cls(screenLeft, screenTop, screenWidth, screenHeight, resize)
def convertXToScreen(self, x):
"""Convert an x coordinate in the recognized image to an x coordinate on the screen.
"""
return self.screenLeft + int(x / self.resizeFactor)
def convertYToScreen(self, y):
"""Convert an y coordinate in the recognized image to a y coordinate on the screen.
"""
return self.screenTop + int(y / self.resizeFactor)
def convertWidthToScreen(self, width):
"""Convert width in the recognized image to the width on the screen.
"""
return int(width / self.resizeFactor)
def convertHeightToScreen(self, height):
"""Convert height in the recognized image to the height on the screen.
"""
return int(height / self.resizeFactor)
class RecognitionResult(object, metaclass=ABCMeta):
"""Provides access to the result of recognition by a recognizer.
The result is textual, but to facilitate navigation by word, line, etc.
and to allow for retrieval of screen coordinates within the text,
L{TextInfo} objects are used.
Callers use the L{makeTextInfo} method to create a L{TextInfo}.
Most implementers should use one of the subclasses provided in this module.
"""
@abstractmethod
def makeTextInfo(self, obj, position):
"""Make a TextInfo within the recognition result text at the requested position.
@param obj: The object to return for the C{obj} property of the TextInfo.
The TextInfo itself doesn't use this, but NVDA requires it to set the review object, etc.
@param position: The requested position; one of the C{textInfos.POSITION_*} constants.
@return: The TextInfo at the requested position in the result.
@rtype: L{textInfos.TextInfo}
"""
raise NotImplementedError
# Used internally by LinesWordsResult.
# (Lwr is short for LinesWordsResult.)
LwrWord = namedtuple("LwrWord", ("offset", "left", "top", "width", "height"))
class LinesWordsResult(RecognitionResult):
"""A L{RecognizerResult} which can create TextInfos based on a simple lines/words data structure.
The data structure is a list of lines, wherein each line is a list of words,
wherein each word is a dict containing the keys x, y, width, height and text.
Several OCR engines produce output in a format which can be easily converted to this.
"""
def __init__(self, data, imageInfo):
"""Constructor.
@param data: The lines/words data structure. For example:
[
[
{"x": 106, "y": 91, "width": 11, "height": 9, "text": "Word1"},
{"x": 117, "y": 91, "width": 11, "height": 9, "text": "Word2"}
],
[
{"x": 106, "y": 105, "width": 11, "height": 9, "text": "Word3"},
{"x": 117, "y": 105, "width": 11, "height": 9, "text": "Word4"}
]
]
@type data: list of lists of dicts
@param imageInfo: Information about the recognized image.
This is used to convert coordinates in the recognized image
to screen coordinates.
@type imageInfo: L{RecogImageInfo}
"""
self.data = data
self.imageInfo = imageInfo
self._textList = []
self.textLen = 0
#: End offsets for each line.
self.lines = []
#: Start offsets and screen coordinates for each word.
self.words = []
self._parseData()
self.text = "".join(self._textList)
def _parseData(self):
for line in self.data:
firstWordOfLine = True
for word in line:
if firstWordOfLine:
firstWordOfLine = False
else:
# Separate with a space.
self._textList.append(" ")
self.textLen += 1
self.words.append(LwrWord(self.textLen,
self.imageInfo.convertXToScreen(word["x"]),
self.imageInfo.convertYToScreen(word["y"]),
self.imageInfo.convertWidthToScreen(word["width"]),
self.imageInfo.convertHeightToScreen(word["height"])))
text = word["text"]
self._textList.append(text)
self.textLen += len(text)
# End with new line.
self._textList.append("\n")
self.textLen += 1
self.lines.append(self.textLen)
def makeTextInfo(self, obj, position):
return LwrTextInfo(obj, position, self)
class LwrTextInfo(textInfos.offsets.OffsetsTextInfo):
"""TextInfo used by L{LinesWordsResult}.
This should only be instantiated by L{LinesWordsResult}.
"""
def __init__(self, obj, position, result):
self.result = result
super(LwrTextInfo, self).__init__(obj, position)
def copy(self):
return self.__class__(self.obj, self.bookmark, self.result)
def _getTextRange(self, start, end):
return self.result.text[start:end]
def _getStoryLength(self):
return self.result.textLen
def _getLineOffsets(self, offset):
start = 0
for end in self.result.lines:
if end > offset:
return (start, end)
start = end
# offset is too big. Fail gracefully by returning the last line.
return (start, self.result.textLen)
def _getWordOffsets(self, offset):
start = 0
for word in self.result.words:
if word.offset > offset:
return (start, word.offset)
start = word.offset
# offset is in the last word (or offset is too big).
return (start, self.result.textLen)
def _getBoundingRectFromOffset(self, offset):
word = None
for nextWord in self.result.words:
if nextWord.offset > offset:
# Stop! We need the word before this.
break
word = nextWord
return RectLTWH(word.left, word.top, word.width, word.height)
class SimpleTextResult(RecognitionResult):
"""A L{RecognitionResult} which presents a simple text string.
This should only be used if the recognizer only returns text
and no coordinate information.
In this case, NVDA calculates words and lines itself based on the text;
e.g. a new line character breaks a line.
Routing the mouse, etc. cannot be supported because even though NVDA
has the coordinates for the entire block of content, it doesn't have
the coordinates for individual words or characters.
"""
def __init__(self, text):
self.text = text
def makeTextInfo(self, obj, position):
return SimpleResultTextInfo(obj, position, self)
class SimpleResultTextInfo(textInfos.offsets.OffsetsTextInfo):
"""TextInfo used by L{SimpleTextResult}.
This should only be instantiated by L{SimpleTextResult}.
"""
def __init__(self, obj, position, result):
self.result = result
super(SimpleResultTextInfo, self).__init__(obj, position)
def copy(self):
return self.__class__(self.obj, self.bookmark, self.result)
def _getStoryText(self):
return self.result.text
def _getStoryLength(self):
return len(self.result.text)
def _getStoryText(self):
return self.result.text