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.

Files changed (117) hide show
  1. ScreenMagnifier/__init__.py +68 -0
  2. ScreenMagnifier/__main__.py +17 -0
  3. ScreenMagnifier/advancedoverlay.py +593 -0
  4. ScreenMagnifier/advancedpanel.py +521 -0
  5. ScreenMagnifier/analysiscontroller.py +533 -0
  6. ScreenMagnifier/analysisserver.py +404 -0
  7. ScreenMagnifier/colordetector/__init__.py +28 -0
  8. ScreenMagnifier/colordetector/colordetector.py +570 -0
  9. ScreenMagnifier/colordetector/core.py +434 -0
  10. ScreenMagnifier/colordetector/main.py +23 -0
  11. ScreenMagnifier/colordetector/mainwindow.py +182 -0
  12. ScreenMagnifier/colorpanel.py +424 -0
  13. ScreenMagnifier/colorswatches/__init__.py +16 -0
  14. ScreenMagnifier/colorswatches/colorswatches.py +316 -0
  15. ScreenMagnifier/colorswatches/main.py +23 -0
  16. ScreenMagnifier/colorswatches/mainwindow.py +60 -0
  17. ScreenMagnifier/controlpanel.py +234 -0
  18. ScreenMagnifier/detectionpanel.py +790 -0
  19. ScreenMagnifier/facedetector/__init__.py +24 -0
  20. ScreenMagnifier/facedetector/core.py +314 -0
  21. ScreenMagnifier/facedetector/facedetector.py +288 -0
  22. ScreenMagnifier/facedetector/main.py +23 -0
  23. ScreenMagnifier/facedetector/mainwindow.py +122 -0
  24. ScreenMagnifier/facedetector/models/__init__.py +4 -0
  25. ScreenMagnifier/facepointer.py +1121 -0
  26. ScreenMagnifier/features.py +50 -0
  27. ScreenMagnifier/hotkeys/__init__.py +16 -0
  28. ScreenMagnifier/hotkeys/hotkeys.py +379 -0
  29. ScreenMagnifier/hotkeys/main.py +23 -0
  30. ScreenMagnifier/hotkeys/mainwindow.py +56 -0
  31. ScreenMagnifier/imagefilters/__init__.py +24 -0
  32. ScreenMagnifier/imagefilters/core.py +172 -0
  33. ScreenMagnifier/imagefilters/imagefilters.py +220 -0
  34. ScreenMagnifier/imagefilters/main.py +23 -0
  35. ScreenMagnifier/imagefilters/mainwindow.py +120 -0
  36. ScreenMagnifier/magnifierview/__init__.py +16 -0
  37. ScreenMagnifier/magnifierview/magnifierview.py +1249 -0
  38. ScreenMagnifier/magnifierview/main.py +23 -0
  39. ScreenMagnifier/magnifierview/mainwindow.py +91 -0
  40. ScreenMagnifier/main.py +157 -0
  41. ScreenMagnifier/mainwindow.py +1368 -0
  42. ScreenMagnifier/mousecatcher/__init__.py +16 -0
  43. ScreenMagnifier/mousecatcher/main.py +23 -0
  44. ScreenMagnifier/mousecatcher/mainwindow.py +78 -0
  45. ScreenMagnifier/mousecatcher/mousecatcher.py +251 -0
  46. ScreenMagnifier/mousemove.py +259 -0
  47. ScreenMagnifier/netprotocol/__init__.py +25 -0
  48. ScreenMagnifier/netprotocol/main.py +23 -0
  49. ScreenMagnifier/netprotocol/mainwindow.py +91 -0
  50. ScreenMagnifier/netprotocol/netprotocol.py +372 -0
  51. ScreenMagnifier/netprotocol/wire.py +189 -0
  52. ScreenMagnifier/regionselector/__init__.py +16 -0
  53. ScreenMagnifier/regionselector/main.py +23 -0
  54. ScreenMagnifier/regionselector/mainwindow.py +70 -0
  55. ScreenMagnifier/regionselector/regionselector.py +549 -0
  56. ScreenMagnifier/remoteclient.py +636 -0
  57. ScreenMagnifier/resources/icon-128.png +0 -0
  58. ScreenMagnifier/resources/icon-16.png +0 -0
  59. ScreenMagnifier/resources/icon-24.png +0 -0
  60. ScreenMagnifier/resources/icon-256.png +0 -0
  61. ScreenMagnifier/resources/icon-32.png +0 -0
  62. ScreenMagnifier/resources/icon-48.png +0 -0
  63. ScreenMagnifier/resources/icon-512.png +0 -0
  64. ScreenMagnifier/resources/icon-64.png +0 -0
  65. ScreenMagnifier/resources/icon.icns +0 -0
  66. ScreenMagnifier/resources/icon.ico +0 -0
  67. ScreenMagnifier/screengrabber/__init__.py +16 -0
  68. ScreenMagnifier/screengrabber/main.py +23 -0
  69. ScreenMagnifier/screengrabber/mainwindow.py +79 -0
  70. ScreenMagnifier/screengrabber/screengrabber.py +558 -0
  71. ScreenMagnifier/server.py +150 -0
  72. ScreenMagnifier/serverpanel.py +379 -0
  73. ScreenMagnifier/shortcuteditor/__init__.py +16 -0
  74. ScreenMagnifier/shortcuteditor/main.py +23 -0
  75. ScreenMagnifier/shortcuteditor/mainwindow.py +54 -0
  76. ScreenMagnifier/shortcuteditor/shortcuteditor.py +411 -0
  77. ScreenMagnifier/shortcuts.py +118 -0
  78. ScreenMagnifier/shortcutspanel.py +140 -0
  79. ScreenMagnifier/support.py +127 -0
  80. ScreenMagnifier/translations/ar.json +387 -0
  81. ScreenMagnifier/translations/de.json +387 -0
  82. ScreenMagnifier/translations/es.json +387 -0
  83. ScreenMagnifier/translations/fr.json +387 -0
  84. ScreenMagnifier/translations/it.json +387 -0
  85. ScreenMagnifier/translations/ja.json +387 -0
  86. ScreenMagnifier/translations/ko.json +387 -0
  87. ScreenMagnifier/translations/pt_BR.json +387 -0
  88. ScreenMagnifier/translations/ru.json +387 -0
  89. ScreenMagnifier/translations/tr.json +387 -0
  90. ScreenMagnifier/translations/zh_CN.json +387 -0
  91. ScreenMagnifier/translator/__init__.py +16 -0
  92. ScreenMagnifier/translator/main.py +23 -0
  93. ScreenMagnifier/translator/mainwindow.py +62 -0
  94. ScreenMagnifier/translator/translator.py +284 -0
  95. ScreenMagnifier/upscaler/__init__.py +24 -0
  96. ScreenMagnifier/upscaler/core.py +315 -0
  97. ScreenMagnifier/upscaler/main.py +23 -0
  98. ScreenMagnifier/upscaler/mainwindow.py +128 -0
  99. ScreenMagnifier/upscaler/models/FSRCNN-small_x2.pb +0 -0
  100. ScreenMagnifier/upscaler/models/FSRCNN-small_x3.pb +0 -0
  101. ScreenMagnifier/upscaler/models/FSRCNN-small_x4.pb +0 -0
  102. ScreenMagnifier/upscaler/models/FSRCNN_x2.pb +0 -0
  103. ScreenMagnifier/upscaler/models/FSRCNN_x3.pb +0 -0
  104. ScreenMagnifier/upscaler/models/FSRCNN_x4.pb +0 -0
  105. ScreenMagnifier/upscaler/models/LICENSE-FSRCNN +201 -0
  106. ScreenMagnifier/upscaler/models/__init__.py +4 -0
  107. ScreenMagnifier/upscaler/upscaler.py +285 -0
  108. ScreenMagnifier/wincheck.py +65 -0
  109. ScreenMagnifier/zoomoverlay/__init__.py +16 -0
  110. ScreenMagnifier/zoomoverlay/main.py +23 -0
  111. ScreenMagnifier/zoomoverlay/mainwindow.py +99 -0
  112. ScreenMagnifier/zoomoverlay/zoomoverlay.py +1779 -0
  113. screenmagnifier-1.11.0.post8.dist-info/METADATA +591 -0
  114. screenmagnifier-1.11.0.post8.dist-info/RECORD +117 -0
  115. screenmagnifier-1.11.0.post8.dist-info/WHEEL +5 -0
  116. screenmagnifier-1.11.0.post8.dist-info/entry_points.txt +5 -0
  117. screenmagnifier-1.11.0.post8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,284 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ CatalogTranslator, LanguageManager: application languages from JSON catalogs.
