ScreenMagnifier 1.11.0.post8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of ScreenMagnifier might be problematic. Click here for more details.
- ScreenMagnifier/__init__.py +68 -0
- ScreenMagnifier/__main__.py +17 -0
- ScreenMagnifier/advancedoverlay.py +593 -0
- ScreenMagnifier/advancedpanel.py +521 -0
- ScreenMagnifier/analysiscontroller.py +533 -0
- ScreenMagnifier/analysisserver.py +404 -0
- ScreenMagnifier/colordetector/__init__.py +28 -0
- ScreenMagnifier/colordetector/colordetector.py +570 -0
- ScreenMagnifier/colordetector/core.py +434 -0
- ScreenMagnifier/colordetector/main.py +23 -0
- ScreenMagnifier/colordetector/mainwindow.py +182 -0
- ScreenMagnifier/colorpanel.py +424 -0
- ScreenMagnifier/colorswatches/__init__.py +16 -0
- ScreenMagnifier/colorswatches/colorswatches.py +316 -0
- ScreenMagnifier/colorswatches/main.py +23 -0
- ScreenMagnifier/colorswatches/mainwindow.py +60 -0
- ScreenMagnifier/controlpanel.py +234 -0
- ScreenMagnifier/detectionpanel.py +790 -0
- ScreenMagnifier/facedetector/__init__.py +24 -0
- ScreenMagnifier/facedetector/core.py +314 -0
- ScreenMagnifier/facedetector/facedetector.py +288 -0
- ScreenMagnifier/facedetector/main.py +23 -0
- ScreenMagnifier/facedetector/mainwindow.py +122 -0
- ScreenMagnifier/facedetector/models/__init__.py +4 -0
- ScreenMagnifier/facepointer.py +1121 -0
- ScreenMagnifier/features.py +50 -0
- ScreenMagnifier/hotkeys/__init__.py +16 -0
- ScreenMagnifier/hotkeys/hotkeys.py +379 -0
- ScreenMagnifier/hotkeys/main.py +23 -0
- ScreenMagnifier/hotkeys/mainwindow.py +56 -0
- ScreenMagnifier/imagefilters/__init__.py +24 -0
- ScreenMagnifier/imagefilters/core.py +172 -0
- ScreenMagnifier/imagefilters/imagefilters.py +220 -0
- ScreenMagnifier/imagefilters/main.py +23 -0
- ScreenMagnifier/imagefilters/mainwindow.py +120 -0
- ScreenMagnifier/magnifierview/__init__.py +16 -0
- ScreenMagnifier/magnifierview/magnifierview.py +1249 -0
- ScreenMagnifier/magnifierview/main.py +23 -0
- ScreenMagnifier/magnifierview/mainwindow.py +91 -0
- ScreenMagnifier/main.py +157 -0
- ScreenMagnifier/mainwindow.py +1368 -0
- ScreenMagnifier/mousecatcher/__init__.py +16 -0
- ScreenMagnifier/mousecatcher/main.py +23 -0
- ScreenMagnifier/mousecatcher/mainwindow.py +78 -0
- ScreenMagnifier/mousecatcher/mousecatcher.py +251 -0
- ScreenMagnifier/mousemove.py +259 -0
- ScreenMagnifier/netprotocol/__init__.py +25 -0
- ScreenMagnifier/netprotocol/main.py +23 -0
- ScreenMagnifier/netprotocol/mainwindow.py +91 -0
- ScreenMagnifier/netprotocol/netprotocol.py +372 -0
- ScreenMagnifier/netprotocol/wire.py +189 -0
- ScreenMagnifier/regionselector/__init__.py +16 -0
- ScreenMagnifier/regionselector/main.py +23 -0
- ScreenMagnifier/regionselector/mainwindow.py +70 -0
- ScreenMagnifier/regionselector/regionselector.py +549 -0
- ScreenMagnifier/remoteclient.py +636 -0
- ScreenMagnifier/resources/icon-128.png +0 -0
- ScreenMagnifier/resources/icon-16.png +0 -0
- ScreenMagnifier/resources/icon-24.png +0 -0
- ScreenMagnifier/resources/icon-256.png +0 -0
- ScreenMagnifier/resources/icon-32.png +0 -0
- ScreenMagnifier/resources/icon-48.png +0 -0
- ScreenMagnifier/resources/icon-512.png +0 -0
- ScreenMagnifier/resources/icon-64.png +0 -0
- ScreenMagnifier/resources/icon.icns +0 -0
- ScreenMagnifier/resources/icon.ico +0 -0
- ScreenMagnifier/screengrabber/__init__.py +16 -0
- ScreenMagnifier/screengrabber/main.py +23 -0
- ScreenMagnifier/screengrabber/mainwindow.py +79 -0
- ScreenMagnifier/screengrabber/screengrabber.py +558 -0
- ScreenMagnifier/server.py +150 -0
- ScreenMagnifier/serverpanel.py +379 -0
- ScreenMagnifier/shortcuteditor/__init__.py +16 -0
- ScreenMagnifier/shortcuteditor/main.py +23 -0
- ScreenMagnifier/shortcuteditor/mainwindow.py +54 -0
- ScreenMagnifier/shortcuteditor/shortcuteditor.py +411 -0
- ScreenMagnifier/shortcuts.py +118 -0
- ScreenMagnifier/shortcutspanel.py +140 -0
- ScreenMagnifier/support.py +127 -0
- ScreenMagnifier/translations/ar.json +387 -0
- ScreenMagnifier/translations/de.json +387 -0
- ScreenMagnifier/translations/es.json +387 -0
- ScreenMagnifier/translations/fr.json +387 -0
- ScreenMagnifier/translations/it.json +387 -0
- ScreenMagnifier/translations/ja.json +387 -0
- ScreenMagnifier/translations/ko.json +387 -0
- ScreenMagnifier/translations/pt_BR.json +387 -0
- ScreenMagnifier/translations/ru.json +387 -0
- ScreenMagnifier/translations/tr.json +387 -0
- ScreenMagnifier/translations/zh_CN.json +387 -0
- ScreenMagnifier/translator/__init__.py +16 -0
- ScreenMagnifier/translator/main.py +23 -0
- ScreenMagnifier/translator/mainwindow.py +62 -0
- ScreenMagnifier/translator/translator.py +284 -0
- ScreenMagnifier/upscaler/__init__.py +24 -0
- ScreenMagnifier/upscaler/core.py +315 -0
- ScreenMagnifier/upscaler/main.py +23 -0
- ScreenMagnifier/upscaler/mainwindow.py +128 -0
- ScreenMagnifier/upscaler/models/FSRCNN-small_x2.pb +0 -0
- ScreenMagnifier/upscaler/models/FSRCNN-small_x3.pb +0 -0
- ScreenMagnifier/upscaler/models/FSRCNN-small_x4.pb +0 -0
- ScreenMagnifier/upscaler/models/FSRCNN_x2.pb +0 -0
- ScreenMagnifier/upscaler/models/FSRCNN_x3.pb +0 -0
- ScreenMagnifier/upscaler/models/FSRCNN_x4.pb +0 -0
- ScreenMagnifier/upscaler/models/LICENSE-FSRCNN +201 -0
- ScreenMagnifier/upscaler/models/__init__.py +4 -0
- ScreenMagnifier/upscaler/upscaler.py +285 -0
- ScreenMagnifier/wincheck.py +65 -0
- ScreenMagnifier/zoomoverlay/__init__.py +16 -0
- ScreenMagnifier/zoomoverlay/main.py +23 -0
- ScreenMagnifier/zoomoverlay/mainwindow.py +99 -0
- ScreenMagnifier/zoomoverlay/zoomoverlay.py +1779 -0
- screenmagnifier-1.11.0.post8.dist-info/METADATA +591 -0
- screenmagnifier-1.11.0.post8.dist-info/RECORD +117 -0
- screenmagnifier-1.11.0.post8.dist-info/WHEEL +5 -0
- screenmagnifier-1.11.0.post8.dist-info/entry_points.txt +5 -0
- screenmagnifier-1.11.0.post8.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
AnalysisServer: real-time upscaling and analysis service for Screen Magnifier clients - pure Python (asyncio),
|
|
4
|
+
NumPy, OpenCV optional, NO Qt: it runs on a desktop or on a phone (Android: Termux, Pydroid).
|
|
5
|
+
Clients send the zoomed frames and receive the upscaled image and / or the analysis (colors, faces).
|
|
6
|
+
Messages (wire.py framing, JSON header + binary payload):
|
|
7
|
+
client -> server -> client
|
|
8
|
+
hello {token, client, version} welcome {version, server, methods, colors, faces, formats}
|
|
9
|
+
upscale {id, channel, width, height, method, sharpness, upscaled {id, channel, timeMs, method, format} + image
|
|
10
|
+
format, quality} + image
|
|
11
|
+
analyze {id, source, colors {...}, faces {...}} + image analysis {id, source, result, hasMask} + mask
|
|
12
|
+
ping {t} pong {t}
|
|
13
|
+
(any error) error {id, code, message}
|
|
14
|
+
'formats' lists the image formats this server decodes: RAWZ always (lossless, zlib only), PNG / JPG with OpenCV
|
|
15
|
+
or Pillow - clients upload RAWZ when JPG is not listed. A token (shared secret) can be required; unauthenticated
|
|
16
|
+
peers may only send 'hello'. Upscaling and analysis run on two worker threads: the network loop stays responsive.
|
|
17
|
+
"""
|
|
18
|
+
from asyncio import get_event_loop, ensure_future, new_event_loop, set_event_loop, start_server
|
|
19
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
20
|
+
from threading import Thread, Event
|
|
21
|
+
from hmac import compare_digest
|
|
22
|
+
from socket import gethostname
|
|
23
|
+
from os.path import dirname
|
|
24
|
+
from time import time
|
|
25
|
+
from sys import path
|
|
26
|
+
|
|
27
|
+
if not __package__ and dirname(__file__) not in path:
|
|
28
|
+
path.append(dirname(__file__))
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
from .netprotocol.wire import packMessage, MessageParser, encodeArray, decodeArray, availableFormats, DEFAULT_PORT
|
|
32
|
+
from .facedetector.core import FaceEngine, userDataDir
|
|
33
|
+
from .colordetector.core import ColorAnalyzer, np
|
|
34
|
+
from .upscaler.core import UpscaleEngine
|
|
35
|
+
except:
|
|
36
|
+
from netprotocol.wire import packMessage, MessageParser, encodeArray, decodeArray, availableFormats, DEFAULT_PORT
|
|
37
|
+
from facedetector.core import FaceEngine, userDataDir
|
|
38
|
+
from colordetector.core import ColorAnalyzer, np
|
|
39
|
+
from upscaler.core import UpscaleEngine
|
|
40
|
+
|
|
41
|
+
PROTOCOL_VERSION = 1 # type: int
|
|
42
|
+
MAX_TARGET_SIDE = 4096 # type: int # Largest upscaled image a client may request.
|
|
43
|
+
MAX_PENDING = 8 # type: int # Analyses queued per client before 'busy' errors.
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _Client(object):
|
|
47
|
+
"""
|
|
48
|
+
_Client class: one connection.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, writer, peer):
|
|
52
|
+
"""
|
|
53
|
+
:param writer: StreamWriter
|
|
54
|
+
:param peer: str | unicode | QString
|
|
55
|
+
"""
|
|
56
|
+
self.writer = writer
|
|
57
|
+
self.peer = peer # type: str
|
|
58
|
+
self.authed = False # type: bool
|
|
59
|
+
self.pending = 0 # type: int
|
|
60
|
+
self.open = True # type: bool
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AnalysisServer(object):
|
|
64
|
+
"""
|
|
65
|
+
AnalysisServer class.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, *args, **kwargs):
|
|
69
|
+
"""
|
|
70
|
+
:param host: (str | unicode | QString)
|
|
71
|
+
Interface to listen on ('127.0.0.1' = this computer only, '0.0.0.0' = the network).
|
|
72
|
+
:param port: (int) TCP port, 0 = any free port (see getPort()).
|
|
73
|
+
:param token: (str | unicode | QString) Shared secret clients must send in 'hello' ('' = none).
|
|
74
|
+
:param maxClients: (int) Simultaneous connections.
|
|
75
|
+
:param logMessage: (callable | None) f(text) for the server log.
|
|
76
|
+
:param args: any
|
|
77
|
+
:param kwargs: any
|
|
78
|
+
"""
|
|
79
|
+
self.__m_host = u'{}'.format(kwargs.pop('host', '127.0.0.1')) # type: str
|
|
80
|
+
self.__m_port = int(kwargs.pop('port', DEFAULT_PORT)) # type: int
|
|
81
|
+
self.__m_token = u'{}'.format(kwargs.pop('token', '') or '') # type: str
|
|
82
|
+
self.__m_maxClients = max(1, int(kwargs.pop('maxClients', 8))) # type: int
|
|
83
|
+
self.__m_logMessage = kwargs.pop('logMessage', None)
|
|
84
|
+
super(AnalysisServer, self).__init__(*args, **kwargs)
|
|
85
|
+
self.__m_upscaler = UpscaleEngine(onError=self._log) # type: UpscaleEngine
|
|
86
|
+
self.__m_colors = ColorAnalyzer() # type: ColorAnalyzer
|
|
87
|
+
self.__m_faces = FaceEngine(dataDir=userDataDir(), onError=self._log) # type: FaceEngine
|
|
88
|
+
self.__m_upscalePool = ThreadPoolExecutor(max_workers=1) # type: ThreadPoolExecutor
|
|
89
|
+
self.__m_analysisPool = ThreadPoolExecutor(max_workers=1) # type: ThreadPoolExecutor
|
|
90
|
+
self.__m_clients = set() # type: set
|
|
91
|
+
self.__m_stats = {'upscaled': 0, 'analyzed': 0, 'upscaleMs': 0.0, 'analyzeMs': 0.0} # type: dict
|
|
92
|
+
self.__m_loop = None
|
|
93
|
+
self.__m_server = None
|
|
94
|
+
self.__m_thread = None # type: Thread | None
|
|
95
|
+
self.__m_ready = Event() # type: Event
|
|
96
|
+
self.__m_error = None # type: Exception | None
|
|
97
|
+
|
|
98
|
+
# ---------- Helpers ----------
|
|
99
|
+
def _log(self, text):
|
|
100
|
+
"""
|
|
101
|
+
:param text: str | unicode | QString
|
|
102
|
+
:return:
|
|
103
|
+
"""
|
|
104
|
+
if callable(self.__m_logMessage):
|
|
105
|
+
self.__m_logMessage(u'{}'.format(text))
|
|
106
|
+
|
|
107
|
+
def _send(self, client, header, payload=b''):
|
|
108
|
+
"""
|
|
109
|
+
Send from the event-loop thread.
|
|
110
|
+
:param client: _Client
|
|
111
|
+
:param header: dict
|
|
112
|
+
:param payload: bytes
|
|
113
|
+
:return:
|
|
114
|
+
"""
|
|
115
|
+
if client.open:
|
|
116
|
+
try:
|
|
117
|
+
client.writer.write(packMessage(header, payload))
|
|
118
|
+
except Exception as e:
|
|
119
|
+
self._log('Send to {} failed: {}'.format(client.peer, e))
|
|
120
|
+
client.open = False
|
|
121
|
+
|
|
122
|
+
def _error(self, client, header, code, message):
|
|
123
|
+
"""
|
|
124
|
+
:param client: _Client
|
|
125
|
+
:param header: dict
|
|
126
|
+
:param code: str | unicode | QString
|
|
127
|
+
:param message: str | Exception
|
|
128
|
+
:return:
|
|
129
|
+
"""
|
|
130
|
+
self._send(client, {'type': 'error', 'id': header.get('id'), 'code': code, 'message': u'{}'.format(message)})
|
|
131
|
+
|
|
132
|
+
def _capabilities(self):
|
|
133
|
+
"""
|
|
134
|
+
:return: dict
|
|
135
|
+
"""
|
|
136
|
+
return {'type': 'welcome', 'version': PROTOCOL_VERSION, 'server': gethostname(),
|
|
137
|
+
'methods': [[int(m), n] for m, n in self.__m_upscaler.availableMethods()],
|
|
138
|
+
'colors': bool(np), 'formats': availableFormats(),
|
|
139
|
+
'faces': {'available': FaceEngine.isAvailable(), 'yunet': self.__m_faces.isModelReady()}}
|
|
140
|
+
|
|
141
|
+
def _decode(self, payload):
|
|
142
|
+
"""
|
|
143
|
+
:param payload: bytes
|
|
144
|
+
:return: numpy.ndarray
|
|
145
|
+
:raise ValueError: undecodable image (e.g. JPEG without OpenCV / Pillow).
|
|
146
|
+
"""
|
|
147
|
+
arr = decodeArray(payload)
|
|
148
|
+
if arr is None or arr.ndim != 3:
|
|
149
|
+
raise ValueError(u'Cannot decode the image here (supported: {}); send RAWZ'.format(
|
|
150
|
+
', '.join(availableFormats())))
|
|
151
|
+
return arr
|
|
152
|
+
|
|
153
|
+
def _upscale(self, header, payload):
|
|
154
|
+
"""
|
|
155
|
+
Worker thread.
|
|
156
|
+
:param header: dict
|
|
157
|
+
:param payload: bytes
|
|
158
|
+
:return: (tuple[dict, bytes]) Reply header and image.
|
|
159
|
+
"""
|
|
160
|
+
arr = self._decode(payload)
|
|
161
|
+
w = int(min(MAX_TARGET_SIDE, max(1, int(header.get('width', arr.shape[1]))))) # type: int
|
|
162
|
+
h = int(min(MAX_TARGET_SIDE, max(1, int(header.get('height', arr.shape[0]))))) # type: int
|
|
163
|
+
method = self.__m_upscaler.resolve(int(header.get('method', 1))) # type: int
|
|
164
|
+
started = time() # type: float
|
|
165
|
+
out = self.__m_upscaler.upscale(arr, w, h, method, float(header.get('sharpness', 0.0)))
|
|
166
|
+
fmt = 'PNG' if u'{}'.format(header.get('format', 'JPG')).upper() == 'PNG' else 'JPG' # type: str
|
|
167
|
+
data, used = encodeArray(out, fmt, int(header.get('quality', 90)))
|
|
168
|
+
ms = (time() - started) * 1000.0 # type: float
|
|
169
|
+
self.__m_stats['upscaled'] += 1
|
|
170
|
+
self.__m_stats['upscaleMs'] = ms
|
|
171
|
+
return {'type': 'upscaled', 'id': header.get('id'), 'channel': header.get('channel', ''),
|
|
172
|
+
'timeMs': round(ms, 2), 'method': int(method), 'format': used}, data
|
|
173
|
+
|
|
174
|
+
def _analyze(self, header, payload):
|
|
175
|
+
"""
|
|
176
|
+
Worker thread.
|
|
177
|
+
:param header: dict
|
|
178
|
+
:param payload: bytes
|
|
179
|
+
:return: (tuple[dict, bytes]) Reply header and label mask (PNG when available, else RAWG).
|
|
180
|
+
"""
|
|
181
|
+
arr = self._decode(payload)
|
|
182
|
+
started = time() # type: float
|
|
183
|
+
result, mask = {}, b'' # type: dict, bytes
|
|
184
|
+
colors = header.get('colors') or {} # type: dict
|
|
185
|
+
if colors.get('enabled'):
|
|
186
|
+
options = {'targets': [u'{}'.format(c) for c in colors.get('targets', [])][:64]} # type: dict
|
|
187
|
+
for key, option in (('tolerance', 'tolerance'), ('minArea', 'minArea'), ('palette', 'paletteSize'),
|
|
188
|
+
('mask', 'returnMask'), ('matchMode', 'matchMode'), ('groupDistance', 'groupDistance')):
|
|
189
|
+
if key in colors:
|
|
190
|
+
options[option] = colors[key]
|
|
191
|
+
self.__m_colors.configure(**options)
|
|
192
|
+
res = self.__m_colors.analyze(arr) # type: dict
|
|
193
|
+
label = res.pop('labelMask', None)
|
|
194
|
+
if label is not None:
|
|
195
|
+
mask = encodeArray(label, 'PNG')[0] # type: bytes # RAWG without a PNG codec
|
|
196
|
+
result['colors'] = res
|
|
197
|
+
faces = header.get('faces') or {} # type: dict
|
|
198
|
+
if faces.get('enabled'):
|
|
199
|
+
fe = self.__m_faces # type: FaceEngine
|
|
200
|
+
fe.backend = u'{}'.format(faces.get('backend', 'auto')) # type str
|
|
201
|
+
fe.scoreThreshold = min(0.99, max(0.1, float(faces.get('score', fe.scoreThreshold)))) # type float
|
|
202
|
+
fe.minFaceSize = max(8, int(faces.get('minSize', fe.minFaceSize))) # type int
|
|
203
|
+
result['faces'] = fe.detect(arr)
|
|
204
|
+
ms = (time() - started) * 1000.0 # type: float
|
|
205
|
+
self.__m_stats['analyzed'] += 1
|
|
206
|
+
self.__m_stats['analyzeMs'] = ms
|
|
207
|
+
return ({'type': 'analysis', 'id': header.get('id'), 'source': header.get('source', ''), 'result': result,
|
|
208
|
+
'origin': header.get('origin'), 'hasMask': bool(mask), 'timeMs': round(ms, 2)}, mask)
|
|
209
|
+
|
|
210
|
+
async def _work(self, client, pool, job, header, payload, analysis=False):
|
|
211
|
+
"""
|
|
212
|
+
Run a job on its worker thread and send the reply (dropped if the client has left meanwhile).
|
|
213
|
+
:param client: _Client
|
|
214
|
+
:param pool: ThreadPoolExecutor
|
|
215
|
+
:param job: callable
|
|
216
|
+
:param header: dict
|
|
217
|
+
:param payload: bytes
|
|
218
|
+
:param analysis: bool
|
|
219
|
+
:return:
|
|
220
|
+
"""
|
|
221
|
+
try:
|
|
222
|
+
reply, data = await get_event_loop().run_in_executor(pool, job, header, payload)
|
|
223
|
+
self._send(client, reply, data)
|
|
224
|
+
except Exception as e:
|
|
225
|
+
self._error(client, header, 'failed', e)
|
|
226
|
+
finally:
|
|
227
|
+
if analysis:
|
|
228
|
+
client.pending -= 1
|
|
229
|
+
|
|
230
|
+
async def _dispatch(self, client, header, payload):
|
|
231
|
+
"""
|
|
232
|
+
:param client: _Client
|
|
233
|
+
:param header: dict
|
|
234
|
+
:param payload: bytes
|
|
235
|
+
:return: (bool) Keep the connection.
|
|
236
|
+
"""
|
|
237
|
+
kind = u'{}'.format(header.get('type', '')) # type: str
|
|
238
|
+
if kind == 'hello':
|
|
239
|
+
if self.__m_token and not compare_digest(u'{}'.format(header.get('token', '')).encode('utf-8'),
|
|
240
|
+
self.__m_token.encode('utf-8')):
|
|
241
|
+
self._log(u'Rejected {}: wrong token'.format(client.peer))
|
|
242
|
+
self._error(client, header, 'auth', u'Wrong or missing token')
|
|
243
|
+
return False
|
|
244
|
+
client.authed = True
|
|
245
|
+
self._send(client, self._capabilities())
|
|
246
|
+
return True
|
|
247
|
+
if not client.authed:
|
|
248
|
+
self._error(client, header, 'auth', u'Send hello first')
|
|
249
|
+
return False
|
|
250
|
+
if kind == 'ping':
|
|
251
|
+
self._send(client, {'type': 'pong', 't': header.get('t')})
|
|
252
|
+
elif kind == 'upscale':
|
|
253
|
+
ensure_future(self._work(client, self.__m_upscalePool, self._upscale, header, payload))
|
|
254
|
+
elif kind == 'analyze':
|
|
255
|
+
if client.pending >= MAX_PENDING:
|
|
256
|
+
self._error(client, header, 'busy', u'Too many pending analyses')
|
|
257
|
+
else:
|
|
258
|
+
client.pending += 1
|
|
259
|
+
ensure_future(self._work(client, self.__m_analysisPool, self._analyze, header, payload, True))
|
|
260
|
+
else:
|
|
261
|
+
self._error(client, header, 'unknown', u'Unknown message type {!r}'.format(kind))
|
|
262
|
+
return True
|
|
263
|
+
|
|
264
|
+
async def _serve(self, reader, writer):
|
|
265
|
+
"""
|
|
266
|
+
:param reader: StreamReader
|
|
267
|
+
:param writer: StreamWriter
|
|
268
|
+
:return:
|
|
269
|
+
"""
|
|
270
|
+
address = writer.get_extra_info('peername')
|
|
271
|
+
client = _Client(writer, '{}:{}'.format(*address[:2]) if address else '?') # type: _Client
|
|
272
|
+
if len(self.__m_clients) >= self.__m_maxClients:
|
|
273
|
+
self._error(client, {}, 'busy', u'Too many clients')
|
|
274
|
+
writer.close()
|
|
275
|
+
return
|
|
276
|
+
self.__m_clients.add(client)
|
|
277
|
+
self._log('Client {} connected ({} connected)'.format(client.peer, len(self.__m_clients)))
|
|
278
|
+
parser = MessageParser() # type: MessageParser
|
|
279
|
+
try:
|
|
280
|
+
while client.open:
|
|
281
|
+
data = await reader.read(1 << 16)
|
|
282
|
+
if not data:
|
|
283
|
+
break
|
|
284
|
+
try:
|
|
285
|
+
messages = parser.feed(data) # type: list
|
|
286
|
+
except ValueError as e:
|
|
287
|
+
self._log(u'Closing {}: {}'.format(client.peer, e))
|
|
288
|
+
break
|
|
289
|
+
for header, payload in messages:
|
|
290
|
+
if not await self._dispatch(client, header, payload):
|
|
291
|
+
client.open = False
|
|
292
|
+
break
|
|
293
|
+
await writer.drain()
|
|
294
|
+
except (ConnectionError, OSError):
|
|
295
|
+
pass
|
|
296
|
+
finally:
|
|
297
|
+
client.open = False
|
|
298
|
+
self.__m_clients.discard(client)
|
|
299
|
+
try:
|
|
300
|
+
writer.close()
|
|
301
|
+
except:
|
|
302
|
+
pass
|
|
303
|
+
self._log(u'Client {} left ({} connected)'.format(client.peer, len(self.__m_clients)))
|
|
304
|
+
|
|
305
|
+
def _run(self):
|
|
306
|
+
"""
|
|
307
|
+
Server thread: its own event loop.
|
|
308
|
+
:return: None
|
|
309
|
+
"""
|
|
310
|
+
loop = new_event_loop()
|
|
311
|
+
set_event_loop(loop)
|
|
312
|
+
self.__m_loop = loop
|
|
313
|
+
try:
|
|
314
|
+
self.__m_server = loop.run_until_complete(start_server(self._serve, self.__m_host, self.__m_port))
|
|
315
|
+
self.__m_port = int(self.__m_server.sockets[0].getsockname()[1]) # type: int
|
|
316
|
+
except Exception as e:
|
|
317
|
+
self.__m_error = e
|
|
318
|
+
self.__m_ready.set()
|
|
319
|
+
return
|
|
320
|
+
self.__m_ready.set()
|
|
321
|
+
try:
|
|
322
|
+
loop.run_forever()
|
|
323
|
+
finally:
|
|
324
|
+
self.__m_server.close()
|
|
325
|
+
loop.run_until_complete(self.__m_server.wait_closed())
|
|
326
|
+
loop.close()
|
|
327
|
+
|
|
328
|
+
# ---------- Public API ----------
|
|
329
|
+
def start(self):
|
|
330
|
+
"""
|
|
331
|
+
Listen in a background thread.
|
|
332
|
+
:return: None
|
|
333
|
+
:raise OSError: the address cannot be used (e.g. port taken).
|
|
334
|
+
"""
|
|
335
|
+
if self.isRunning():
|
|
336
|
+
return
|
|
337
|
+
self.__m_ready.clear()
|
|
338
|
+
self.__m_error = None
|
|
339
|
+
self.__m_thread = Thread(target=self._run, name='AnalysisServer')
|
|
340
|
+
self.__m_thread.daemon = True
|
|
341
|
+
self.__m_thread.start()
|
|
342
|
+
self.__m_ready.wait(10.0)
|
|
343
|
+
if self.__m_error is not None:
|
|
344
|
+
error, self.__m_error = self.__m_error, None
|
|
345
|
+
raise error
|
|
346
|
+
|
|
347
|
+
def stop(self):
|
|
348
|
+
"""
|
|
349
|
+
:return:
|
|
350
|
+
"""
|
|
351
|
+
if self.__m_loop is not None and self.__m_thread is not None:
|
|
352
|
+
self.__m_loop.call_soon_threadsafe(self.__m_loop.stop)
|
|
353
|
+
self.__m_thread.join(5.0)
|
|
354
|
+
self.__m_thread, self.__m_loop = None, None
|
|
355
|
+
|
|
356
|
+
def serveForever(self):
|
|
357
|
+
"""
|
|
358
|
+
Start and block until stop() or Ctrl+C.
|
|
359
|
+
:return:
|
|
360
|
+
"""
|
|
361
|
+
self.start()
|
|
362
|
+
try:
|
|
363
|
+
while self.isRunning():
|
|
364
|
+
self.__m_thread.join(0.5)
|
|
365
|
+
except KeyboardInterrupt:
|
|
366
|
+
pass
|
|
367
|
+
finally:
|
|
368
|
+
self.stop()
|
|
369
|
+
|
|
370
|
+
def isRunning(self):
|
|
371
|
+
"""
|
|
372
|
+
:return: bool
|
|
373
|
+
"""
|
|
374
|
+
return self.__m_thread is not None and self.__m_thread.is_alive()
|
|
375
|
+
|
|
376
|
+
def getPort(self):
|
|
377
|
+
"""
|
|
378
|
+
:return: int
|
|
379
|
+
"""
|
|
380
|
+
return self.__m_port
|
|
381
|
+
|
|
382
|
+
def getClientCount(self):
|
|
383
|
+
"""
|
|
384
|
+
:return: int
|
|
385
|
+
"""
|
|
386
|
+
return len(self.__m_clients)
|
|
387
|
+
|
|
388
|
+
def getStats(self):
|
|
389
|
+
"""
|
|
390
|
+
:return: dict
|
|
391
|
+
"""
|
|
392
|
+
return dict(self.__m_stats)
|
|
393
|
+
|
|
394
|
+
def getFaceEngine(self):
|
|
395
|
+
"""
|
|
396
|
+
:return: FaceEngine
|
|
397
|
+
"""
|
|
398
|
+
return self.__m_faces
|
|
399
|
+
|
|
400
|
+
def getUpscaleEngine(self):
|
|
401
|
+
"""
|
|
402
|
+
:return: UpscaleEngine
|
|
403
|
+
"""
|
|
404
|
+
return self.__m_upscaler
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
"""
|
|
3
|
+
colordetector package: the Qt-free part (core.py) is always available - the headless server uses it, also where Qt is
|
|
4
|
+
not installed (e.g. Android); the Qt classes are available when a Qt binding is installed (None otherwise).
|
|
5
|
+
"""
|
|
6
|
+
from os.path import dirname
|
|
7
|
+
from sys import path
|
|
8
|
+
|
|
9
|
+
if not __package__ and dirname(__file__) not in path:
|
|
10
|
+
path.append(dirname(__file__))
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from .core import ColorAnalyzer, CSS_COLORS
|
|
14
|
+
except:
|
|
15
|
+
from core import ColorAnalyzer, CSS_COLORS
|
|
16
|
+
try:
|
|
17
|
+
from .colordetector import ColorDetector, colorInfo, nearestColorName, contrastRatio, wcagRating, maskToOverlay, \
|
|
18
|
+
complementary, formatColor, sampleColor, refinePick, COLOR_FORMATS
|
|
19
|
+
except:
|
|
20
|
+
try:
|
|
21
|
+
from colordetector import ColorDetector, colorInfo, nearestColorName, contrastRatio, wcagRating, \
|
|
22
|
+
maskToOverlay, complementary, formatColor, sampleColor, refinePick, COLOR_FORMATS
|
|
23
|
+
except: # No Qt binding: the Qt-free part only.
|
|
24
|
+
ColorDetector = colorInfo = nearestColorName = contrastRatio = wcagRating = maskToOverlay = complementary = formatColor = sampleColor = refinePick = COLOR_FORMATS = None
|
|
25
|
+
|
|
26
|
+
__all__ = ['ColorAnalyzer', 'CSS_COLORS', 'ColorDetector', 'colorInfo', 'nearestColorName', 'contrastRatio',
|
|
27
|
+
'wcagRating', 'maskToOverlay', 'complementary', 'formatColor', 'sampleColor', 'refinePick',
|
|
28
|
+
'COLOR_FORMATS'] # type: list[str]
|