4
+ - Works with every Qt binding and needs no Qt tool (no lupdate / lrelease): a QTranslator subclass answers the
5
+ application's tr() calls from a dictionary, so the existing self.tr(u'...') calls are translated unchanged.
6
+ - Catalog <folder>/<code>.json: {"language": "fr", "name": "Fran\u00e7ais", "direction": "ltr" | "rtl",
7
+ "strings": {"English source text": "translation", ...}}. Empty or missing translations fall back to English.
8
+ - Lookup by source text: PyQt and PySide compute different tr() contexts for subclasses; the text is the same.
9
+ - LanguageManager: available languages, 'auto' (system language), installs the catalog and Qt's own translations
10
+ (qtbase_<code>.qm: standard dialogs), sets the layout direction (right-to-left for Arabic) and the default locale.
11
+ """
12
+ from ManyQt.QtCore import QObject, QTranslator, QLocale, QLibraryInfo, Qt, pyqtSignal, pyqtSlot, pyqtProperty
13
+ from ManyQt.QtWidgets import QApplication
14
+ from os.path import isdir, isfile, join, splitext
15
+ from os import listdir
16
+ from io import open as iopen
17
+ import json
18
+
19
+ LANGUAGES = { # code -> (English name, native name, right-to-left)
20
+ 'en': ('English', 'English', False),
21
+ 'fr': ('French', 'Fran\u00e7ais', False),
22
+ 'ar': ('Arabic', '\u0627\u0644\u0639\u0631\u0628\u064a\u0629', True),
23
+ 'es': ('Spanish', 'Espa\u00f1ol', False),
24
+ 'de': ('German', 'Deutsch', False),
25
+ 'it': ('Italian', 'Italiano', False),
26
+ 'pt_BR': ('Portuguese (Brazil)', 'Portugu\u00eas (Brasil)', False),
27
+ 'ru': ('Russian', '\u0420\u0443\u0441\u0441\u043a\u0438\u0439', False),
28
+ 'tr': ('Turkish', 'T\u00fcrk\u00e7e', False),
29
+ 'ja': ('Japanese', '\u65e5\u672c\u8a9e', False),
30
+ 'ko': ('Korean', '\ud55c\uad6d\uc5b4', False),
31
+ 'zh_CN': ('Chinese (Simplified)', '\u7b80\u4f53\u4e2d\u6587', False),
32
+ } # type: dict
33
+ ALIASES = {'jp': 'ja', 'cn': 'zh_CN', 'zh': 'zh_CN', 'pt': 'pt_BR', 'br': 'pt_BR', 'kr': 'ko'} # type: dict # common names
34
+
35
+
36
+ def loadCatalog(path):
37
+ """
38
+ :param path: (str | unicode | QString) JSON catalog.
39
+ :return: (dict) {'language', 'name', 'direction', 'strings'} - strings without empty translations.
40
+ """
41
+ with iopen(path, encoding='utf-8') as f:
42
+ data = json.load(f)
43
+ data['strings'] = {k: v for k, v in (data.get('strings') or {}).items() if hasattr(v, 'encode') and v}
44
+ return data
45
+
46
+
47
+ def qtTranslationsPath():
48
+ """
49
+ :return: (str | unicode | QString) Folder of Qt's own .qm translations ('' if unknown).
50
+ """
51
+ try:
52
+ if hasattr(QLibraryInfo, 'path'): # Qt 6
53
+ return u'{}'.format(QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath))
54
+ return u'{}'.format(QLibraryInfo.location(QLibraryInfo.TranslationsPath)) # Qt 5
55
+ except Exception:
56
+ return ''
57
+
58
+
59
+ class CatalogTranslator(QTranslator):
60
+ """
61
+ CatalogTranslator class: a QTranslator answering from a {source: translation} dictionary.
62
+ """
63
+
64
+ def __init__(self, *args, **kwargs):
65
+ """
66
+ :param strings: (dict) {English source: translation}.
67
+ :param args: any
68
+ :param kwargs: any
69
+ """
70
+ strings = kwargs.pop('strings', {}) # type: dict
71
+ super(CatalogTranslator, self).__init__(*args, **kwargs)
72
+ self.__m_strings = dict(strings or {}) # type: dict
73
+
74
+ def translate(self, context, sourceText, disambiguation=None, n=-1):
75
+ """
76
+ :param context: str | unicode | QString
77
+ :param sourceText: str | unicode | QString
78
+ :param disambiguation: str | None
79
+ :param n: int
80
+ :return: (str | None) Translation; None when unknown - a NULL string, so Qt keeps the source text (an empty
81
+ string would count as a translation and blank the text, e.g. toolbar buttons labelled '-' or '+').
82
+ """
83
+ return self.__m_strings.get(sourceText) if sourceText else None
84
+
85
+ def isEmpty(self):
86
+ """
87
+ :return: bool
88
+ """
89
+ return not self.__m_strings
90
+
91
+ def getStrings(self):
92
+ """
93
+ :return: dict
94
+ """
95
+ return dict(self.__m_strings)
96
+
97
+ @pyqtSlot(object)
98
+ def setStrings(self, strings):
99
+ """
100
+ :param strings: dict
101
+ :return:
102
+ """
103
+ self.__m_strings = dict(strings or {}) # type: dict
104
+
105
+ # ---------- Properties ----------
106
+ strings = pyqtProperty(object, fget=getStrings, fset=setStrings) # type: pyqtProperty
107
+
108
+
109
+ class LanguageManager(QObject):
110
+ """
111
+ LanguageManager class.
112
+ """
113
+ languageChanged = pyqtSignal('QString') # type: pyqtSignal
114
+
115
+ def __init__(self, *args, **kwargs):
116
+ """
117
+ :param folder: (str | unicode | QString) Folder of the <code>.json catalogs.
118
+ :param language: (str | None) Language to apply now: a code, 'auto' (system language) or None (none yet).
119
+ :param languageChanged: callable | None
120
+ :param args: any
121
+ :param kwargs: any
122
+ """
123
+ folder = kwargs.pop('folder', '') # type: str
124
+ language = kwargs.pop('language', None) # type: str | None
125
+ languageChanged = kwargs.pop('languageChanged', None) # type: callable | None
126
+ super(LanguageManager, self).__init__(*args, **kwargs)
127
+ if callable(languageChanged):
128
+ self.languageChanged.connect(languageChanged)
129
+ self.__m_folder = u'{}'.format(folder) # type: str
130
+ self.__m_language = 'en' # type: str
131
+ self.__m_requested = 'en' # type: str
132
+ self.__m_installed = [] # type: list # translators installed by this manager
133
+ if language is not None:
134
+ self.setLanguage(language)
135
+
136
+ # ---------- Helpers ----------
137
+ def _catalogPath(self, code):
138
+ """
139
+ :param code: str | unicode | QString
140
+ :return: str | unicode | QString
141
+ """
142
+ return join(self.__m_folder, '{}.json'.format(code))
143
+
144
+ def catalog(self, code):
145
+ """
146
+ :param code: str | unicode | QString
147
+ :return: (dict) Catalog of a language ({} for English or unknown).
148
+ """
149
+ path = self._catalogPath(code) # type: str
150
+ return loadCatalog(path) if code != 'en' and isfile(path) else {}
151
+
152
+ # ---------- Public API ----------
153
+ def availableLanguages(self):
154
+ """
155
+ :return: (list[tuple[str, str]]) (code, native name), English first.
156
+ """
157
+ codes = ['en'] # type: list
158
+ if isdir(self.__m_folder):
159
+ codes += sorted(splitext(f)[0] for f in listdir(self.__m_folder) if f.endswith('.json'))
160
+ return [(c, self.nativeName(c)) for c in codes]
161
+
162
+ def nativeName(self, code):
163
+ """
164
+ :param code: str | unicode | QString
165
+ :return: str | unicode | QString
166
+ """
167
+ if code in LANGUAGES:
168
+ return LANGUAGES[code][1]
169
+ return u'{}'.format(self.catalog(code).get('name', code))
170
+
171
+ def match(self, name):
172
+ """
173
+ Best available language for a locale name: exact ('pt_BR'), alias ('jp', 'cn'), language ('de' for 'de_AT'),
174
+ then a regional variant of the language ('pt_BR' for 'pt_PT', 'zh_CN' for 'zh_TW').
175
+ :param name: str | unicode | QString
176
+ :return: (str | unicode | QString) Code, '' if none.
177
+ """
178
+ available = [c for c, n in self.availableLanguages()] # type: list
179
+ name = name.replace('-', '_') # type: str
180
+ lang = name.split('_')[0].lower() # type: str
181
+ region = name.split('_')[1].upper() if '_' in name else '' # type: str
182
+ for candidate in ('{}_{}'.format(lang, region) if region else '', ALIASES.get(name.lower(), ''), lang,
183
+ ALIASES.get(lang, '')):
184
+ if candidate and candidate in available:
185
+ return candidate
186
+ return next((c for c in available if c.split('_')[0] == lang), '')
187
+
188
+ def systemLanguage(self):
189
+ """
190
+ :return: (str | unicode | QString) The system language if a catalog matches it, else 'en'.
191
+ """
192
+ return self.match(u'{}'.format(QLocale.system().name())) or 'en'
193
+
194
+ def resolve(self, code):
195
+ """
196
+ :param code: (str | unicode | QString) Code or 'auto'.
197
+ :return: (str | unicode | QString) An available language code.
198
+ """
199
+ if u'{}'.format(code or 'auto').lower() == 'auto':
200
+ return self.systemLanguage()
201
+ return self.match(code) or 'en'
202
+
203
+ def isRightToLeft(self, code=None):
204
+ """
205
+ :param code: (str | None) None = current language.
206
+ :return: bool
207
+ """
208
+ code = self.__m_language if code is None else self.resolve(code) # type: str
209
+ if code in LANGUAGES:
210
+ return LANGUAGES[code][2]
211
+ return self.catalog(code).get('direction') == 'rtl'
212
+
213
+ def translateIn(self, code, text):
214
+ """
215
+ Translate one text into a given language (e.g. to ask "restart?" in the language just chosen).
216
+ :param code: str | unicode | QString
217
+ :param text: str | unicode | QString
218
+ :return: str | unicode | QString
219
+ """
220
+ return self.catalog(self.resolve(code)).get('strings', {}).get(text) or text
221
+
222
+ def getLanguage(self):
223
+ """
224
+ :return: (str | unicode | QString) Current language code.
225
+ """
226
+ return self.__m_language
227
+
228
+ def getRequestedLanguage(self):
229
+ """
230
+ :return: (str | unicode | QString) As requested: a code or 'auto'.
231
+ """
232
+ return self.__m_requested
233
+
234
+ @pyqtSlot('QString')
235
+ @pyqtSlot(str)
236
+ def setLanguage(self, language):
237
+ """
238
+ Install a language for the whole application. Widgets built afterwards are translated; the application
239
+ restarts its window to switch an open interface.
240
+ :param language: (str | unicode | QString) Code ('fr', 'ar'...) or 'auto'.
241
+ :return:
242
+ """
243
+ app = QApplication.instance()
244
+ self.__m_requested = u'{}'.format(language or 'auto') # type: str
245
+ if self.__m_requested.lower() == 'auto':
246
+ self.__m_requested = 'auto' # type: str
247
+ code = self.resolve(self.__m_requested) # type: str
248
+ for t in self.__m_installed:
249
+ app.removeTranslator(t)
250
+ self.__m_installed = [] # type: list
251
+ if code != 'en':
252
+ strings = self.catalog(code).get('strings', {}) # type: dict
253
+ translator = CatalogTranslator(strings=strings, parent=self) # type: CatalogTranslator
254
+ app.installTranslator(translator)
255
+ self.__m_installed.append(translator)
256
+ qt = QTranslator(self) # type: QTranslator # Qt's own dialogs and buttons
257
+ if qt.load(QLocale(code), 'qtbase', '_', qtTranslationsPath()): # regional fallbacks by Qt
258
+ app.installTranslator(qt)
259
+ self.__m_installed.append(qt)
260
+ app.setLayoutDirection(Qt.RightToLeft if self.isRightToLeft(code) else Qt.LeftToRight)
261
+ QLocale.setDefault(QLocale(code))
262
+ changed = code != self.__m_language # type: bool
263
+ self.__m_language = code # type: str
264
+ if changed:
265
+ self.languageChanged.emit(code)
266
+
267
+ def getFolder(self):
268
+ """
269
+ :return: str | unicode | QString
270
+ """
271
+ return self.__m_folder
272
+
273
+ @pyqtSlot('QString')
274
+ @pyqtSlot(str)
275
+ def setFolder(self, folder):
276
+ """
277
+ :param folder: str | unicode | QString
278
+ :return:
279
+ """
280
+ self.__m_folder = u'{}'.format(folder) # type: str
281
+
282
+ # ---------- Properties ----------
283
+ language = pyqtProperty('QString', fget=getLanguage, fset=setLanguage, notify=languageChanged) # type: pyqtProperty
284
+ folder = pyqtProperty('QString', fget=getFolder, fset=setFolder) # type: pyqtProperty
@@ -0,0 +1,24 @@
1
+ # coding=utf-8
2
+ """
3
+ upscaler 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 UpscaleEngine, METHOD_NAMES
14
+ except:
15
+ from core import UpscaleEngine, METHOD_NAMES
16
+ try:
17
+ from .upscaler import Upscaler
18
+ except:
19
+ try:
20
+ from upscaler import Upscaler
21
+ except: # No Qt binding: the Qt-free part only.
22
+ Upscaler = None
23
+
24
+ __all__ = ['UpscaleEngine', 'METHOD_NAMES', 'Upscaler'] # type: list[str]
@@ -0,0 +1,315 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Upscaling algorithms on NumPy arrays - pure Python + NumPy, OpenCV optional, no Qt: used by the Qt Upscaler and
4
+ by the headless server (which also runs without Qt, e.g. on Android).
5
+ Methods (same numbers as Upscaler.Method):
6
+ 0 Nearest NumPy 1 Bilinear OpenCV, else NumPy 2 Bicubic OpenCV
7
+ 3 Lanczos OpenCV 4 PixelArt NumPy (Scale2x / EPX) 5 AIFast OpenCV contrib (FSRCNN-small)
8
+ 6 AIQuality OpenCV contrib (FSRCNN)
9
+ An unavailable method falls back to the closest available one.
10
+ """
11
+ from os.path import dirname, join, isfile
12
+
13
+ try:
14
+ from numpy import arange, where, empty, ascontiguousarray, uint8, uint32, pad, float32, clip, ndarray, minimum
15
+
16
+ hasNumpy = True # type: bool
17
+ except:
18
+ hasNumpy = False # type: bool
19
+ try:
20
+ from cv2 import GaussianBlur, addWeighted, resize, INTER_LINEAR, INTER_LANCZOS4, INTER_AREA, INTER_CUBIC, \
21
+ INTER_NEAREST
22
+
23
+ hasCV2 = True # type: bool
24
+ except:
25
+ hasCV2 = False # type: bool
26
+ try:
27
+ from cv2 import dnn_superres # opencv-contrib-python only: must not disable the classic OpenCV methods.
28
+ except:
29
+ dnn_superres = None
30
+
31
+ NEAREST, BILINEAR, BICUBIC, LANCZOS, PIXEL_ART, AI_FAST, AI_QUALITY = range(7)
32
+ METHOD_NAMES = {
33
+ NEAREST: 'Nearest (pixel-perfect)',
34
+ BILINEAR: 'Bilinear (smooth)',
35
+ BICUBIC: 'Bicubic',
36
+ LANCZOS: 'Lanczos (sharp)',
37
+ PIXEL_ART: 'Pixel art (Scale2x)',
38
+ AI_FAST: 'AI super-res - fast',
39
+ AI_QUALITY: 'AI super-res - quality',
40
+ } # type: dict[int, str]
41
+ MODEL_FILES = {AI_FAST: 'FSRCNN-small_x{}.pb', AI_QUALITY: 'FSRCNN_x{}.pb'} # type: dict
42
+ MODELS_DIR = join(dirname(__file__), 'models') # type: str
43
+ FALLBACKS = {
44
+ AI_QUALITY: [AI_QUALITY, AI_FAST, LANCZOS, BILINEAR],
45
+ AI_FAST: [AI_FAST, LANCZOS, BILINEAR],
46
+ LANCZOS: [LANCZOS, BICUBIC, BILINEAR],
47
+ BICUBIC: [BICUBIC, BILINEAR],
48
+ PIXEL_ART: [PIXEL_ART, NEAREST],
49
+ } # type: dict
50
+
51
+
52
+ def clamp(x, a, b):
53
+ """
54
+ :param x: float | int
55
+ :param a: float | int
56
+ :param b: float | int
57
+ :return: float | int
58
+ """
59
+ return a if x < a else b if x > b else x
60
+
61
+
62
+ def nearestResize(arr, w, h):
63
+ """
64
+ Pure NumPy nearest-neighbor resize.
65
+ :param arr: ndarray
66
+ :param w: int
67
+ :param h: int
68
+ :return: ndarray
69
+ """
70
+ sh, sw = arr.shape[:2] # type: int, int
71
+ rows = (arange(h) * sh // h).clip(0, sh - 1)
72
+ cols = (arange(w) * sw // w).clip(0, sw - 1)
73
+ return arr[rows[:, None], cols[None, :]]
74
+
75
+
76
+ def bilinearResize(arr, w, h):
77
+ """
78
+ Pure NumPy bilinear resize (pixel centres aligned like OpenCV): Bilinear without OpenCV.
79
+ :param arr: (ndarray) (H, W, C) uint8.
80
+ :param w: int
81
+ :param h: int
82
+ :return: ndarray
83
+ """
84
+ sh, sw = arr.shape[:2] # type: int, int
85
+ ys = clip((arange(h, dtype=float32) + 0.5) * (sh / float(h)) - 0.5, 0, sh - 1)
86
+ xs = clip((arange(w, dtype=float32) + 0.5) * (sw / float(w)) - 0.5, 0, sw - 1)
87
+ y0, x0 = ys.astype(int), xs.astype(int)
88
+ y1, x1 = minimum(y0 + 1, sh - 1), minimum(x0 + 1, sw - 1)
89
+ fy, fx = (ys - y0)[:, None, None], (xs - x0)[None, :, None]
90
+ a = arr.astype(float32)
91
+ top = a[y0][:, x0] * (1 - fx) + a[y0][:, x1] * fx
92
+ bottom = a[y1][:, x0] * (1 - fx) + a[y1][:, x1] * fx
93
+ return clip(top * (1 - fy) + bottom * fy + 0.5, 0, 255).astype(uint8)
94
+
95
+
96
+ def scale2x(arr):
97
+ """
98
+ One Scale2x / EPX pass: doubles the image while keeping diagonal edges crisp.
99
+ :param arr: (ndarray) (H, W, 3) uint8.
100
+ :return: ndarray
101
+ """
102
+ a = arr.astype(uint32)
103
+ p = (a[..., 0] << 16) | (a[..., 1] << 8) | a[..., 2]
104
+ pd = pad(p, 1, mode='edge')
105
+ b, d, f, hh = pd[:-2, 1:-1], pd[1:-1, :-2], pd[1:-1, 2:], pd[2:, 1:-1]
106
+ cond = (b != hh) & (d != f)
107
+ out = empty((p.shape[0] * 2, p.shape[1] * 2), uint32)
108
+ out[0::2, 0::2] = where(cond & (d == b), d, p)
109
+ out[0::2, 1::2] = where(cond & (b == f), f, p)
110
+ out[1::2, 0::2] = where(cond & (d == hh), d, p)
111
+ out[1::2, 1::2] = where(cond & (hh == f), f, p)
112
+ rgb = empty(out.shape + (3,), uint8)
113
+ rgb[..., 0] = (out >> 16) & 0xFF
114
+ rgb[..., 1] = (out >> 8) & 0xFF
115
+ rgb[..., 2] = out & 0xFF
116
+ return rgb
117
+
118
+
119
+ class UpscaleEngine(object):
120
+ """
121
+ UpscaleEngine class: resizes NumPy RGB arrays with the requested method (no Qt).
122
+ """
123
+
124
+ def __init__(self, *args, **kwargs):
125
+ """
126
+ :param modelsDir: (str | unicode | QString) Folder of the FSRCNN networks.
127
+ :param aiMinScale: (float | int) Below this factor the AI methods use Lanczos (faster, same quality).
128
+ :param onError: (callable | None) f(message) when a network cannot be loaded.
129
+ :param args: any
130
+ :param kwargs: any
131
+ """
132
+ self.__m_modelsDir = kwargs.pop('modelsDir', MODELS_DIR) # type: str
133
+ self.__m_aiMinScale = float(kwargs.pop('aiMinScale', 1.5)) # type: float
134
+ self.__m_onError = kwargs.pop('onError', None)
135
+ super(UpscaleEngine, self).__init__(*args, **kwargs)
136
+ self.__m_models = {} # type: dict
137
+
138
+ # ---------- Availability ----------
139
+ @staticmethod
140
+ def hasNumpy():
141
+ """
142
+ :return: bool
143
+ """
144
+ return hasNumpy
145
+
146
+ @staticmethod
147
+ def hasOpenCV():
148
+ """
149
+ :return: bool
150
+ """
151
+ return bool(hasCV2)
152
+
153
+ @staticmethod
154
+ def hasSuperRes():
155
+ """
156
+ :return: bool
157
+ """
158
+ return bool(hasCV2) and dnn_superres is not None
159
+
160
+ def isMethodAvailable(self, method):
161
+ """
162
+ :param method: int
163
+ :return: bool
164
+ """
165
+ method = int(method) # type: int
166
+ if method == NEAREST:
167
+ return True
168
+ if method in (BILINEAR, PIXEL_ART):
169
+ return UpscaleEngine.hasNumpy() or method == BILINEAR
170
+ if method in (BICUBIC, LANCZOS):
171
+ return UpscaleEngine.hasOpenCV()
172
+ if not UpscaleEngine.hasSuperRes():
173
+ return False
174
+ return all(isfile(join(self.__m_modelsDir, MODEL_FILES[method].format(s))) for s in (2, 3, 4))
175
+
176
+ def availableMethods(self):
177
+ """
178
+ :return: (list[tuple[int, str | unicode | QString]]) Available methods with their (English) names.
179
+ """
180
+ return [(m, METHOD_NAMES[m]) for m in sorted(METHOD_NAMES) if self.isMethodAvailable(m)]
181
+
182
+ def resolve(self, method):
183
+ """
184
+ :param method: int
185
+ :return: (int) The method itself if available, else the closest available fallback.
186
+ """
187
+ for m in FALLBACKS.get(int(method), [int(method)]):
188
+ if self.isMethodAvailable(m):
189
+ return m
190
+ return BILINEAR
191
+
192
+ # ---------- Processing ----------
193
+ def _model(self, method, scale):
194
+ """
195
+ :param method: int
196
+ :param scale: int
197
+ :return: dnn_superres.DnnSuperResImpl | None
198
+ """
199
+ key = (int(method), int(scale)) # type: tuple
200
+ if key not in self.__m_models:
201
+ sr = None
202
+ try:
203
+ sr = dnn_superres.DnnSuperResImpl_create()
204
+ sr.readModel(join(self.__m_modelsDir, MODEL_FILES[method].format(scale)))
205
+ sr.setModel('fsrcnn', int(scale))
206
+ except Exception as e:
207
+ sr = None
208
+ if callable(self.__m_onError):
209
+ self.__m_onError(u'Could not load super-resolution model: {}'.format(e))
210
+ self.__m_models[key] = sr
211
+ return self.__m_models[key]
212
+
213
+ def _superRes(self, arr, w, h, scale, method):
214
+ """
215
+ :param arr: ndarray
216
+ :param w: int
217
+ :param h: int
218
+ :param scale: float | int
219
+ :param method: int
220
+ :return: ndarray
221
+ """
222
+ if scale < self.__m_aiMinScale:
223
+ return resize(arr, (w, h), interpolation=INTER_LANCZOS4)
224
+ k = 2 if scale < 2.5 else 3 if scale < 3.5 else 4 # type: int
225
+ sr = self._model(method, k)
226
+ if sr is None:
227
+ return resize(arr, (w, h), interpolation=INTER_LANCZOS4)
228
+ up = sr.upsample(ascontiguousarray(arr[..., ::-1]))[..., ::-1] # Network expects BGR.
229
+ if up.shape[1] == w and up.shape[0] == h:
230
+ return up
231
+ return resize(up, (w, h), interpolation=INTER_AREA if up.shape[1] > w else INTER_CUBIC)
232
+
233
+ @staticmethod
234
+ def _pixelArt(arr, w, h):
235
+ """
236
+ :param arr: ndarray
237
+ :param w: int
238
+ :param h: int
239
+ :return: ndarray
240
+ """
241
+ passes = 0 # type: int
242
+ while passes < 3 and arr.shape[1] * 2 <= w and arr.shape[0] * 2 <= h:
243
+ arr = scale2x(arr)
244
+ passes += 1
245
+ if arr.shape[1] == w and arr.shape[0] == h:
246
+ return arr
247
+ return resize(arr, (w, h), interpolation=INTER_NEAREST) if hasCV2 else nearestResize(arr, w, h)
248
+
249
+ @staticmethod
250
+ def _sharpen(arr, scale, amount):
251
+ """
252
+ Unsharp mask whose radius follows the upscale factor.
253
+ :param arr: ndarray
254
+ :param scale: float | int
255
+ :param amount: float | int
256
+ :return: ndarray
257
+ """
258
+ return addWeighted(arr, 1.0 + amount, GaussianBlur(arr, (0, 0), clamp(0.5 * scale, 0.8, 4.0)), -amount, 0)
259
+
260
+ def upscale(self, arr, w, h, method=BILINEAR, sharpness=0.0):
261
+ """
262
+ Resize to exactly w x h with a method (resolved to an available one).
263
+ :param arr: (ndarray) (H, W, 3) uint8 RGB.
264
+ :param w: int
265
+ :param h: int
266
+ :param method: int
267
+ :param sharpness: (float | int) Unsharp-mask amount (OpenCV; not for Nearest / PixelArt).
268
+ :return: (ndarray) (h, w, 3) uint8 RGB.
269
+ """
270
+ m = self.resolve(method) # type: int
271
+ scale = max(w / float(arr.shape[1]), h / float(arr.shape[0])) # type: float
272
+ if m == NEAREST:
273
+ up = resize(arr, (w, h), interpolation=INTER_NEAREST) if hasCV2 else nearestResize(arr, w, h)
274
+ elif m == PIXEL_ART:
275
+ up = UpscaleEngine._pixelArt(arr, w, h)
276
+ elif not hasCV2:
277
+ up = bilinearResize(arr, w, h)
278
+ elif scale <= 1.0:
279
+ up = resize(arr, (w, h), interpolation=INTER_AREA)
280
+ elif m in (AI_FAST, AI_QUALITY):
281
+ up = self._superRes(arr, w, h, scale, m)
282
+ else:
283
+ up = resize(arr, (w, h),
284
+ interpolation={BILINEAR: INTER_LINEAR, BICUBIC: INTER_CUBIC}.get(m, INTER_LANCZOS4))
285
+ if sharpness > 0.0 and scale > 1.0 and hasCV2 and m not in (NEAREST, PIXEL_ART):
286
+ up = UpscaleEngine._sharpen(up, scale, float(sharpness))
287
+ return up
288
+
289
+ # ---------- Options ----------
290
+ def getModelsDir(self):
291
+ """
292
+ :return: str | unicode | QString
293
+ """
294
+ return self.__m_modelsDir
295
+
296
+ def setModelsDir(self, modelsDir):
297
+ """
298
+ :param modelsDir: str | unicode | QString
299
+ :return:
300
+ """
301
+ self.__m_modelsDir = modelsDir # type: str
302
+ self.__m_models = {} # type: dict
303
+
304
+ def getAiMinScale(self):
305
+ """
306
+ :return: float | int
307
+ """
308
+ return self.__m_aiMinScale
309
+
310
+ def setAiMinScale(self, aiMinScale):
311
+ """
312
+ :param aiMinScale: float | int
313
+ :return:
314
+ """
315
+ self.__m_aiMinScale = float(aiMinScale) # type: float
@@ -0,0 +1,23 @@
1
+ # coding=utf-8
2
+ """
3
+ Entry point for the Upscaler demo.
4
+ """
5
+ from os.path import dirname
6
+ from sys import path
7
+
8
+ if not __package__ and dirname(__file__) not in path:
9
+ path.append(dirname(__file__))
10
+
11
+ try:
12
+ from .mainwindow import MainWindow
13
+ except:
14
+ from mainwindow import MainWindow
15
+
16
+ if __name__ == '__main__':
17
+ from ManyQt.QtWidgets import QApplication
18
+ from sys import argv, exit
19
+
20
+ a = QApplication(argv) # type: QApplication
21
+ w = MainWindow() # type: MainWindow
22
+ w.show()
23
+ exit(a.exec_())