Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- python_embeded/Lib/site-packages/pymatting-1.1.14.dist-info/licenses/LICENSE.md +21 -0
- python_embeded/Lib/site-packages/pymatting/alpha/__init__.py +7 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_cf.py +78 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_knn.py +56 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lbdm.py +56 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lkm.py +64 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_rw.py +56 -0
- python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_sm.py +613 -0
- python_embeded/Lib/site-packages/pymatting/config/__init__.py +1 -0
- python_embeded/Lib/site-packages/pymatting/cutout/__init__.py +1 -0
- python_embeded/Lib/site-packages/pymatting/cutout/cutout.py +36 -0
- python_embeded/Lib/site-packages/pymatting/foreground/__init__.py +5 -0
- python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_cf.py +130 -0
- python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml.py +253 -0
- python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_cupy.py +230 -0
- python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_pyopencl.py +229 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/__init__.py +19 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/cf_laplacian.py +177 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/knn_laplacian.py +92 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/laplacian.py +60 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/lbdm_laplacian.py +94 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/lkm_laplacian.py +76 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/rw_laplacian.py +81 -0
- python_embeded/Lib/site-packages/pymatting/laplacian/uniform_laplacian.py +31 -0
- python_embeded/Lib/site-packages/pymatting/preconditioner/__init__.py +3 -0
- python_embeded/Lib/site-packages/pymatting/preconditioner/ichol.py +301 -0
- python_embeded/Lib/site-packages/pymatting/preconditioner/jacobi.py +31 -0
- python_embeded/Lib/site-packages/pymatting/preconditioner/vcycle.py +153 -0
- python_embeded/Lib/site-packages/pymatting/solver/__init__.py +2 -0
- python_embeded/Lib/site-packages/pymatting/solver/callback.py +23 -0
- python_embeded/Lib/site-packages/pymatting/solver/cg.py +117 -0
- python_embeded/Lib/site-packages/pyparsing/diagram/__init__.py +754 -0
- python_embeded/Lib/site-packages/pyparsing/tools/__init__.py +0 -0
- python_embeded/Lib/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py +116 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/__init__.py +16 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/api.py +27 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/get_clipboard_text_and_convert.py +75 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/ironpython_clipboard.py +31 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/no_clipboard.py +19 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/obsolete.py +30 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/py.typed +0 -0
- python_embeded/Lib/site-packages/pyreadline3/clipboard/win32_clipboard.py +157 -0
- python_embeded/Lib/site-packages/pyreadline3/configuration/pyreadlineconfig.ini +89 -0
- python_embeded/Lib/site-packages/pyreadline3/configuration/startup.py +38 -0
- python_embeded/Lib/site-packages/pyreadline3/console/__init__.py +16 -0
- python_embeded/Lib/site-packages/pyreadline3/console/ansi.py +253 -0
- python_embeded/Lib/site-packages/pyreadline3/console/console.py +901 -0
- python_embeded/Lib/site-packages/pyreadline3/console/console_attributes.py +15 -0
- python_embeded/Lib/site-packages/pyreadline3/console/consolebase.py +50 -0
- python_embeded/Lib/site-packages/pyreadline3/console/event.py +37 -0
python_embeded/Lib/site-packages/pymatting-1.1.14.dist-info/licenses/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2020 PyMatting
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
python_embeded/Lib/site-packages/pymatting/alpha/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.alpha.estimate_alpha_lkm import estimate_alpha_lkm
|
| 2 |
+
from pymatting.alpha.estimate_alpha_lbdm import estimate_alpha_lbdm
|
| 3 |
+
from pymatting.alpha.estimate_alpha_rw import estimate_alpha_rw
|
| 4 |
+
from pymatting.alpha.estimate_alpha_knn import estimate_alpha_knn
|
| 5 |
+
from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf
|
| 6 |
+
from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf as estimate_alpha
|
| 7 |
+
from pymatting.alpha.estimate_alpha_sm import estimate_alpha_sm
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_cf.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import sanity_check_image, trimap_split
|
| 2 |
+
from pymatting.laplacian.cf_laplacian import cf_laplacian
|
| 3 |
+
from pymatting.preconditioner.ichol import ichol
|
| 4 |
+
from pymatting.solver.cg import cg
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def estimate_alpha_cf(
|
| 9 |
+
image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
|
| 10 |
+
):
|
| 11 |
+
"""
|
| 12 |
+
Estimate alpha from an input image and an input trimap using Closed-Form Alpha Matting as proposed by :cite:`levin2007closed`.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
image: numpy.ndarray
|
| 17 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 18 |
+
trimap: numpy.ndarray
|
| 19 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 20 |
+
preconditioner: function or scipy.sparse.linalg.LinearOperator
|
| 21 |
+
Function or sparse matrix that applies the preconditioner to a vector (default: ichol)
|
| 22 |
+
laplacian_kwargs: dictionary
|
| 23 |
+
Arguments passed to the :code:`cf_laplacian` function
|
| 24 |
+
cg_kwargs: dictionary
|
| 25 |
+
Arguments passed to the :code:`cg` solver
|
| 26 |
+
is_known: numpy.ndarray
|
| 27 |
+
Binary mask of pixels for which to compute the laplacian matrix.
|
| 28 |
+
Providing this parameter might improve performance if few pixels are unknown.
|
| 29 |
+
|
| 30 |
+
Returns
|
| 31 |
+
-------
|
| 32 |
+
alpha: numpy.ndarray
|
| 33 |
+
Estimated alpha matte
|
| 34 |
+
|
| 35 |
+
Example
|
| 36 |
+
-------
|
| 37 |
+
>>> from pymatting import *
|
| 38 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 39 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 40 |
+
>>> alpha = estimate_alpha_cf(
|
| 41 |
+
... image,
|
| 42 |
+
... trimap,
|
| 43 |
+
... laplacian_kwargs={"epsilon": 1e-6},
|
| 44 |
+
... cg_kwargs={"maxiter":2000})
|
| 45 |
+
"""
|
| 46 |
+
if preconditioner is None:
|
| 47 |
+
preconditioner = ichol
|
| 48 |
+
|
| 49 |
+
sanity_check_image(image)
|
| 50 |
+
|
| 51 |
+
h, w = trimap.shape[:2]
|
| 52 |
+
|
| 53 |
+
is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
|
| 54 |
+
|
| 55 |
+
L = cf_laplacian(image, **laplacian_kwargs, is_known=is_known)
|
| 56 |
+
|
| 57 |
+
# Split Laplacian matrix L into
|
| 58 |
+
#
|
| 59 |
+
# [L_U R ]
|
| 60 |
+
# [R^T L_K]
|
| 61 |
+
#
|
| 62 |
+
# and then solve L_U x_U = -R is_fg_K for x where K (is_known) corresponds to
|
| 63 |
+
# fixed pixels and U (is_unknown) corresponds to unknown pixels. For reference, see
|
| 64 |
+
# Grady, Leo, et al. "Random walks for interactive alpha-matting." Proceedings of VIIP. Vol. 2005. 2005.
|
| 65 |
+
|
| 66 |
+
L_U = L[is_unknown, :][:, is_unknown]
|
| 67 |
+
|
| 68 |
+
R = L[is_unknown, :][:, is_known]
|
| 69 |
+
|
| 70 |
+
m = is_fg[is_known]
|
| 71 |
+
|
| 72 |
+
x = trimap.copy().ravel()
|
| 73 |
+
|
| 74 |
+
x[is_unknown] = cg(L_U, -R.dot(m), M=preconditioner(L_U), **cg_kwargs)
|
| 75 |
+
|
| 76 |
+
alpha = np.clip(x, 0, 1).reshape(trimap.shape)
|
| 77 |
+
|
| 78 |
+
return alpha
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_knn.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import sanity_check_image
|
| 2 |
+
from pymatting.laplacian.laplacian import make_linear_system
|
| 3 |
+
from pymatting.laplacian.knn_laplacian import knn_laplacian
|
| 4 |
+
from pymatting.preconditioner.jacobi import jacobi
|
| 5 |
+
from pymatting.solver.cg import cg
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def estimate_alpha_knn(
|
| 10 |
+
image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
|
| 11 |
+
):
|
| 12 |
+
"""
|
| 13 |
+
Estimate alpha from an input image and an input trimap using KNN Matting similar to :cite:`chen2013knn`.
|
| 14 |
+
See `knn_laplacian` for more details.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
image: numpy.ndarray
|
| 19 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 20 |
+
trimap: numpy.ndarray
|
| 21 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 22 |
+
preconditioner: function or scipy.sparse.linalg.LinearOperator
|
| 23 |
+
Function or sparse matrix that applies the preconditioner to a vector (default: jacobi)
|
| 24 |
+
laplacian_kwargs: dictionary
|
| 25 |
+
Arguments passed to the :code:`knn_laplacian` function
|
| 26 |
+
cg_kwargs: dictionary
|
| 27 |
+
Arguments passed to the :code:`cg` solver
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
alpha: numpy.ndarray
|
| 32 |
+
Estimated alpha matte
|
| 33 |
+
|
| 34 |
+
Example
|
| 35 |
+
-------
|
| 36 |
+
>>> from pymatting import *
|
| 37 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 38 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 39 |
+
>>> alpha = estimate_alpha_knn(
|
| 40 |
+
... image,
|
| 41 |
+
... trimap,
|
| 42 |
+
... laplacian_kwargs={"n_neighbors": [15, 10]},
|
| 43 |
+
... cg_kwargs={"maxiter":2000})
|
| 44 |
+
"""
|
| 45 |
+
if preconditioner is None:
|
| 46 |
+
preconditioner = jacobi
|
| 47 |
+
|
| 48 |
+
sanity_check_image(image)
|
| 49 |
+
|
| 50 |
+
A, b = make_linear_system(knn_laplacian(image, **laplacian_kwargs), trimap)
|
| 51 |
+
|
| 52 |
+
x = cg(A, b, M=preconditioner(A), **cg_kwargs)
|
| 53 |
+
|
| 54 |
+
alpha = np.clip(x, 0, 1).reshape(trimap.shape)
|
| 55 |
+
|
| 56 |
+
return alpha
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lbdm.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import sanity_check_image
|
| 2 |
+
from pymatting.laplacian.laplacian import make_linear_system
|
| 3 |
+
from pymatting.laplacian.lbdm_laplacian import lbdm_laplacian
|
| 4 |
+
from pymatting.preconditioner.ichol import ichol
|
| 5 |
+
from pymatting.solver.cg import cg
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def estimate_alpha_lbdm(
|
| 10 |
+
image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
|
| 11 |
+
):
|
| 12 |
+
"""
|
| 13 |
+
Estimate alpha from an input image and an input trimap using Learning Based Digital Matting as proposed by :cite:`zheng2009learning`.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
image: numpy.ndarray
|
| 18 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 19 |
+
trimap: numpy.ndarray
|
| 20 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 21 |
+
preconditioner: function or scipy.sparse.linalg.LinearOperator
|
| 22 |
+
Function or sparse matrix that applies the preconditioner to a vector (default: ichol)
|
| 23 |
+
laplacian_kwargs: dictionary
|
| 24 |
+
Arguments passed to the :code:`lbdm_laplacian` function
|
| 25 |
+
cg_kwargs: dictionary
|
| 26 |
+
Arguments passed to the :code:`cg` solver
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
-------
|
| 30 |
+
alpha: numpy.ndarray
|
| 31 |
+
Estimated alpha matte
|
| 32 |
+
|
| 33 |
+
Example
|
| 34 |
+
-------
|
| 35 |
+
>>> from pymatting import *
|
| 36 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 37 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 38 |
+
>>> alpha = estimate_alpha_lbdm(
|
| 39 |
+
... image,
|
| 40 |
+
... trimap,
|
| 41 |
+
... laplacian_kwargs={"epsilon": 1e-6},
|
| 42 |
+
... cg_kwargs={"maxiter":2000})
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
if preconditioner is None:
|
| 46 |
+
preconditioner = ichol
|
| 47 |
+
|
| 48 |
+
sanity_check_image(image)
|
| 49 |
+
|
| 50 |
+
A, b = make_linear_system(lbdm_laplacian(image, **laplacian_kwargs), trimap)
|
| 51 |
+
|
| 52 |
+
x = cg(A, b, M=preconditioner(A), **cg_kwargs)
|
| 53 |
+
|
| 54 |
+
alpha = np.clip(x, 0, 1).reshape(trimap.shape)
|
| 55 |
+
|
| 56 |
+
return alpha
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lkm.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import sanity_check_image
|
| 2 |
+
from pymatting.laplacian.lkm_laplacian import lkm_laplacian
|
| 3 |
+
from pymatting.util.util import trimap_split
|
| 4 |
+
from pymatting.solver.cg import cg
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def estimate_alpha_lkm(image, trimap, laplacian_kwargs={}, cg_kwargs={}):
|
| 9 |
+
"""
|
| 10 |
+
Estimate alpha from an input image and an input trimap as described in Fast Matting Using Large Kernel Matting Laplacian Matrices by :cite:`he2010fast`.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
image: numpy.ndarray
|
| 15 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 16 |
+
trimap: numpy.ndarray
|
| 17 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 18 |
+
laplacian_kwargs: dictionary
|
| 19 |
+
Arguments passed to the :code:`lkm_laplacian` function
|
| 20 |
+
cg_kwargs: dictionary
|
| 21 |
+
Arguments passed to the :code:`cg` solver
|
| 22 |
+
|
| 23 |
+
Returns
|
| 24 |
+
-------
|
| 25 |
+
alpha: numpy.ndarray
|
| 26 |
+
Estimated alpha matte
|
| 27 |
+
|
| 28 |
+
Example
|
| 29 |
+
-------
|
| 30 |
+
>>> from pymatting import *
|
| 31 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 32 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 33 |
+
>>> alpha = estimate_alpha_lkm(
|
| 34 |
+
... image,
|
| 35 |
+
... trimap,
|
| 36 |
+
... laplacian_kwargs={"epsilon": 1e-6, "radius": 15},
|
| 37 |
+
... cg_kwargs={"maxiter":2000})
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
sanity_check_image(image)
|
| 42 |
+
|
| 43 |
+
L_matvec, diag_L = lkm_laplacian(image, **laplacian_kwargs)
|
| 44 |
+
|
| 45 |
+
is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
|
| 46 |
+
|
| 47 |
+
lambda_value = 100.0
|
| 48 |
+
|
| 49 |
+
c = lambda_value * is_known
|
| 50 |
+
b = lambda_value * is_fg
|
| 51 |
+
|
| 52 |
+
inv_diag_A = 1.0 / (diag_L + c)
|
| 53 |
+
|
| 54 |
+
def A_matvec(x):
|
| 55 |
+
return L_matvec(x) + c * x
|
| 56 |
+
|
| 57 |
+
def jacobi(x):
|
| 58 |
+
return inv_diag_A * x
|
| 59 |
+
|
| 60 |
+
x = cg(A_matvec, b, M=jacobi, **cg_kwargs)
|
| 61 |
+
|
| 62 |
+
alpha = np.clip(x, 0, 1).reshape(trimap.shape)
|
| 63 |
+
|
| 64 |
+
return alpha
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_rw.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import sanity_check_image
|
| 2 |
+
from pymatting.laplacian.laplacian import make_linear_system
|
| 3 |
+
from pymatting.laplacian.rw_laplacian import rw_laplacian
|
| 4 |
+
from pymatting.preconditioner.jacobi import jacobi
|
| 5 |
+
from pymatting.solver.cg import cg
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def estimate_alpha_rw(
|
| 10 |
+
image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
|
| 11 |
+
):
|
| 12 |
+
"""
|
| 13 |
+
Estimate alpha from an input image and an input trimap using Learning Based Digital Matting as proposed by :cite:`grady2005random`.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
image: numpy.ndarray
|
| 18 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 19 |
+
trimap: numpy.ndarray
|
| 20 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 21 |
+
preconditioner: function or scipy.sparse.linalg.LinearOperator
|
| 22 |
+
Function or sparse matrix that applies the preconditioner to a vector (default: jacobi)
|
| 23 |
+
laplacian_kwargs: dictionary
|
| 24 |
+
Arguments passed to the :code:`rw_laplacian` function
|
| 25 |
+
cg_kwargs: dictionary
|
| 26 |
+
Arguments passed to the :code:`cg` solver
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
-------
|
| 30 |
+
alpha: numpy.ndarray
|
| 31 |
+
Estimated alpha matte
|
| 32 |
+
|
| 33 |
+
Example
|
| 34 |
+
-------
|
| 35 |
+
>>> from pymatting import *
|
| 36 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 37 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 38 |
+
>>> alpha = estimate_alpha_rw(
|
| 39 |
+
.... image,
|
| 40 |
+
... trimap,
|
| 41 |
+
... laplacian_kwargs={"sigma": 0.03},
|
| 42 |
+
... cg_kwargs={"maxiter":2000})
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
if preconditioner is None:
|
| 46 |
+
preconditioner = jacobi
|
| 47 |
+
|
| 48 |
+
sanity_check_image(image)
|
| 49 |
+
|
| 50 |
+
A, b = make_linear_system(rw_laplacian(image, **laplacian_kwargs), trimap)
|
| 51 |
+
|
| 52 |
+
x = cg(A, b, M=preconditioner(A), **cg_kwargs)
|
| 53 |
+
|
| 54 |
+
alpha = np.clip(x, 0, 1).reshape(trimap.shape)
|
| 55 |
+
|
| 56 |
+
return alpha
|
python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_sm.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba import njit, pndindex
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def estimate_alpha_sm(
|
| 5 |
+
image,
|
| 6 |
+
trimap,
|
| 7 |
+
return_foreground_background=False,
|
| 8 |
+
trimap_expansion_radius=10,
|
| 9 |
+
trimap_expansion_threshold=0.02,
|
| 10 |
+
sample_gathering_angles=4,
|
| 11 |
+
sample_gathering_weights=(3.0, 2.0, 1.0, 4.0),
|
| 12 |
+
sample_gathering_Np_radius=1,
|
| 13 |
+
sample_refinement_radius=5,
|
| 14 |
+
local_smoothing_radius1=5,
|
| 15 |
+
local_smoothing_radius2=5,
|
| 16 |
+
local_smoothing_radius3=5,
|
| 17 |
+
local_smoothing_sigma_sq1=None,
|
| 18 |
+
local_smoothing_sigma_sq2=0.1,
|
| 19 |
+
local_smoothing_sigma_sq3=None,
|
| 20 |
+
|
| 21 |
+
):
|
| 22 |
+
"""
|
| 23 |
+
Estimate alpha from an input image and an input trimap using Shared Matting as proposed by :cite:`GastalOliveira2010SharedMatting`.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
image: numpy.ndarray
|
| 28 |
+
Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
|
| 29 |
+
trimap: numpy.ndarray
|
| 30 |
+
Trimap with shape :math:`h \\times w` of the image
|
| 31 |
+
return_foreground_background: numpy.ndarray
|
| 32 |
+
Whether to return foreground and background estimate. They will be computed either way
|
| 33 |
+
trimap_expansion_radius: int
|
| 34 |
+
How much to expand trimap.
|
| 35 |
+
trimap_expansion_threshold: float
|
| 36 |
+
Which pixel colors are similar enough to expand trimap into
|
| 37 |
+
sample_gathering_angles: int
|
| 38 |
+
In how many directions to search for new samples.
|
| 39 |
+
sample_gathering_weights: Tuple[float, float, float, float]
|
| 40 |
+
Weights for various cost functions
|
| 41 |
+
sample_gathering_Np_radius: int
|
| 42 |
+
Radius of Np function
|
| 43 |
+
sample_refinement_radius: int
|
| 44 |
+
Search region for better neighboring samples
|
| 45 |
+
local_smoothing_radius1: int
|
| 46 |
+
Radius for foreground/background smoothing
|
| 47 |
+
local_smoothing_radius2: int
|
| 48 |
+
Radius for confidence computation
|
| 49 |
+
local_smoothing_radius3: int
|
| 50 |
+
Radius for low frequency alpha computation
|
| 51 |
+
local_smoothing_sigma_sq1: float
|
| 52 |
+
Squared sigma value for foreground/background smoothing
|
| 53 |
+
Defaults to :code:`(2 * local_smoothing_radius1 + 1)**2 / (9 * pi)` if not given
|
| 54 |
+
local_smoothing_sigma_sq2: float
|
| 55 |
+
Squared sigma value for confidence computation
|
| 56 |
+
local_smoothing_sigma_sq3: float
|
| 57 |
+
Squared sigma value for low frequency alpha computation
|
| 58 |
+
Defaults to :code:`(2 * local_smoothing_radius3 + 1)**2 / (9 * pi)` if not given
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
alpha: numpy.ndarray
|
| 63 |
+
Estimated alpha matte
|
| 64 |
+
foreground: numpy.ndarray
|
| 65 |
+
Estimated foreground
|
| 66 |
+
background: numpy.ndarray
|
| 67 |
+
Estimated background
|
| 68 |
+
|
| 69 |
+
Example
|
| 70 |
+
-------
|
| 71 |
+
>>> from pymatting import *
|
| 72 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 73 |
+
>>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
|
| 74 |
+
>>> alpha, foreground, background = estimate_alpha_sm(
|
| 75 |
+
... image,
|
| 76 |
+
... trimap,
|
| 77 |
+
... return_foreground_background=True,
|
| 78 |
+
... sample_gathering_angles=4)
|
| 79 |
+
"""
|
| 80 |
+
assert image.dtype in [np.float32, np.float64], f"image.dtype should be float32 or float64, but is {image.dtype}"
|
| 81 |
+
assert trimap.dtype in [np.float32, np.float64], f"trimap.dtype should be float32 or float64, but is {trimap.dtype}"
|
| 82 |
+
assert trimap.shape == image.shape[:2], f"image height and width should match trimap height and width, but image shape is {image.shape} and trimap shape is {trimap.shape}"
|
| 83 |
+
assert len(image.shape) == 3 and image.shape[2] == 3, f"image should be RGB, but shape is {image.shape}"
|
| 84 |
+
|
| 85 |
+
if local_smoothing_sigma_sq1 is None:
|
| 86 |
+
local_smoothing_sigma_sq1 = (2 * local_smoothing_radius1 + 1)**2 / (9.0 * np.pi)
|
| 87 |
+
|
| 88 |
+
if local_smoothing_sigma_sq3 is None:
|
| 89 |
+
local_smoothing_sigma_sq3 = (2 * local_smoothing_radius1 + 1)**2 / (9.0 * np.pi)
|
| 90 |
+
|
| 91 |
+
# Convert to float32 if float64. Precision should be sufficient.
|
| 92 |
+
image = image.astype(np.float32)
|
| 93 |
+
trimap = trimap.astype(np.float32)
|
| 94 |
+
|
| 95 |
+
expanded_trimap = trimap.copy()
|
| 96 |
+
|
| 97 |
+
if trimap_expansion_radius > 0 and trimap_expansion_threshold > 0.0:
|
| 98 |
+
expand_trimap(
|
| 99 |
+
expanded_trimap,
|
| 100 |
+
trimap,
|
| 101 |
+
image,
|
| 102 |
+
k_i=trimap_expansion_radius,
|
| 103 |
+
k_c=trimap_expansion_threshold)
|
| 104 |
+
|
| 105 |
+
avg_F = image[expanded_trimap == 1.0].mean(axis=0)
|
| 106 |
+
avg_B = image[expanded_trimap == 0.0].mean(axis=0)
|
| 107 |
+
|
| 108 |
+
gathering_F = np.zeros_like(image) + avg_F
|
| 109 |
+
gathering_B = np.zeros_like(image) + avg_B
|
| 110 |
+
|
| 111 |
+
gathering_alpha = np.zeros_like(trimap)
|
| 112 |
+
|
| 113 |
+
eN, eA, ef, eb = sample_gathering_weights
|
| 114 |
+
|
| 115 |
+
sample_gathering(
|
| 116 |
+
gathering_F,
|
| 117 |
+
gathering_B,
|
| 118 |
+
gathering_alpha,
|
| 119 |
+
image,
|
| 120 |
+
expanded_trimap,
|
| 121 |
+
num_angles=sample_gathering_angles,
|
| 122 |
+
eN=eN,
|
| 123 |
+
eA=eA,
|
| 124 |
+
ef=ef,
|
| 125 |
+
eb=eb,
|
| 126 |
+
Np_radius=sample_gathering_Np_radius)
|
| 127 |
+
|
| 128 |
+
refined_F = np.zeros_like(image)
|
| 129 |
+
refined_B = np.zeros_like(image)
|
| 130 |
+
refined_alpha = np.zeros_like(trimap)
|
| 131 |
+
|
| 132 |
+
sample_refinement(
|
| 133 |
+
refined_F,
|
| 134 |
+
refined_B,
|
| 135 |
+
refined_alpha,
|
| 136 |
+
gathering_F,
|
| 137 |
+
gathering_B,
|
| 138 |
+
image,
|
| 139 |
+
expanded_trimap,
|
| 140 |
+
radius=sample_refinement_radius)
|
| 141 |
+
|
| 142 |
+
final_F = np.zeros_like(image)
|
| 143 |
+
final_B = np.zeros_like(image)
|
| 144 |
+
final_alpha = np.zeros_like(trimap)
|
| 145 |
+
|
| 146 |
+
local_smoothing(
|
| 147 |
+
final_F,
|
| 148 |
+
final_B,
|
| 149 |
+
final_alpha,
|
| 150 |
+
refined_F,
|
| 151 |
+
refined_B,
|
| 152 |
+
refined_alpha,
|
| 153 |
+
image,
|
| 154 |
+
expanded_trimap,
|
| 155 |
+
radius1=local_smoothing_radius1,
|
| 156 |
+
radius2=local_smoothing_radius2,
|
| 157 |
+
radius3=local_smoothing_radius3,
|
| 158 |
+
sigma_sq1=local_smoothing_sigma_sq1,
|
| 159 |
+
sigma_sq2=local_smoothing_sigma_sq2,
|
| 160 |
+
sigma_sq3=local_smoothing_sigma_sq3)
|
| 161 |
+
|
| 162 |
+
if return_foreground_background:
|
| 163 |
+
return final_alpha, final_F, final_B
|
| 164 |
+
else:
|
| 165 |
+
return final_alpha
|
| 166 |
+
|
| 167 |
+
@njit("f4(f4[::1], f4[::1], f4[::1])", cache=True, nogil=True)
|
| 168 |
+
def estimate_alpha(I, F, B):
|
| 169 |
+
fb0 = F[0] - B[0]
|
| 170 |
+
fb1 = F[1] - B[1]
|
| 171 |
+
fb2 = F[2] - B[2]
|
| 172 |
+
|
| 173 |
+
ib0 = I[0] - B[0]
|
| 174 |
+
ib1 = I[1] - B[1]
|
| 175 |
+
ib2 = I[2] - B[2]
|
| 176 |
+
|
| 177 |
+
denom = fb0 * fb0 + fb1 * fb1 + fb2 * fb2 + 1e-5
|
| 178 |
+
|
| 179 |
+
alpha = (ib0 * fb0 + ib1 * fb1 + ib2 * fb2) / denom
|
| 180 |
+
|
| 181 |
+
alpha = max(0.0, min(1.0, alpha))
|
| 182 |
+
|
| 183 |
+
return alpha
|
| 184 |
+
|
| 185 |
+
@njit("f4(f4[::1], f4[::1])", cache=True, nogil=True)
|
| 186 |
+
def inner(a, b):
|
| 187 |
+
s = 0.0
|
| 188 |
+
for i in range(len(a)):
|
| 189 |
+
s += a[i] * b[i]
|
| 190 |
+
return s
|
| 191 |
+
|
| 192 |
+
@njit("f4(f4[::1], f4[::1], f4[::1])", cache=True, nogil=True)
|
| 193 |
+
def Mp2(I, F, B):
|
| 194 |
+
a = estimate_alpha(I, F, B)
|
| 195 |
+
|
| 196 |
+
d0 = a * F[0] + (1.0 - a) * B[0] - I[0]
|
| 197 |
+
d1 = a * F[1] + (1.0 - a) * B[1] - I[1]
|
| 198 |
+
d2 = a * F[2] + (1.0 - a) * B[2] - I[2]
|
| 199 |
+
|
| 200 |
+
return d0 * d0 + d1 * d1 + d2 * d2
|
| 201 |
+
|
| 202 |
+
@njit("f4(f4[:, :, ::1], i8, i8, f4[::1], f4[::1], i8)", cache=True, nogil=True)
|
| 203 |
+
def Np(image, x, y, F, B, r):
|
| 204 |
+
h, w = image.shape[:2]
|
| 205 |
+
result = 0.0
|
| 206 |
+
for y2 in range(y - r, y + r + 1):
|
| 207 |
+
y2 = max(0, min(h - 1, y2))
|
| 208 |
+
for x2 in range(x - r, x + r + 1):
|
| 209 |
+
x2 = max(0, min(w - 1, x2))
|
| 210 |
+
result += Mp2(image[y2, x2], F, B)
|
| 211 |
+
return result
|
| 212 |
+
|
| 213 |
+
@njit("f4(f4[:, :, ::1], i8, i8, i8, i8)", cache=True, nogil=True)
|
| 214 |
+
def Ep(image, px, py, sx, sy):
|
| 215 |
+
result = 0.0
|
| 216 |
+
|
| 217 |
+
spx = sx - px
|
| 218 |
+
spy = sy - py
|
| 219 |
+
|
| 220 |
+
d = np.hypot(spx, spy)
|
| 221 |
+
|
| 222 |
+
if d == 0.0: return 0.0
|
| 223 |
+
|
| 224 |
+
num_steps = int(np.ceil(d))
|
| 225 |
+
num_steps = max(1, min(10, num_steps))
|
| 226 |
+
|
| 227 |
+
step_x = spx / num_steps
|
| 228 |
+
step_y = spy / num_steps
|
| 229 |
+
|
| 230 |
+
h, w = image.shape[:2]
|
| 231 |
+
|
| 232 |
+
for i in range(num_steps + 1):
|
| 233 |
+
qx = int(px + float(i) * step_x)
|
| 234 |
+
qy = int(py + float(i) * step_x)
|
| 235 |
+
|
| 236 |
+
q_l = max(0, min(w - 1, qx - 1))
|
| 237 |
+
q_r = max(0, min(w - 1, qx + 1))
|
| 238 |
+
q_u = max(0, min(h - 1, qy + 1))
|
| 239 |
+
q_d = max(0, min(h - 1, qy - 1))
|
| 240 |
+
qx = max(0, min(w - 1, qx))
|
| 241 |
+
qy = max(0, min(h - 1, qy))
|
| 242 |
+
|
| 243 |
+
Ix0 = 0.5 * (image[qy, q_r, 0] - image[qy, q_l, 0])
|
| 244 |
+
Ix1 = 0.5 * (image[qy, q_r, 1] - image[qy, q_l, 1])
|
| 245 |
+
Ix2 = 0.5 * (image[qy, q_r, 2] - image[qy, q_l, 2])
|
| 246 |
+
|
| 247 |
+
Iy0 = 0.5 * (image[q_u, qx, 0] - image[q_d, qx, 0])
|
| 248 |
+
Iy1 = 0.5 * (image[q_u, qx, 1] - image[q_d, qx, 1])
|
| 249 |
+
Iy2 = 0.5 * (image[q_u, qx, 2] - image[q_d, qx, 2])
|
| 250 |
+
|
| 251 |
+
v0 = step_x * Ix0 + step_y * Iy0
|
| 252 |
+
v1 = step_x * Ix1 + step_y * Iy1
|
| 253 |
+
v2 = step_x * Ix2 + step_y * Iy2
|
| 254 |
+
|
| 255 |
+
result += np.sqrt(v0 * v0 + v1 * v1 + v2 * v2)
|
| 256 |
+
|
| 257 |
+
return result
|
| 258 |
+
|
| 259 |
+
@njit("f4(f4[::1], f4[::1])", cache=True, nogil=True)
|
| 260 |
+
def dist(a, b):
|
| 261 |
+
d2 = 0.0
|
| 262 |
+
for i in range(a.shape[0]):
|
| 263 |
+
d2 += (a[i] - b[i]) ** 2
|
| 264 |
+
return np.sqrt(d2)
|
| 265 |
+
|
| 266 |
+
@njit("f4(f4[::1])", cache=True, nogil=True)
|
| 267 |
+
def length(a):
|
| 268 |
+
return np.sqrt(inner(a, a))
|
| 269 |
+
|
| 270 |
+
@njit("void(f4[:, ::1], f4[:, ::1], f4[:, :, ::1], i8, f4)", cache=True, parallel=True, nogil=True)
|
| 271 |
+
def expand_trimap(expanded_trimap, trimap, image, k_i, k_c):
|
| 272 |
+
# NB: Description in paper does not match published test images.
|
| 273 |
+
# The radius appears to be larger and expanded trimap is sparser.
|
| 274 |
+
h, w = trimap.shape
|
| 275 |
+
|
| 276 |
+
for y, x in pndindex((h, w)):
|
| 277 |
+
if trimap[y, x] == 0 or trimap[y, x] == 1: continue
|
| 278 |
+
|
| 279 |
+
closest = np.inf
|
| 280 |
+
|
| 281 |
+
for y2 in range(y - k_i, y + k_i + 1):
|
| 282 |
+
for x2 in range(x - k_i, x + k_i + 1):
|
| 283 |
+
if x2 < 0 or x2 >= w or y2 < 0 or y2 >= h: continue
|
| 284 |
+
if trimap[y2, x2] != 0 and trimap[y2, x2] != 1: continue
|
| 285 |
+
|
| 286 |
+
dr = image[y, x, 0] - image[y2, x2, 0]
|
| 287 |
+
dg = image[y, x, 1] - image[y2, x2, 1]
|
| 288 |
+
db = image[y, x, 2] - image[y2, x2, 2]
|
| 289 |
+
|
| 290 |
+
color_distance = np.sqrt(dr * dr + dg * dg + db * db)
|
| 291 |
+
|
| 292 |
+
spatial_distance = np.hypot(x - x2, y - y2)
|
| 293 |
+
|
| 294 |
+
if color_distance > k_c: continue
|
| 295 |
+
if spatial_distance > k_i: continue
|
| 296 |
+
|
| 297 |
+
if spatial_distance < closest:
|
| 298 |
+
closest = spatial_distance
|
| 299 |
+
expanded_trimap[y, x] = trimap[y2, x2]
|
| 300 |
+
|
| 301 |
+
@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, f4, f4, f4, f4, i8)", cache=True, parallel=True, nogil=True)
|
| 302 |
+
def sample_gathering(
|
| 303 |
+
gathering_F,
|
| 304 |
+
gathering_B,
|
| 305 |
+
gathering_alpha,
|
| 306 |
+
image,
|
| 307 |
+
trimap,
|
| 308 |
+
num_angles,
|
| 309 |
+
eN,
|
| 310 |
+
eA,
|
| 311 |
+
ef,
|
| 312 |
+
eb,
|
| 313 |
+
Np_radius,
|
| 314 |
+
):
|
| 315 |
+
h, w = trimap.shape
|
| 316 |
+
|
| 317 |
+
max_steps = 2 * max(w, h)
|
| 318 |
+
|
| 319 |
+
for y, x in pndindex((h, w)):
|
| 320 |
+
fg_samples = np.zeros((num_angles, 3), dtype=np.float32)
|
| 321 |
+
fg_samples_xy = np.zeros((num_angles, 2), dtype=np.int32)
|
| 322 |
+
bg_samples = np.zeros((num_angles, 3), dtype=np.float32)
|
| 323 |
+
bg_samples_xy = np.zeros((num_angles, 2), dtype=np.int32)
|
| 324 |
+
|
| 325 |
+
C_p = image[y, x]
|
| 326 |
+
|
| 327 |
+
gathering_alpha[y, x] = trimap[y, x]
|
| 328 |
+
|
| 329 |
+
if trimap[y, x] == 0:
|
| 330 |
+
gathering_B[y, x] = C_p
|
| 331 |
+
continue
|
| 332 |
+
|
| 333 |
+
if trimap[y, x] == 1:
|
| 334 |
+
gathering_F[y, x] = C_p
|
| 335 |
+
continue
|
| 336 |
+
|
| 337 |
+
# Fixed start angles in 8-by-8 grid for reproducible tests
|
| 338 |
+
n = 8
|
| 339 |
+
i = (x % n) + (y % n) * n
|
| 340 |
+
# Shuffle (99991 is a prime number)
|
| 341 |
+
i = (i * 99991) % (n * n)
|
| 342 |
+
start_angle = 2.0 * np.pi / (n * n) * i
|
| 343 |
+
|
| 344 |
+
num_fg_samples = 0
|
| 345 |
+
num_bg_samples = 0
|
| 346 |
+
|
| 347 |
+
for i in range(num_angles):
|
| 348 |
+
angle = 2.0 * np.pi / num_angles * i + start_angle
|
| 349 |
+
|
| 350 |
+
c = np.cos(angle)
|
| 351 |
+
s = np.sin(angle)
|
| 352 |
+
|
| 353 |
+
has_fg = False
|
| 354 |
+
has_bg = False
|
| 355 |
+
|
| 356 |
+
for step in range(max_steps):
|
| 357 |
+
if has_fg and has_bg: break
|
| 358 |
+
|
| 359 |
+
x2 = int(x + step * c)
|
| 360 |
+
y2 = int(y + step * s)
|
| 361 |
+
|
| 362 |
+
if x2 < 0 or y2 < 0 or x2 >= w or y2 >= h: break
|
| 363 |
+
|
| 364 |
+
if not has_fg and trimap[y2, x2] == 1:
|
| 365 |
+
fg_samples[num_fg_samples] = image[y2, x2]
|
| 366 |
+
fg_samples_xy[num_fg_samples, 0] = x2
|
| 367 |
+
fg_samples_xy[num_fg_samples, 1] = y2
|
| 368 |
+
num_fg_samples += 1
|
| 369 |
+
has_fg = True
|
| 370 |
+
|
| 371 |
+
if not has_bg and trimap[y2, x2] == 0:
|
| 372 |
+
bg_samples[num_bg_samples] = image[y2, x2]
|
| 373 |
+
bg_samples_xy[num_bg_samples, 0] = x2
|
| 374 |
+
bg_samples_xy[num_bg_samples, 1] = y2
|
| 375 |
+
num_bg_samples += 1
|
| 376 |
+
has_bg = True
|
| 377 |
+
|
| 378 |
+
if num_fg_samples == 0:
|
| 379 |
+
fg_samples[num_fg_samples] = gathering_F[y, x]
|
| 380 |
+
fg_samples_xy[num_fg_samples, 0] = x
|
| 381 |
+
fg_samples_xy[num_fg_samples, 1] = y
|
| 382 |
+
num_fg_samples += 1
|
| 383 |
+
|
| 384 |
+
if num_bg_samples == 0:
|
| 385 |
+
bg_samples[num_bg_samples] = gathering_B[y, x]
|
| 386 |
+
bg_samples_xy[num_bg_samples, 0] = x
|
| 387 |
+
bg_samples_xy[num_bg_samples, 1] = y
|
| 388 |
+
num_bg_samples += 1
|
| 389 |
+
|
| 390 |
+
min_Ep_f = np.inf
|
| 391 |
+
min_Ep_b = np.inf
|
| 392 |
+
|
| 393 |
+
for i in range(num_fg_samples):
|
| 394 |
+
Ep_f = Ep(image, x, y, fg_samples_xy[i, 0], fg_samples_xy[i, 1])
|
| 395 |
+
|
| 396 |
+
min_Ep_f = min(min_Ep_f, Ep_f)
|
| 397 |
+
|
| 398 |
+
for j in range(num_bg_samples):
|
| 399 |
+
Ep_b = Ep(image, x, y, bg_samples_xy[j, 0], bg_samples_xy[j, 1])
|
| 400 |
+
|
| 401 |
+
min_Ep_b = min(min_Ep_b, Ep_b)
|
| 402 |
+
|
| 403 |
+
PF_p = min_Ep_b / (min_Ep_f + min_Ep_b + 1e-5)
|
| 404 |
+
|
| 405 |
+
min_cost = np.inf
|
| 406 |
+
|
| 407 |
+
# Find best foreground/background pair
|
| 408 |
+
for i in range(num_fg_samples):
|
| 409 |
+
for j in range(num_bg_samples):
|
| 410 |
+
F = fg_samples[i]
|
| 411 |
+
B = bg_samples[j]
|
| 412 |
+
|
| 413 |
+
alpha_p = estimate_alpha(C_p, F, B)
|
| 414 |
+
|
| 415 |
+
Ap = PF_p + (1.0 - 2.0 * PF_p) * alpha_p
|
| 416 |
+
|
| 417 |
+
Dp_f = np.hypot(x - fg_samples_xy[i, 0], y - fg_samples_xy[i, 1])
|
| 418 |
+
Dp_b = np.hypot(x - bg_samples_xy[j, 0], y - bg_samples_xy[j, 1])
|
| 419 |
+
|
| 420 |
+
g_p = (
|
| 421 |
+
Np(image, x, y, F, B, Np_radius)**eN *
|
| 422 |
+
Ap**eA *
|
| 423 |
+
Dp_f**ef *
|
| 424 |
+
Dp_b**eb)
|
| 425 |
+
|
| 426 |
+
if min_cost > g_p:
|
| 427 |
+
min_cost = g_p
|
| 428 |
+
gathering_alpha[y, x] = alpha_p
|
| 429 |
+
gathering_F[y, x] = F
|
| 430 |
+
gathering_B[y, x] = B
|
| 431 |
+
|
| 432 |
+
@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], i8)", cache=True, parallel=False, nogil=True)
|
| 433 |
+
def sample_refinement(
|
| 434 |
+
refined_F,
|
| 435 |
+
refined_B,
|
| 436 |
+
refined_alpha,
|
| 437 |
+
gathering_F,
|
| 438 |
+
gathering_B,
|
| 439 |
+
image,
|
| 440 |
+
trimap,
|
| 441 |
+
radius,
|
| 442 |
+
):
|
| 443 |
+
h, w = trimap.shape
|
| 444 |
+
|
| 445 |
+
refined_F[:] = gathering_F
|
| 446 |
+
refined_B[:] = gathering_B
|
| 447 |
+
refined_alpha[:] = trimap
|
| 448 |
+
|
| 449 |
+
for y, x in pndindex((h, w)):
|
| 450 |
+
C_p = image[y, x]
|
| 451 |
+
|
| 452 |
+
if trimap[y, x] == 0 or trimap[y, x] == 1:
|
| 453 |
+
continue
|
| 454 |
+
|
| 455 |
+
max_samples = 3
|
| 456 |
+
sample_F = np.zeros((max_samples, 3), dtype=np.float32)
|
| 457 |
+
sample_B = np.zeros((max_samples, 3), dtype=np.float32)
|
| 458 |
+
sample_cost = np.zeros(max_samples, dtype=np.float32)
|
| 459 |
+
sample_cost[:] = np.inf
|
| 460 |
+
|
| 461 |
+
for dy in range(-radius, radius + 1):
|
| 462 |
+
for dx in range(-radius, radius + 1):
|
| 463 |
+
x2 = x + dx
|
| 464 |
+
y2 = y + dy
|
| 465 |
+
|
| 466 |
+
if 0 <= x2 < w and 0 <= y2 < h:
|
| 467 |
+
F_q = gathering_F[y2, x2]
|
| 468 |
+
B_q = gathering_B[y2, x2]
|
| 469 |
+
|
| 470 |
+
cost = Mp2(C_p, F_q, B_q)
|
| 471 |
+
|
| 472 |
+
i = np.argmax(sample_cost)
|
| 473 |
+
|
| 474 |
+
if cost < sample_cost[i]:
|
| 475 |
+
sample_cost[i] = cost
|
| 476 |
+
sample_F[i] = F_q
|
| 477 |
+
sample_B[i] = B_q
|
| 478 |
+
|
| 479 |
+
F_mean = sample_F.sum(axis=0) / max_samples
|
| 480 |
+
B_mean = sample_B.sum(axis=0) / max_samples
|
| 481 |
+
|
| 482 |
+
refined_F[y, x] = F_mean
|
| 483 |
+
refined_B[y, x] = B_mean
|
| 484 |
+
|
| 485 |
+
refined_alpha[y, x] = estimate_alpha(C_p, F_mean, B_mean)
|
| 486 |
+
|
| 487 |
+
@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, i8, i8, f4, f4, f4)", cache=True, parallel=True, nogil=True)
|
| 488 |
+
def local_smoothing(
|
| 489 |
+
final_F,
|
| 490 |
+
final_B,
|
| 491 |
+
final_alpha,
|
| 492 |
+
refined_F,
|
| 493 |
+
refined_B,
|
| 494 |
+
refined_alpha,
|
| 495 |
+
image,
|
| 496 |
+
trimap,
|
| 497 |
+
radius1,
|
| 498 |
+
radius2,
|
| 499 |
+
radius3,
|
| 500 |
+
sigma_sq1,
|
| 501 |
+
sigma_sq2,
|
| 502 |
+
sigma_sq3,
|
| 503 |
+
):
|
| 504 |
+
h, w = trimap.shape
|
| 505 |
+
|
| 506 |
+
final_confidence = np.zeros((h, w), dtype=np.float32)
|
| 507 |
+
W_FB = np.zeros((h, w), dtype=np.float32)
|
| 508 |
+
low_frequency_alpha = np.zeros((h, w), dtype=np.float32)
|
| 509 |
+
|
| 510 |
+
final_F[:] = refined_F
|
| 511 |
+
final_B[:] = refined_B
|
| 512 |
+
|
| 513 |
+
for y, x in pndindex((h, w)):
|
| 514 |
+
C_p = image[y, x]
|
| 515 |
+
|
| 516 |
+
if trimap[y, x] == 0 or trimap[y, x] == 1:
|
| 517 |
+
continue
|
| 518 |
+
|
| 519 |
+
F_p = np.zeros(3, dtype=np.float32)
|
| 520 |
+
B_p = np.zeros(3, dtype=np.float32)
|
| 521 |
+
|
| 522 |
+
sum_F = 0.0
|
| 523 |
+
sum_B = 0.0
|
| 524 |
+
|
| 525 |
+
alpha_p = refined_alpha[y, x]
|
| 526 |
+
|
| 527 |
+
for dy in range(-radius1, radius1 + 1):
|
| 528 |
+
for dx in range(-radius1, radius1 + 1):
|
| 529 |
+
x2 = x + dx
|
| 530 |
+
y2 = y + dy
|
| 531 |
+
|
| 532 |
+
if 0 <= x2 < w and 0 <= y2 < h:
|
| 533 |
+
# NB: Gaussian not normalized, not using confidence
|
| 534 |
+
Wc_pq = np.exp(-1.0 / sigma_sq1 * (dx * dx + dy * dy))
|
| 535 |
+
|
| 536 |
+
if x != x2 or y != y2:
|
| 537 |
+
Wc_pq *= abs(refined_alpha[y, x] - refined_alpha[y2, x2])
|
| 538 |
+
|
| 539 |
+
alpha_q = refined_alpha[y2, x2]
|
| 540 |
+
|
| 541 |
+
W_F = Wc_pq * alpha_q
|
| 542 |
+
W_B = Wc_pq * (1.0 - alpha_q)
|
| 543 |
+
|
| 544 |
+
W_F = max(W_F, 1e-5)
|
| 545 |
+
W_B = max(W_B, 1e-5)
|
| 546 |
+
|
| 547 |
+
sum_F += W_F
|
| 548 |
+
sum_B += W_B
|
| 549 |
+
|
| 550 |
+
for c in range(3):
|
| 551 |
+
F_p[c] += W_F * refined_F[y2, x2, c]
|
| 552 |
+
B_p[c] += W_B * refined_B[y2, x2, c]
|
| 553 |
+
|
| 554 |
+
F_p /= sum_F
|
| 555 |
+
B_p /= sum_B
|
| 556 |
+
|
| 557 |
+
final_F[y, x] = F_p
|
| 558 |
+
final_B[y, x] = B_p
|
| 559 |
+
|
| 560 |
+
final_alpha[y, x] = estimate_alpha(C_p, F_p, B_p)
|
| 561 |
+
|
| 562 |
+
# NB: Not using confidence
|
| 563 |
+
W_FB[y, x] = alpha_p * (1.0 - alpha_p)
|
| 564 |
+
|
| 565 |
+
for y, x in pndindex((h, w)):
|
| 566 |
+
C_p = image[y, x]
|
| 567 |
+
|
| 568 |
+
if trimap[y, x] == 0 or trimap[y, x] == 1:
|
| 569 |
+
final_confidence[y, x] = trimap[y, x]
|
| 570 |
+
continue
|
| 571 |
+
|
| 572 |
+
D_FB = 0.0
|
| 573 |
+
weight_sum = 0.0
|
| 574 |
+
for dy in range(-radius2, radius2 + 1):
|
| 575 |
+
for dx in range(-radius2, radius2 + 1):
|
| 576 |
+
x2 = x + dx
|
| 577 |
+
y2 = y + dy
|
| 578 |
+
if 0 <= x2 < w and 0 <= y2 < h:
|
| 579 |
+
weight_sum += W_FB[y2, x2]
|
| 580 |
+
D_FB += W_FB[y2, x2] * dist(final_F[y2, x2], final_B[y2, x2])
|
| 581 |
+
|
| 582 |
+
D_FB /= weight_sum + 1e-5
|
| 583 |
+
D_FB += 1e-5
|
| 584 |
+
|
| 585 |
+
FB_dist = dist(final_F[y, x], final_B[y, x])
|
| 586 |
+
|
| 587 |
+
F_p = final_F[y, x]
|
| 588 |
+
B_p = final_B[y, x]
|
| 589 |
+
|
| 590 |
+
final_confidence[y, x] = min(1.0, FB_dist / D_FB) * np.exp(-1.0 / sigma_sq2 * np.sqrt(Mp2(C_p, F_p, B_p)))
|
| 591 |
+
|
| 592 |
+
for y, x in pndindex((h, w)):
|
| 593 |
+
if trimap[y, x] == 0 or trimap[y, x] == 1:
|
| 594 |
+
final_alpha[y, x] = trimap[y, x]
|
| 595 |
+
continue
|
| 596 |
+
|
| 597 |
+
alpha_sum = 0.0
|
| 598 |
+
weight_sum = 0.0
|
| 599 |
+
for dy in range(-radius3, radius3 + 1):
|
| 600 |
+
for dx in range(-radius3, radius3 + 1):
|
| 601 |
+
x2 = x + dx
|
| 602 |
+
y2 = y + dy
|
| 603 |
+
if 0 <= x2 < w and 0 <= y2 < h:
|
| 604 |
+
# NB: Gaussian not normalized, not using final_confidence(x2, y2)
|
| 605 |
+
D_image_squared = dx * dx + dy * dy
|
| 606 |
+
is_known = trimap[y2, x2] == 0 or trimap[y2, x2] == 1
|
| 607 |
+
W_alpha = np.exp(-1.0 / sigma_sq3 * (dx * dx + dy * dy)) + is_known
|
| 608 |
+
alpha_sum += W_alpha * refined_alpha[y2, x2]
|
| 609 |
+
weight_sum += W_alpha
|
| 610 |
+
|
| 611 |
+
low_frequency_alpha[y, x] = alpha_sum / weight_sum
|
| 612 |
+
|
| 613 |
+
final_alpha[y, x] = final_confidence[y, x] * final_alpha[y, x] + (1.0 - final_confidence[y, x]) * low_frequency_alpha[y, x]
|
python_embeded/Lib/site-packages/pymatting/config/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
python_embeded/Lib/site-packages/pymatting/cutout/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from pymatting.cutout.cutout import cutout
|
python_embeded/Lib/site-packages/pymatting/cutout/cutout.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import load_image, save_image, stack_images
|
| 2 |
+
from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf
|
| 3 |
+
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def cutout(image_path, trimap_path, cutout_path):
|
| 7 |
+
"""
|
| 8 |
+
Generate a cutout image from an input image and an input trimap.
|
| 9 |
+
This method is using closed-form alpha matting as proposed by :cite:`levin2007closed` and multi-level foreground extraction :cite:`germer2020multilevel`.
|
| 10 |
+
|
| 11 |
+
Parameters
|
| 12 |
+
----------
|
| 13 |
+
image_path: str
|
| 14 |
+
Path of input image
|
| 15 |
+
trimap_path: str
|
| 16 |
+
Path of input trimap
|
| 17 |
+
cutout_path: str
|
| 18 |
+
Path of output cutout image
|
| 19 |
+
|
| 20 |
+
Example
|
| 21 |
+
-------
|
| 22 |
+
>>> cutout("../data/lemur.png", "../data/lemur_trimap.png", "lemur_cutout.png")
|
| 23 |
+
"""
|
| 24 |
+
image = load_image(image_path, "RGB")
|
| 25 |
+
trimap = load_image(trimap_path, "GRAY")
|
| 26 |
+
|
| 27 |
+
if image.shape[:2] != trimap.shape[:2]:
|
| 28 |
+
raise ValueError("Input image and trimap must have same size")
|
| 29 |
+
|
| 30 |
+
alpha = estimate_alpha_cf(image, trimap)
|
| 31 |
+
|
| 32 |
+
foreground = estimate_foreground_ml(image, alpha)
|
| 33 |
+
|
| 34 |
+
cutout = stack_images(foreground, alpha)
|
| 35 |
+
|
| 36 |
+
save_image(cutout_path, cutout)
|
python_embeded/Lib/site-packages/pymatting/foreground/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.foreground.estimate_foreground_cf import estimate_foreground_cf
|
| 2 |
+
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
|
| 3 |
+
from pymatting.foreground.estimate_foreground_ml import (
|
| 4 |
+
estimate_foreground_ml as estimate_foreground,
|
| 5 |
+
)
|
python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_cf.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.preconditioner.ichol import ichol
|
| 2 |
+
from pymatting.util.util import sparse_conv_matrix_with_offsets
|
| 3 |
+
from pymatting.solver.cg import cg
|
| 4 |
+
import scipy.sparse
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def estimate_foreground_cf(
|
| 9 |
+
image,
|
| 10 |
+
alpha,
|
| 11 |
+
regularization=1e-5,
|
| 12 |
+
rtol=1e-5,
|
| 13 |
+
neighbors=[(-1, 0), (1, 0), (0, -1), (0, 1)],
|
| 14 |
+
return_background=False,
|
| 15 |
+
foreground_guess=None,
|
| 16 |
+
background_guess=None,
|
| 17 |
+
ichol_kwargs={},
|
| 18 |
+
cg_kwargs={},
|
| 19 |
+
):
|
| 20 |
+
"""Estimates the foreground of an image given alpha matte and image.
|
| 21 |
+
|
| 22 |
+
This method is based on the publication :cite:`levin2007closed`.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
image: numpy.ndarray
|
| 27 |
+
Input image with shape :math:`h \\times w \\times d`
|
| 28 |
+
alpha: numpy.ndarray
|
| 29 |
+
Input alpha matte with shape :math:`h \\times w`
|
| 30 |
+
regularization: float
|
| 31 |
+
Regularization strength :math:`\\epsilon`, defaults to :math:`10^{-5}`
|
| 32 |
+
neighbors: list of tuples of ints
|
| 33 |
+
List of relative positions that define the neighborhood of a pixel
|
| 34 |
+
return_background: bool
|
| 35 |
+
Whether to return the estimated background in addition to the foreground
|
| 36 |
+
foreground_guess: numpy.ndarray
|
| 37 |
+
An initial guess for the foreground image in order to accelerate convergence.
|
| 38 |
+
Using input image by default.
|
| 39 |
+
background_guess: numpy.ndarray
|
| 40 |
+
An initial guess for the background image.
|
| 41 |
+
Using input image by default.
|
| 42 |
+
ichol_kwargs: dictionary
|
| 43 |
+
Keyword arguments for the incomplete Cholesky preconditioner
|
| 44 |
+
cg_kwargs: dictionary
|
| 45 |
+
Keyword arguments for the conjugate gradient descent solver
|
| 46 |
+
|
| 47 |
+
Returns
|
| 48 |
+
-------
|
| 49 |
+
F: numpy.ndarray
|
| 50 |
+
Extracted foreground
|
| 51 |
+
B: numpy.ndarray
|
| 52 |
+
Extracted background (not returned by default)
|
| 53 |
+
|
| 54 |
+
Example
|
| 55 |
+
-------
|
| 56 |
+
>>> from pymatting import *
|
| 57 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 58 |
+
>>> alpha = load_image("data/lemur/lemur_alpha.png", "GRAY")
|
| 59 |
+
>>> F = estimate_foreground_cf(image, alpha, return_background=False)
|
| 60 |
+
>>> F, B = estimate_foreground_cf(image, alpha, return_background=True)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
See Also
|
| 64 |
+
--------
|
| 65 |
+
stack_images: This function can be used to place the foreground on a new background.
|
| 66 |
+
"""
|
| 67 |
+
h, w, d = image.shape
|
| 68 |
+
|
| 69 |
+
assert alpha.shape == (h, w)
|
| 70 |
+
|
| 71 |
+
n = w * h
|
| 72 |
+
|
| 73 |
+
a = alpha.flatten()
|
| 74 |
+
|
| 75 |
+
S = None
|
| 76 |
+
for dx, dy in neighbors:
|
| 77 |
+
# directional derivative
|
| 78 |
+
D = sparse_conv_matrix_with_offsets(w, h, [1.0, -1.0], [0, dx], [0, dy])
|
| 79 |
+
|
| 80 |
+
S2 = D.T.dot(scipy.sparse.diags(regularization + np.abs(D.dot(a)))).dot(D)
|
| 81 |
+
|
| 82 |
+
S = S2 if S is None else S + S2
|
| 83 |
+
|
| 84 |
+
del D, S2
|
| 85 |
+
|
| 86 |
+
V = scipy.sparse.bmat([[S, None], [None, S]])
|
| 87 |
+
|
| 88 |
+
del S
|
| 89 |
+
|
| 90 |
+
U = scipy.sparse.bmat([[scipy.sparse.diags(a), scipy.sparse.diags(1 - a)]])
|
| 91 |
+
|
| 92 |
+
A = U.T.dot(U) + V
|
| 93 |
+
|
| 94 |
+
A.sum_duplicates()
|
| 95 |
+
|
| 96 |
+
del V
|
| 97 |
+
|
| 98 |
+
# Compute preconditioner for faster convergence
|
| 99 |
+
precondition = ichol(A, **ichol_kwargs)
|
| 100 |
+
|
| 101 |
+
# By default use input image as initialization
|
| 102 |
+
foreground = (image if foreground_guess is None else foreground_guess).copy()
|
| 103 |
+
background = (image if background_guess is None else background_guess).copy()
|
| 104 |
+
|
| 105 |
+
# For each image color channel
|
| 106 |
+
for channel in range(d):
|
| 107 |
+
image_channel = image[:, :, channel].flatten()
|
| 108 |
+
|
| 109 |
+
b = U.T.dot(image_channel)
|
| 110 |
+
|
| 111 |
+
# Initialization vector for conjugate gradient descent
|
| 112 |
+
f0 = foreground[:, :, channel].flatten()
|
| 113 |
+
b0 = background[:, :, channel].flatten()
|
| 114 |
+
fb = np.concatenate([f0, b0])
|
| 115 |
+
|
| 116 |
+
# Solve linear system
|
| 117 |
+
# A fb = b
|
| 118 |
+
# for fb using conjugate gradient descent
|
| 119 |
+
fb = cg(A, b, x0=fb, M=precondition, rtol=rtol, **cg_kwargs)
|
| 120 |
+
|
| 121 |
+
foreground[:, :, channel] = fb[:n].reshape(h, w)
|
| 122 |
+
background[:, :, channel] = fb[n:].reshape(h, w)
|
| 123 |
+
|
| 124 |
+
foreground = np.clip(foreground, 0, 1)
|
| 125 |
+
background = np.clip(background, 0, 1)
|
| 126 |
+
|
| 127 |
+
if return_background:
|
| 128 |
+
return foreground, background
|
| 129 |
+
|
| 130 |
+
return foreground
|
python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numba import njit, prange
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@njit("void(f4[:, :, :], f4[:, :, :])", cache=True, nogil=True, parallel=True)
|
| 6 |
+
def _resize_nearest_multichannel(dst, src):
|
| 7 |
+
"""
|
| 8 |
+
Internal method.
|
| 9 |
+
|
| 10 |
+
Resize image src to dst using nearest neighbors filtering.
|
| 11 |
+
Images must have multiple color channels, i.e. :code:`len(shape) == 3`.
|
| 12 |
+
|
| 13 |
+
Parameters
|
| 14 |
+
----------
|
| 15 |
+
dst: numpy.ndarray of type np.float32
|
| 16 |
+
output image
|
| 17 |
+
src: numpy.ndarray of type np.float32
|
| 18 |
+
input image
|
| 19 |
+
"""
|
| 20 |
+
h_src, w_src, depth = src.shape
|
| 21 |
+
h_dst, w_dst, depth = dst.shape
|
| 22 |
+
|
| 23 |
+
for y_dst in prange(h_dst):
|
| 24 |
+
for x_dst in range(w_dst):
|
| 25 |
+
x_src = max(0, min(w_src - 1, x_dst * w_src // w_dst))
|
| 26 |
+
y_src = max(0, min(h_src - 1, y_dst * h_src // h_dst))
|
| 27 |
+
|
| 28 |
+
for c in range(depth):
|
| 29 |
+
dst[y_dst, x_dst, c] = src[y_src, x_src, c]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@njit("void(f4[:, :], f4[:, :])", cache=True, nogil=True, parallel=True)
|
| 33 |
+
def _resize_nearest(dst, src):
|
| 34 |
+
"""
|
| 35 |
+
Internal method.
|
| 36 |
+
|
| 37 |
+
Resize image src to dst using nearest neighbors filtering.
|
| 38 |
+
Images must be grayscale, i.e. :code:`len(shape) == 3`.
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
dst: numpy.ndarray of type np.float32
|
| 43 |
+
output image
|
| 44 |
+
src: numpy.ndarray of type np.float32
|
| 45 |
+
input image
|
| 46 |
+
"""
|
| 47 |
+
h_src, w_src = src.shape
|
| 48 |
+
h_dst, w_dst = dst.shape
|
| 49 |
+
|
| 50 |
+
for y_dst in prange(h_dst):
|
| 51 |
+
for x_dst in range(w_dst):
|
| 52 |
+
x_src = max(0, min(w_src - 1, x_dst * w_src // w_dst))
|
| 53 |
+
y_src = max(0, min(h_src - 1, y_dst * h_src // h_dst))
|
| 54 |
+
|
| 55 |
+
dst[y_dst, x_dst] = src[y_src, x_src]
|
| 56 |
+
|
| 57 |
+
# TODO
|
| 58 |
+
# There should be an option to switch @njit(parallel=True) on or off.
|
| 59 |
+
# parallel=True would be faster, but might cause race conditions.
|
| 60 |
+
# User should have the option to turn it on or off.
|
| 61 |
+
@njit("Tuple((f4[:, :, :], f4[:, :, :]))(f4[:, :, :], f4[:, :], f4, i4, i4, i4, f4)", cache=True, nogil=True)
|
| 62 |
+
def _estimate_fb_ml(
|
| 63 |
+
input_image,
|
| 64 |
+
input_alpha,
|
| 65 |
+
regularization,
|
| 66 |
+
n_small_iterations,
|
| 67 |
+
n_big_iterations,
|
| 68 |
+
small_size,
|
| 69 |
+
gradient_weight,
|
| 70 |
+
):
|
| 71 |
+
h0, w0, depth = input_image.shape
|
| 72 |
+
|
| 73 |
+
dtype = np.float32
|
| 74 |
+
|
| 75 |
+
w_prev = 1
|
| 76 |
+
h_prev = 1
|
| 77 |
+
|
| 78 |
+
# Compute average foreground and background color
|
| 79 |
+
F_mean_color = np.zeros(depth, dtype=dtype)
|
| 80 |
+
B_mean_color = np.zeros(depth, dtype=dtype)
|
| 81 |
+
F_count = 0
|
| 82 |
+
B_count = 0
|
| 83 |
+
for y in range(h0):
|
| 84 |
+
for x in range(w0):
|
| 85 |
+
if input_alpha[y, x] > 0.9:
|
| 86 |
+
for c in range(depth):
|
| 87 |
+
F_mean_color[c] += input_image[y, x, c]
|
| 88 |
+
F_count += 1
|
| 89 |
+
if input_alpha[y, x] < 0.1:
|
| 90 |
+
for c in range(depth):
|
| 91 |
+
B_mean_color[c] += input_image[y, x, c]
|
| 92 |
+
B_count += 1
|
| 93 |
+
|
| 94 |
+
F_mean_color /= F_count + 1e-5
|
| 95 |
+
B_mean_color /= B_count + 1e-5
|
| 96 |
+
|
| 97 |
+
# Initialize initial foreground and background with average color
|
| 98 |
+
F_prev = np.zeros((h_prev, w_prev, depth), dtype=dtype) + F_mean_color
|
| 99 |
+
B_prev = np.zeros((h_prev, w_prev, depth), dtype=dtype) + B_mean_color
|
| 100 |
+
|
| 101 |
+
n_levels = int(np.ceil(np.log2(max(w0, h0))))
|
| 102 |
+
|
| 103 |
+
for i_level in range(n_levels + 1):
|
| 104 |
+
w = round(w0 ** (i_level / n_levels))
|
| 105 |
+
h = round(h0 ** (i_level / n_levels))
|
| 106 |
+
|
| 107 |
+
image = np.empty((h, w, depth), dtype=dtype)
|
| 108 |
+
alpha = np.empty((h, w), dtype=dtype)
|
| 109 |
+
|
| 110 |
+
_resize_nearest_multichannel(image, input_image)
|
| 111 |
+
_resize_nearest(alpha, input_alpha)
|
| 112 |
+
|
| 113 |
+
F = np.empty((h, w, depth), dtype=dtype)
|
| 114 |
+
B = np.empty((h, w, depth), dtype=dtype)
|
| 115 |
+
|
| 116 |
+
_resize_nearest_multichannel(F, F_prev)
|
| 117 |
+
_resize_nearest_multichannel(B, B_prev)
|
| 118 |
+
|
| 119 |
+
if w <= small_size and h <= small_size:
|
| 120 |
+
n_iter = n_small_iterations
|
| 121 |
+
else:
|
| 122 |
+
n_iter = n_big_iterations
|
| 123 |
+
|
| 124 |
+
b = np.zeros((2, depth), dtype=dtype)
|
| 125 |
+
|
| 126 |
+
dx = [-1, 1, 0, 0]
|
| 127 |
+
dy = [0, 0, -1, 1]
|
| 128 |
+
|
| 129 |
+
for i_iter in range(n_iter):
|
| 130 |
+
for y in prange(h):
|
| 131 |
+
for x in range(w):
|
| 132 |
+
a0 = alpha[y, x]
|
| 133 |
+
a1 = 1.0 - a0
|
| 134 |
+
|
| 135 |
+
a00 = a0 * a0
|
| 136 |
+
a01 = a0 * a1
|
| 137 |
+
# a10 = a01 can be omitted due to symmetry of matrix
|
| 138 |
+
a11 = a1 * a1
|
| 139 |
+
|
| 140 |
+
for c in range(depth):
|
| 141 |
+
b[0, c] = a0 * image[y, x, c]
|
| 142 |
+
b[1, c] = a1 * image[y, x, c]
|
| 143 |
+
|
| 144 |
+
for d in range(4):
|
| 145 |
+
x2 = max(0, min(w - 1, x + dx[d]))
|
| 146 |
+
y2 = max(0, min(h - 1, y + dy[d]))
|
| 147 |
+
|
| 148 |
+
gradient = abs(a0 - alpha[y2, x2])
|
| 149 |
+
|
| 150 |
+
da = regularization + gradient_weight * gradient
|
| 151 |
+
|
| 152 |
+
a00 += da
|
| 153 |
+
a11 += da
|
| 154 |
+
|
| 155 |
+
for c in range(depth):
|
| 156 |
+
b[0, c] += da * F[y2, x2, c]
|
| 157 |
+
b[1, c] += da * B[y2, x2, c]
|
| 158 |
+
|
| 159 |
+
determinant = a00 * a11 - a01 * a01
|
| 160 |
+
|
| 161 |
+
inv_det = 1.0 / determinant
|
| 162 |
+
|
| 163 |
+
b00 = inv_det * a11
|
| 164 |
+
b01 = inv_det * -a01
|
| 165 |
+
b11 = inv_det * a00
|
| 166 |
+
|
| 167 |
+
for c in range(depth):
|
| 168 |
+
F_c = b00 * b[0, c] + b01 * b[1, c]
|
| 169 |
+
B_c = b01 * b[0, c] + b11 * b[1, c]
|
| 170 |
+
|
| 171 |
+
F_c = max(0.0, min(1.0, F_c))
|
| 172 |
+
B_c = max(0.0, min(1.0, B_c))
|
| 173 |
+
|
| 174 |
+
F[y, x, c] = F_c
|
| 175 |
+
B[y, x, c] = B_c
|
| 176 |
+
|
| 177 |
+
F_prev = F
|
| 178 |
+
B_prev = B
|
| 179 |
+
|
| 180 |
+
w_prev = w
|
| 181 |
+
h_prev = h
|
| 182 |
+
|
| 183 |
+
return F, B
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def estimate_foreground_ml(
|
| 187 |
+
image,
|
| 188 |
+
alpha,
|
| 189 |
+
regularization=1e-5,
|
| 190 |
+
n_small_iterations=10,
|
| 191 |
+
n_big_iterations=2,
|
| 192 |
+
small_size=32,
|
| 193 |
+
return_background=False,
|
| 194 |
+
gradient_weight=1.0,
|
| 195 |
+
):
|
| 196 |
+
"""Estimates the foreground of an image given its alpha matte.
|
| 197 |
+
|
| 198 |
+
See :cite:`germer2020multilevel` for reference.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
image: numpy.ndarray
|
| 203 |
+
Input image with shape :math:`h \\times w \\times d`
|
| 204 |
+
alpha: numpy.ndarray
|
| 205 |
+
Input alpha matte shape :math:`h \\times w`
|
| 206 |
+
regularization: float
|
| 207 |
+
Regularization strength :math:`\\epsilon`, defaults to :math:`10^{-5}`.
|
| 208 |
+
Higher regularization results in smoother colors.
|
| 209 |
+
n_small_iterations: int
|
| 210 |
+
Number of iterations performed on small scale, defaults to :math:`10`
|
| 211 |
+
n_big_iterations: int
|
| 212 |
+
Number of iterations performed on large scale, defaults to :math:`2`
|
| 213 |
+
small_size: int
|
| 214 |
+
Threshold that determines at which size `n_small_iterations` should be used
|
| 215 |
+
return_background: bool
|
| 216 |
+
Whether to return the estimated background in addition to the foreground
|
| 217 |
+
gradient_weight: float
|
| 218 |
+
Larger values enforce smoother foregrounds, defaults to :math:`1`
|
| 219 |
+
|
| 220 |
+
Returns
|
| 221 |
+
-------
|
| 222 |
+
F: numpy.ndarray
|
| 223 |
+
Extracted foreground
|
| 224 |
+
B: numpy.ndarray
|
| 225 |
+
Extracted background
|
| 226 |
+
|
| 227 |
+
Example
|
| 228 |
+
-------
|
| 229 |
+
>>> from pymatting import *
|
| 230 |
+
>>> image = load_image("data/lemur/lemur.png", "RGB")
|
| 231 |
+
>>> alpha = load_image("data/lemur/lemur_alpha.png", "GRAY")
|
| 232 |
+
>>> F = estimate_foreground_ml(image, alpha, return_background=False)
|
| 233 |
+
>>> F, B = estimate_foreground_ml(image, alpha, return_background=True)
|
| 234 |
+
|
| 235 |
+
See Also
|
| 236 |
+
--------
|
| 237 |
+
stack_images: This function can be used to place the foreground on a new background.
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
foreground, background = _estimate_fb_ml(
|
| 241 |
+
image.astype(np.float32),
|
| 242 |
+
alpha.astype(np.float32),
|
| 243 |
+
regularization,
|
| 244 |
+
n_small_iterations,
|
| 245 |
+
n_big_iterations,
|
| 246 |
+
small_size,
|
| 247 |
+
gradient_weight,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if return_background:
|
| 251 |
+
return foreground, background
|
| 252 |
+
|
| 253 |
+
return foreground
|
python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_cupy.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cupy as cp
|
| 3 |
+
from pymatting.util.util import div_round_up
|
| 4 |
+
|
| 5 |
+
_resize_nearest = cp.RawKernel(
|
| 6 |
+
r"""
|
| 7 |
+
extern "C" __global__
|
| 8 |
+
void resize_nearest(
|
| 9 |
+
float *dst,
|
| 10 |
+
const float *src,
|
| 11 |
+
int w_src, int h_src,
|
| 12 |
+
int w_dst, int h_dst,
|
| 13 |
+
int depth
|
| 14 |
+
){
|
| 15 |
+
int x_dst = blockDim.x * blockIdx.x + threadIdx.x;
|
| 16 |
+
int y_dst = blockDim.y * blockIdx.y + threadIdx.y;
|
| 17 |
+
|
| 18 |
+
if (x_dst >= w_dst || y_dst >= h_dst) return;
|
| 19 |
+
|
| 20 |
+
int x_src = min(x_dst * w_src / w_dst, w_src - 1);
|
| 21 |
+
int y_src = min(y_dst * h_src / h_dst, h_src - 1);
|
| 22 |
+
|
| 23 |
+
float *ptr_dst = dst + (x_dst + y_dst * w_dst) * depth;
|
| 24 |
+
const float *ptr_src = src + (x_src + y_src * w_src) * depth;
|
| 25 |
+
|
| 26 |
+
for (int channel = 0; channel < depth; channel++){
|
| 27 |
+
ptr_dst[channel] = ptr_src[channel];
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
""",
|
| 31 |
+
"resize_nearest",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
ml_iteration = cp.RawKernel(
|
| 35 |
+
r"""
|
| 36 |
+
extern "C" __global__
|
| 37 |
+
void ml_iteration(
|
| 38 |
+
float *F,
|
| 39 |
+
float *B,
|
| 40 |
+
const float *F_prev,
|
| 41 |
+
const float *B_prev,
|
| 42 |
+
const float *image,
|
| 43 |
+
const float *alpha,
|
| 44 |
+
int w,
|
| 45 |
+
int h,
|
| 46 |
+
float regularization
|
| 47 |
+
){
|
| 48 |
+
int x = blockDim.x * blockIdx.x + threadIdx.x;
|
| 49 |
+
int y = blockDim.y * blockIdx.y + threadIdx.y;
|
| 50 |
+
|
| 51 |
+
int i = x + y * w;
|
| 52 |
+
|
| 53 |
+
if (x >= w || y >= h) return;
|
| 54 |
+
|
| 55 |
+
float a0 = alpha[i];
|
| 56 |
+
float a1 = 1.0f - a0;
|
| 57 |
+
|
| 58 |
+
float b00 = a0 * image[i * 3 + 0];
|
| 59 |
+
float b01 = a0 * image[i * 3 + 1];
|
| 60 |
+
float b02 = a0 * image[i * 3 + 2];
|
| 61 |
+
|
| 62 |
+
float b10 = a1 * image[i * 3 + 0];
|
| 63 |
+
float b11 = a1 * image[i * 3 + 1];
|
| 64 |
+
float b12 = a1 * image[i * 3 + 2];
|
| 65 |
+
|
| 66 |
+
int js[4] = {
|
| 67 |
+
max( 0, x - 1) + y * w,
|
| 68 |
+
min(w - 1, x + 1) + y * w,
|
| 69 |
+
x + max( 0, y - 1) * w,
|
| 70 |
+
x + min(h - 1, y + 1) * w,
|
| 71 |
+
};
|
| 72 |
+
|
| 73 |
+
float a_sum = 0.0f;
|
| 74 |
+
|
| 75 |
+
for (int d = 0; d < 4; d++){
|
| 76 |
+
int j = js[d];
|
| 77 |
+
|
| 78 |
+
float da = regularization + fabsf(a0 - alpha[j]);
|
| 79 |
+
|
| 80 |
+
a_sum += da;
|
| 81 |
+
|
| 82 |
+
b00 += da * F_prev[j * 3 + 0];
|
| 83 |
+
b01 += da * F_prev[j * 3 + 1];
|
| 84 |
+
b02 += da * F_prev[j * 3 + 2];
|
| 85 |
+
|
| 86 |
+
b10 += da * B_prev[j * 3 + 0];
|
| 87 |
+
b11 += da * B_prev[j * 3 + 1];
|
| 88 |
+
b12 += da * B_prev[j * 3 + 2];
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
float a00 = a0 * a0 + a_sum;
|
| 92 |
+
float a11 = a1 * a1 + a_sum;
|
| 93 |
+
float a01 = a0 * a1;
|
| 94 |
+
|
| 95 |
+
float inv_det = 1.0f / (a00 * a11 - a01 * a01);
|
| 96 |
+
|
| 97 |
+
F[i * 3 + 0] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b00 - a01 * b10)));
|
| 98 |
+
F[i * 3 + 1] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b01 - a01 * b11)));
|
| 99 |
+
F[i * 3 + 2] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b02 - a01 * b12)));
|
| 100 |
+
|
| 101 |
+
B[i * 3 + 0] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b10 - a01 * b00)));
|
| 102 |
+
B[i * 3 + 1] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b11 - a01 * b01)));
|
| 103 |
+
B[i * 3 + 2] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b12 - a01 * b02)));
|
| 104 |
+
}
|
| 105 |
+
""",
|
| 106 |
+
"ml_iteration",
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def estimate_foreground_ml_cupy(
|
| 111 |
+
input_image,
|
| 112 |
+
input_alpha,
|
| 113 |
+
regularization=1e-5,
|
| 114 |
+
n_small_iterations=10,
|
| 115 |
+
n_big_iterations=2,
|
| 116 |
+
small_size=32,
|
| 117 |
+
block_size=(32, 32),
|
| 118 |
+
return_background=False,
|
| 119 |
+
to_numpy=True,
|
| 120 |
+
):
|
| 121 |
+
"""See the :code:`estimate_foreground` method for documentation."""
|
| 122 |
+
h0, w0, depth = input_image.shape
|
| 123 |
+
|
| 124 |
+
assert depth == 3
|
| 125 |
+
|
| 126 |
+
n = h0 * w0 * depth
|
| 127 |
+
|
| 128 |
+
if isinstance(input_image, cp.ndarray):
|
| 129 |
+
input_image = input_image.astype(cp.float32).ravel()
|
| 130 |
+
else:
|
| 131 |
+
input_image = cp.asarray(input_image.astype(np.float32).flatten())
|
| 132 |
+
|
| 133 |
+
if isinstance(input_alpha, cp.ndarray):
|
| 134 |
+
input_alpha = input_alpha.astype(cp.float32).ravel()
|
| 135 |
+
else:
|
| 136 |
+
input_alpha = cp.asarray(input_alpha.astype(np.float32).flatten())
|
| 137 |
+
|
| 138 |
+
F_prev = cp.zeros(n, dtype=cp.float32)
|
| 139 |
+
B_prev = cp.zeros(n, dtype=cp.float32)
|
| 140 |
+
|
| 141 |
+
F = cp.zeros(n, dtype=cp.float32)
|
| 142 |
+
B = cp.zeros(n, dtype=cp.float32)
|
| 143 |
+
|
| 144 |
+
image_level = cp.zeros(n, dtype=cp.float32)
|
| 145 |
+
alpha_level = cp.zeros(h0 * w0, dtype=cp.float32)
|
| 146 |
+
|
| 147 |
+
n_levels = (max(w0, h0) - 1).bit_length()
|
| 148 |
+
|
| 149 |
+
w_prev = 1
|
| 150 |
+
h_prev = 1
|
| 151 |
+
|
| 152 |
+
def resize_nearest(dst, src, w_src, h_src, w_dst, h_dst, depth):
|
| 153 |
+
grid_size = (
|
| 154 |
+
div_round_up(w_dst, block_size[0]),
|
| 155 |
+
div_round_up(h_dst, block_size[1]),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
_resize_nearest(
|
| 159 |
+
grid_size,
|
| 160 |
+
block_size,
|
| 161 |
+
(
|
| 162 |
+
dst,
|
| 163 |
+
src,
|
| 164 |
+
w_src,
|
| 165 |
+
h_src,
|
| 166 |
+
w_dst,
|
| 167 |
+
h_dst,
|
| 168 |
+
depth,
|
| 169 |
+
),
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
resize_nearest(F, input_image, w0, h0, w_prev, h_prev, depth)
|
| 173 |
+
resize_nearest(B, input_image, w0, h0, w_prev, h_prev, depth)
|
| 174 |
+
|
| 175 |
+
for i_level in range(n_levels + 1):
|
| 176 |
+
w = round(w0 ** (i_level / n_levels))
|
| 177 |
+
h = round(h0 ** (i_level / n_levels))
|
| 178 |
+
|
| 179 |
+
resize_nearest(image_level, input_image, w0, h0, w, h, depth)
|
| 180 |
+
resize_nearest(alpha_level, input_alpha, w0, h0, w, h, 1)
|
| 181 |
+
|
| 182 |
+
resize_nearest(F_prev, F, w_prev, h_prev, w, h, depth)
|
| 183 |
+
resize_nearest(B_prev, B, w_prev, h_prev, w, h, depth)
|
| 184 |
+
|
| 185 |
+
# Do more iterations for low resolution.
|
| 186 |
+
n_iter = n_big_iterations
|
| 187 |
+
if min(w, h) <= small_size:
|
| 188 |
+
n_iter = n_small_iterations
|
| 189 |
+
|
| 190 |
+
grid_size = (div_round_up(w, block_size[0]), div_round_up(h, block_size[1]))
|
| 191 |
+
|
| 192 |
+
for i_iter in range(n_iter):
|
| 193 |
+
ml_iteration(
|
| 194 |
+
grid_size,
|
| 195 |
+
block_size,
|
| 196 |
+
(
|
| 197 |
+
F,
|
| 198 |
+
B,
|
| 199 |
+
F_prev,
|
| 200 |
+
B_prev,
|
| 201 |
+
image_level,
|
| 202 |
+
alpha_level,
|
| 203 |
+
w,
|
| 204 |
+
h,
|
| 205 |
+
np.float32(regularization),
|
| 206 |
+
),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
F_prev, F = F, F_prev
|
| 210 |
+
B_prev, B = B, B_prev
|
| 211 |
+
|
| 212 |
+
w_prev = w
|
| 213 |
+
h_prev = h
|
| 214 |
+
|
| 215 |
+
# Reshape back to original shape.
|
| 216 |
+
F = F.reshape(h0, w0, depth)
|
| 217 |
+
B = B.reshape(h0, w0, depth)
|
| 218 |
+
|
| 219 |
+
# Convert to NumPy if requested
|
| 220 |
+
if to_numpy:
|
| 221 |
+
F_out = cp.asnumpy(F)
|
| 222 |
+
B_out = cp.asnumpy(B)
|
| 223 |
+
else:
|
| 224 |
+
F_out = F
|
| 225 |
+
B_out = B
|
| 226 |
+
|
| 227 |
+
if return_background:
|
| 228 |
+
return F_out, B_out
|
| 229 |
+
|
| 230 |
+
return F_out
|
python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_pyopencl.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pyopencl as cl
|
| 4 |
+
|
| 5 |
+
source = """
|
| 6 |
+
__kernel void resize_nearest(
|
| 7 |
+
__global float *dst,
|
| 8 |
+
__global const float *src,
|
| 9 |
+
int w_src, int h_src,
|
| 10 |
+
int w_dst, int h_dst,
|
| 11 |
+
int depth
|
| 12 |
+
){
|
| 13 |
+
int x_dst = get_global_id(0);
|
| 14 |
+
int y_dst = get_global_id(1);
|
| 15 |
+
|
| 16 |
+
if (x_dst >= w_dst || y_dst >= h_dst) return;
|
| 17 |
+
|
| 18 |
+
int x_src = min(x_dst * w_src / w_dst, w_src - 1);
|
| 19 |
+
int y_src = min(y_dst * h_src / h_dst, h_src - 1);
|
| 20 |
+
|
| 21 |
+
__global float *ptr_dst = dst + (x_dst + y_dst * w_dst) * depth;
|
| 22 |
+
__global const float *ptr_src = src + (x_src + y_src * w_src) * depth;
|
| 23 |
+
|
| 24 |
+
for (int channel = 0; channel < depth; channel++){
|
| 25 |
+
ptr_dst[channel] = ptr_src[channel];
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
__kernel void ml_iteration(
|
| 30 |
+
__global float *F,
|
| 31 |
+
__global float *B,
|
| 32 |
+
__global const float *F_prev,
|
| 33 |
+
__global const float *B_prev,
|
| 34 |
+
__global const float *image,
|
| 35 |
+
__global const float *alpha,
|
| 36 |
+
int w,
|
| 37 |
+
int h,
|
| 38 |
+
float regularization
|
| 39 |
+
){
|
| 40 |
+
int x = get_global_id(0);
|
| 41 |
+
int y = get_global_id(1);
|
| 42 |
+
|
| 43 |
+
int i = x + y * w;
|
| 44 |
+
|
| 45 |
+
if (x >= w || y >= h) return;
|
| 46 |
+
|
| 47 |
+
float a0 = alpha[i];
|
| 48 |
+
float a1 = 1.0f - a0;
|
| 49 |
+
|
| 50 |
+
float b00 = a0 * image[i * 3 + 0];
|
| 51 |
+
float b01 = a0 * image[i * 3 + 1];
|
| 52 |
+
float b02 = a0 * image[i * 3 + 2];
|
| 53 |
+
|
| 54 |
+
float b10 = a1 * image[i * 3 + 0];
|
| 55 |
+
float b11 = a1 * image[i * 3 + 1];
|
| 56 |
+
float b12 = a1 * image[i * 3 + 2];
|
| 57 |
+
|
| 58 |
+
int js[4] = {
|
| 59 |
+
max( 0, x - 1) + y * w,
|
| 60 |
+
min(w - 1, x + 1) + y * w,
|
| 61 |
+
x + max( 0, y - 1) * w,
|
| 62 |
+
x + min(h - 1, y + 1) * w,
|
| 63 |
+
};
|
| 64 |
+
|
| 65 |
+
float a_sum = 0.0f;
|
| 66 |
+
|
| 67 |
+
for (int d = 0; d < 4; d++){
|
| 68 |
+
int j = js[d];
|
| 69 |
+
|
| 70 |
+
float da = regularization + fabs(a0 - alpha[j]);
|
| 71 |
+
|
| 72 |
+
a_sum += da;
|
| 73 |
+
|
| 74 |
+
b00 += da * F_prev[j * 3 + 0];
|
| 75 |
+
b01 += da * F_prev[j * 3 + 1];
|
| 76 |
+
b02 += da * F_prev[j * 3 + 2];
|
| 77 |
+
|
| 78 |
+
b10 += da * B_prev[j * 3 + 0];
|
| 79 |
+
b11 += da * B_prev[j * 3 + 1];
|
| 80 |
+
b12 += da * B_prev[j * 3 + 2];
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
float a00 = a0 * a0 + a_sum;
|
| 84 |
+
float a11 = a1 * a1 + a_sum;
|
| 85 |
+
float a01 = a0 * a1;
|
| 86 |
+
|
| 87 |
+
float inv_det = 1.0f / (a00 * a11 - a01 * a01);
|
| 88 |
+
|
| 89 |
+
F[i * 3 + 0] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b00 - a01 * b10)));
|
| 90 |
+
F[i * 3 + 1] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b01 - a01 * b11)));
|
| 91 |
+
F[i * 3 + 2] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b02 - a01 * b12)));
|
| 92 |
+
B[i * 3 + 0] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b10 - a01 * b00)));
|
| 93 |
+
B[i * 3 + 1] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b11 - a01 * b01)));
|
| 94 |
+
B[i * 3 + 2] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b12 - a01 * b02)));
|
| 95 |
+
}
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
platform = cl.get_platforms()[0]
|
| 99 |
+
device = platform.get_devices(cl.device_type.GPU)[0]
|
| 100 |
+
context = cl.Context([device])
|
| 101 |
+
queue = cl.CommandQueue(context)
|
| 102 |
+
program = cl.Program(context, source).build()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def estimate_foreground_ml_pyopencl(
|
| 106 |
+
input_image,
|
| 107 |
+
input_alpha,
|
| 108 |
+
regularization=1e-5,
|
| 109 |
+
n_small_iterations=10,
|
| 110 |
+
n_big_iterations=2,
|
| 111 |
+
small_size=32,
|
| 112 |
+
return_background=False,
|
| 113 |
+
):
|
| 114 |
+
"""See the :code:`estimate_foreground` method for documentation."""
|
| 115 |
+
|
| 116 |
+
def upload(array):
|
| 117 |
+
hostbuf = array.astype(np.float32).flatten()
|
| 118 |
+
return cl.Buffer(
|
| 119 |
+
context,
|
| 120 |
+
cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR,
|
| 121 |
+
hostbuf=hostbuf,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def alloc(*shape):
|
| 125 |
+
n = math.prod(shape)
|
| 126 |
+
buffer = cl.Buffer(context, cl.mem_flags.READ_WRITE, n * 4)
|
| 127 |
+
zero = np.uint32(0)
|
| 128 |
+
cl.enqueue_fill_buffer(queue, buffer, zero, 0, n*4)
|
| 129 |
+
return buffer
|
| 130 |
+
|
| 131 |
+
def download(device_buf, shape):
|
| 132 |
+
host_buf = np.empty(shape, dtype=np.float32)
|
| 133 |
+
|
| 134 |
+
cl.enqueue_copy(queue, host_buf, device_buf)
|
| 135 |
+
|
| 136 |
+
return host_buf.reshape(shape)
|
| 137 |
+
|
| 138 |
+
h0, w0, depth = input_image.shape
|
| 139 |
+
|
| 140 |
+
assert depth == 3
|
| 141 |
+
|
| 142 |
+
n = h0 * w0 * depth
|
| 143 |
+
|
| 144 |
+
input_image = upload(input_image)
|
| 145 |
+
input_alpha = upload(input_alpha)
|
| 146 |
+
|
| 147 |
+
F_prev = alloc(n)
|
| 148 |
+
B_prev = alloc(n)
|
| 149 |
+
|
| 150 |
+
F = alloc(n)
|
| 151 |
+
B = alloc(n)
|
| 152 |
+
|
| 153 |
+
image_level = alloc(n)
|
| 154 |
+
alpha_level = alloc(h0 * w0)
|
| 155 |
+
|
| 156 |
+
n_levels = (max(w0, h0) - 1).bit_length()
|
| 157 |
+
|
| 158 |
+
def resize_nearest(dst, src, w_src, h_src, w_dst, h_dst, depth):
|
| 159 |
+
program.resize_nearest(
|
| 160 |
+
queue,
|
| 161 |
+
(w_dst, h_dst),
|
| 162 |
+
None,
|
| 163 |
+
dst,
|
| 164 |
+
src,
|
| 165 |
+
*np.int32([w_src, h_src, w_dst, h_dst, depth])
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
w_prev = 1
|
| 169 |
+
h_prev = 1
|
| 170 |
+
|
| 171 |
+
resize_nearest(F, input_image, w0, h0, w_prev, h_prev, depth)
|
| 172 |
+
resize_nearest(B, input_image, w0, h0, w_prev, h_prev, depth)
|
| 173 |
+
|
| 174 |
+
for i_level in range(n_levels + 1):
|
| 175 |
+
w = round(w0 ** (i_level / n_levels))
|
| 176 |
+
h = round(h0 ** (i_level / n_levels))
|
| 177 |
+
|
| 178 |
+
resize_nearest(image_level, input_image, w0, h0, w, h, depth)
|
| 179 |
+
resize_nearest(alpha_level, input_alpha, w0, h0, w, h, 1)
|
| 180 |
+
|
| 181 |
+
resize_nearest(F_prev, F, w_prev, h_prev, w, h, depth)
|
| 182 |
+
resize_nearest(B_prev, B, w_prev, h_prev, w, h, depth)
|
| 183 |
+
|
| 184 |
+
# Do more iterations for low resolution.
|
| 185 |
+
n_iter = n_big_iterations
|
| 186 |
+
if min(w, h) <= small_size:
|
| 187 |
+
n_iter = n_small_iterations
|
| 188 |
+
|
| 189 |
+
for i_iter in range(n_iter):
|
| 190 |
+
program.ml_iteration(
|
| 191 |
+
queue,
|
| 192 |
+
(w, h),
|
| 193 |
+
None,
|
| 194 |
+
F,
|
| 195 |
+
B,
|
| 196 |
+
F_prev,
|
| 197 |
+
B_prev,
|
| 198 |
+
image_level,
|
| 199 |
+
alpha_level,
|
| 200 |
+
np.int32(w),
|
| 201 |
+
np.int32(h),
|
| 202 |
+
np.float32(regularization),
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
F_prev, F = F, F_prev
|
| 206 |
+
B_prev, B = B, B_prev
|
| 207 |
+
|
| 208 |
+
w_prev = w
|
| 209 |
+
h_prev = h
|
| 210 |
+
|
| 211 |
+
F_host = download(F, (h0, w0, depth))
|
| 212 |
+
B_host = download(B, (h0, w0, depth))
|
| 213 |
+
|
| 214 |
+
for buf in [
|
| 215 |
+
F,
|
| 216 |
+
B,
|
| 217 |
+
F_prev,
|
| 218 |
+
B_prev,
|
| 219 |
+
input_image,
|
| 220 |
+
input_alpha,
|
| 221 |
+
image_level,
|
| 222 |
+
alpha_level,
|
| 223 |
+
]:
|
| 224 |
+
buf.release()
|
| 225 |
+
|
| 226 |
+
if return_background:
|
| 227 |
+
return F_host, B_host
|
| 228 |
+
|
| 229 |
+
return F_host
|
python_embeded/Lib/site-packages/pymatting/laplacian/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.laplacian.cf_laplacian import cf_laplacian
|
| 2 |
+
from pymatting.laplacian.knn_laplacian import knn_laplacian
|
| 3 |
+
from pymatting.laplacian.lkm_laplacian import lkm_laplacian
|
| 4 |
+
from pymatting.laplacian.rw_laplacian import rw_laplacian
|
| 5 |
+
from pymatting.laplacian.lbdm_laplacian import lbdm_laplacian
|
| 6 |
+
from pymatting.laplacian.uniform_laplacian import uniform_laplacian
|
| 7 |
+
from pymatting.laplacian.laplacian import make_linear_system
|
| 8 |
+
|
| 9 |
+
LAPLACIANS = [
|
| 10 |
+
cf_laplacian,
|
| 11 |
+
knn_laplacian,
|
| 12 |
+
lbdm_laplacian,
|
| 13 |
+
rw_laplacian,
|
| 14 |
+
uniform_laplacian,
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
LAPLACIAN_OPERATORS = [
|
| 18 |
+
lkm_laplacian,
|
| 19 |
+
]
|
python_embeded/Lib/site-packages/pymatting/laplacian/cf_laplacian.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
from numba import njit
|
| 4 |
+
|
| 5 |
+
@njit("void(f8[:, :, :], f8, i8, f8[:, :, :], i8[:], i8[:], b1[:, :])", cache=True, nogil=True)
|
| 6 |
+
def _cf_laplacian(image, epsilon, r, values, indices, indptr, is_known):
|
| 7 |
+
h, w, d = image.shape
|
| 8 |
+
assert d == 3
|
| 9 |
+
size = 2 * r + 1
|
| 10 |
+
window_area = size * size
|
| 11 |
+
|
| 12 |
+
for yi in range(h):
|
| 13 |
+
for xi in range(w):
|
| 14 |
+
i = xi + yi * w
|
| 15 |
+
k = i * (4 * r + 1) ** 2
|
| 16 |
+
for yj in range(yi - 2 * r, yi + 2 * r + 1):
|
| 17 |
+
for xj in range(xi - 2 * r, xi + 2 * r + 1):
|
| 18 |
+
j = xj + yj * w
|
| 19 |
+
|
| 20 |
+
if 0 <= xj < w and 0 <= yj < h:
|
| 21 |
+
indices[k] = j
|
| 22 |
+
|
| 23 |
+
k += 1
|
| 24 |
+
|
| 25 |
+
indptr[i + 1] = k
|
| 26 |
+
|
| 27 |
+
# Centered and normalized window colors
|
| 28 |
+
c = np.zeros((2 * r + 1, 2 * r + 1, 3))
|
| 29 |
+
|
| 30 |
+
# For each pixel of image
|
| 31 |
+
for y in range(r, h - r):
|
| 32 |
+
for x in range(r, w - r):
|
| 33 |
+
|
| 34 |
+
if np.all(is_known[y - r : y + r + 1, x - r : x + r + 1]):
|
| 35 |
+
continue
|
| 36 |
+
|
| 37 |
+
# For each color channel
|
| 38 |
+
for dc in range(3):
|
| 39 |
+
# Calculate sum of color channel in window
|
| 40 |
+
s = 0.0
|
| 41 |
+
for dy in range(size):
|
| 42 |
+
for dx in range(size):
|
| 43 |
+
s += image[y + dy - r, x + dx - r, dc]
|
| 44 |
+
|
| 45 |
+
# Calculate centered window color
|
| 46 |
+
for dy in range(2 * r + 1):
|
| 47 |
+
for dx in range(2 * r + 1):
|
| 48 |
+
c[dy, dx, dc] = (
|
| 49 |
+
image[y + dy - r, x + dx - r, dc] - s / window_area
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Calculate covariance matrix over color channels with epsilon regularization
|
| 53 |
+
a00 = epsilon
|
| 54 |
+
a01 = 0.0
|
| 55 |
+
a02 = 0.0
|
| 56 |
+
a11 = epsilon
|
| 57 |
+
a12 = 0.0
|
| 58 |
+
a22 = epsilon
|
| 59 |
+
|
| 60 |
+
for dy in range(size):
|
| 61 |
+
for dx in range(size):
|
| 62 |
+
a00 += c[dy, dx, 0] * c[dy, dx, 0]
|
| 63 |
+
a01 += c[dy, dx, 0] * c[dy, dx, 1]
|
| 64 |
+
a02 += c[dy, dx, 0] * c[dy, dx, 2]
|
| 65 |
+
a11 += c[dy, dx, 1] * c[dy, dx, 1]
|
| 66 |
+
a12 += c[dy, dx, 1] * c[dy, dx, 2]
|
| 67 |
+
a22 += c[dy, dx, 2] * c[dy, dx, 2]
|
| 68 |
+
|
| 69 |
+
a00 /= window_area
|
| 70 |
+
a01 /= window_area
|
| 71 |
+
a02 /= window_area
|
| 72 |
+
a11 /= window_area
|
| 73 |
+
a12 /= window_area
|
| 74 |
+
a22 /= window_area
|
| 75 |
+
|
| 76 |
+
det = (
|
| 77 |
+
a00 * a12 * a12
|
| 78 |
+
+ a01 * a01 * a22
|
| 79 |
+
+ a02 * a02 * a11
|
| 80 |
+
- a00 * a11 * a22
|
| 81 |
+
- 2 * a01 * a02 * a12
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
inv_det = 1.0 / det
|
| 85 |
+
|
| 86 |
+
# Calculate inverse covariance matrix
|
| 87 |
+
m00 = (a12 * a12 - a11 * a22) * inv_det
|
| 88 |
+
m01 = (a01 * a22 - a02 * a12) * inv_det
|
| 89 |
+
m02 = (a02 * a11 - a01 * a12) * inv_det
|
| 90 |
+
m11 = (a02 * a02 - a00 * a22) * inv_det
|
| 91 |
+
m12 = (a00 * a12 - a01 * a02) * inv_det
|
| 92 |
+
m22 = (a01 * a01 - a00 * a11) * inv_det
|
| 93 |
+
|
| 94 |
+
# For each pair ((xi, yi), (xj, yj)) in a (2 r + 1)x(2 r + 1) window
|
| 95 |
+
for dyi in range(2 * r + 1):
|
| 96 |
+
for dxi in range(2 * r + 1):
|
| 97 |
+
s = c[dyi, dxi, 0]
|
| 98 |
+
t = c[dyi, dxi, 1]
|
| 99 |
+
u = c[dyi, dxi, 2]
|
| 100 |
+
|
| 101 |
+
c0 = m00 * s + m01 * t + m02 * u
|
| 102 |
+
c1 = m01 * s + m11 * t + m12 * u
|
| 103 |
+
c2 = m02 * s + m12 * t + m22 * u
|
| 104 |
+
|
| 105 |
+
for dyj in range(2 * r + 1):
|
| 106 |
+
for dxj in range(2 * r + 1):
|
| 107 |
+
xi = x + dxi - r
|
| 108 |
+
yi = y + dyi - r
|
| 109 |
+
xj = x + dxj - r
|
| 110 |
+
yj = y + dyj - r
|
| 111 |
+
|
| 112 |
+
i = xi + yi * w
|
| 113 |
+
j = xj + yj * w
|
| 114 |
+
|
| 115 |
+
# Calculate contribution of pixel pair to L_ij
|
| 116 |
+
temp = (
|
| 117 |
+
c0 * c[dyj, dxj, 0]
|
| 118 |
+
+ c1 * c[dyj, dxj, 1]
|
| 119 |
+
+ c2 * c[dyj, dxj, 2]
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
value = (1.0 if (i == j) else 0.0) - (
|
| 123 |
+
1 + temp
|
| 124 |
+
) / window_area
|
| 125 |
+
|
| 126 |
+
dx = xj - xi + 2 * r
|
| 127 |
+
dy = yj - yi + 2 * r
|
| 128 |
+
|
| 129 |
+
values[i, dy, dx] += value
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def cf_laplacian(image, epsilon=1e-7, radius=1, is_known=None):
|
| 133 |
+
"""
|
| 134 |
+
This function implements the alpha estimator for closed-form alpha matting
|
| 135 |
+
as proposed by :cite:`levin2007closed`.
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
----------
|
| 139 |
+
image: numpy.ndarray
|
| 140 |
+
Image with shape :math:`h\\times w \\times 3`
|
| 141 |
+
epsilon: float
|
| 142 |
+
Regularization strength, defaults to :math:`10^{-7}`. Strong
|
| 143 |
+
regularization improves convergence but results in smoother alpha mattes.
|
| 144 |
+
radius: int
|
| 145 |
+
Radius of local window size, defaults to :math:`1`, i.e. only adjacent
|
| 146 |
+
pixels are considered.
|
| 147 |
+
The size of the local window is given as :math:`(2 r + 1)^2`, where
|
| 148 |
+
:math:`r` denotes the radius. A larger radius might lead to
|
| 149 |
+
violated color line constraints, but also
|
| 150 |
+
favors further propagation of information within the image.
|
| 151 |
+
is_known: numpy.ndarray
|
| 152 |
+
Binary mask of pixels for which to compute the laplacian matrix.
|
| 153 |
+
Laplacian entries for known pixels will have undefined values.
|
| 154 |
+
|
| 155 |
+
Returns
|
| 156 |
+
-------
|
| 157 |
+
L: scipy.sparse.spmatrix
|
| 158 |
+
Matting Laplacian
|
| 159 |
+
"""
|
| 160 |
+
h, w, d = image.shape
|
| 161 |
+
n = h * w
|
| 162 |
+
|
| 163 |
+
if is_known is None:
|
| 164 |
+
is_known = np.zeros((h, w), dtype=np.bool_)
|
| 165 |
+
|
| 166 |
+
is_known = is_known.reshape(h, w)
|
| 167 |
+
|
| 168 |
+
# Data for matting laplacian in csr format
|
| 169 |
+
indptr = np.zeros(n + 1, dtype=np.int64)
|
| 170 |
+
indices = np.zeros(n * (4 * radius + 1) ** 2, dtype=np.int64)
|
| 171 |
+
values = np.zeros((n, 4 * radius + 1, 4 * radius + 1), dtype=np.float64)
|
| 172 |
+
|
| 173 |
+
_cf_laplacian(image, epsilon, radius, values, indices, indptr, is_known)
|
| 174 |
+
|
| 175 |
+
L = scipy.sparse.csr_matrix((values.ravel(), indices, indptr), (n, n))
|
| 176 |
+
|
| 177 |
+
return L
|
python_embeded/Lib/site-packages/pymatting/laplacian/knn_laplacian.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
from pymatting.util.kdtree import knn
|
| 4 |
+
from pymatting.util.util import normalize_rows
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def knn_laplacian(
|
| 8 |
+
image,
|
| 9 |
+
n_neighbors=[20, 10],
|
| 10 |
+
distance_weights=[2.0, 0.1],
|
| 11 |
+
kernel="binary",
|
| 12 |
+
):
|
| 13 |
+
"""
|
| 14 |
+
This function calculates the KNN matting Laplacian matrix similar to
|
| 15 |
+
:cite:`chen2013knn`.
|
| 16 |
+
We use a kernel of 1 instead of a soft kernel by default since the former is
|
| 17 |
+
faster to compute and both produce almost identical results in all our
|
| 18 |
+
experiments, which is to be expected as the soft kernel is very close to 1
|
| 19 |
+
in most cases.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
image: numpy.ndarray
|
| 24 |
+
Image with shape :math:`h\\times w \\times 3`
|
| 25 |
+
n_neighbors: list of ints
|
| 26 |
+
Number of neighbors to consider. If :code:`len(n_neighbors)>1` multiple
|
| 27 |
+
nearest neighbor calculations are done and merged, defaults to
|
| 28 |
+
`[20, 10]`, i.e. first 20 neighbors are considered and in the second run
|
| 29 |
+
:math:`10` neighbors. The pixel distances are then weighted by the
|
| 30 |
+
:code:`distance_weights`.
|
| 31 |
+
distance_weights: list of floats
|
| 32 |
+
Weight of distance in feature vector, defaults to `[2.0, 0.1]`.
|
| 33 |
+
kernel: str
|
| 34 |
+
Must be either "binary" or "soft". Default is "binary".
|
| 35 |
+
|
| 36 |
+
Returns
|
| 37 |
+
-------
|
| 38 |
+
L: scipy.sparse.spmatrix
|
| 39 |
+
Matting Laplacian matrix
|
| 40 |
+
"""
|
| 41 |
+
h, w = image.shape[:2]
|
| 42 |
+
r, g, b = image.reshape(-1, 3).T
|
| 43 |
+
n = w * h
|
| 44 |
+
|
| 45 |
+
if kernel not in ["binary", "soft"]:
|
| 46 |
+
raise ValueError("kernel must be binary/soft, but not " + kernel + ".")
|
| 47 |
+
|
| 48 |
+
x = np.tile(np.linspace(0, 1, w), h)
|
| 49 |
+
y = np.repeat(np.linspace(0, 1, h), w)
|
| 50 |
+
|
| 51 |
+
# Store weight matrix indices and values in sparse coordinate form.
|
| 52 |
+
i, j, coo_data = [], [], []
|
| 53 |
+
|
| 54 |
+
for k, distance_weight in zip(n_neighbors, distance_weights):
|
| 55 |
+
# Features consist of RGB color values and weighted spatial coordinates.
|
| 56 |
+
f = np.stack(
|
| 57 |
+
[r, g, b, distance_weight * x, distance_weight * y],
|
| 58 |
+
axis=1,
|
| 59 |
+
out=np.zeros((n, 5), dtype=np.float32),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Find indices of nearest neighbors in feature space.
|
| 63 |
+
_, neighbor_indices = knn(f, f, k=k)
|
| 64 |
+
|
| 65 |
+
# [0 0 0 0 0 (k times) 1 1 1 1 1 2 2 2 2 2 ...]
|
| 66 |
+
i.append(np.repeat(np.arange(n), k))
|
| 67 |
+
j.append(neighbor_indices.ravel())
|
| 68 |
+
|
| 69 |
+
W_ij = np.ones(k * n)
|
| 70 |
+
|
| 71 |
+
if kernel == "soft":
|
| 72 |
+
W_ij -= np.abs(f[i[-1]] - f[j[-1]]).sum(axis=1) / f.shape[1]
|
| 73 |
+
|
| 74 |
+
coo_data.append(W_ij)
|
| 75 |
+
|
| 76 |
+
# Add matrix to itself to get a symmetric matrix.
|
| 77 |
+
# The '+' here is list concatenation and not addition.
|
| 78 |
+
# The csr_matrix constructor will do the addition later.
|
| 79 |
+
ij = np.concatenate(i + j)
|
| 80 |
+
ji = np.concatenate(j + i)
|
| 81 |
+
coo_data = np.concatenate(coo_data + coo_data)
|
| 82 |
+
|
| 83 |
+
# Assemble weights from coordinate sparse matrix format.
|
| 84 |
+
W = scipy.sparse.csr_matrix((coo_data, (ij, ji)), (n, n))
|
| 85 |
+
|
| 86 |
+
W = normalize_rows(W)
|
| 87 |
+
|
| 88 |
+
I = scipy.sparse.identity(n)
|
| 89 |
+
|
| 90 |
+
L = I - W
|
| 91 |
+
|
| 92 |
+
return L
|
python_embeded/Lib/site-packages/pymatting/laplacian/laplacian.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import trimap_split
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def make_linear_system(L, trimap, lambda_value=100.0, return_c=False):
|
| 6 |
+
"""This function constructs a linear system from a matting Laplacian by
|
| 7 |
+
constraining the foreground and background pixels with a diagonal matrix
|
| 8 |
+
`C` to values in the right-hand-side vector `b`. The constraints are
|
| 9 |
+
weighted by a factor :math:`\\lambda`. The linear system is given as
|
| 10 |
+
|
| 11 |
+
.. math::
|
| 12 |
+
|
| 13 |
+
A = L + \\lambda C,
|
| 14 |
+
|
| 15 |
+
where :math:`C=\\mathop{Diag}(c)` having :math:`c_i = 1` if pixel i is known
|
| 16 |
+
and :math:`c_i = 0` otherwise.
|
| 17 |
+
The right-hand-side :math:`b` is a vector with entries :math:`b_i = 1` is
|
| 18 |
+
pixel is is a foreground pixel and :math:`b_i = 0` otherwise.
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
L: scipy.sparse.spmatrix
|
| 24 |
+
Laplacian matrix, e.g. calculated with :code:`lbdm_laplacian` function
|
| 25 |
+
trimap: numpy.ndarray
|
| 26 |
+
Trimap with shape :math:`h\\times w`
|
| 27 |
+
lambda_value: float
|
| 28 |
+
Constraint penalty, defaults to 100
|
| 29 |
+
return_c: bool
|
| 30 |
+
Whether to return the constraint matrix `C`, defaults to False
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
A: scipy.sparse.spmatrix
|
| 35 |
+
Matrix describing the system of linear equations
|
| 36 |
+
b: numpy.ndarray
|
| 37 |
+
Vector describing the right-hand side of the system
|
| 38 |
+
C: numpy.ndarray
|
| 39 |
+
Vector describing the diagonal entries of the matrix `C`, only returned
|
| 40 |
+
if `return_c` is set to True
|
| 41 |
+
"""
|
| 42 |
+
h, w = trimap.shape[:2]
|
| 43 |
+
|
| 44 |
+
is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
|
| 45 |
+
|
| 46 |
+
c = lambda_value * is_known
|
| 47 |
+
b = lambda_value * is_fg
|
| 48 |
+
|
| 49 |
+
C = scipy.sparse.diags(c)
|
| 50 |
+
|
| 51 |
+
A = L + C
|
| 52 |
+
|
| 53 |
+
A = A.tocsr()
|
| 54 |
+
|
| 55 |
+
A.sum_duplicates()
|
| 56 |
+
|
| 57 |
+
if return_c:
|
| 58 |
+
return A, b, c
|
| 59 |
+
|
| 60 |
+
return A, b
|
python_embeded/Lib/site-packages/pymatting/laplacian/lbdm_laplacian.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
from numba import njit
|
| 4 |
+
|
| 5 |
+
@njit("f8[:, :](f8[:, :], f8)", cache=True, nogil=True)
|
| 6 |
+
def calculate_kernel_matrix(X, v):
|
| 7 |
+
n, m = X.shape
|
| 8 |
+
K = np.zeros((n, n))
|
| 9 |
+
for i in range(n):
|
| 10 |
+
for j in range(n):
|
| 11 |
+
K[i, j] = np.exp(-np.sqrt(v) * np.sum(np.square(X[i] - X[j])))
|
| 12 |
+
return K
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@njit("Tuple((f8[:], i4[:], i4[:]))(f8[:, :, :], f8, i4)", cache=True, nogil=True)
|
| 16 |
+
def _lbdm_laplacian(image, epsilon, r):
|
| 17 |
+
h, w = image.shape[:2]
|
| 18 |
+
n = h * w
|
| 19 |
+
|
| 20 |
+
area = (2 * r + 1) ** 2
|
| 21 |
+
|
| 22 |
+
indices = np.arange(n).reshape(h, w)
|
| 23 |
+
|
| 24 |
+
values = np.zeros((n, area ** 2))
|
| 25 |
+
i_inds = np.zeros((n, area ** 2), dtype=np.int32)
|
| 26 |
+
j_inds = np.zeros((n, area ** 2), dtype=np.int32)
|
| 27 |
+
|
| 28 |
+
# gray = (image[:, :, 0] + image[:, :, 1] + image[:, :, 2]) / 3.0
|
| 29 |
+
# v = np.std(gray)
|
| 30 |
+
|
| 31 |
+
for y in range(r, h - r):
|
| 32 |
+
for x in range(r, w - r):
|
| 33 |
+
i = x + y * w
|
| 34 |
+
|
| 35 |
+
X = np.ones((area, 3 + 1))
|
| 36 |
+
|
| 37 |
+
k = 0
|
| 38 |
+
for y2 in range(y - r, y + r + 1):
|
| 39 |
+
for x2 in range(x - r, x + r + 1):
|
| 40 |
+
for c in range(3):
|
| 41 |
+
X[k, c] = image[y2, x2, c]
|
| 42 |
+
k += 1
|
| 43 |
+
|
| 44 |
+
window_indices = indices[y - r : y + r + 1, x - r : x + r + 1].flatten()
|
| 45 |
+
|
| 46 |
+
# does not produce better results than no kernel
|
| 47 |
+
# K = calculate_kernel_matrix(X, v)
|
| 48 |
+
|
| 49 |
+
K = np.dot(X, X.T)
|
| 50 |
+
|
| 51 |
+
f = np.linalg.solve(K + epsilon * np.eye(area), K)
|
| 52 |
+
|
| 53 |
+
tmp2 = np.eye(f.shape[0]) - f
|
| 54 |
+
tmp3 = tmp2.dot(tmp2.T)
|
| 55 |
+
|
| 56 |
+
for k in range(area):
|
| 57 |
+
i_inds[i, k::area] = window_indices
|
| 58 |
+
j_inds[i, k * area : k * area + area] = window_indices
|
| 59 |
+
values[i] = tmp3.ravel()
|
| 60 |
+
|
| 61 |
+
return values.ravel(), i_inds.ravel(), j_inds.ravel()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def lbdm_laplacian(image, epsilon=1e-7, radius=1):
|
| 65 |
+
"""
|
| 66 |
+
Calculate a Laplacian matrix based on :cite:`zheng2009learning`.
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
----------
|
| 70 |
+
image: numpy.ndarray
|
| 71 |
+
Image with shape :math:`h\\times w \\times 3`
|
| 72 |
+
epsilon: float
|
| 73 |
+
Regularization strength, defaults to :math:`10^{-7}`. Strong
|
| 74 |
+
regularization improves convergence but results in smoother alpha mattes.
|
| 75 |
+
radius: int
|
| 76 |
+
Radius of local window size, defaults to :math:`1`, i.e. only adjacent
|
| 77 |
+
pixels are considered. The size of the local window is given as
|
| 78 |
+
:math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
|
| 79 |
+
might lead to violated color line constraints, but also favors further
|
| 80 |
+
propagation of information within the image.
|
| 81 |
+
|
| 82 |
+
Returns
|
| 83 |
+
-------
|
| 84 |
+
L: scipy.sparse.csr_matrix
|
| 85 |
+
Matting Laplacian
|
| 86 |
+
"""
|
| 87 |
+
h, w = image.shape[:2]
|
| 88 |
+
n = h * w
|
| 89 |
+
|
| 90 |
+
values, i_inds, j_inds = _lbdm_laplacian(image, epsilon, radius)
|
| 91 |
+
|
| 92 |
+
L = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), shape=(n, n))
|
| 93 |
+
|
| 94 |
+
return L
|
python_embeded/Lib/site-packages/pymatting/laplacian/lkm_laplacian.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from pymatting.util.util import vec_vec_dot, mat_vec_dot, vec_vec_outer
|
| 3 |
+
from pymatting.util.boxfilter import boxfilter
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def lkm_laplacian(image, epsilon=1e-7, radius=10, return_diagonal=True):
|
| 7 |
+
"""Calculates the Laplacian for large kernel matting :cite:`he2010fast`
|
| 8 |
+
|
| 9 |
+
Parameters
|
| 10 |
+
----------
|
| 11 |
+
image: numpy.ndarray
|
| 12 |
+
Image of shape :math:`h\\times w \\times 3`
|
| 13 |
+
epsilons: float
|
| 14 |
+
Regularization strength, defaults to :math:`10^{-7}`
|
| 15 |
+
radius: int
|
| 16 |
+
Radius of local window size, defaults to :math:`10`, i.e. only adjacent
|
| 17 |
+
pixels are considered. The size of the local window is given as
|
| 18 |
+
:math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
|
| 19 |
+
might lead to violated color line constraints, but also favors further
|
| 20 |
+
propagation of information within the image.
|
| 21 |
+
return_diagonal: bool
|
| 22 |
+
Whether to also return the diagonal of the laplacian, defaults to True
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
L_matvec: function
|
| 27 |
+
Function that applies the Laplacian matrix to a vector
|
| 28 |
+
diag_L: numpy.ndarray
|
| 29 |
+
Diagonal entries of the matting Laplacian, only returns if
|
| 30 |
+
`return_diagonal` is True
|
| 31 |
+
"""
|
| 32 |
+
image = image.astype(np.float64)
|
| 33 |
+
|
| 34 |
+
window_size = 2 * radius + 1
|
| 35 |
+
window_area = window_size * window_size
|
| 36 |
+
h, w, depth = image.shape
|
| 37 |
+
|
| 38 |
+
# means over neighboring pixels
|
| 39 |
+
means = boxfilter(image, radius, mode="valid") / window_area
|
| 40 |
+
|
| 41 |
+
# color covariance over neighboring pixels
|
| 42 |
+
covs = boxfilter(vec_vec_outer(image, image), radius, mode="valid") / window_area
|
| 43 |
+
covs -= vec_vec_outer(means, means)
|
| 44 |
+
|
| 45 |
+
# precompute values which do not depend on p
|
| 46 |
+
V = np.linalg.inv(covs + epsilon / window_area * np.eye(depth)) / window_area
|
| 47 |
+
Vm = mat_vec_dot(V, means)
|
| 48 |
+
mVm = 1 / window_area + vec_vec_dot(means, Vm)
|
| 49 |
+
c = boxfilter(np.ones((h - 2 * radius, w - 2 * radius)), radius, mode="full")
|
| 50 |
+
|
| 51 |
+
def L_matvec(p):
|
| 52 |
+
p = p.reshape(h, w)
|
| 53 |
+
|
| 54 |
+
p_sums = boxfilter(p, radius, mode="valid")
|
| 55 |
+
pI_sums = boxfilter(p[:, :, np.newaxis] * image, radius, mode="valid")
|
| 56 |
+
|
| 57 |
+
p_L = c * p
|
| 58 |
+
|
| 59 |
+
temp = p_sums[:, :, np.newaxis] * Vm - mat_vec_dot(V, pI_sums)
|
| 60 |
+
p_L += vec_vec_dot(image, boxfilter(temp, radius, mode="full"))
|
| 61 |
+
|
| 62 |
+
temp = p_sums * mVm - vec_vec_dot(pI_sums, Vm)
|
| 63 |
+
p_L -= boxfilter(temp, radius, mode="full")
|
| 64 |
+
|
| 65 |
+
return p_L.flatten()
|
| 66 |
+
|
| 67 |
+
if return_diagonal:
|
| 68 |
+
# compute diagonal of L
|
| 69 |
+
diag_L = boxfilter(1.0 - mVm, radius, mode="full")
|
| 70 |
+
temp = 2 * boxfilter(Vm, radius, mode="full")
|
| 71 |
+
temp -= mat_vec_dot(boxfilter(V, radius, mode="full"), image)
|
| 72 |
+
diag_L += vec_vec_dot(image, temp)
|
| 73 |
+
|
| 74 |
+
return L_matvec, diag_L.flatten()
|
| 75 |
+
|
| 76 |
+
return L_matvec
|
python_embeded/Lib/site-packages/pymatting/laplacian/rw_laplacian.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
from pymatting.util.util import weights_to_laplacian
|
| 4 |
+
from numba import njit
|
| 5 |
+
|
| 6 |
+
@njit("Tuple((f8[:], i4[:], i4[:]))(f8[:,:,:], f8, i4)", cache=True, nogil=True)
|
| 7 |
+
def _rw_laplacian(image, sigma, r):
|
| 8 |
+
h, w = image.shape[:2]
|
| 9 |
+
n = h * w
|
| 10 |
+
|
| 11 |
+
m = n * (2 * r + 1) ** 2
|
| 12 |
+
|
| 13 |
+
i_inds = np.empty(m, dtype=np.int32)
|
| 14 |
+
j_inds = np.empty(m, dtype=np.int32)
|
| 15 |
+
values = np.empty(m)
|
| 16 |
+
|
| 17 |
+
k = 0
|
| 18 |
+
|
| 19 |
+
for y in range(h):
|
| 20 |
+
for x in range(w):
|
| 21 |
+
for dy in range(-r, r + 1):
|
| 22 |
+
for dx in range(-r, r + 1):
|
| 23 |
+
x2 = x + dx
|
| 24 |
+
y2 = y + dy
|
| 25 |
+
|
| 26 |
+
x2 = max(0, min(w - 1, x2))
|
| 27 |
+
y2 = max(0, min(h - 1, y2))
|
| 28 |
+
|
| 29 |
+
i = x + y * w
|
| 30 |
+
j = x2 + y2 * w
|
| 31 |
+
|
| 32 |
+
zi = image[y, x]
|
| 33 |
+
zj = image[y2, x2]
|
| 34 |
+
|
| 35 |
+
wij = np.exp(-900 * np.linalg.norm(zi - zj) ** 2)
|
| 36 |
+
|
| 37 |
+
i_inds[k] = i
|
| 38 |
+
j_inds[k] = j
|
| 39 |
+
|
| 40 |
+
values[k] = wij
|
| 41 |
+
|
| 42 |
+
k += 1
|
| 43 |
+
|
| 44 |
+
return values, i_inds, j_inds
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def rw_laplacian(image, sigma=0.033, radius=1, regularization=1e-8):
|
| 48 |
+
"""
|
| 49 |
+
This function implements the alpha estimator for random walk alpha matting
|
| 50 |
+
as described in :cite:`grady2005random`.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
image: numpy.ndarray
|
| 55 |
+
Image with shape :math:`h\\times w \\times 3`
|
| 56 |
+
sigma: float
|
| 57 |
+
Sigma used to calculate the weights (see Equation 4 in
|
| 58 |
+
:cite:`grady2005random`), defaults to :math:`0.033`
|
| 59 |
+
radius: int
|
| 60 |
+
Radius of local window size, defaults to :math:`1`, i.e. only adjacent
|
| 61 |
+
pixels are considered. The size of the local window is given as
|
| 62 |
+
:math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
|
| 63 |
+
might lead to violated color line constraints, but also favors further
|
| 64 |
+
propagation of information within the image.
|
| 65 |
+
regularization: float
|
| 66 |
+
Regularization strength, defaults to :math:`10^{-8}`. Strong
|
| 67 |
+
regularization improves convergence but results in smoother alpha matte.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
L: scipy.sparse.spmatrix
|
| 72 |
+
Matting Laplacian
|
| 73 |
+
"""
|
| 74 |
+
h, w = image.shape[:2]
|
| 75 |
+
n = h * w
|
| 76 |
+
|
| 77 |
+
values, i_inds, j_inds = _rw_laplacian(image, sigma, radius)
|
| 78 |
+
|
| 79 |
+
W = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), shape=(n, n))
|
| 80 |
+
|
| 81 |
+
return weights_to_laplacian(W, regularization=regularization)
|
python_embeded/Lib/site-packages/pymatting/laplacian/uniform_laplacian.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.util.util import (
|
| 2 |
+
grid_coordinates,
|
| 3 |
+
sparse_conv_matrix,
|
| 4 |
+
weights_to_laplacian,
|
| 5 |
+
)
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def uniform_laplacian(image, radius=1):
|
| 10 |
+
"""This function returns a Laplacian matrix with all weights equal to one.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
image: numpy.ndarray
|
| 15 |
+
Image with shape :math:`h\\times w \\times 3`
|
| 16 |
+
radius: int
|
| 17 |
+
Radius of local window size, defaults to 1, i.e. only adjacent pixels are considered.
|
| 18 |
+
The size of the local window is given as :math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius might lead to violated color line constraints, but also
|
| 19 |
+
favors further propagation of information within the image.
|
| 20 |
+
|
| 21 |
+
Returns
|
| 22 |
+
-------
|
| 23 |
+
L: scipy.sparse.spmatrix
|
| 24 |
+
Matting Laplacian
|
| 25 |
+
"""
|
| 26 |
+
height, width = image.shape[:2]
|
| 27 |
+
window_size = 2 * radius + 1
|
| 28 |
+
|
| 29 |
+
W = sparse_conv_matrix(width, height, np.ones((window_size, window_size)))
|
| 30 |
+
|
| 31 |
+
return weights_to_laplacian(W)
|
python_embeded/Lib/site-packages/pymatting/preconditioner/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.preconditioner.ichol import ichol
|
| 2 |
+
from pymatting.preconditioner.jacobi import jacobi
|
| 3 |
+
from pymatting.preconditioner.vcycle import vcycle
|
python_embeded/Lib/site-packages/pymatting/preconditioner/ichol.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
from numba import njit
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@njit(
|
| 7 |
+
"i8(i8, f8[:], i8[:], i8[:], f8[:], i8[:], i8[:], f8, f8, i8, f8, b1)",
|
| 8 |
+
cache=True,
|
| 9 |
+
nogil=True,
|
| 10 |
+
)
|
| 11 |
+
def _ichol(
|
| 12 |
+
n,
|
| 13 |
+
Av,
|
| 14 |
+
Ar,
|
| 15 |
+
Ap,
|
| 16 |
+
Lv,
|
| 17 |
+
Lr,
|
| 18 |
+
Lp,
|
| 19 |
+
discard_threshold,
|
| 20 |
+
shift,
|
| 21 |
+
max_nnz,
|
| 22 |
+
relative_discard_threshold,
|
| 23 |
+
diag_keep_discarded,
|
| 24 |
+
):
|
| 25 |
+
"""
|
| 26 |
+
:cite:`jones1995improved` might be slightly interesting for the general idea
|
| 27 |
+
to use linked list to keep track of the sparse matrix values. But instead of
|
| 28 |
+
pointers, we have to use indices here, since this is Python and not C.
|
| 29 |
+
"""
|
| 30 |
+
nnz = 0
|
| 31 |
+
c_n = 0
|
| 32 |
+
s = np.zeros(n, np.int64) # Next non-zero row index i in column j of L
|
| 33 |
+
t = np.zeros(n, np.int64) # First subdiagonal index i in column j of A
|
| 34 |
+
l = np.zeros(n, np.int64) - 1 # Linked list of non-zero columns in row k of L
|
| 35 |
+
a = np.zeros(n, np.float64) # Values of column j
|
| 36 |
+
r = np.zeros(n, np.float64) # r[j] = sum(abs(A[j:, j])) for relative threshold
|
| 37 |
+
b = np.zeros(n, np.bool_) # b[i] indicates if the i-th element of column j is non-zero
|
| 38 |
+
c = np.empty(n, np.int64) # Row indices of non-zero elements in column j
|
| 39 |
+
d = np.full(n, shift, np.float64) # Diagonal elements of A
|
| 40 |
+
for j in range(n):
|
| 41 |
+
for idx in range(Ap[j], Ap[j + 1]):
|
| 42 |
+
i = Ar[idx]
|
| 43 |
+
if i == j:
|
| 44 |
+
d[j] += Av[idx]
|
| 45 |
+
t[j] = idx + 1
|
| 46 |
+
if i >= j:
|
| 47 |
+
r[j] += abs(Av[idx])
|
| 48 |
+
for j in range(n): # For each column j
|
| 49 |
+
for idx in range(t[j], Ap[j + 1]): # For each L_ij
|
| 50 |
+
i = Ar[idx]
|
| 51 |
+
L_ij = Av[idx]
|
| 52 |
+
if L_ij != 0.0 and i > j:
|
| 53 |
+
a[i] += L_ij # Assign non-zero value to L_ij in sparse column
|
| 54 |
+
if not b[i]:
|
| 55 |
+
b[i] = True # Mark it as non-zero
|
| 56 |
+
c[c_n] = i # Remember index for later deletion
|
| 57 |
+
c_n += 1
|
| 58 |
+
k = l[j] # Find index k of column with non-zero element in row j
|
| 59 |
+
while k != -1: # For each column of that type
|
| 60 |
+
k0 = s[k] # Start index of non-zero elements in column k
|
| 61 |
+
k1 = Lp[k + 1] # End index
|
| 62 |
+
k2 = l[k] # Remember next column index before it is overwritten
|
| 63 |
+
L_jk = Lv[k0] # Value of non-zero element at start of column
|
| 64 |
+
k0 += 1 # Advance to next non-zero element in column
|
| 65 |
+
if k0 < k1: # If there is a next non-zero element
|
| 66 |
+
s[k] = k0 # Advance start index in column k to next non-zero element
|
| 67 |
+
i = Lr[k0] # Row index of next non-zero element in column k
|
| 68 |
+
l[k] = l[i] # Remember old list i index in list k
|
| 69 |
+
l[i] = k # Insert index of non-zero element into list i
|
| 70 |
+
for idx in range(k0, k1): # For each non-zero L_ik in column k
|
| 71 |
+
i = Lr[idx]
|
| 72 |
+
L_ik = Lv[idx]
|
| 73 |
+
a[i] -= L_ik * L_jk # Update element L_ij in sparse column
|
| 74 |
+
if not b[i]: # Check if sparse column element was zero
|
| 75 |
+
b[i] = True # Mark as non-zero in sparse column
|
| 76 |
+
c[c_n] = i # Remember index for later deletion
|
| 77 |
+
c_n += 1
|
| 78 |
+
k = k2 # Advance to next column k
|
| 79 |
+
if d[j] <= 0.0:
|
| 80 |
+
return -1
|
| 81 |
+
if nnz + 1 + c_n > max_nnz:
|
| 82 |
+
return -2
|
| 83 |
+
d[j] = np.sqrt(d[j]) # Update diagonal element L_ii
|
| 84 |
+
Lv[nnz] = d[j] # Add diagonal element L_ii to L
|
| 85 |
+
Lr[nnz] = j # Add row index of L_ii to L
|
| 86 |
+
nnz += 1
|
| 87 |
+
s[j] = nnz # Set first non-zero index of column j
|
| 88 |
+
for i in np.sort(
|
| 89 |
+
c[:c_n]
|
| 90 |
+
): # Sort row indices of column j for correct insertion order into L
|
| 91 |
+
L_ij = a[i] / d[j] # Get non-zero element from sparse column j
|
| 92 |
+
if diag_keep_discarded:
|
| 93 |
+
d[i] -= L_ij * L_ij # Update diagonal element L_ii
|
| 94 |
+
rel = (
|
| 95 |
+
relative_discard_threshold * r[j]
|
| 96 |
+
) # Relative discard threshold (before div)
|
| 97 |
+
if (
|
| 98 |
+
abs(L_ij) > discard_threshold and abs(a[i]) > rel
|
| 99 |
+
): # If element is sufficiently non-zero
|
| 100 |
+
if not diag_keep_discarded:
|
| 101 |
+
d[i] -= L_ij * L_ij # Update diagonal element L_ii
|
| 102 |
+
Lv[nnz] = L_ij # Add element L_ij to L
|
| 103 |
+
Lr[nnz] = i # Add row index of L_ij
|
| 104 |
+
nnz += 1
|
| 105 |
+
a[i] = 0.0 # Set element i in column j to zero
|
| 106 |
+
b[i] = False # Mark element as zero
|
| 107 |
+
c_n = 0 # Discard row indices of non-zero elements in column j.
|
| 108 |
+
Lp[j + 1] = nnz # Update count of non-zero elements up to column j
|
| 109 |
+
if Lp[j] + 1 < Lp[j + 1]: # If column j has a non-zero element below diagonal
|
| 110 |
+
i = Lr[Lp[j] + 1] # Row index of first off-diagonal non-zero element
|
| 111 |
+
l[j] = l[i] # Remember old list i index in list j
|
| 112 |
+
l[i] = j # Insert index of non-zero element into list i
|
| 113 |
+
return nnz
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@njit("void(f8[:], i8[:], i8[:], f8[:], i8)", cache=True, nogil=True)
|
| 117 |
+
def _backsub_L_csc_inplace(data, indices, indptr, x, n):
|
| 118 |
+
for j in range(n):
|
| 119 |
+
k = indptr[j]
|
| 120 |
+
L_jj = data[k]
|
| 121 |
+
temp = x[j] / L_jj
|
| 122 |
+
|
| 123 |
+
x[j] = temp
|
| 124 |
+
|
| 125 |
+
for k in range(indptr[j] + 1, indptr[j + 1]):
|
| 126 |
+
i = indices[k]
|
| 127 |
+
L_ij = data[k]
|
| 128 |
+
|
| 129 |
+
x[i] -= L_ij * temp
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@njit("void(f8[:], i8[:], i8[:], f8[:], i8)", cache=True, nogil=True)
|
| 133 |
+
def _backsub_LT_csc_inplace(data, indices, indptr, x, n):
|
| 134 |
+
for i in range(n - 1, -1, -1):
|
| 135 |
+
s = x[i]
|
| 136 |
+
|
| 137 |
+
for k in range(indptr[i] + 1, indptr[i + 1]):
|
| 138 |
+
j = indices[k]
|
| 139 |
+
L_ji = data[k]
|
| 140 |
+
s -= L_ji * x[j]
|
| 141 |
+
|
| 142 |
+
k = indptr[i]
|
| 143 |
+
L_ii = data[k]
|
| 144 |
+
|
| 145 |
+
x[i] = s / L_ii
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class CholeskyDecomposition(object):
|
| 149 |
+
"""Cholesky Decomposition
|
| 150 |
+
|
| 151 |
+
Calling this object applies the preconditioner to a vector by forward and back substitution.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
Ltuple: tuple of numpy.ndarrays
|
| 156 |
+
Tuple of array describing values, row indices and row pointers for Cholesky factor in the compressed sparse column format (csc)
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
def __init__(self, Ltuple):
|
| 160 |
+
self.Ltuple = Ltuple
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def L(self):
|
| 164 |
+
"""Returns the Cholesky factor
|
| 165 |
+
|
| 166 |
+
Returns
|
| 167 |
+
-------
|
| 168 |
+
L: scipy.sparse.csc_matrix
|
| 169 |
+
Cholesky factor
|
| 170 |
+
"""
|
| 171 |
+
Lv, Lr, Lp = self.Ltuple
|
| 172 |
+
n = len(Lp) - 1
|
| 173 |
+
return scipy.sparse.csc_matrix(self.Ltuple, (n, n))
|
| 174 |
+
|
| 175 |
+
def __call__(self, b):
|
| 176 |
+
Lv, Lr, Lp = self.Ltuple
|
| 177 |
+
n = len(b)
|
| 178 |
+
x = b.copy()
|
| 179 |
+
_backsub_L_csc_inplace(Lv, Lr, Lp, x, n)
|
| 180 |
+
_backsub_LT_csc_inplace(Lv, Lr, Lp, x, n)
|
| 181 |
+
return x
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def ichol(
|
| 185 |
+
A,
|
| 186 |
+
discard_threshold=1e-4,
|
| 187 |
+
shifts=[0.0, 1e-4, 1e-3, 1e-2, 0.1, 0.5, 1.0, 10.0, 100, 1e3, 1e4, 1e5],
|
| 188 |
+
max_nnz=int(4e9 / 16),
|
| 189 |
+
relative_discard_threshold=0.0,
|
| 190 |
+
diag_keep_discarded=True,
|
| 191 |
+
):
|
| 192 |
+
"""Implements the thresholded incomplete Cholesky decomposition.
|
| 193 |
+
For reference, a dense ichol implementation with relative threshold would look like this:
|
| 194 |
+
|
| 195 |
+
L = np.tril(A)
|
| 196 |
+
for j in range(n):
|
| 197 |
+
col = L[j:, j]
|
| 198 |
+
col -= np.sum(L[j, :j] * L[j:, :j], axis=1)
|
| 199 |
+
discard_mask = abs(col[1:]) < relative_discard_threshold * np.sum(np.abs(A[j:, j]))
|
| 200 |
+
col[1:][discard_mask] = 0
|
| 201 |
+
col[0] **= 0.5
|
| 202 |
+
col[1:] /= col[0]
|
| 203 |
+
|
| 204 |
+
Parameters
|
| 205 |
+
----------
|
| 206 |
+
A: scipy.sparse.csc_matrix
|
| 207 |
+
Matrix for which the preconditioner should be calculated
|
| 208 |
+
discard_threshold: float
|
| 209 |
+
Values having an absolute value smaller than this threshold will be discarded while calculating the Cholesky decompositions
|
| 210 |
+
shifts: array of floats
|
| 211 |
+
Values to try for regularizing the matrix of interest in case it is not positive definite after discarding the small values
|
| 212 |
+
max_nnz: int
|
| 213 |
+
Maximum number of non-zero entries in the Cholesky decomposition. Defaults to 250 million, which should usually be around 4 GB.
|
| 214 |
+
relative_discard_threshold: float
|
| 215 |
+
Values with an absolute value of less than :code:`relative_discard_threshold * sum(abs(A[j:, j]))` will be discarded.
|
| 216 |
+
diag_keep_discarded: bool
|
| 217 |
+
Whether to update the diagonal with the discarded values. Usually better if :code:`True`.
|
| 218 |
+
|
| 219 |
+
Returns
|
| 220 |
+
-------
|
| 221 |
+
chol: CholeskyDecomposition
|
| 222 |
+
Preconditioner or solver object.
|
| 223 |
+
|
| 224 |
+
Raises
|
| 225 |
+
------
|
| 226 |
+
ValueError:
|
| 227 |
+
If inappropriate parameter values were passed
|
| 228 |
+
|
| 229 |
+
Example
|
| 230 |
+
-------
|
| 231 |
+
>>> from pymatting import *
|
| 232 |
+
>>> import numpy as np
|
| 233 |
+
>>> from scipy.sparse import csc_matrix
|
| 234 |
+
>>> A = np.array([[2.0, 3.0], [3.0, 5.0]])
|
| 235 |
+
>>> cholesky_decomposition = ichol(csc_matrix(A))
|
| 236 |
+
>>> cholesky_decomposition(np.array([1.0, 2.0]))
|
| 237 |
+
array([-1., 1.])
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
if isinstance(A, scipy.sparse.csr_matrix):
|
| 241 |
+
A = A.T
|
| 242 |
+
|
| 243 |
+
if not isinstance(A, scipy.sparse.csc_matrix):
|
| 244 |
+
raise ValueError("Matrix A must be a scipy.sparse.csc_matrix")
|
| 245 |
+
|
| 246 |
+
if not A.has_canonical_format:
|
| 247 |
+
A.sum_duplicates()
|
| 248 |
+
|
| 249 |
+
m, n = A.shape
|
| 250 |
+
|
| 251 |
+
assert m == n
|
| 252 |
+
|
| 253 |
+
Lv = np.empty(max_nnz, dtype=np.float64) # Values of non-zero elements of L
|
| 254 |
+
Lr = np.empty(max_nnz, dtype=np.int64) # Row indices of non-zero elements of L
|
| 255 |
+
Lp = np.zeros(
|
| 256 |
+
n + 1, dtype=np.int64
|
| 257 |
+
) # Start(Lp[i]) and end(Lp[i+1]) index of L[:, i] in Lv
|
| 258 |
+
|
| 259 |
+
for shift in shifts:
|
| 260 |
+
nnz = _ichol(
|
| 261 |
+
n,
|
| 262 |
+
A.data,
|
| 263 |
+
A.indices.astype(np.int64),
|
| 264 |
+
A.indptr.astype(np.int64),
|
| 265 |
+
Lv,
|
| 266 |
+
Lr,
|
| 267 |
+
Lp,
|
| 268 |
+
discard_threshold,
|
| 269 |
+
shift,
|
| 270 |
+
max_nnz,
|
| 271 |
+
relative_discard_threshold,
|
| 272 |
+
diag_keep_discarded,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if nnz >= 0:
|
| 276 |
+
break
|
| 277 |
+
|
| 278 |
+
if nnz == -1:
|
| 279 |
+
print("PERFORMANCE WARNING:")
|
| 280 |
+
print(
|
| 281 |
+
"Thresholded incomplete Cholesky decomposition failed due to insufficient positive-definiteness of matrix A with parameters:"
|
| 282 |
+
)
|
| 283 |
+
print(" discard_threshold = %e" % discard_threshold)
|
| 284 |
+
print(" shift = %e" % shift)
|
| 285 |
+
print("Try decreasing discard_threshold or start with a larger shift")
|
| 286 |
+
print("")
|
| 287 |
+
|
| 288 |
+
if nnz == -2:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
"Thresholded incomplete Cholesky decomposition failed because more than max_nnz non-zero elements were created. Try increasing max_nnz or discard_threshold."
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
if nnz < 0:
|
| 294 |
+
raise ValueError(
|
| 295 |
+
"Thresholded incomplete Cholesky decomposition failed due to insufficient positive-definiteness of matrix A and diagonal shifts did not help."
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
Lv = Lv[:nnz]
|
| 299 |
+
Lr = Lr[:nnz]
|
| 300 |
+
|
| 301 |
+
return CholeskyDecomposition((Lv, Lr, Lp))
|
python_embeded/Lib/site-packages/pymatting/preconditioner/jacobi.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def jacobi(A):
|
| 2 |
+
"""
|
| 3 |
+
Compute the Jacobi preconditioner function for the matrix A.
|
| 4 |
+
|
| 5 |
+
Parameters
|
| 6 |
+
----------
|
| 7 |
+
A: np.array
|
| 8 |
+
Input matrix to compute the Jacobi preconditioner for.
|
| 9 |
+
|
| 10 |
+
Returns
|
| 11 |
+
-------
|
| 12 |
+
precondition_matvec: function
|
| 13 |
+
Function which applies the Jacobi preconditioner to a vector
|
| 14 |
+
|
| 15 |
+
Example
|
| 16 |
+
-------
|
| 17 |
+
>>> from pymatting import *
|
| 18 |
+
>>> import numpy as np
|
| 19 |
+
>>> A = np.array([[2, 3], [3, 5]])
|
| 20 |
+
>>> preconditioner = jacobi(A)
|
| 21 |
+
>>> preconditioner(np.array([1, 2]))
|
| 22 |
+
array([0.5, 0.4])
|
| 23 |
+
"""
|
| 24 |
+
diagonal = A.diagonal()
|
| 25 |
+
|
| 26 |
+
inverse_diagonal = 1.0 / diagonal
|
| 27 |
+
|
| 28 |
+
def precondition_matvec(x):
|
| 29 |
+
return x * inverse_diagonal
|
| 30 |
+
|
| 31 |
+
return precondition_matvec
|
python_embeded/Lib/site-packages/pymatting/preconditioner/vcycle.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import scipy.sparse
|
| 3 |
+
import scipy.sparse.linalg
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def make_P(shape):
|
| 7 |
+
h, w = shape
|
| 8 |
+
n = h * w
|
| 9 |
+
h2 = h // 2
|
| 10 |
+
w2 = w // 2
|
| 11 |
+
n2 = w2 * h2
|
| 12 |
+
weights = np.float64([1, 2, 1, 2, 4, 2, 1, 2, 1]) / 16
|
| 13 |
+
|
| 14 |
+
x2 = np.repeat(np.tile(np.arange(w2), h2), 9)
|
| 15 |
+
y2 = np.repeat(np.repeat(np.arange(h2), w2), 9)
|
| 16 |
+
|
| 17 |
+
x = x2 * 2 + np.tile([-1, 0, 1, -1, 0, 1, -1, 0, 1], n2)
|
| 18 |
+
y = y2 * 2 + np.tile([-1, -1, -1, 0, 0, 0, 1, 1, 1], n2)
|
| 19 |
+
|
| 20 |
+
mask = (0 <= x) & (x < w) & (0 <= y) & (y <= h)
|
| 21 |
+
|
| 22 |
+
i_inds = (x2 + y2 * w2)[mask]
|
| 23 |
+
j_inds = (x + y * w)[mask]
|
| 24 |
+
values = np.tile(weights, n2)[mask]
|
| 25 |
+
|
| 26 |
+
downsample = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), (n2, n))
|
| 27 |
+
upsample = downsample.T
|
| 28 |
+
|
| 29 |
+
return upsample, downsample
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def jacobi_step(A, A_diag, b, x, num_iter, omega):
|
| 33 |
+
if x is None:
|
| 34 |
+
if num_iter > 0:
|
| 35 |
+
x = omega * b / A_diag
|
| 36 |
+
num_iter -= 1
|
| 37 |
+
else:
|
| 38 |
+
x = np.zeros_like(b)
|
| 39 |
+
|
| 40 |
+
for _ in range(num_iter):
|
| 41 |
+
x = x + omega * (b - A.dot(x)) / A_diag
|
| 42 |
+
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _vcycle_step(
|
| 47 |
+
A,
|
| 48 |
+
b,
|
| 49 |
+
shape,
|
| 50 |
+
cache,
|
| 51 |
+
num_pre_iter,
|
| 52 |
+
num_post_iter,
|
| 53 |
+
omega,
|
| 54 |
+
direct_solve_size,
|
| 55 |
+
):
|
| 56 |
+
h, w = shape
|
| 57 |
+
n = h * w
|
| 58 |
+
|
| 59 |
+
if n <= direct_solve_size:
|
| 60 |
+
return scipy.sparse.linalg.spsolve(A, b)
|
| 61 |
+
|
| 62 |
+
if shape not in cache:
|
| 63 |
+
upsample, downsample = make_P(shape)
|
| 64 |
+
|
| 65 |
+
coarse_A = downsample.dot(A).dot(upsample)
|
| 66 |
+
|
| 67 |
+
A_diag = A.diagonal()
|
| 68 |
+
|
| 69 |
+
cache[shape] = (upsample, downsample, coarse_A, A_diag)
|
| 70 |
+
else:
|
| 71 |
+
upsample, downsample, coarse_A, A_diag = cache[shape]
|
| 72 |
+
|
| 73 |
+
# smooth error
|
| 74 |
+
x = jacobi_step(A, A_diag, b, None, num_pre_iter, omega)
|
| 75 |
+
|
| 76 |
+
# calculate residual error to perfect solution
|
| 77 |
+
residual = b - A.dot(x)
|
| 78 |
+
|
| 79 |
+
# downsample residual error
|
| 80 |
+
coarse_residual = downsample.dot(residual)
|
| 81 |
+
|
| 82 |
+
# calculate coarse solution for residual
|
| 83 |
+
coarse_x = _vcycle_step(
|
| 84 |
+
coarse_A,
|
| 85 |
+
coarse_residual,
|
| 86 |
+
(h // 2, w // 2),
|
| 87 |
+
cache,
|
| 88 |
+
num_pre_iter,
|
| 89 |
+
num_post_iter,
|
| 90 |
+
omega,
|
| 91 |
+
direct_solve_size,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# apply coarse correction
|
| 95 |
+
x += upsample.dot(coarse_x)
|
| 96 |
+
|
| 97 |
+
# smooth error
|
| 98 |
+
x = jacobi_step(A, A_diag, b, x, num_post_iter, omega)
|
| 99 |
+
|
| 100 |
+
return x
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def vcycle(
|
| 104 |
+
A,
|
| 105 |
+
shape,
|
| 106 |
+
num_pre_iter=1,
|
| 107 |
+
num_post_iter=1,
|
| 108 |
+
omega=0.8,
|
| 109 |
+
direct_solve_size=64,
|
| 110 |
+
cache=None,
|
| 111 |
+
):
|
| 112 |
+
"""
|
| 113 |
+
Implements the V-Cycle preconditioner.
|
| 114 |
+
The V-Cycle solver was recommended by :cite:`lee2014scalable` to solve the alpha matting problem.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
----------
|
| 118 |
+
A: numpy.ndarray
|
| 119 |
+
Input matrix
|
| 120 |
+
shape: tuple of ints
|
| 121 |
+
Describing the height and width of the image
|
| 122 |
+
num_pre_iter: int
|
| 123 |
+
Number of Jacobi iterations before each V-Cycle, defaults to 1
|
| 124 |
+
num_post_iter: int
|
| 125 |
+
Number of Jacobi iterations after each V-Cycle, defaults to 1
|
| 126 |
+
omega: float
|
| 127 |
+
Weight parameter for the Jacobi method. If method fails to converge, try different values.
|
| 128 |
+
|
| 129 |
+
Returns
|
| 130 |
+
-------
|
| 131 |
+
precondition: function
|
| 132 |
+
Function which applies the V-Cycle preconditioner to a vector
|
| 133 |
+
|
| 134 |
+
Example
|
| 135 |
+
-------
|
| 136 |
+
>>> from pymatting import *
|
| 137 |
+
>>> import numpy as np
|
| 138 |
+
>>> from scipy.sparse import csc_matrix
|
| 139 |
+
>>> A = np.array([[2, 3], [3, 5]])
|
| 140 |
+
>>> preconditioner = vcycle(A, (2, 2))
|
| 141 |
+
>>> preconditioner(np.array([1, 2]))
|
| 142 |
+
array([-1., 1.])
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
if cache is None:
|
| 146 |
+
cache = {}
|
| 147 |
+
|
| 148 |
+
def precondition(r):
|
| 149 |
+
return _vcycle_step(
|
| 150 |
+
A, r, shape, cache, num_pre_iter, num_post_iter, omega, direct_solve_size
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
return precondition
|
python_embeded/Lib/site-packages/pymatting/solver/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pymatting.solver.cg import cg
|
| 2 |
+
from pymatting.solver.callback import CounterCallback, ProgressCallback
|
python_embeded/Lib/site-packages/pymatting/solver/callback.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class CounterCallback(object):
|
| 2 |
+
"""Callback to count number of iterations of iterative solvers."""
|
| 3 |
+
|
| 4 |
+
def __init__(self):
|
| 5 |
+
self.n = 0
|
| 6 |
+
|
| 7 |
+
def __call__(self, A, x, b, norm_b, r, norm_r):
|
| 8 |
+
self.n += 1
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ProgressCallback(object):
|
| 12 |
+
"""
|
| 13 |
+
Callback to count number of iterations of iterative solvers.
|
| 14 |
+
Also prints residual error.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.n = 0
|
| 19 |
+
|
| 20 |
+
def __call__(self, A, x, b, norm_b, r, norm_r):
|
| 21 |
+
self.n += 1
|
| 22 |
+
|
| 23 |
+
print("iteration %7d - %e (%.20f)" % (self.n, norm_r, norm_r))
|
python_embeded/Lib/site-packages/pymatting/solver/cg.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def cg(
|
| 5 |
+
A,
|
| 6 |
+
b,
|
| 7 |
+
x0=None,
|
| 8 |
+
atol=0.0,
|
| 9 |
+
rtol=1e-7,
|
| 10 |
+
maxiter=10000,
|
| 11 |
+
callback=None,
|
| 12 |
+
M=None,
|
| 13 |
+
reorthogonalize=False,
|
| 14 |
+
):
|
| 15 |
+
"""Solves a system of linear equations :math:`Ax=b` using conjugate gradient descent :cite:`hestenes1952methods`
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
A: scipy.sparse.csr_matrix
|
| 20 |
+
Square matrix
|
| 21 |
+
b: numpy.ndarray
|
| 22 |
+
Vector describing the right-hand side of the system
|
| 23 |
+
x0: numpy.ndarray
|
| 24 |
+
Initialization, if `None` then :code:`x=np.zeros_like(b)`
|
| 25 |
+
atol: float
|
| 26 |
+
Absolute tolerance. The loop terminates if the :math:`||r||` is smaller than `atol`, where :math:`r` denotes the residual of the current iterate.
|
| 27 |
+
rtol: float
|
| 28 |
+
Relative tolerance. The loop terminates if :math:`{||r||}/{||b||}` is smaller than `rtol`, where :math:`r` denotes the residual of the current iterate.
|
| 29 |
+
callback: function
|
| 30 |
+
Function :code:`callback(A, x, b, norm_b, r, norm_r)` called after each iteration, defaults to `None`
|
| 31 |
+
M: function or scipy.sparse.csr_matrix
|
| 32 |
+
Function that applies the preconditioner to a vector. Alternatively, `M` can be a matrix describing the precondioner.
|
| 33 |
+
reorthogonalize: boolean
|
| 34 |
+
Whether to apply reorthogonalization of the residuals after each update, defaults to `False`
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Returns
|
| 38 |
+
-------
|
| 39 |
+
x: numpy.ndarray
|
| 40 |
+
Solution of the system
|
| 41 |
+
|
| 42 |
+
Example
|
| 43 |
+
-------
|
| 44 |
+
>>> from pymatting import *
|
| 45 |
+
>>> import numpy as np
|
| 46 |
+
>>> A = np.array([[3.0, 1.0], [1.0, 2.0]])
|
| 47 |
+
>>> M = jacobi(A)
|
| 48 |
+
>>> b = np.array([4.0, 3.0])
|
| 49 |
+
>>> cg(A, b, M=M)
|
| 50 |
+
array([1., 1.])
|
| 51 |
+
"""
|
| 52 |
+
if M is None:
|
| 53 |
+
|
| 54 |
+
def precondition(x):
|
| 55 |
+
return x
|
| 56 |
+
|
| 57 |
+
elif callable(M):
|
| 58 |
+
precondition = M
|
| 59 |
+
else:
|
| 60 |
+
|
| 61 |
+
def precondition(x):
|
| 62 |
+
return M.dot(x)
|
| 63 |
+
|
| 64 |
+
x = np.zeros_like(b) if x0 is None else x0.copy()
|
| 65 |
+
|
| 66 |
+
norm_b = np.linalg.norm(b)
|
| 67 |
+
|
| 68 |
+
if callable(A):
|
| 69 |
+
r = b - A(x)
|
| 70 |
+
else:
|
| 71 |
+
r = b - A.dot(x)
|
| 72 |
+
|
| 73 |
+
norm_r = np.linalg.norm(r)
|
| 74 |
+
|
| 75 |
+
if norm_r < atol or norm_r < rtol * norm_b:
|
| 76 |
+
return x
|
| 77 |
+
|
| 78 |
+
z = precondition(r)
|
| 79 |
+
p = z.copy()
|
| 80 |
+
rz = np.inner(r, z)
|
| 81 |
+
|
| 82 |
+
for iteration in range(maxiter):
|
| 83 |
+
r_old = r.copy()
|
| 84 |
+
|
| 85 |
+
if callable(A):
|
| 86 |
+
Ap = A(p)
|
| 87 |
+
else:
|
| 88 |
+
Ap = A.dot(p)
|
| 89 |
+
|
| 90 |
+
alpha = rz / np.inner(p, Ap)
|
| 91 |
+
x += alpha * p
|
| 92 |
+
r -= alpha * Ap
|
| 93 |
+
|
| 94 |
+
norm_r = np.linalg.norm(r)
|
| 95 |
+
|
| 96 |
+
if callback is not None:
|
| 97 |
+
callback(A, x, b, norm_b, r, norm_r)
|
| 98 |
+
|
| 99 |
+
if norm_r < atol or norm_r < rtol * norm_b:
|
| 100 |
+
return x
|
| 101 |
+
|
| 102 |
+
z = precondition(r)
|
| 103 |
+
|
| 104 |
+
if reorthogonalize:
|
| 105 |
+
beta = np.inner(r - r_old, z) / rz
|
| 106 |
+
rz = np.inner(r, z)
|
| 107 |
+
else:
|
| 108 |
+
beta = 1.0 / rz
|
| 109 |
+
rz = np.inner(r, z)
|
| 110 |
+
beta *= rz
|
| 111 |
+
|
| 112 |
+
p *= beta
|
| 113 |
+
p += z
|
| 114 |
+
|
| 115 |
+
raise ValueError(
|
| 116 |
+
"Conjugate gradient descent did not converge within %d iterations" % maxiter
|
| 117 |
+
)
|
python_embeded/Lib/site-packages/pyparsing/diagram/__init__.py
ADDED
|
@@ -0,0 +1,754 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import itertools
|
| 5 |
+
import railroad
|
| 6 |
+
import pyparsing
|
| 7 |
+
import dataclasses
|
| 8 |
+
import typing
|
| 9 |
+
from typing import (
|
| 10 |
+
Generic,
|
| 11 |
+
TypeVar,
|
| 12 |
+
Callable,
|
| 13 |
+
Iterable,
|
| 14 |
+
)
|
| 15 |
+
from jinja2 import Template
|
| 16 |
+
from io import StringIO
|
| 17 |
+
import inspect
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
jinja2_template_source = """\
|
| 22 |
+
{% if not embed %}
|
| 23 |
+
<!DOCTYPE html>
|
| 24 |
+
<html>
|
| 25 |
+
<head>
|
| 26 |
+
{% endif %}
|
| 27 |
+
{% if not head %}
|
| 28 |
+
<style>
|
| 29 |
+
.railroad-heading {
|
| 30 |
+
font-family: monospace;
|
| 31 |
+
}
|
| 32 |
+
</style>
|
| 33 |
+
{% else %}
|
| 34 |
+
{{ head | safe }}
|
| 35 |
+
{% endif %}
|
| 36 |
+
{% if not embed %}
|
| 37 |
+
</head>
|
| 38 |
+
<body>
|
| 39 |
+
{% endif %}
|
| 40 |
+
<meta charset="UTF-8"/>
|
| 41 |
+
{{ body | safe }}
|
| 42 |
+
{% for diagram in diagrams %}
|
| 43 |
+
<div class="railroad-group">
|
| 44 |
+
<h1 class="railroad-heading" id="{{ diagram.bookmark }}">{{ diagram.title }}</h1>
|
| 45 |
+
<div class="railroad-description">{{ diagram.text }}</div>
|
| 46 |
+
<div class="railroad-svg">
|
| 47 |
+
{{ diagram.svg }}
|
| 48 |
+
</div>
|
| 49 |
+
</div>
|
| 50 |
+
{% endfor %}
|
| 51 |
+
{% if not embed %}
|
| 52 |
+
</body>
|
| 53 |
+
</html>
|
| 54 |
+
{% endif %}
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
template = Template(jinja2_template_source)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
_bookmark_lookup = {}
|
| 61 |
+
_bookmark_ids = itertools.count(start=1)
|
| 62 |
+
|
| 63 |
+
def _make_bookmark(s: str) -> str:
|
| 64 |
+
"""
|
| 65 |
+
Converts a string into a valid HTML bookmark (ID or anchor name).
|
| 66 |
+
"""
|
| 67 |
+
if s in _bookmark_lookup:
|
| 68 |
+
return _bookmark_lookup[s]
|
| 69 |
+
|
| 70 |
+
# Replace invalid characters with hyphens and ensure only valid characters
|
| 71 |
+
bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s)
|
| 72 |
+
|
| 73 |
+
# Ensure it starts with a letter by adding 'z' if necessary
|
| 74 |
+
if not bookmark[:1].isalpha():
|
| 75 |
+
bookmark = f"z{bookmark}"
|
| 76 |
+
|
| 77 |
+
# Convert to lowercase and strip hyphens
|
| 78 |
+
bookmark = bookmark.lower().strip('-')
|
| 79 |
+
|
| 80 |
+
_bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}"
|
| 81 |
+
|
| 82 |
+
return bookmark
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _collapse_verbose_regex(regex_str: str) -> str:
|
| 86 |
+
if "\n" not in regex_str:
|
| 87 |
+
return regex_str
|
| 88 |
+
collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str)
|
| 89 |
+
collapsed = re.sub(r"\s*\n\s*", "", collapsed)
|
| 90 |
+
return collapsed
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclasses.dataclass
|
| 94 |
+
class NamedDiagram:
|
| 95 |
+
"""
|
| 96 |
+
A simple structure for associating a name with a railroad diagram
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
name: str
|
| 100 |
+
index: int
|
| 101 |
+
diagram: railroad.DiagramItem = None
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def bookmark(self):
|
| 105 |
+
bookmark = _make_bookmark(self.name)
|
| 106 |
+
return bookmark
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
T = TypeVar("T")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class EachItem(railroad.Group):
|
| 113 |
+
"""
|
| 114 |
+
Custom railroad item to compose a:
|
| 115 |
+
- Group containing a
|
| 116 |
+
- OneOrMore containing a
|
| 117 |
+
- Choice of the elements in the Each
|
| 118 |
+
with the group label indicating that all must be matched
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
all_label = "[ALL]"
|
| 122 |
+
|
| 123 |
+
def __init__(self, *items) -> None:
|
| 124 |
+
choice_item = railroad.Choice(len(items) - 1, *items)
|
| 125 |
+
one_or_more_item = railroad.OneOrMore(item=choice_item)
|
| 126 |
+
super().__init__(one_or_more_item, label=self.all_label)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class AnnotatedItem(railroad.Group):
|
| 130 |
+
"""
|
| 131 |
+
Simple subclass of Group that creates an annotation label
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def __init__(self, label: str, item) -> None:
|
| 135 |
+
super().__init__(item=item, label=f"[{label}]" if label else "")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class EditablePartial(Generic[T]):
|
| 139 |
+
"""
|
| 140 |
+
Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
|
| 141 |
+
constructed.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
# We need this here because the railroad constructors actually transform the data, so can't be called until the
|
| 145 |
+
# entire tree is assembled
|
| 146 |
+
|
| 147 |
+
def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None:
|
| 148 |
+
self.func = func
|
| 149 |
+
self.args = args
|
| 150 |
+
self.kwargs = kwargs
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]:
|
| 154 |
+
"""
|
| 155 |
+
If you call this function in the same way that you would call the constructor, it will store the arguments
|
| 156 |
+
as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)
|
| 157 |
+
"""
|
| 158 |
+
return EditablePartial(func=func, args=list(args), kwargs=kwargs)
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def name(self):
|
| 162 |
+
return self.kwargs["name"]
|
| 163 |
+
|
| 164 |
+
def __call__(self) -> T:
|
| 165 |
+
"""
|
| 166 |
+
Evaluate the partial and return the result
|
| 167 |
+
"""
|
| 168 |
+
args = self.args.copy()
|
| 169 |
+
kwargs = self.kwargs.copy()
|
| 170 |
+
|
| 171 |
+
# This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
|
| 172 |
+
# args=['list', 'of', 'things'])
|
| 173 |
+
arg_spec = inspect.getfullargspec(self.func)
|
| 174 |
+
if arg_spec.varargs in self.kwargs:
|
| 175 |
+
args += kwargs.pop(arg_spec.varargs)
|
| 176 |
+
|
| 177 |
+
return self.func(*args, **kwargs)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str:
|
| 181 |
+
"""
|
| 182 |
+
Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams
|
| 183 |
+
:params kwargs: kwargs to be passed in to the template
|
| 184 |
+
"""
|
| 185 |
+
data = []
|
| 186 |
+
for diagram in diagrams:
|
| 187 |
+
if diagram.diagram is None:
|
| 188 |
+
continue
|
| 189 |
+
io = StringIO()
|
| 190 |
+
try:
|
| 191 |
+
css = kwargs.get("css")
|
| 192 |
+
diagram.diagram.writeStandalone(io.write, css=css)
|
| 193 |
+
except AttributeError:
|
| 194 |
+
diagram.diagram.writeSvg(io.write)
|
| 195 |
+
title = diagram.name
|
| 196 |
+
if diagram.index == 0:
|
| 197 |
+
title += " (root)"
|
| 198 |
+
data.append(
|
| 199 |
+
{
|
| 200 |
+
"title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark
|
| 201 |
+
}
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
return template.render(diagrams=data, embed=embed, **kwargs)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def resolve_partial(partial: EditablePartial[T]) -> T:
|
| 208 |
+
"""
|
| 209 |
+
Recursively resolves a collection of Partials into whatever type they are
|
| 210 |
+
"""
|
| 211 |
+
if isinstance(partial, EditablePartial):
|
| 212 |
+
partial.args = resolve_partial(partial.args)
|
| 213 |
+
partial.kwargs = resolve_partial(partial.kwargs)
|
| 214 |
+
return partial()
|
| 215 |
+
elif isinstance(partial, list):
|
| 216 |
+
return [resolve_partial(x) for x in partial]
|
| 217 |
+
elif isinstance(partial, dict):
|
| 218 |
+
return {key: resolve_partial(x) for key, x in partial.items()}
|
| 219 |
+
else:
|
| 220 |
+
return partial
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def to_railroad(
|
| 224 |
+
element: pyparsing.ParserElement,
|
| 225 |
+
diagram_kwargs: typing.Optional[dict] = None,
|
| 226 |
+
vertical: int = 3,
|
| 227 |
+
show_results_names: bool = False,
|
| 228 |
+
show_groups: bool = False,
|
| 229 |
+
show_hidden: bool = False,
|
| 230 |
+
) -> list[NamedDiagram]:
|
| 231 |
+
"""
|
| 232 |
+
Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
|
| 233 |
+
creation if you want to access the Railroad tree before it is converted to HTML
|
| 234 |
+
:param element: base element of the parser being diagrammed
|
| 235 |
+
:param diagram_kwargs: kwargs to pass to the Diagram() constructor
|
| 236 |
+
:param vertical: (optional) - int - limit at which number of alternatives should be
|
| 237 |
+
shown vertically instead of horizontally
|
| 238 |
+
:param show_results_names - bool to indicate whether results name annotations should be
|
| 239 |
+
included in the diagram
|
| 240 |
+
:param show_groups - bool to indicate whether groups should be highlighted with an unlabeled
|
| 241 |
+
surrounding box
|
| 242 |
+
:param show_hidden - bool to indicate whether internal elements that are typically hidden
|
| 243 |
+
should be shown
|
| 244 |
+
"""
|
| 245 |
+
# Convert the whole tree underneath the root
|
| 246 |
+
lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
|
| 247 |
+
_to_diagram_element(
|
| 248 |
+
element,
|
| 249 |
+
lookup=lookup,
|
| 250 |
+
parent=None,
|
| 251 |
+
vertical=vertical,
|
| 252 |
+
show_results_names=show_results_names,
|
| 253 |
+
show_groups=show_groups,
|
| 254 |
+
show_hidden=show_hidden,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
root_id = id(element)
|
| 258 |
+
# Convert the root if it hasn't been already
|
| 259 |
+
if root_id in lookup:
|
| 260 |
+
if not element.customName:
|
| 261 |
+
lookup[root_id].name = ""
|
| 262 |
+
lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
|
| 263 |
+
|
| 264 |
+
# Now that we're finished, we can convert from intermediate structures into Railroad elements
|
| 265 |
+
diags = list(lookup.diagrams.values())
|
| 266 |
+
if len(diags) > 1:
|
| 267 |
+
# collapse out duplicate diags with the same name
|
| 268 |
+
seen = set()
|
| 269 |
+
deduped_diags = []
|
| 270 |
+
for d in diags:
|
| 271 |
+
# don't extract SkipTo elements, they are uninformative as subdiagrams
|
| 272 |
+
if d.name == "...":
|
| 273 |
+
continue
|
| 274 |
+
if d.name is not None and d.name not in seen:
|
| 275 |
+
seen.add(d.name)
|
| 276 |
+
deduped_diags.append(d)
|
| 277 |
+
resolved = [resolve_partial(partial) for partial in deduped_diags]
|
| 278 |
+
else:
|
| 279 |
+
# special case - if just one diagram, always display it, even if
|
| 280 |
+
# it has no name
|
| 281 |
+
resolved = [resolve_partial(partial) for partial in diags]
|
| 282 |
+
return sorted(resolved, key=lambda diag: diag.index)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _should_vertical(
|
| 286 |
+
specification: int, exprs: Iterable[pyparsing.ParserElement]
|
| 287 |
+
) -> bool:
|
| 288 |
+
"""
|
| 289 |
+
Returns true if we should return a vertical list of elements
|
| 290 |
+
"""
|
| 291 |
+
if specification is None:
|
| 292 |
+
return False
|
| 293 |
+
else:
|
| 294 |
+
return len(_visible_exprs(exprs)) >= specification
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@dataclasses.dataclass
|
| 298 |
+
class ElementState:
|
| 299 |
+
"""
|
| 300 |
+
State recorded for an individual pyparsing Element
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
#: The pyparsing element that this represents
|
| 304 |
+
element: pyparsing.ParserElement
|
| 305 |
+
#: The output Railroad element in an unconverted state
|
| 306 |
+
converted: EditablePartial
|
| 307 |
+
#: The parent Railroad element, which we store so that we can extract this if it's duplicated
|
| 308 |
+
parent: EditablePartial
|
| 309 |
+
#: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
|
| 310 |
+
number: int
|
| 311 |
+
#: The name of the element
|
| 312 |
+
name: str = None
|
| 313 |
+
#: The index of this inside its parent
|
| 314 |
+
parent_index: typing.Optional[int] = None
|
| 315 |
+
#: If true, we should extract this out into a subdiagram
|
| 316 |
+
extract: bool = False
|
| 317 |
+
#: If true, all of this element's children have been filled out
|
| 318 |
+
complete: bool = False
|
| 319 |
+
|
| 320 |
+
def mark_for_extraction(
|
| 321 |
+
self, el_id: int, state: ConverterState, name: str = None, force: bool = False
|
| 322 |
+
):
|
| 323 |
+
"""
|
| 324 |
+
Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
|
| 325 |
+
:param el_id: id of the element
|
| 326 |
+
:param state: element/diagram state tracker
|
| 327 |
+
:param name: name to use for this element's text
|
| 328 |
+
:param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
|
| 329 |
+
root element when we know we're finished
|
| 330 |
+
"""
|
| 331 |
+
self.extract = True
|
| 332 |
+
|
| 333 |
+
# Set the name
|
| 334 |
+
if not self.name:
|
| 335 |
+
if name:
|
| 336 |
+
# Allow forcing a custom name
|
| 337 |
+
self.name = name
|
| 338 |
+
elif self.element.customName:
|
| 339 |
+
self.name = self.element.customName
|
| 340 |
+
else:
|
| 341 |
+
self.name = ""
|
| 342 |
+
|
| 343 |
+
# Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
|
| 344 |
+
# to be added
|
| 345 |
+
# Also, if this is just a string literal etc, don't bother extracting it
|
| 346 |
+
if force or (self.complete and _worth_extracting(self.element)):
|
| 347 |
+
state.extract_into_diagram(el_id)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class ConverterState:
|
| 351 |
+
"""
|
| 352 |
+
Stores some state that persists between recursions into the element tree
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None:
|
| 356 |
+
#: A dictionary mapping ParserElements to state relating to them
|
| 357 |
+
self._element_diagram_states: dict[int, ElementState] = {}
|
| 358 |
+
#: A dictionary mapping ParserElement IDs to subdiagrams generated from them
|
| 359 |
+
self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {}
|
| 360 |
+
#: The index of the next unnamed element
|
| 361 |
+
self.unnamed_index: int = 1
|
| 362 |
+
#: The index of the next element. This is used for sorting
|
| 363 |
+
self.index: int = 0
|
| 364 |
+
#: Shared kwargs that are used to customize the construction of diagrams
|
| 365 |
+
self.diagram_kwargs: dict = diagram_kwargs or {}
|
| 366 |
+
self.extracted_diagram_names: set[str] = set()
|
| 367 |
+
|
| 368 |
+
def __setitem__(self, key: int, value: ElementState):
|
| 369 |
+
self._element_diagram_states[key] = value
|
| 370 |
+
|
| 371 |
+
def __getitem__(self, key: int) -> ElementState:
|
| 372 |
+
return self._element_diagram_states[key]
|
| 373 |
+
|
| 374 |
+
def __delitem__(self, key: int):
|
| 375 |
+
del self._element_diagram_states[key]
|
| 376 |
+
|
| 377 |
+
def __contains__(self, key: int):
|
| 378 |
+
return key in self._element_diagram_states
|
| 379 |
+
|
| 380 |
+
def get(self, key, default=None):
|
| 381 |
+
try:
|
| 382 |
+
return self[key]
|
| 383 |
+
except KeyError:
|
| 384 |
+
return default
|
| 385 |
+
|
| 386 |
+
def generate_unnamed(self) -> int:
|
| 387 |
+
"""
|
| 388 |
+
Generate a number used in the name of an otherwise unnamed diagram
|
| 389 |
+
"""
|
| 390 |
+
self.unnamed_index += 1
|
| 391 |
+
return self.unnamed_index
|
| 392 |
+
|
| 393 |
+
def generate_index(self) -> int:
|
| 394 |
+
"""
|
| 395 |
+
Generate a number used to index a diagram
|
| 396 |
+
"""
|
| 397 |
+
self.index += 1
|
| 398 |
+
return self.index
|
| 399 |
+
|
| 400 |
+
def extract_into_diagram(self, el_id: int):
|
| 401 |
+
"""
|
| 402 |
+
Used when we encounter the same token twice in the same tree. When this
|
| 403 |
+
happens, we replace all instances of that token with a terminal, and
|
| 404 |
+
create a new subdiagram for the token
|
| 405 |
+
"""
|
| 406 |
+
position = self[el_id]
|
| 407 |
+
|
| 408 |
+
# Replace the original definition of this element with a regular block
|
| 409 |
+
if position.parent:
|
| 410 |
+
href = f"#{_make_bookmark(position.name)}"
|
| 411 |
+
ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href)
|
| 412 |
+
if "item" in position.parent.kwargs:
|
| 413 |
+
position.parent.kwargs["item"] = ret
|
| 414 |
+
elif "items" in position.parent.kwargs:
|
| 415 |
+
position.parent.kwargs["items"][position.parent_index] = ret
|
| 416 |
+
|
| 417 |
+
# If the element we're extracting is a group, skip to its content but keep the title
|
| 418 |
+
if position.converted.func == railroad.Group:
|
| 419 |
+
content = position.converted.kwargs["item"]
|
| 420 |
+
else:
|
| 421 |
+
content = position.converted
|
| 422 |
+
|
| 423 |
+
self.diagrams[el_id] = EditablePartial.from_call(
|
| 424 |
+
NamedDiagram,
|
| 425 |
+
name=position.name,
|
| 426 |
+
diagram=EditablePartial.from_call(
|
| 427 |
+
railroad.Diagram, content, **self.diagram_kwargs
|
| 428 |
+
),
|
| 429 |
+
index=position.number,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
del self[el_id]
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _worth_extracting(element: pyparsing.ParserElement) -> bool:
|
| 436 |
+
"""
|
| 437 |
+
Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
|
| 438 |
+
themselves have children, then its complex enough to extract
|
| 439 |
+
"""
|
| 440 |
+
children = element.recurse()
|
| 441 |
+
return any(child.recurse() for child in children)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _apply_diagram_item_enhancements(fn):
|
| 445 |
+
"""
|
| 446 |
+
decorator to ensure enhancements to a diagram item (such as results name annotations)
|
| 447 |
+
get applied on return from _to_diagram_element (we do this since there are several
|
| 448 |
+
returns in _to_diagram_element)
|
| 449 |
+
"""
|
| 450 |
+
|
| 451 |
+
def _inner(
|
| 452 |
+
element: pyparsing.ParserElement,
|
| 453 |
+
parent: typing.Optional[EditablePartial],
|
| 454 |
+
lookup: ConverterState = None,
|
| 455 |
+
vertical: int = None,
|
| 456 |
+
index: int = 0,
|
| 457 |
+
name_hint: str = None,
|
| 458 |
+
show_results_names: bool = False,
|
| 459 |
+
show_groups: bool = False,
|
| 460 |
+
show_hidden: bool = False,
|
| 461 |
+
) -> typing.Optional[EditablePartial]:
|
| 462 |
+
ret = fn(
|
| 463 |
+
element,
|
| 464 |
+
parent,
|
| 465 |
+
lookup,
|
| 466 |
+
vertical,
|
| 467 |
+
index,
|
| 468 |
+
name_hint,
|
| 469 |
+
show_results_names,
|
| 470 |
+
show_groups,
|
| 471 |
+
show_hidden,
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
# apply annotation for results name, if present
|
| 475 |
+
if show_results_names and ret is not None:
|
| 476 |
+
element_results_name = element.resultsName
|
| 477 |
+
if element_results_name:
|
| 478 |
+
# add "*" to indicate if this is a "list all results" name
|
| 479 |
+
modal_tag = "" if element.modalResults else "*"
|
| 480 |
+
ret = EditablePartial.from_call(
|
| 481 |
+
railroad.Group,
|
| 482 |
+
item=ret,
|
| 483 |
+
label=f"{repr(element_results_name)}{modal_tag}",
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
return ret
|
| 487 |
+
|
| 488 |
+
return _inner
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
|
| 492 |
+
non_diagramming_exprs = (
|
| 493 |
+
pyparsing.ParseElementEnhance,
|
| 494 |
+
pyparsing.PositionToken,
|
| 495 |
+
pyparsing.And._ErrorStop,
|
| 496 |
+
)
|
| 497 |
+
return [
|
| 498 |
+
e
|
| 499 |
+
for e in exprs
|
| 500 |
+
if not isinstance(e, non_diagramming_exprs)
|
| 501 |
+
]
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@_apply_diagram_item_enhancements
|
| 505 |
+
def _to_diagram_element(
|
| 506 |
+
element: pyparsing.ParserElement,
|
| 507 |
+
parent: typing.Optional[EditablePartial],
|
| 508 |
+
lookup: ConverterState = None,
|
| 509 |
+
vertical: int = None,
|
| 510 |
+
index: int = 0,
|
| 511 |
+
name_hint: str = None,
|
| 512 |
+
show_results_names: bool = False,
|
| 513 |
+
show_groups: bool = False,
|
| 514 |
+
show_hidden: bool = False,
|
| 515 |
+
) -> typing.Optional[EditablePartial]:
|
| 516 |
+
"""
|
| 517 |
+
Recursively converts a PyParsing Element to a railroad Element
|
| 518 |
+
:param lookup: The shared converter state that keeps track of useful things
|
| 519 |
+
:param index: The index of this element within the parent
|
| 520 |
+
:param parent: The parent of this element in the output tree
|
| 521 |
+
:param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
|
| 522 |
+
it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
|
| 523 |
+
do so
|
| 524 |
+
:param name_hint: If provided, this will override the generated name
|
| 525 |
+
:param show_results_names: bool flag indicating whether to add annotations for results names
|
| 526 |
+
:param show_groups: bool flag indicating whether to show groups using bounding box
|
| 527 |
+
:param show_hidden: bool flag indicating whether to show elements that are typically hidden
|
| 528 |
+
:returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
|
| 529 |
+
"""
|
| 530 |
+
exprs = element.recurse()
|
| 531 |
+
name = name_hint or element.customName or type(element).__name__
|
| 532 |
+
|
| 533 |
+
# Python's id() is used to provide a unique identifier for elements
|
| 534 |
+
el_id = id(element)
|
| 535 |
+
|
| 536 |
+
element_results_name = element.resultsName
|
| 537 |
+
|
| 538 |
+
# Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
|
| 539 |
+
if not element.customName:
|
| 540 |
+
if isinstance(
|
| 541 |
+
element,
|
| 542 |
+
(
|
| 543 |
+
# pyparsing.TokenConverter,
|
| 544 |
+
pyparsing.Forward,
|
| 545 |
+
pyparsing.Located,
|
| 546 |
+
),
|
| 547 |
+
):
|
| 548 |
+
# However, if this element has a useful custom name, and its child does not, we can pass it on to the child
|
| 549 |
+
if exprs:
|
| 550 |
+
if not exprs[0].customName:
|
| 551 |
+
propagated_name = name
|
| 552 |
+
else:
|
| 553 |
+
propagated_name = None
|
| 554 |
+
|
| 555 |
+
return _to_diagram_element(
|
| 556 |
+
element.expr,
|
| 557 |
+
parent=parent,
|
| 558 |
+
lookup=lookup,
|
| 559 |
+
vertical=vertical,
|
| 560 |
+
index=index,
|
| 561 |
+
name_hint=propagated_name,
|
| 562 |
+
show_results_names=show_results_names,
|
| 563 |
+
show_groups=show_groups,
|
| 564 |
+
show_hidden=show_hidden,
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
# If the element isn't worth extracting, we always treat it as the first time we say it
|
| 568 |
+
if _worth_extracting(element):
|
| 569 |
+
looked_up = lookup.get(el_id)
|
| 570 |
+
if looked_up and looked_up.name is not None:
|
| 571 |
+
# If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
|
| 572 |
+
# so we have to extract it into a new diagram.
|
| 573 |
+
looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
|
| 574 |
+
href = f"#{_make_bookmark(looked_up.name)}"
|
| 575 |
+
ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href)
|
| 576 |
+
return ret
|
| 577 |
+
|
| 578 |
+
elif el_id in lookup.diagrams:
|
| 579 |
+
# If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
|
| 580 |
+
# just put in a marker element that refers to the sub-diagram
|
| 581 |
+
text = lookup.diagrams[el_id].kwargs["name"]
|
| 582 |
+
ret = EditablePartial.from_call(
|
| 583 |
+
railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}"
|
| 584 |
+
)
|
| 585 |
+
return ret
|
| 586 |
+
|
| 587 |
+
# Recursively convert child elements
|
| 588 |
+
# Here we find the most relevant Railroad element for matching pyparsing Element
|
| 589 |
+
# We use ``items=[]`` here to hold the place for where the child elements will go once created
|
| 590 |
+
|
| 591 |
+
# see if this element is normally hidden, and whether hidden elements are desired
|
| 592 |
+
# if not, just return None
|
| 593 |
+
if not element.show_in_diagram and not show_hidden:
|
| 594 |
+
return None
|
| 595 |
+
|
| 596 |
+
if isinstance(element, pyparsing.And):
|
| 597 |
+
# detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
|
| 598 |
+
# (all will have the same name, and resultsName)
|
| 599 |
+
if not exprs:
|
| 600 |
+
return None
|
| 601 |
+
if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2:
|
| 602 |
+
ret = EditablePartial.from_call(
|
| 603 |
+
railroad.OneOrMore, item="", repeat=str(len(exprs))
|
| 604 |
+
)
|
| 605 |
+
elif _should_vertical(vertical, exprs):
|
| 606 |
+
ret = EditablePartial.from_call(railroad.Stack, items=[])
|
| 607 |
+
else:
|
| 608 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
| 609 |
+
elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
|
| 610 |
+
if not exprs:
|
| 611 |
+
return None
|
| 612 |
+
if _should_vertical(vertical, exprs):
|
| 613 |
+
ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
|
| 614 |
+
else:
|
| 615 |
+
ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
|
| 616 |
+
elif isinstance(element, pyparsing.Each):
|
| 617 |
+
if not exprs:
|
| 618 |
+
return None
|
| 619 |
+
ret = EditablePartial.from_call(EachItem, items=[])
|
| 620 |
+
elif isinstance(element, pyparsing.NotAny):
|
| 621 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
|
| 622 |
+
elif isinstance(element, pyparsing.FollowedBy):
|
| 623 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
|
| 624 |
+
elif isinstance(element, pyparsing.PrecededBy):
|
| 625 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
|
| 626 |
+
elif isinstance(element, pyparsing.Group):
|
| 627 |
+
if show_groups:
|
| 628 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="", item="")
|
| 629 |
+
else:
|
| 630 |
+
ret = EditablePartial.from_call(
|
| 631 |
+
railroad.Group, item=None, label=element_results_name
|
| 632 |
+
)
|
| 633 |
+
elif isinstance(element, pyparsing.TokenConverter):
|
| 634 |
+
label = type(element).__name__.lower()
|
| 635 |
+
if label == "tokenconverter":
|
| 636 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
| 637 |
+
else:
|
| 638 |
+
ret = EditablePartial.from_call(AnnotatedItem, label=label, item="")
|
| 639 |
+
elif isinstance(element, pyparsing.Opt):
|
| 640 |
+
ret = EditablePartial.from_call(railroad.Optional, item="")
|
| 641 |
+
elif isinstance(element, pyparsing.OneOrMore):
|
| 642 |
+
if element.not_ender is not None:
|
| 643 |
+
args = [
|
| 644 |
+
parent,
|
| 645 |
+
lookup,
|
| 646 |
+
vertical,
|
| 647 |
+
index,
|
| 648 |
+
name_hint,
|
| 649 |
+
show_results_names,
|
| 650 |
+
show_groups,
|
| 651 |
+
show_hidden,
|
| 652 |
+
]
|
| 653 |
+
return _to_diagram_element(
|
| 654 |
+
(~element.not_ender.expr + element.expr)[1, ...].set_name(element.name),
|
| 655 |
+
*args,
|
| 656 |
+
)
|
| 657 |
+
ret = EditablePartial.from_call(railroad.OneOrMore, item=None)
|
| 658 |
+
elif isinstance(element, pyparsing.ZeroOrMore):
|
| 659 |
+
if element.not_ender is not None:
|
| 660 |
+
args = [
|
| 661 |
+
parent,
|
| 662 |
+
lookup,
|
| 663 |
+
vertical,
|
| 664 |
+
index,
|
| 665 |
+
name_hint,
|
| 666 |
+
show_results_names,
|
| 667 |
+
show_groups,
|
| 668 |
+
show_hidden,
|
| 669 |
+
]
|
| 670 |
+
return _to_diagram_element(
|
| 671 |
+
(~element.not_ender.expr + element.expr)[...].set_name(element.name),
|
| 672 |
+
*args,
|
| 673 |
+
)
|
| 674 |
+
ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
|
| 675 |
+
elif isinstance(element, pyparsing.Empty) and not element.customName:
|
| 676 |
+
# Skip unnamed "Empty" elements
|
| 677 |
+
ret = None
|
| 678 |
+
elif isinstance(element, pyparsing.ParseElementEnhance):
|
| 679 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
| 680 |
+
elif len(exprs) > 0 and not element_results_name:
|
| 681 |
+
ret = EditablePartial.from_call(railroad.Group, item="", label=name)
|
| 682 |
+
elif isinstance(element, pyparsing.Regex):
|
| 683 |
+
collapsed_patt = _collapse_verbose_regex(element.pattern)
|
| 684 |
+
ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt)
|
| 685 |
+
elif len(exprs) > 0:
|
| 686 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
| 687 |
+
else:
|
| 688 |
+
terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
|
| 689 |
+
ret = terminal
|
| 690 |
+
|
| 691 |
+
if ret is None:
|
| 692 |
+
return
|
| 693 |
+
|
| 694 |
+
# Indicate this element's position in the tree so we can extract it if necessary
|
| 695 |
+
lookup[el_id] = ElementState(
|
| 696 |
+
element=element,
|
| 697 |
+
converted=ret,
|
| 698 |
+
parent=parent,
|
| 699 |
+
parent_index=index,
|
| 700 |
+
number=lookup.generate_index(),
|
| 701 |
+
)
|
| 702 |
+
if element.customName:
|
| 703 |
+
lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
|
| 704 |
+
|
| 705 |
+
i = 0
|
| 706 |
+
for expr in exprs:
|
| 707 |
+
# Add a placeholder index in case we have to extract the child before we even add it to the parent
|
| 708 |
+
if "items" in ret.kwargs:
|
| 709 |
+
ret.kwargs["items"].insert(i, None)
|
| 710 |
+
|
| 711 |
+
item = _to_diagram_element(
|
| 712 |
+
expr,
|
| 713 |
+
parent=ret,
|
| 714 |
+
lookup=lookup,
|
| 715 |
+
vertical=vertical,
|
| 716 |
+
index=i,
|
| 717 |
+
show_results_names=show_results_names,
|
| 718 |
+
show_groups=show_groups,
|
| 719 |
+
show_hidden=show_hidden,
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
# Some elements don't need to be shown in the diagram
|
| 723 |
+
if item is not None:
|
| 724 |
+
if "item" in ret.kwargs:
|
| 725 |
+
ret.kwargs["item"] = item
|
| 726 |
+
elif "items" in ret.kwargs:
|
| 727 |
+
# If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
|
| 728 |
+
ret.kwargs["items"][i] = item
|
| 729 |
+
i += 1
|
| 730 |
+
elif "items" in ret.kwargs:
|
| 731 |
+
# If we're supposed to skip this element, remove it from the parent
|
| 732 |
+
del ret.kwargs["items"][i]
|
| 733 |
+
|
| 734 |
+
# If all this items children are none, skip this item
|
| 735 |
+
if ret and (
|
| 736 |
+
("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
|
| 737 |
+
or ("item" in ret.kwargs and ret.kwargs["item"] is None)
|
| 738 |
+
):
|
| 739 |
+
ret = EditablePartial.from_call(railroad.Terminal, name)
|
| 740 |
+
|
| 741 |
+
# Mark this element as "complete", ie it has all of its children
|
| 742 |
+
if el_id in lookup:
|
| 743 |
+
lookup[el_id].complete = True
|
| 744 |
+
|
| 745 |
+
if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
|
| 746 |
+
lookup.extract_into_diagram(el_id)
|
| 747 |
+
if ret is not None:
|
| 748 |
+
text = lookup.diagrams[el_id].kwargs["name"]
|
| 749 |
+
href = f"#{_make_bookmark(text)}"
|
| 750 |
+
ret = EditablePartial.from_call(
|
| 751 |
+
railroad.NonTerminal, text=text, href=href
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
return ret
|
python_embeded/Lib/site-packages/pyparsing/tools/__init__.py
ADDED
|
File without changes
|
python_embeded/Lib/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache
|
| 2 |
+
import pyparsing as pp
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@lru_cache(maxsize=None)
|
| 6 |
+
def camel_to_snake(s: str) -> str:
|
| 7 |
+
"""
|
| 8 |
+
Convert CamelCase to snake_case.
|
| 9 |
+
"""
|
| 10 |
+
return "".join("_" + c.lower() if c.isupper() else c for c in s).lstrip("_")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
pre_pep8_method_names = """
|
| 14 |
+
addCondition addParseAction anyCloseTag anyOpenTag asDict asList cStyleComment canParseNext conditionAsParseAction
|
| 15 |
+
convertToDate convertToDatetime convertToFloat convertToInteger countedArray cppStyleComment dblQuotedString
|
| 16 |
+
dblSlashComment defaultName dictOf disableMemoization downcaseTokens enableLeftRecursion enablePackrat getName
|
| 17 |
+
htmlComment ignoreWhitespace indentedBlock infixNotation inlineLiteralsUsing javaStyleComment leaveWhitespace
|
| 18 |
+
lineEnd lineStart locatedExpr matchOnlyAtCol matchPreviousExpr matchPreviousLiteral nestedExpr nullDebugAction oneOf
|
| 19 |
+
originalTextFor parseFile parseString parseWithTabs pythonStyleComment quotedString removeQuotes replaceWith
|
| 20 |
+
resetCache restOfLine runTests scanString searchString setBreak setDebug setDebugActions setDefaultWhitespaceChars
|
| 21 |
+
setFailAction setName setParseAction setResultsName setWhitespaceChars sglQuotedString stringEnd stringStart tokenMap
|
| 22 |
+
traceParseAction transformString tryParse unicodeString upcaseTokens withAttribute withClass
|
| 23 |
+
""".split()
|
| 24 |
+
|
| 25 |
+
special_changes = {
|
| 26 |
+
"opAssoc": "OpAssoc",
|
| 27 |
+
"delimitedList": "DelimitedList",
|
| 28 |
+
"delimited_list": "DelimitedList",
|
| 29 |
+
"replaceHTMLEntity": "replace_html_entity",
|
| 30 |
+
"makeHTMLTags": "make_html_tags",
|
| 31 |
+
"makeXMLTags": "make_xml_tags",
|
| 32 |
+
"commonHTMLEntity": "common_html_entity",
|
| 33 |
+
"stripHTMLTags": "strip_html_tags",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
pre_pep8_arg_names = """parseAll maxMatches listAllMatches callDuringTry includeSeparators fullDump printResults
|
| 37 |
+
failureTests postParse matchString identChars maxMismatches initChars bodyChars asKeyword excludeChars asGroupList
|
| 38 |
+
asMatch quoteChar escChar escQuote unquoteResults endQuoteChar convertWhitespaceEscapes notChars wordChars stopOn
|
| 39 |
+
failOn joinString markerString intExpr useRegex asString ignoreExpr""".split()
|
| 40 |
+
|
| 41 |
+
pre_pep8_method_name = pp.one_of(pre_pep8_method_names, as_keyword=True)
|
| 42 |
+
pre_pep8_method_name.set_parse_action(lambda t: camel_to_snake(t[0]))
|
| 43 |
+
special_pre_pep8_name = pp.one_of(special_changes, as_keyword=True)
|
| 44 |
+
special_pre_pep8_name.set_parse_action(lambda t: special_changes[t[0]])
|
| 45 |
+
# only replace arg names if part of an arg list
|
| 46 |
+
pre_pep8_arg_name = pp.Regex(
|
| 47 |
+
rf"{pp.util.make_compressed_re(pre_pep8_arg_names)}\s*="
|
| 48 |
+
)
|
| 49 |
+
pre_pep8_arg_name.set_parse_action(lambda t: camel_to_snake(t[0]))
|
| 50 |
+
|
| 51 |
+
pep8_converter = pre_pep8_method_name | special_pre_pep8_name | pre_pep8_arg_name
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
import argparse
|
| 55 |
+
from pathlib import Path
|
| 56 |
+
import sys
|
| 57 |
+
|
| 58 |
+
argparser = argparse.ArgumentParser(
|
| 59 |
+
description = (
|
| 60 |
+
"Utility to convert Python pyparsing scripts using legacy"
|
| 61 |
+
" camelCase names to use PEP8 snake_case names."
|
| 62 |
+
"\nBy default, this script will only show whether this script would make any changes."
|
| 63 |
+
)
|
| 64 |
+
)
|
| 65 |
+
argparser.add_argument("--verbose", "-v", action="store_true", help="Show unified diff for each source file")
|
| 66 |
+
argparser.add_argument("-vv", action="store_true", dest="verbose2", help="Show unified diff for each source file, plus names of scanned files with no changes")
|
| 67 |
+
argparser.add_argument("--update", "-u", action="store_true", help="Update source files in-place")
|
| 68 |
+
argparser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of source files (default: utf-8)")
|
| 69 |
+
argparser.add_argument("--exit-zero-even-if-changed", "-exit0", action="store_true", help="Exit with status code 0 even if changes were made")
|
| 70 |
+
argparser.add_argument("source_filename", nargs="+", help="Source filenames or filename patterns of Python files to be converted")
|
| 71 |
+
args = argparser.parse_args()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def show_diffs(original, modified):
|
| 75 |
+
import difflib
|
| 76 |
+
|
| 77 |
+
diff = difflib.unified_diff(
|
| 78 |
+
original.splitlines(), modified.splitlines(), lineterm=""
|
| 79 |
+
)
|
| 80 |
+
sys.stdout.writelines(f"{diff_line}\n" for diff_line in diff)
|
| 81 |
+
|
| 82 |
+
exit_status = 0
|
| 83 |
+
|
| 84 |
+
for filename_pattern in args.source_filename:
|
| 85 |
+
|
| 86 |
+
for filename in Path().glob(filename_pattern):
|
| 87 |
+
if not Path(filename).is_file():
|
| 88 |
+
continue
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
original_contents = Path(filename).read_text(encoding=args.encoding)
|
| 92 |
+
modified_contents = pep8_converter.transform_string(
|
| 93 |
+
original_contents
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
if modified_contents != original_contents:
|
| 97 |
+
if args.update:
|
| 98 |
+
Path(filename).write_text(modified_contents, encoding=args.encoding)
|
| 99 |
+
print(f"Converted {filename}")
|
| 100 |
+
else:
|
| 101 |
+
print(f"Found required changes in {filename}")
|
| 102 |
+
|
| 103 |
+
if args.verbose:
|
| 104 |
+
show_diffs(original_contents, modified_contents)
|
| 105 |
+
print()
|
| 106 |
+
|
| 107 |
+
exit_status = 1
|
| 108 |
+
|
| 109 |
+
else:
|
| 110 |
+
if args.verbose2:
|
| 111 |
+
print(f"No required changes in {filename}")
|
| 112 |
+
|
| 113 |
+
except Exception as e:
|
| 114 |
+
print(f"Failed to convert {filename}: {type(e).__name__}: {e}")
|
| 115 |
+
|
| 116 |
+
sys.exit(exit_status if not args.exit_zero_even_if_changed else 0)
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
from .api import set_clipboard_text
|
| 11 |
+
from .get_clipboard_text_and_convert import get_clipboard_text_and_convert
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"set_clipboard_text",
|
| 15 |
+
"get_clipboard_text_and_convert",
|
| 16 |
+
]
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/api.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
from pyreadline3.py3k_compat import is_ironpython
|
| 11 |
+
|
| 12 |
+
if is_ironpython:
|
| 13 |
+
try:
|
| 14 |
+
from .ironpython_clipboard import get_clipboard_text, set_clipboard_text
|
| 15 |
+
except ImportError:
|
| 16 |
+
from .no_clipboard import get_clipboard_text, set_clipboard_text
|
| 17 |
+
|
| 18 |
+
else:
|
| 19 |
+
try:
|
| 20 |
+
from .win32_clipboard import get_clipboard_text, set_clipboard_text
|
| 21 |
+
except ImportError:
|
| 22 |
+
from .no_clipboard import get_clipboard_text, set_clipboard_text
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"get_clipboard_text",
|
| 26 |
+
"set_clipboard_text",
|
| 27 |
+
]
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/get_clipboard_text_and_convert.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
from typing import Any, List, Tuple
|
| 11 |
+
|
| 12 |
+
from .api import get_clipboard_text
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _make_num(x: Any) -> Any:
|
| 16 |
+
try:
|
| 17 |
+
return int(x)
|
| 18 |
+
except ValueError:
|
| 19 |
+
try:
|
| 20 |
+
return float(x)
|
| 21 |
+
except ValueError:
|
| 22 |
+
try:
|
| 23 |
+
return complex(x)
|
| 24 |
+
except ValueError:
|
| 25 |
+
return x
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _make_list_of_list(txt: str) -> Tuple[
|
| 29 |
+
List[List[Any]],
|
| 30 |
+
bool,
|
| 31 |
+
]:
|
| 32 |
+
|
| 33 |
+
ut = []
|
| 34 |
+
flag = False
|
| 35 |
+
|
| 36 |
+
for line in [x for x in txt.split("\r\n") if x != ""]:
|
| 37 |
+
words = [_make_num(x) for x in line.split("\t")]
|
| 38 |
+
|
| 39 |
+
if str in list(map(type, words)):
|
| 40 |
+
flag = True
|
| 41 |
+
|
| 42 |
+
ut.append(words)
|
| 43 |
+
|
| 44 |
+
return (
|
| 45 |
+
ut,
|
| 46 |
+
flag,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_clipboard_text_and_convert(paste_list: bool = False) -> str:
|
| 51 |
+
"""Get txt from clipboard. if paste_list==True the convert tab separated
|
| 52 |
+
data to list of lists. Enclose list of list in array() if all elements are
|
| 53 |
+
numeric"""
|
| 54 |
+
|
| 55 |
+
txt = get_clipboard_text()
|
| 56 |
+
|
| 57 |
+
if not txt:
|
| 58 |
+
return ""
|
| 59 |
+
|
| 60 |
+
if not paste_list:
|
| 61 |
+
return txt
|
| 62 |
+
|
| 63 |
+
if "\t" not in txt:
|
| 64 |
+
return txt
|
| 65 |
+
|
| 66 |
+
array, flag = _make_list_of_list(txt)
|
| 67 |
+
|
| 68 |
+
if flag:
|
| 69 |
+
txt = repr(array)
|
| 70 |
+
else:
|
| 71 |
+
txt = "array(%s)" % repr(array)
|
| 72 |
+
|
| 73 |
+
txt = "".join([c for c in txt if c not in " \t\r\n"])
|
| 74 |
+
|
| 75 |
+
return txt
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/ironpython_clipboard.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import clr
|
| 12 |
+
import System.Windows.Forms.Clipboard as cb
|
| 13 |
+
|
| 14 |
+
clr.AddReferenceByPartialName("System.Windows.Forms")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_clipboard_text() -> str:
|
| 18 |
+
text = ""
|
| 19 |
+
if cb.ContainsText():
|
| 20 |
+
text = cb.GetText()
|
| 21 |
+
|
| 22 |
+
return text
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def set_clipboard_text(text: str) -> None:
|
| 26 |
+
cb.SetText(text)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
txt = get_clipboard_text() # display last text clipped
|
| 31 |
+
print(txt)
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/no_clipboard.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
GLOBAL_CLIPBOARD_BUFFER = ""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_clipboard_text() -> str:
|
| 14 |
+
return GLOBAL_CLIPBOARD_BUFFER
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def set_clipboard_text(text: str) -> None:
|
| 18 |
+
global GLOBAL_CLIPBOARD_BUFFER
|
| 19 |
+
GLOBAL_CLIPBOARD_BUFFER = text
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/obsolete.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 4 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
# *****************************************************************************
|
| 9 |
+
|
| 10 |
+
from typing import Any, List
|
| 11 |
+
|
| 12 |
+
from .api import set_clipboard_text
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _make_tab(lists: List[Any]) -> str:
|
| 16 |
+
if hasattr(lists, "tolist"):
|
| 17 |
+
lists = lists.tolist()
|
| 18 |
+
|
| 19 |
+
ut = []
|
| 20 |
+
for rad in lists:
|
| 21 |
+
if type(rad) in [list, tuple]:
|
| 22 |
+
ut.append("\t".join(["%s" % x for x in rad]))
|
| 23 |
+
else:
|
| 24 |
+
ut.append("%s" % rad)
|
| 25 |
+
|
| 26 |
+
return "\n".join(ut)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _send_data(lists: List[Any]) -> None:
|
| 30 |
+
set_clipboard_text(_make_tab(lists))
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/py.typed
ADDED
|
File without changes
|
python_embeded/Lib/site-packages/pyreadline3/clipboard/win32_clipboard.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2003-2006 Jack Trainor.
|
| 4 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 5 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 6 |
+
#
|
| 7 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 8 |
+
# the file COPYING, distributed as part of this software.
|
| 9 |
+
# *****************************************************************************
|
| 10 |
+
###################################
|
| 11 |
+
#
|
| 12 |
+
# Based on recipe posted to ctypes-users
|
| 13 |
+
# see archive
|
| 14 |
+
# http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1771866
|
| 15 |
+
#
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
##########################################################################
|
| 19 |
+
#
|
| 20 |
+
# The Python win32clipboard lib functions work well enough ... except that they
|
| 21 |
+
# can only cut and paste items from within one application, not across
|
| 22 |
+
# applications or processes.
|
| 23 |
+
#
|
| 24 |
+
# I've written a number of Python text filters I like to run on the contents of
|
| 25 |
+
# the clipboard so I need to call the Windows clipboard API with global memory
|
| 26 |
+
# for my filters to work properly.
|
| 27 |
+
#
|
| 28 |
+
# Here's some sample code solving this problem using ctypes.
|
| 29 |
+
#
|
| 30 |
+
# This is my first work with ctypes. It's powerful stuff, but passing
|
| 31 |
+
# arguments in and out of functions is tricky. More sample code would have
|
| 32 |
+
# been helpful, hence this contribution.
|
| 33 |
+
#
|
| 34 |
+
##########################################################################
|
| 35 |
+
|
| 36 |
+
import ctypes
|
| 37 |
+
import ctypes.wintypes as wintypes
|
| 38 |
+
from ctypes import (
|
| 39 |
+
addressof,
|
| 40 |
+
c_buffer,
|
| 41 |
+
c_char_p,
|
| 42 |
+
c_int,
|
| 43 |
+
c_size_t,
|
| 44 |
+
c_void_p,
|
| 45 |
+
c_wchar_p,
|
| 46 |
+
cast,
|
| 47 |
+
create_unicode_buffer,
|
| 48 |
+
sizeof,
|
| 49 |
+
windll,
|
| 50 |
+
wstring_at,
|
| 51 |
+
)
|
| 52 |
+
from typing import Union
|
| 53 |
+
|
| 54 |
+
from pyreadline3.keysyms.winconstants import CF_UNICODETEXT, GHND
|
| 55 |
+
from pyreadline3.unicode_helper import ensure_unicode
|
| 56 |
+
|
| 57 |
+
OpenClipboard = windll.user32.OpenClipboard
|
| 58 |
+
OpenClipboard.argtypes = [wintypes.HWND]
|
| 59 |
+
OpenClipboard.restype = wintypes.BOOL
|
| 60 |
+
|
| 61 |
+
EmptyClipboard = windll.user32.EmptyClipboard
|
| 62 |
+
|
| 63 |
+
GetClipboardData = windll.user32.GetClipboardData
|
| 64 |
+
GetClipboardData.argtypes = [wintypes.UINT]
|
| 65 |
+
GetClipboardData.restype = wintypes.HANDLE
|
| 66 |
+
|
| 67 |
+
GetClipboardFormatName = windll.user32.GetClipboardFormatNameA
|
| 68 |
+
GetClipboardFormatName.argtypes = [wintypes.UINT, c_char_p, c_int]
|
| 69 |
+
|
| 70 |
+
SetClipboardData = windll.user32.SetClipboardData
|
| 71 |
+
SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]
|
| 72 |
+
SetClipboardData.restype = wintypes.HANDLE
|
| 73 |
+
|
| 74 |
+
EnumClipboardFormats = windll.user32.EnumClipboardFormats
|
| 75 |
+
EnumClipboardFormats.argtypes = [c_int]
|
| 76 |
+
|
| 77 |
+
CloseClipboard = windll.user32.CloseClipboard
|
| 78 |
+
CloseClipboard.argtypes = []
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
GlobalAlloc = windll.kernel32.GlobalAlloc
|
| 82 |
+
GlobalAlloc.argtypes = [wintypes.UINT, c_size_t]
|
| 83 |
+
GlobalAlloc.restype = wintypes.HGLOBAL
|
| 84 |
+
GlobalLock = windll.kernel32.GlobalLock
|
| 85 |
+
GlobalLock.argtypes = [wintypes.HGLOBAL]
|
| 86 |
+
GlobalLock.restype = c_void_p
|
| 87 |
+
GlobalUnlock = windll.kernel32.GlobalUnlock
|
| 88 |
+
GlobalUnlock.argtypes = [c_int]
|
| 89 |
+
|
| 90 |
+
_strncpy = ctypes.windll.kernel32.lstrcpynW
|
| 91 |
+
_strncpy.restype = c_wchar_p
|
| 92 |
+
_strncpy.argtypes = [c_wchar_p, c_wchar_p, c_size_t]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _enum() -> None:
|
| 96 |
+
OpenClipboard(0)
|
| 97 |
+
|
| 98 |
+
q = EnumClipboardFormats(0)
|
| 99 |
+
while q:
|
| 100 |
+
q = EnumClipboardFormats(q)
|
| 101 |
+
|
| 102 |
+
CloseClipboard()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _get_format_name(format_str: str) -> bytes:
|
| 106 |
+
buffer = c_buffer(100)
|
| 107 |
+
bufferSize = sizeof(buffer)
|
| 108 |
+
|
| 109 |
+
OpenClipboard(0)
|
| 110 |
+
|
| 111 |
+
GetClipboardFormatName(format_str, buffer, bufferSize)
|
| 112 |
+
|
| 113 |
+
CloseClipboard()
|
| 114 |
+
|
| 115 |
+
return buffer.value
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def get_clipboard_text() -> str:
|
| 119 |
+
text = ""
|
| 120 |
+
|
| 121 |
+
if OpenClipboard(0):
|
| 122 |
+
h_clip_mem = GetClipboardData(CF_UNICODETEXT)
|
| 123 |
+
|
| 124 |
+
if h_clip_mem:
|
| 125 |
+
text = wstring_at(GlobalLock(h_clip_mem))
|
| 126 |
+
GlobalUnlock(h_clip_mem)
|
| 127 |
+
|
| 128 |
+
CloseClipboard()
|
| 129 |
+
|
| 130 |
+
return text
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def set_clipboard_text(text: Union[str, bytes]) -> None:
|
| 134 |
+
buffer = create_unicode_buffer(ensure_unicode(text))
|
| 135 |
+
buffer_size = sizeof(buffer)
|
| 136 |
+
|
| 137 |
+
h_global_mem = GlobalAlloc(GHND, c_size_t(buffer_size))
|
| 138 |
+
GlobalLock.restype = c_void_p
|
| 139 |
+
lp_global_mem = GlobalLock(h_global_mem)
|
| 140 |
+
|
| 141 |
+
_strncpy(
|
| 142 |
+
cast(lp_global_mem, c_wchar_p),
|
| 143 |
+
cast(addressof(buffer), c_wchar_p),
|
| 144 |
+
c_size_t(buffer_size),
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
GlobalUnlock(c_int(h_global_mem))
|
| 148 |
+
|
| 149 |
+
if OpenClipboard(0):
|
| 150 |
+
EmptyClipboard()
|
| 151 |
+
SetClipboardData(CF_UNICODETEXT, h_global_mem)
|
| 152 |
+
CloseClipboard()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
txt = get_clipboard_text() # display last text clipped
|
| 157 |
+
print(txt)
|
python_embeded/Lib/site-packages/pyreadline3/configuration/pyreadlineconfig.ini
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#Bind keys for exit (keys only work on empty lines
|
| 2 |
+
#disable_readline(True) #Disable pyreadline3 completely.
|
| 3 |
+
from __future__ import absolute_import
|
| 4 |
+
debug_output("off") #"on" saves log info to./pyreadline_debug_log.txt
|
| 5 |
+
#"on_nologfile" only enables print warning messages
|
| 6 |
+
bind_exit_key("Control-d")
|
| 7 |
+
bind_exit_key("Control-z")
|
| 8 |
+
|
| 9 |
+
#Commands for moving
|
| 10 |
+
bind_key("Home", "beginning_of_line")
|
| 11 |
+
bind_key("End", "end_of_line")
|
| 12 |
+
bind_key("Left", "backward_char")
|
| 13 |
+
bind_key("Control-b", "backward_char")
|
| 14 |
+
bind_key("Right", "forward_char")
|
| 15 |
+
bind_key("Control-f", "forward_char")
|
| 16 |
+
bind_key("Alt-f", "forward_word")
|
| 17 |
+
bind_key("Alt-b", "backward_word")
|
| 18 |
+
bind_key("Clear", "clear_screen")
|
| 19 |
+
bind_key("Control-l", "clear_screen")
|
| 20 |
+
bind_key("Control-a", "beginning_of_line")
|
| 21 |
+
bind_key("Control-e", "end_of_line")
|
| 22 |
+
#bind_key("Control-l", "redraw_current_line")
|
| 23 |
+
|
| 24 |
+
#Commands for Manipulating the History
|
| 25 |
+
bind_key("Return", "accept_line")
|
| 26 |
+
bind_key("Control-p", "previous_history")
|
| 27 |
+
bind_key("Control-n", "next_history")
|
| 28 |
+
bind_key("Up", "history_search_backward")
|
| 29 |
+
bind_key("Down", "history_search_forward")
|
| 30 |
+
bind_key("Alt-<", "beginning_of_history")
|
| 31 |
+
bind_key("Alt->", "end_of_history")
|
| 32 |
+
bind_key("Control-r", "reverse_search_history")
|
| 33 |
+
bind_key("Control-s", "forward_search_history")
|
| 34 |
+
bind_key("Alt-p", "non_incremental_reverse_search_history")
|
| 35 |
+
bind_key("Alt-n", "non_incremental_forward_search_history")
|
| 36 |
+
|
| 37 |
+
bind_key("Control-z", "undo")
|
| 38 |
+
bind_key("Control-_", "undo")
|
| 39 |
+
|
| 40 |
+
#Commands for Changing Text
|
| 41 |
+
bind_key("Delete", "delete_char")
|
| 42 |
+
bind_key("Control-d", "delete_char")
|
| 43 |
+
bind_key("BackSpace", "backward_delete_char")
|
| 44 |
+
#bind_key("Control-Shift-v", "quoted_insert")
|
| 45 |
+
bind_key("Control-space", "self_insert")
|
| 46 |
+
bind_key("Control-BackSpace", "backward_delete_word")
|
| 47 |
+
|
| 48 |
+
#Killing and Yanking
|
| 49 |
+
bind_key("Control-k", "kill_line")
|
| 50 |
+
bind_key("Control-shift-k", "kill_whole_line")
|
| 51 |
+
bind_key("Escape", "kill_whole_line")
|
| 52 |
+
bind_key("Meta-d", "kill_word")
|
| 53 |
+
bind_key("Control-w", "unix_word_rubout")
|
| 54 |
+
#bind_key("Control-Delete", "forward_kill_word")
|
| 55 |
+
|
| 56 |
+
#Copy paste
|
| 57 |
+
bind_key("Shift-Right", "forward_char_extend_selection")
|
| 58 |
+
bind_key("Shift-Left", "backward_char_extend_selection")
|
| 59 |
+
bind_key("Shift-Control-Right", "forward_word_extend_selection")
|
| 60 |
+
bind_key("Shift-Control-Left", "backward_word_extend_selection")
|
| 61 |
+
bind_key("Control-m", "set_mark")
|
| 62 |
+
|
| 63 |
+
bind_key("Control-Shift-x", "copy_selection_to_clipboard")
|
| 64 |
+
#bind_key("Control-c", "copy_selection_to_clipboard") #Needs allow_ctrl_c(True) below to be uncommented
|
| 65 |
+
bind_key("Control-q", "copy_region_to_clipboard")
|
| 66 |
+
bind_key('Control-Shift-v', "paste_mulitline_code")
|
| 67 |
+
bind_key("Control-x", "cut_selection_to_clipboard")
|
| 68 |
+
|
| 69 |
+
bind_key("Control-v", "paste")
|
| 70 |
+
bind_key("Control-y", "yank")
|
| 71 |
+
bind_key("Alt-v", "ipython_paste")
|
| 72 |
+
|
| 73 |
+
#Unbinding keys:
|
| 74 |
+
#un_bind_key("Home")
|
| 75 |
+
|
| 76 |
+
#Other
|
| 77 |
+
bell_style("none") #modes: none, audible, visible(not implemented)
|
| 78 |
+
show_all_if_ambiguous("on")
|
| 79 |
+
mark_directories("on")
|
| 80 |
+
completer_delims(" \t\n\"\\'`@$><=;|&{(?")
|
| 81 |
+
complete_filesystem("off")
|
| 82 |
+
debug_output("off")
|
| 83 |
+
#allow_ctrl_c(True) #(Allows use of ctrl-c as copy key, still propagate keyboardinterrupt when not waiting for input)
|
| 84 |
+
|
| 85 |
+
history_filename("~/.pythonhistory")
|
| 86 |
+
history_length(200) #value of -1 means no limit
|
| 87 |
+
|
| 88 |
+
#set_mode("vi") #will cause following bind_keys to bind to vi mode as well as activate vi mode
|
| 89 |
+
#ctrl_c_tap_time_interval(0.3)
|
python_embeded/Lib/site-packages/pyreadline3/configuration/startup.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: UTF-8 -*-
|
| 2 |
+
# Example snippet to use in a PYTHONSTARTUP file
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
try:
|
| 6 |
+
import atexit
|
| 7 |
+
|
| 8 |
+
# pyreadline3.rlmain.config_path=r"c:\xxx\pyreadlineconfig.ini"
|
| 9 |
+
import readline
|
| 10 |
+
|
| 11 |
+
import pyreadline3.rlmain
|
| 12 |
+
import pyreadline3.unicode_helper
|
| 13 |
+
|
| 14 |
+
#
|
| 15 |
+
#
|
| 16 |
+
# Normally the codepage for pyreadline3 is set to be sys.stdout.encoding
|
| 17 |
+
# if you need to change this uncomment the following line
|
| 18 |
+
# pyreadline3.unicode_helper.pyreadline_codepage="utf8"
|
| 19 |
+
except ImportError:
|
| 20 |
+
print("Module readline not available.")
|
| 21 |
+
else:
|
| 22 |
+
# import tab completion functionality
|
| 23 |
+
import rlcompleter
|
| 24 |
+
|
| 25 |
+
# Override completer from rlcompleter to disable automatic ( on callable
|
| 26 |
+
completer_obj = rlcompleter.Completer()
|
| 27 |
+
|
| 28 |
+
def nop(val, word):
|
| 29 |
+
return word
|
| 30 |
+
|
| 31 |
+
completer_obj._callable_postfix = nop
|
| 32 |
+
readline.set_completer(completer_obj.complete)
|
| 33 |
+
|
| 34 |
+
# activate tab completion
|
| 35 |
+
readline.parse_and_bind("tab: complete")
|
| 36 |
+
readline.read_history_file()
|
| 37 |
+
atexit.register(readline.write_history_file)
|
| 38 |
+
del readline, rlcompleter, atexit
|
python_embeded/Lib/site-packages/pyreadline3/console/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pyreadline3.py3k_compat import is_ironpython
|
| 2 |
+
|
| 3 |
+
if is_ironpython:
|
| 4 |
+
try:
|
| 5 |
+
from .ironpython_console import *
|
| 6 |
+
except ImportError as x:
|
| 7 |
+
raise ImportError(
|
| 8 |
+
"Could not find a console implementation for local " "ironpython version"
|
| 9 |
+
) from x
|
| 10 |
+
else:
|
| 11 |
+
try:
|
| 12 |
+
from .console import *
|
| 13 |
+
except ImportError as x:
|
| 14 |
+
raise ImportError(
|
| 15 |
+
"Could not find a console implementation for local " "python version"
|
| 16 |
+
) from x
|
python_embeded/Lib/site-packages/pyreadline3/console/ansi.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: ISO-8859-1 -*-
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
terminal_escape = re.compile("(\001?\033\\[[0-9;]*m\002?)")
|
| 9 |
+
escape_parts = re.compile("\001?\033\\[([0-9;]*)m\002?")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class AnsiState(object):
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
bold=False,
|
| 16 |
+
inverse=False,
|
| 17 |
+
color="white",
|
| 18 |
+
background="black",
|
| 19 |
+
backgroundbold=False,
|
| 20 |
+
):
|
| 21 |
+
self.bold = bold
|
| 22 |
+
self.inverse = inverse
|
| 23 |
+
self.color = color
|
| 24 |
+
self.background = background
|
| 25 |
+
self.backgroundbold = backgroundbold
|
| 26 |
+
|
| 27 |
+
trtable = {
|
| 28 |
+
"black": 0,
|
| 29 |
+
"red": 4,
|
| 30 |
+
"green": 2,
|
| 31 |
+
"yellow": 6,
|
| 32 |
+
"blue": 1,
|
| 33 |
+
"magenta": 5,
|
| 34 |
+
"cyan": 3,
|
| 35 |
+
"white": 7,
|
| 36 |
+
}
|
| 37 |
+
revtable = dict(zip(trtable.values(), trtable.keys()))
|
| 38 |
+
|
| 39 |
+
def get_winattr(self):
|
| 40 |
+
attr = 0
|
| 41 |
+
if self.bold:
|
| 42 |
+
attr |= 0x0008
|
| 43 |
+
if self.backgroundbold:
|
| 44 |
+
attr |= 0x0080
|
| 45 |
+
if self.inverse:
|
| 46 |
+
attr |= 0x4000
|
| 47 |
+
attr |= self.trtable[self.color]
|
| 48 |
+
attr |= self.trtable[self.background] << 4
|
| 49 |
+
return attr
|
| 50 |
+
|
| 51 |
+
def set_winattr(self, attr):
|
| 52 |
+
self.bold = bool(attr & 0x0008)
|
| 53 |
+
self.backgroundbold = bool(attr & 0x0080)
|
| 54 |
+
self.inverse = bool(attr & 0x4000)
|
| 55 |
+
self.color = self.revtable[attr & 0x0007]
|
| 56 |
+
self.background = self.revtable[(attr & 0x0070) >> 4]
|
| 57 |
+
|
| 58 |
+
winattr = property(get_winattr, set_winattr)
|
| 59 |
+
|
| 60 |
+
def __repr__(self):
|
| 61 |
+
return (
|
| 62 |
+
"AnsiState(bold=%s,inverse=%s,color=%9s,"
|
| 63 |
+
"background=%9s,backgroundbold=%s)# 0x%x"
|
| 64 |
+
% (
|
| 65 |
+
self.bold,
|
| 66 |
+
self.inverse,
|
| 67 |
+
'"%s"' % self.color,
|
| 68 |
+
'"%s"' % self.background,
|
| 69 |
+
self.backgroundbold,
|
| 70 |
+
self.winattr,
|
| 71 |
+
)
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def copy(self):
|
| 75 |
+
x = AnsiState()
|
| 76 |
+
x.bold = self.bold
|
| 77 |
+
x.inverse = self.inverse
|
| 78 |
+
x.color = self.color
|
| 79 |
+
x.background = self.background
|
| 80 |
+
x.backgroundbold = self.backgroundbold
|
| 81 |
+
return x
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
defaultstate = AnsiState(False, False, "white")
|
| 85 |
+
|
| 86 |
+
trtable = {
|
| 87 |
+
0: "black",
|
| 88 |
+
1: "red",
|
| 89 |
+
2: "green",
|
| 90 |
+
3: "yellow",
|
| 91 |
+
4: "blue",
|
| 92 |
+
5: "magenta",
|
| 93 |
+
6: "cyan",
|
| 94 |
+
7: "white",
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class AnsiWriter(object):
|
| 99 |
+
def __init__(self, default=defaultstate):
|
| 100 |
+
if isinstance(defaultstate, AnsiState):
|
| 101 |
+
self.defaultstate = default
|
| 102 |
+
else:
|
| 103 |
+
self.defaultstate = AnsiState()
|
| 104 |
+
self.defaultstate.winattr = defaultstate
|
| 105 |
+
|
| 106 |
+
def write_color(self, text, attr=None):
|
| 107 |
+
"""write text at current cursor position and interpret color escapes.
|
| 108 |
+
|
| 109 |
+
return the number of characters written.
|
| 110 |
+
"""
|
| 111 |
+
if isinstance(attr, AnsiState):
|
| 112 |
+
defaultstate = attr
|
| 113 |
+
elif attr is None: # use attribute form initial console
|
| 114 |
+
attr = self.defaultstate.copy()
|
| 115 |
+
else:
|
| 116 |
+
defaultstate = AnsiState()
|
| 117 |
+
defaultstate.winattr = attr
|
| 118 |
+
attr = defaultstate
|
| 119 |
+
chunks = terminal_escape.split(text)
|
| 120 |
+
n = 0 # count the characters we actually write, omitting the escapes
|
| 121 |
+
res = []
|
| 122 |
+
for chunk in chunks:
|
| 123 |
+
m = escape_parts.match(chunk)
|
| 124 |
+
if m:
|
| 125 |
+
parts = m.group(1).split(";")
|
| 126 |
+
if len(parts) == 1 and parts[0] == "0":
|
| 127 |
+
attr = self.defaultstate.copy()
|
| 128 |
+
continue
|
| 129 |
+
for part in parts:
|
| 130 |
+
if part == "0": # No text attribute
|
| 131 |
+
attr = self.defaultstate.copy()
|
| 132 |
+
attr.bold = False
|
| 133 |
+
elif part == "7": # switch on reverse
|
| 134 |
+
attr.inverse = True
|
| 135 |
+
# switch on bold (i.e. intensify foreground color)
|
| 136 |
+
elif part == "1":
|
| 137 |
+
attr.bold = True
|
| 138 |
+
elif len(part) == 2:
|
| 139 |
+
if part == "22": # Normal foreground color
|
| 140 |
+
attr.bold = False
|
| 141 |
+
elif "30" <= part <= "37": # set foreground color
|
| 142 |
+
attr.color = trtable[int(part) - 30]
|
| 143 |
+
elif part == "39": # Default foreground color
|
| 144 |
+
attr.color = self.defaultstate.color
|
| 145 |
+
elif "40" <= part <= "47": # set background color
|
| 146 |
+
attr.background = trtable[int(part) - 40]
|
| 147 |
+
elif part == "49": # Default background color
|
| 148 |
+
attr.background = self.defaultstate.background
|
| 149 |
+
continue
|
| 150 |
+
n += len(chunk)
|
| 151 |
+
|
| 152 |
+
res.append((attr.copy(), chunk))
|
| 153 |
+
|
| 154 |
+
return n, res
|
| 155 |
+
|
| 156 |
+
def parse_color(self, text, attr=None):
|
| 157 |
+
n, res = self.write_color(text, attr)
|
| 158 |
+
return n, [attr.winattr for attr, text in res]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def write_color(text, attr=None):
|
| 162 |
+
a = AnsiWriter(defaultstate)
|
| 163 |
+
return a.write_color(text, attr)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def write_color_old(text, attr=None):
|
| 167 |
+
"""write text at current cursor position and interpret color escapes.
|
| 168 |
+
|
| 169 |
+
return the number of characters written.
|
| 170 |
+
"""
|
| 171 |
+
res = []
|
| 172 |
+
chunks = terminal_escape.split(text)
|
| 173 |
+
n = 0 # count the characters we actually write, omitting the escapes
|
| 174 |
+
if attr is None: # use attribute from initial console
|
| 175 |
+
attr = 15
|
| 176 |
+
for chunk in chunks:
|
| 177 |
+
m = escape_parts.match(chunk)
|
| 178 |
+
if m:
|
| 179 |
+
for part in m.group(1).split(";"):
|
| 180 |
+
if part == "0": # No text attribute
|
| 181 |
+
attr = 0
|
| 182 |
+
elif part == "7": # switch on reverse
|
| 183 |
+
attr |= 0x4000
|
| 184 |
+
# switch on bold (i.e. intensify foreground color)
|
| 185 |
+
if part == "1":
|
| 186 |
+
attr |= 0x08
|
| 187 |
+
elif len(part) == 2 and "30" <= part <= "37": # set foreground color
|
| 188 |
+
part = int(part) - 30
|
| 189 |
+
# we have to mirror bits
|
| 190 |
+
attr = (
|
| 191 |
+
(attr & ~0x07)
|
| 192 |
+
| ((part & 0x1) << 2)
|
| 193 |
+
| (part & 0x2)
|
| 194 |
+
| ((part & 0x4) >> 2)
|
| 195 |
+
)
|
| 196 |
+
elif len(part) == 2 and "40" <= part <= "47": # set background color
|
| 197 |
+
part = int(part) - 40
|
| 198 |
+
# we have to mirror bits
|
| 199 |
+
attr = (
|
| 200 |
+
(attr & ~0x70)
|
| 201 |
+
| ((part & 0x1) << 6)
|
| 202 |
+
| ((part & 0x2) << 4)
|
| 203 |
+
| ((part & 0x4) << 2)
|
| 204 |
+
)
|
| 205 |
+
# ignore blink, underline and anything we don't understand
|
| 206 |
+
continue
|
| 207 |
+
n += len(chunk)
|
| 208 |
+
if chunk:
|
| 209 |
+
res.append(("0x%x" % attr, chunk))
|
| 210 |
+
return res
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"}
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__x":
|
| 216 |
+
import pprint
|
| 217 |
+
|
| 218 |
+
pprint = pprint.pprint
|
| 219 |
+
|
| 220 |
+
s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
|
| 221 |
+
pprint(write_color(s))
|
| 222 |
+
pprint(write_color_old(s))
|
| 223 |
+
s = "\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m"
|
| 224 |
+
pprint(write_color(s))
|
| 225 |
+
pprint(write_color_old(s))
|
| 226 |
+
|
| 227 |
+
s = "\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m"
|
| 228 |
+
pprint(write_color(s))
|
| 229 |
+
pprint(write_color_old(s))
|
| 230 |
+
s = "\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m"
|
| 231 |
+
pprint(write_color(s))
|
| 232 |
+
pprint(write_color_old(s))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == "__main__":
|
| 236 |
+
import pprint
|
| 237 |
+
|
| 238 |
+
import console
|
| 239 |
+
|
| 240 |
+
pprint = pprint.pprint
|
| 241 |
+
|
| 242 |
+
c = console.Console()
|
| 243 |
+
c.write_color("dhsjdhs")
|
| 244 |
+
c.write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:")
|
| 245 |
+
print
|
| 246 |
+
pprint(write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__x":
|
| 249 |
+
import pprint
|
| 250 |
+
|
| 251 |
+
pprint = pprint.pprint
|
| 252 |
+
s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
|
| 253 |
+
pprint(write_color(s))
|
python_embeded/Lib/site-packages/pyreadline3/console/console.py
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# *****************************************************************************
|
| 3 |
+
# Copyright (C) 2003-2006 Gary Bishop.
|
| 4 |
+
# Copyright (C) 2006-2020 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
|
| 5 |
+
# Copyright (C) 2020 Bassem Girgis. <brgirgis@gmail.com>
|
| 6 |
+
#
|
| 7 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 8 |
+
# the file COPYING, distributed as part of this software.
|
| 9 |
+
# *****************************************************************************
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from .event import Event
|
| 13 |
+
|
| 14 |
+
"""Cursor control and color for the Windows console.
|
| 15 |
+
|
| 16 |
+
This was modeled after the C extension of the same name by Fredrik Lundh.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
# primitive debug printing that won't interfere with the screen
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import sys
|
| 24 |
+
import traceback
|
| 25 |
+
|
| 26 |
+
import pyreadline3.unicode_helper as unicode_helper
|
| 27 |
+
from pyreadline3.console.ansi import AnsiState, AnsiWriter
|
| 28 |
+
from pyreadline3.keysyms import KeyPress, make_KeyPress
|
| 29 |
+
from pyreadline3.logger import log
|
| 30 |
+
from pyreadline3.unicode_helper import ensure_str, ensure_unicode
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import ctypes.util
|
| 34 |
+
from ctypes import *
|
| 35 |
+
from ctypes.wintypes import *
|
| 36 |
+
|
| 37 |
+
from _ctypes import call_function
|
| 38 |
+
except ImportError:
|
| 39 |
+
raise ImportError("You need ctypes to run this code")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def nolog(string):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
log = nolog
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# some constants we need
|
| 50 |
+
STD_INPUT_HANDLE = -10
|
| 51 |
+
STD_OUTPUT_HANDLE = -11
|
| 52 |
+
ENABLE_WINDOW_INPUT = 0x0008
|
| 53 |
+
ENABLE_MOUSE_INPUT = 0x0010
|
| 54 |
+
ENABLE_PROCESSED_INPUT = 0x0001
|
| 55 |
+
WHITE = 0x7
|
| 56 |
+
BLACK = 0
|
| 57 |
+
MENU_EVENT = 0x0008
|
| 58 |
+
KEY_EVENT = 0x0001
|
| 59 |
+
MOUSE_MOVED = 0x0001
|
| 60 |
+
MOUSE_EVENT = 0x0002
|
| 61 |
+
WINDOW_BUFFER_SIZE_EVENT = 0x0004
|
| 62 |
+
FOCUS_EVENT = 0x0010
|
| 63 |
+
MENU_EVENT = 0x0008
|
| 64 |
+
VK_SHIFT = 0x10
|
| 65 |
+
VK_CONTROL = 0x11
|
| 66 |
+
VK_MENU = 0x12
|
| 67 |
+
GENERIC_READ = int(0x80000000)
|
| 68 |
+
GENERIC_WRITE = 0x40000000
|
| 69 |
+
|
| 70 |
+
# Windows structures we'll need later
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class COORD(Structure):
|
| 74 |
+
_fields_ = [("X", c_short), ("Y", c_short)]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class SMALL_RECT(Structure):
|
| 78 |
+
_fields_ = [
|
| 79 |
+
("Left", c_short),
|
| 80 |
+
("Top", c_short),
|
| 81 |
+
("Right", c_short),
|
| 82 |
+
("Bottom", c_short),
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
|
| 87 |
+
_fields_ = [
|
| 88 |
+
("dwSize", COORD),
|
| 89 |
+
("dwCursorPosition", COORD),
|
| 90 |
+
("wAttributes", c_short),
|
| 91 |
+
("srWindow", SMALL_RECT),
|
| 92 |
+
("dwMaximumWindowSize", COORD),
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class CHAR_UNION(Union):
|
| 97 |
+
_fields_ = [("UnicodeChar", c_wchar), ("AsciiChar", c_char)]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class CHAR_INFO(Structure):
|
| 101 |
+
_fields_ = [("Char", CHAR_UNION), ("Attributes", c_short)]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class KEY_EVENT_RECORD(Structure):
|
| 105 |
+
_fields_ = [
|
| 106 |
+
("bKeyDown", c_byte),
|
| 107 |
+
("pad2", c_byte),
|
| 108 |
+
("pad1", c_short),
|
| 109 |
+
("wRepeatCount", c_short),
|
| 110 |
+
("wVirtualKeyCode", c_short),
|
| 111 |
+
("wVirtualScanCode", c_short),
|
| 112 |
+
("uChar", CHAR_UNION),
|
| 113 |
+
("dwControlKeyState", c_int),
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MOUSE_EVENT_RECORD(Structure):
|
| 118 |
+
_fields_ = [
|
| 119 |
+
("dwMousePosition", COORD),
|
| 120 |
+
("dwButtonState", c_int),
|
| 121 |
+
("dwControlKeyState", c_int),
|
| 122 |
+
("dwEventFlags", c_int),
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class WINDOW_BUFFER_SIZE_RECORD(Structure):
|
| 127 |
+
_fields_ = [("dwSize", COORD)]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class MENU_EVENT_RECORD(Structure):
|
| 131 |
+
_fields_ = [("dwCommandId", c_uint)]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class FOCUS_EVENT_RECORD(Structure):
|
| 135 |
+
_fields_ = [("bSetFocus", c_byte)]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class INPUT_UNION(Union):
|
| 139 |
+
_fields_ = [
|
| 140 |
+
("KeyEvent", KEY_EVENT_RECORD),
|
| 141 |
+
("MouseEvent", MOUSE_EVENT_RECORD),
|
| 142 |
+
("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD),
|
| 143 |
+
("MenuEvent", MENU_EVENT_RECORD),
|
| 144 |
+
("FocusEvent", FOCUS_EVENT_RECORD),
|
| 145 |
+
]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class INPUT_RECORD(Structure):
|
| 149 |
+
_fields_ = [("EventType", c_short), ("Event", INPUT_UNION)]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class CONSOLE_CURSOR_INFO(Structure):
|
| 153 |
+
_fields_ = [("dwSize", c_int), ("bVisible", c_byte)]
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# I didn't want to have to individually import these so I made a list, they are
|
| 157 |
+
# added to the Console class later in this file.
|
| 158 |
+
|
| 159 |
+
funcs = [
|
| 160 |
+
"AllocConsole",
|
| 161 |
+
"CreateConsoleScreenBuffer",
|
| 162 |
+
"FillConsoleOutputAttribute",
|
| 163 |
+
"FillConsoleOutputCharacterW",
|
| 164 |
+
"FreeConsole",
|
| 165 |
+
"GetConsoleCursorInfo",
|
| 166 |
+
"GetConsoleMode",
|
| 167 |
+
"GetConsoleScreenBufferInfo",
|
| 168 |
+
"GetConsoleTitleW",
|
| 169 |
+
"GetProcAddress",
|
| 170 |
+
"GetStdHandle",
|
| 171 |
+
"PeekConsoleInputW",
|
| 172 |
+
"ReadConsoleInputW",
|
| 173 |
+
"ScrollConsoleScreenBufferW",
|
| 174 |
+
"SetConsoleActiveScreenBuffer",
|
| 175 |
+
"SetConsoleCursorInfo",
|
| 176 |
+
"SetConsoleCursorPosition",
|
| 177 |
+
"SetConsoleMode",
|
| 178 |
+
"SetConsoleScreenBufferSize",
|
| 179 |
+
"SetConsoleTextAttribute",
|
| 180 |
+
"SetConsoleTitleW",
|
| 181 |
+
"SetConsoleWindowInfo",
|
| 182 |
+
"WriteConsoleW",
|
| 183 |
+
"WriteConsoleOutputCharacterW",
|
| 184 |
+
"WriteFile",
|
| 185 |
+
]
|
| 186 |
+
|
| 187 |
+
# I don't want events for these keys, they are just a bother for my application
|
| 188 |
+
key_modifiers = {
|
| 189 |
+
VK_SHIFT: 1,
|
| 190 |
+
VK_CONTROL: 1,
|
| 191 |
+
VK_MENU: 1, # alt key
|
| 192 |
+
0x5B: 1, # windows key
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def split_block(text, size=1000):
|
| 197 |
+
return [text[start : start + size] for start in range(0, len(text), size)]
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class Console(object):
|
| 201 |
+
"""Console driver for Windows."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, newbuffer=0):
|
| 204 |
+
"""Initialize the Console object.
|
| 205 |
+
|
| 206 |
+
newbuffer=1 will allocate a new buffer so the old content will be restored
|
| 207 |
+
on exit.
|
| 208 |
+
"""
|
| 209 |
+
# Do I need the following line? It causes a console to be created whenever
|
| 210 |
+
# readline is imported into a pythonw application which seems wrong. Things
|
| 211 |
+
# seem to work without it...
|
| 212 |
+
# self.AllocConsole()
|
| 213 |
+
|
| 214 |
+
if newbuffer:
|
| 215 |
+
self.hout = self.CreateConsoleScreenBuffer(
|
| 216 |
+
GENERIC_READ | GENERIC_WRITE, 0, None, 1, None
|
| 217 |
+
)
|
| 218 |
+
self.SetConsoleActiveScreenBuffer(self.hout)
|
| 219 |
+
else:
|
| 220 |
+
self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)
|
| 221 |
+
|
| 222 |
+
self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
|
| 223 |
+
self.inmode = DWORD(0)
|
| 224 |
+
self.GetConsoleMode(self.hin, byref(self.inmode))
|
| 225 |
+
self.SetConsoleMode(self.hin, 0xF)
|
| 226 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 227 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 228 |
+
self.attr = info.wAttributes
|
| 229 |
+
self.saveattr = info.wAttributes # remember the initial colors
|
| 230 |
+
self.defaultstate = AnsiState()
|
| 231 |
+
self.defaultstate.winattr = info.wAttributes
|
| 232 |
+
self.ansiwriter = AnsiWriter(self.defaultstate)
|
| 233 |
+
|
| 234 |
+
background = self.attr & 0xF0
|
| 235 |
+
for escape in self.escape_to_color:
|
| 236 |
+
if self.escape_to_color[escape] is not None:
|
| 237 |
+
self.escape_to_color[escape] |= background
|
| 238 |
+
log("initial attr=%x" % self.attr)
|
| 239 |
+
self.softspace = 0 # this is for using it as a file-like object
|
| 240 |
+
self.serial = 0
|
| 241 |
+
|
| 242 |
+
self.pythondll = ctypes.pythonapi
|
| 243 |
+
self.inputHookPtr = c_void_p.from_address(
|
| 244 |
+
addressof(self.pythondll.PyOS_InputHook)
|
| 245 |
+
).value
|
| 246 |
+
|
| 247 |
+
self.pythondll.PyMem_RawMalloc.restype = c_size_t
|
| 248 |
+
self.pythondll.PyMem_RawMalloc.argtypes = [c_size_t]
|
| 249 |
+
setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_RawMalloc)
|
| 250 |
+
|
| 251 |
+
def __del__(self):
|
| 252 |
+
"""Cleanup the console when finished."""
|
| 253 |
+
# I don't think this ever gets called
|
| 254 |
+
self.SetConsoleTextAttribute(self.hout, self.saveattr)
|
| 255 |
+
self.SetConsoleMode(self.hin, self.inmode)
|
| 256 |
+
self.FreeConsole()
|
| 257 |
+
|
| 258 |
+
def _get_top_bot(self):
|
| 259 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 260 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 261 |
+
rect = info.srWindow
|
| 262 |
+
top = rect.Top
|
| 263 |
+
bot = rect.Bottom
|
| 264 |
+
return top, bot
|
| 265 |
+
|
| 266 |
+
def fixcoord(self, x, y):
|
| 267 |
+
"""Return a long with x and y packed inside,
|
| 268 |
+
also handle negative x and y."""
|
| 269 |
+
if x < 0 or y < 0:
|
| 270 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 271 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 272 |
+
if x < 0:
|
| 273 |
+
x = info.srWindow.Right - x
|
| 274 |
+
y = info.srWindow.Bottom + y
|
| 275 |
+
|
| 276 |
+
# this is a hack! ctypes won't pass structures but COORD is
|
| 277 |
+
# just like a long, so this works.
|
| 278 |
+
return c_int(y << 16 | x)
|
| 279 |
+
|
| 280 |
+
def pos(self, x=None, y=None):
|
| 281 |
+
"""Move or query the window cursor."""
|
| 282 |
+
if x is None:
|
| 283 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 284 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 285 |
+
return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
|
| 286 |
+
else:
|
| 287 |
+
return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y))
|
| 288 |
+
|
| 289 |
+
def home(self):
|
| 290 |
+
"""Move to home."""
|
| 291 |
+
self.pos(0, 0)
|
| 292 |
+
|
| 293 |
+
# Map ANSI color escape sequences into Windows Console Attributes
|
| 294 |
+
|
| 295 |
+
terminal_escape = re.compile("(\001?\033\\[[0-9;]+m\002?)")
|
| 296 |
+
escape_parts = re.compile("\001?\033\\[([0-9;]+)m\002?")
|
| 297 |
+
escape_to_color = {
|
| 298 |
+
"0;30": 0x0, # black
|
| 299 |
+
"0;31": 0x4, # red
|
| 300 |
+
"0;32": 0x2, # green
|
| 301 |
+
"0;33": 0x4 + 0x2, # brown?
|
| 302 |
+
"0;34": 0x1, # blue
|
| 303 |
+
"0;35": 0x1 + 0x4, # purple
|
| 304 |
+
"0;36": 0x2 + 0x4, # cyan
|
| 305 |
+
"0;37": 0x1 + 0x2 + 0x4, # grey
|
| 306 |
+
"1;30": 0x1 + 0x2 + 0x4, # dark gray
|
| 307 |
+
"1;31": 0x4 + 0x8, # red
|
| 308 |
+
"1;32": 0x2 + 0x8, # light green
|
| 309 |
+
"1;33": 0x4 + 0x2 + 0x8, # yellow
|
| 310 |
+
"1;34": 0x1 + 0x8, # light blue
|
| 311 |
+
"1;35": 0x1 + 0x4 + 0x8, # light purple
|
| 312 |
+
"1;36": 0x1 + 0x2 + 0x8, # light cyan
|
| 313 |
+
"1;37": 0x1 + 0x2 + 0x4 + 0x8, # white
|
| 314 |
+
"0": None,
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
# This pattern should match all characters that change the cursor position differently
|
| 318 |
+
# than a normal character.
|
| 319 |
+
motion_char_re = re.compile("([\n\r\t\010\007])")
|
| 320 |
+
|
| 321 |
+
def write_scrolling(self, text, attr=None):
|
| 322 |
+
"""write text at current cursor position while watching for scrolling.
|
| 323 |
+
|
| 324 |
+
If the window scrolls because you are at the bottom of the screen
|
| 325 |
+
buffer, all positions that you are storing will be shifted by the
|
| 326 |
+
scroll amount. For example, I remember the cursor position of the
|
| 327 |
+
prompt so that I can redraw the line but if the window scrolls,
|
| 328 |
+
the remembered position is off.
|
| 329 |
+
|
| 330 |
+
This variant of write tries to keep track of the cursor position
|
| 331 |
+
so that it will know when the screen buffer is scrolled. It
|
| 332 |
+
returns the number of lines that the buffer scrolled.
|
| 333 |
+
|
| 334 |
+
"""
|
| 335 |
+
text = ensure_unicode(text)
|
| 336 |
+
x, y = self.pos()
|
| 337 |
+
w, h = self.size()
|
| 338 |
+
scroll = 0 # the result
|
| 339 |
+
# split the string into ordinary characters and funny characters
|
| 340 |
+
chunks = self.motion_char_re.split(text)
|
| 341 |
+
for chunk in chunks:
|
| 342 |
+
n = self.write_color(chunk, attr)
|
| 343 |
+
if len(chunk) == 1: # the funny characters will be alone
|
| 344 |
+
if chunk[0] == "\n": # newline
|
| 345 |
+
x = 0
|
| 346 |
+
y += 1
|
| 347 |
+
elif chunk[0] == "\r": # carriage return
|
| 348 |
+
x = 0
|
| 349 |
+
elif chunk[0] == "\t": # tab
|
| 350 |
+
x = 8 * (int(x / 8) + 1)
|
| 351 |
+
if x > w: # newline
|
| 352 |
+
x -= w
|
| 353 |
+
y += 1
|
| 354 |
+
elif chunk[0] == "\007": # bell
|
| 355 |
+
pass
|
| 356 |
+
elif chunk[0] == "\010":
|
| 357 |
+
x -= 1
|
| 358 |
+
if x < 0:
|
| 359 |
+
y -= 1 # backed up 1 line
|
| 360 |
+
else: # ordinary character
|
| 361 |
+
x += 1
|
| 362 |
+
if x == w: # wrap
|
| 363 |
+
x = 0
|
| 364 |
+
y += 1
|
| 365 |
+
if y == h: # scroll
|
| 366 |
+
scroll += 1
|
| 367 |
+
y = h - 1
|
| 368 |
+
else: # chunk of ordinary characters
|
| 369 |
+
x += n
|
| 370 |
+
l = int(x / w) # lines we advanced
|
| 371 |
+
x = x % w # new x value
|
| 372 |
+
y += l
|
| 373 |
+
if y >= h: # scroll
|
| 374 |
+
scroll += y - h + 1
|
| 375 |
+
y = h - 1
|
| 376 |
+
return scroll
|
| 377 |
+
|
| 378 |
+
def write_color(self, text, attr=None):
|
| 379 |
+
text = ensure_unicode(text)
|
| 380 |
+
n, res = self.ansiwriter.write_color(text, attr)
|
| 381 |
+
junk = DWORD(0)
|
| 382 |
+
for attr, chunk in res:
|
| 383 |
+
log("console.attr:%s" % (attr))
|
| 384 |
+
log("console.chunk:%s" % (chunk))
|
| 385 |
+
self.SetConsoleTextAttribute(self.hout, attr.winattr)
|
| 386 |
+
for short_chunk in split_block(chunk):
|
| 387 |
+
self.WriteConsoleW(
|
| 388 |
+
self.hout, short_chunk, len(short_chunk), byref(junk), None
|
| 389 |
+
)
|
| 390 |
+
return n
|
| 391 |
+
|
| 392 |
+
def write_plain(self, text, attr=None):
|
| 393 |
+
"""write text at current cursor position."""
|
| 394 |
+
text = ensure_unicode(text)
|
| 395 |
+
log('write("%s", %s)' % (text, attr))
|
| 396 |
+
if attr is None:
|
| 397 |
+
attr = self.attr
|
| 398 |
+
junk = DWORD(0)
|
| 399 |
+
self.SetConsoleTextAttribute(self.hout, attr)
|
| 400 |
+
for short_chunk in split_block(chunk):
|
| 401 |
+
self.WriteConsoleW(
|
| 402 |
+
self.hout,
|
| 403 |
+
ensure_unicode(short_chunk),
|
| 404 |
+
len(short_chunk),
|
| 405 |
+
byref(junk),
|
| 406 |
+
None,
|
| 407 |
+
)
|
| 408 |
+
return len(text)
|
| 409 |
+
|
| 410 |
+
# This function must be used to ensure functioning with EMACS
|
| 411 |
+
# Emacs sets the EMACS environment variable
|
| 412 |
+
if "EMACS" in os.environ:
|
| 413 |
+
|
| 414 |
+
def write_color(self, text, attr=None):
|
| 415 |
+
text = ensure_str(text)
|
| 416 |
+
junk = DWORD(0)
|
| 417 |
+
self.WriteFile(self.hout, text, len(text), byref(junk), None)
|
| 418 |
+
return len(text)
|
| 419 |
+
|
| 420 |
+
write_plain = write_color
|
| 421 |
+
|
| 422 |
+
# make this class look like a file object
|
| 423 |
+
def write(self, text):
|
| 424 |
+
text = ensure_unicode(text)
|
| 425 |
+
log('write("%s")' % text)
|
| 426 |
+
return self.write_color(text)
|
| 427 |
+
|
| 428 |
+
# write = write_scrolling
|
| 429 |
+
|
| 430 |
+
def isatty(self):
|
| 431 |
+
return True
|
| 432 |
+
|
| 433 |
+
def flush(self):
|
| 434 |
+
pass
|
| 435 |
+
|
| 436 |
+
def page(self, attr=None, fill=" "):
|
| 437 |
+
"""Fill the entire screen."""
|
| 438 |
+
if attr is None:
|
| 439 |
+
attr = self.attr
|
| 440 |
+
if len(fill) != 1:
|
| 441 |
+
raise ValueError
|
| 442 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 443 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 444 |
+
if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
|
| 445 |
+
self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))
|
| 446 |
+
|
| 447 |
+
w = info.dwSize.X
|
| 448 |
+
n = DWORD(0)
|
| 449 |
+
for y in range(info.dwSize.Y):
|
| 450 |
+
self.FillConsoleOutputAttribute(
|
| 451 |
+
self.hout, attr, w, self.fixcoord(0, y), byref(n)
|
| 452 |
+
)
|
| 453 |
+
self.FillConsoleOutputCharacterW(
|
| 454 |
+
self.hout, ord(fill[0]), w, self.fixcoord(0, y), byref(n)
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
self.attr = attr
|
| 458 |
+
|
| 459 |
+
def text(self, x, y, text, attr=None):
|
| 460 |
+
"""Write text at the given position."""
|
| 461 |
+
if attr is None:
|
| 462 |
+
attr = self.attr
|
| 463 |
+
|
| 464 |
+
pos = self.fixcoord(x, y)
|
| 465 |
+
n = DWORD(0)
|
| 466 |
+
self.WriteConsoleOutputCharacterW(self.hout, text, len(text), pos, byref(n))
|
| 467 |
+
self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))
|
| 468 |
+
|
| 469 |
+
def clear_to_end_of_window(self):
|
| 470 |
+
top, bot = self._get_top_bot()
|
| 471 |
+
pos = self.pos()
|
| 472 |
+
w, h = self.size()
|
| 473 |
+
self.rectangle((pos[0], pos[1], w, pos[1] + 1))
|
| 474 |
+
if pos[1] < bot:
|
| 475 |
+
self.rectangle((0, pos[1] + 1, w, bot + 1))
|
| 476 |
+
|
| 477 |
+
def rectangle(self, rect, attr=None, fill=" "):
|
| 478 |
+
"""Fill Rectangle."""
|
| 479 |
+
x0, y0, x1, y1 = rect
|
| 480 |
+
n = DWORD(0)
|
| 481 |
+
if attr is None:
|
| 482 |
+
attr = self.attr
|
| 483 |
+
for y in range(y0, y1):
|
| 484 |
+
pos = self.fixcoord(x0, y)
|
| 485 |
+
self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0, pos, byref(n))
|
| 486 |
+
self.FillConsoleOutputCharacterW(
|
| 487 |
+
self.hout, ord(fill[0]), x1 - x0, pos, byref(n)
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
def scroll(self, rect, dx, dy, attr=None, fill=" "):
|
| 491 |
+
"""Scroll a rectangle."""
|
| 492 |
+
if attr is None:
|
| 493 |
+
attr = self.attr
|
| 494 |
+
x0, y0, x1, y1 = rect
|
| 495 |
+
source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
|
| 496 |
+
dest = self.fixcoord(x0 + dx, y0 + dy)
|
| 497 |
+
style = CHAR_INFO()
|
| 498 |
+
style.Char.AsciiChar = ensure_str(fill[0])
|
| 499 |
+
style.Attributes = attr
|
| 500 |
+
|
| 501 |
+
return self.ScrollConsoleScreenBufferW(
|
| 502 |
+
self.hout, byref(source), byref(source), dest, byref(style)
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
def scroll_window(self, lines):
|
| 506 |
+
"""Scroll the window by the indicated number of lines."""
|
| 507 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 508 |
+
self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 509 |
+
rect = info.srWindow
|
| 510 |
+
log("sw: rtop=%d rbot=%d" % (rect.Top, rect.Bottom))
|
| 511 |
+
top = rect.Top + lines
|
| 512 |
+
bot = rect.Bottom + lines
|
| 513 |
+
h = bot - top
|
| 514 |
+
maxbot = info.dwSize.Y - 1
|
| 515 |
+
if top < 0:
|
| 516 |
+
top = 0
|
| 517 |
+
bot = h
|
| 518 |
+
if bot > maxbot:
|
| 519 |
+
bot = maxbot
|
| 520 |
+
top = bot - h
|
| 521 |
+
|
| 522 |
+
nrect = SMALL_RECT()
|
| 523 |
+
nrect.Top = top
|
| 524 |
+
nrect.Bottom = bot
|
| 525 |
+
nrect.Left = rect.Left
|
| 526 |
+
nrect.Right = rect.Right
|
| 527 |
+
log("sn: top=%d bot=%d" % (top, bot))
|
| 528 |
+
r = self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
|
| 529 |
+
log("r=%d" % r)
|
| 530 |
+
|
| 531 |
+
def get(self):
|
| 532 |
+
"""Get next event from queue."""
|
| 533 |
+
inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
|
| 534 |
+
|
| 535 |
+
Cevent = INPUT_RECORD()
|
| 536 |
+
count = DWORD(0)
|
| 537 |
+
while True:
|
| 538 |
+
if inputHookFunc:
|
| 539 |
+
call_function(inputHookFunc, ())
|
| 540 |
+
status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
|
| 541 |
+
if status and count.value == 1:
|
| 542 |
+
e = event(self, Cevent)
|
| 543 |
+
return e
|
| 544 |
+
|
| 545 |
+
def getkeypress(self):
|
| 546 |
+
"""Return next key press event from the queue, ignoring others."""
|
| 547 |
+
while True:
|
| 548 |
+
e = self.get()
|
| 549 |
+
if e.type == "KeyPress" and e.keycode not in key_modifiers:
|
| 550 |
+
log("console.getkeypress %s" % e)
|
| 551 |
+
if e.keyinfo.keyname == "next":
|
| 552 |
+
self.scroll_window(12)
|
| 553 |
+
elif e.keyinfo.keyname == "prior":
|
| 554 |
+
self.scroll_window(-12)
|
| 555 |
+
else:
|
| 556 |
+
return e
|
| 557 |
+
elif (e.type == "KeyRelease") and (
|
| 558 |
+
e.keyinfo == KeyPress("S", False, True, False, "S")
|
| 559 |
+
or e.keyinfo == KeyPress("C", False, True, False, "C")
|
| 560 |
+
):
|
| 561 |
+
log("getKeypress:%s,%s,%s" % (e.keyinfo, e.keycode, e.type))
|
| 562 |
+
return e
|
| 563 |
+
|
| 564 |
+
def getchar(self):
|
| 565 |
+
"""Get next character from queue."""
|
| 566 |
+
|
| 567 |
+
Cevent = INPUT_RECORD()
|
| 568 |
+
count = DWORD(0)
|
| 569 |
+
while True:
|
| 570 |
+
status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
|
| 571 |
+
if (
|
| 572 |
+
status
|
| 573 |
+
and (count.value == 1)
|
| 574 |
+
and (Cevent.EventType == 1)
|
| 575 |
+
and Cevent.Event.KeyEvent.bKeyDown
|
| 576 |
+
):
|
| 577 |
+
sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
|
| 578 |
+
if len(sym) == 0:
|
| 579 |
+
sym = Cevent.Event.KeyEvent.uChar.AsciiChar
|
| 580 |
+
return sym
|
| 581 |
+
|
| 582 |
+
def peek(self):
|
| 583 |
+
"""Check event queue."""
|
| 584 |
+
Cevent = INPUT_RECORD()
|
| 585 |
+
count = DWORD(0)
|
| 586 |
+
status = self.PeekConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
|
| 587 |
+
if status and count == 1:
|
| 588 |
+
return event(self, Cevent)
|
| 589 |
+
|
| 590 |
+
def title(self, txt=None):
|
| 591 |
+
"""Set/get title."""
|
| 592 |
+
if txt:
|
| 593 |
+
self.SetConsoleTitleW(txt)
|
| 594 |
+
else:
|
| 595 |
+
buffer = create_unicode_buffer(200)
|
| 596 |
+
n = self.GetConsoleTitleW(buffer, 200)
|
| 597 |
+
if n > 0:
|
| 598 |
+
return buffer.value[:n]
|
| 599 |
+
|
| 600 |
+
def size(self, width=None, height=None):
|
| 601 |
+
"""Set/get window size."""
|
| 602 |
+
info = CONSOLE_SCREEN_BUFFER_INFO()
|
| 603 |
+
status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
|
| 604 |
+
if not status:
|
| 605 |
+
return None
|
| 606 |
+
if width is not None and height is not None:
|
| 607 |
+
wmin = info.srWindow.Right - info.srWindow.Left + 1
|
| 608 |
+
hmin = info.srWindow.Bottom - info.srWindow.Top + 1
|
| 609 |
+
# print wmin, hmin
|
| 610 |
+
width = max(width, wmin)
|
| 611 |
+
height = max(height, hmin)
|
| 612 |
+
# print width, height
|
| 613 |
+
self.SetConsoleScreenBufferSize(self.hout, self.fixcoord(width, height))
|
| 614 |
+
else:
|
| 615 |
+
return (info.dwSize.X, info.dwSize.Y)
|
| 616 |
+
|
| 617 |
+
def cursor(self, visible=None, size=None):
|
| 618 |
+
"""Set cursor on or off."""
|
| 619 |
+
info = CONSOLE_CURSOR_INFO()
|
| 620 |
+
if self.GetConsoleCursorInfo(self.hout, byref(info)):
|
| 621 |
+
if visible is not None:
|
| 622 |
+
info.bVisible = visible
|
| 623 |
+
if size is not None:
|
| 624 |
+
info.dwSize = size
|
| 625 |
+
self.SetConsoleCursorInfo(self.hout, byref(info))
|
| 626 |
+
|
| 627 |
+
def bell(self):
|
| 628 |
+
self.write("\007")
|
| 629 |
+
|
| 630 |
+
def next_serial(self):
|
| 631 |
+
"""Get next event serial number."""
|
| 632 |
+
self.serial += 1
|
| 633 |
+
return self.serial
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
# add the functions from the dll to the class
|
| 637 |
+
for func in funcs:
|
| 638 |
+
setattr(Console, func, getattr(windll.kernel32, func))
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
_strncpy = ctypes.windll.kernel32.lstrcpynA
|
| 642 |
+
_strncpy.restype = c_char_p
|
| 643 |
+
_strncpy.argtypes = [c_char_p, c_char_p, c_size_t]
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
LPVOID = c_void_p
|
| 647 |
+
LPCVOID = c_void_p
|
| 648 |
+
FARPROC = c_void_p
|
| 649 |
+
LPDWORD = POINTER(DWORD)
|
| 650 |
+
|
| 651 |
+
Console.AllocConsole.restype = BOOL
|
| 652 |
+
Console.AllocConsole.argtypes = [] # void
|
| 653 |
+
Console.CreateConsoleScreenBuffer.restype = HANDLE
|
| 654 |
+
Console.CreateConsoleScreenBuffer.argtypes = [
|
| 655 |
+
DWORD,
|
| 656 |
+
DWORD,
|
| 657 |
+
c_void_p,
|
| 658 |
+
DWORD,
|
| 659 |
+
LPVOID,
|
| 660 |
+
] # DWORD, DWORD, SECURITY_ATTRIBUTES*, DWORD, LPVOID
|
| 661 |
+
Console.FillConsoleOutputAttribute.restype = BOOL
|
| 662 |
+
Console.FillConsoleOutputAttribute.argtypes = [
|
| 663 |
+
HANDLE,
|
| 664 |
+
WORD,
|
| 665 |
+
DWORD,
|
| 666 |
+
c_int,
|
| 667 |
+
LPDWORD,
|
| 668 |
+
] # HANDLE, WORD, DWORD, COORD, LPDWORD
|
| 669 |
+
Console.FillConsoleOutputCharacterW.restype = BOOL
|
| 670 |
+
Console.FillConsoleOutputCharacterW.argtypes = [
|
| 671 |
+
HANDLE,
|
| 672 |
+
c_ushort,
|
| 673 |
+
DWORD,
|
| 674 |
+
c_int,
|
| 675 |
+
LPDWORD,
|
| 676 |
+
] # HANDLE, TCHAR, DWORD, COORD, LPDWORD
|
| 677 |
+
Console.FreeConsole.restype = BOOL
|
| 678 |
+
Console.FreeConsole.argtypes = [] # void
|
| 679 |
+
Console.GetConsoleCursorInfo.restype = BOOL
|
| 680 |
+
Console.GetConsoleCursorInfo.argtypes = [
|
| 681 |
+
HANDLE,
|
| 682 |
+
c_void_p,
|
| 683 |
+
] # HANDLE, PCONSOLE_CURSOR_INFO
|
| 684 |
+
Console.GetConsoleMode.restype = BOOL
|
| 685 |
+
Console.GetConsoleMode.argtypes = [HANDLE, LPDWORD] # HANDLE, LPDWORD
|
| 686 |
+
Console.GetConsoleScreenBufferInfo.restype = BOOL
|
| 687 |
+
Console.GetConsoleScreenBufferInfo.argtypes = [
|
| 688 |
+
HANDLE,
|
| 689 |
+
c_void_p,
|
| 690 |
+
] # HANDLE, PCONSOLE_SCREEN_BUFFER_INFO
|
| 691 |
+
Console.GetConsoleTitleW.restype = DWORD
|
| 692 |
+
Console.GetConsoleTitleW.argtypes = [c_wchar_p, DWORD] # LPTSTR , DWORD
|
| 693 |
+
Console.GetProcAddress.restype = FARPROC
|
| 694 |
+
Console.GetProcAddress.argtypes = [HMODULE, c_char_p] # HMODULE , LPCSTR
|
| 695 |
+
Console.GetStdHandle.restype = HANDLE
|
| 696 |
+
Console.GetStdHandle.argtypes = [DWORD]
|
| 697 |
+
Console.PeekConsoleInputW.restype = BOOL
|
| 698 |
+
# HANDLE, PINPUT_RECORD, DWORD, LPDWORD
|
| 699 |
+
Console.PeekConsoleInputW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD]
|
| 700 |
+
Console.ReadConsoleInputW.restype = BOOL
|
| 701 |
+
# HANDLE, PINPUT_RECORD, DWORD, LPDWORD
|
| 702 |
+
Console.ReadConsoleInputW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD]
|
| 703 |
+
Console.ScrollConsoleScreenBufferW.restype = BOOL
|
| 704 |
+
Console.ScrollConsoleScreenBufferW.argtypes = [
|
| 705 |
+
HANDLE,
|
| 706 |
+
c_void_p,
|
| 707 |
+
c_void_p,
|
| 708 |
+
c_int,
|
| 709 |
+
c_void_p,
|
| 710 |
+
] # HANDLE, SMALL_RECT*, SMALL_RECT*, COORD, LPDWORD
|
| 711 |
+
Console.SetConsoleActiveScreenBuffer.restype = BOOL
|
| 712 |
+
Console.SetConsoleActiveScreenBuffer.argtypes = [HANDLE] # HANDLE
|
| 713 |
+
Console.SetConsoleCursorInfo.restype = BOOL
|
| 714 |
+
Console.SetConsoleCursorInfo.argtypes = [
|
| 715 |
+
HANDLE,
|
| 716 |
+
c_void_p,
|
| 717 |
+
] # HANDLE, CONSOLE_CURSOR_INFO*
|
| 718 |
+
Console.SetConsoleCursorPosition.restype = BOOL
|
| 719 |
+
Console.SetConsoleCursorPosition.argtypes = [HANDLE, c_int] # HANDLE, COORD
|
| 720 |
+
Console.SetConsoleMode.restype = BOOL
|
| 721 |
+
Console.SetConsoleMode.argtypes = [HANDLE, DWORD] # HANDLE, DWORD
|
| 722 |
+
Console.SetConsoleScreenBufferSize.restype = BOOL
|
| 723 |
+
Console.SetConsoleScreenBufferSize.argtypes = [HANDLE, c_int] # HANDLE, COORD
|
| 724 |
+
Console.SetConsoleTextAttribute.restype = BOOL
|
| 725 |
+
Console.SetConsoleTextAttribute.argtypes = [HANDLE, WORD] # HANDLE, WORD
|
| 726 |
+
Console.SetConsoleTitleW.restype = BOOL
|
| 727 |
+
Console.SetConsoleTitleW.argtypes = [c_wchar_p] # LPCTSTR
|
| 728 |
+
Console.SetConsoleWindowInfo.restype = BOOL
|
| 729 |
+
Console.SetConsoleWindowInfo.argtypes = [
|
| 730 |
+
HANDLE,
|
| 731 |
+
BOOL,
|
| 732 |
+
c_void_p,
|
| 733 |
+
] # HANDLE, BOOL, SMALL_RECT*
|
| 734 |
+
Console.WriteConsoleW.restype = BOOL
|
| 735 |
+
# HANDLE, VOID*, DWORD, LPDWORD, LPVOID
|
| 736 |
+
Console.WriteConsoleW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD, LPVOID]
|
| 737 |
+
Console.WriteConsoleOutputCharacterW.restype = BOOL
|
| 738 |
+
Console.WriteConsoleOutputCharacterW.argtypes = [
|
| 739 |
+
HANDLE,
|
| 740 |
+
c_wchar_p,
|
| 741 |
+
DWORD,
|
| 742 |
+
c_int,
|
| 743 |
+
LPDWORD,
|
| 744 |
+
] # HANDLE, LPCTSTR, DWORD, COORD, LPDWORD
|
| 745 |
+
Console.WriteFile.restype = BOOL
|
| 746 |
+
# HANDLE, LPCVOID , DWORD, LPDWORD , LPOVERLAPPED
|
| 747 |
+
Console.WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, c_void_p]
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
VkKeyScan = windll.user32.VkKeyScanA
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
class event(Event):
|
| 754 |
+
"""Represent events from the console."""
|
| 755 |
+
|
| 756 |
+
def __init__(self, console, input):
|
| 757 |
+
"""Initialize an event from the Windows input structure."""
|
| 758 |
+
self.type = "??"
|
| 759 |
+
self.serial = console.next_serial()
|
| 760 |
+
self.width = 0
|
| 761 |
+
self.height = 0
|
| 762 |
+
self.x = 0
|
| 763 |
+
self.y = 0
|
| 764 |
+
self.char = ""
|
| 765 |
+
self.keycode = 0
|
| 766 |
+
self.keysym = "??"
|
| 767 |
+
# a tuple with (control, meta, shift, keycode) for dispatch
|
| 768 |
+
self.keyinfo = None
|
| 769 |
+
self.width = None
|
| 770 |
+
|
| 771 |
+
if input.EventType == KEY_EVENT:
|
| 772 |
+
if input.Event.KeyEvent.bKeyDown:
|
| 773 |
+
self.type = "KeyPress"
|
| 774 |
+
else:
|
| 775 |
+
self.type = "KeyRelease"
|
| 776 |
+
self.char = input.Event.KeyEvent.uChar.UnicodeChar
|
| 777 |
+
self.keycode = input.Event.KeyEvent.wVirtualKeyCode
|
| 778 |
+
self.state = input.Event.KeyEvent.dwControlKeyState
|
| 779 |
+
self.keyinfo = make_KeyPress(self.char, self.state, self.keycode)
|
| 780 |
+
|
| 781 |
+
elif input.EventType == MOUSE_EVENT:
|
| 782 |
+
if input.Event.MouseEvent.dwEventFlags & MOUSE_MOVED:
|
| 783 |
+
self.type = "Motion"
|
| 784 |
+
else:
|
| 785 |
+
self.type = "Button"
|
| 786 |
+
self.x = input.Event.MouseEvent.dwMousePosition.X
|
| 787 |
+
self.y = input.Event.MouseEvent.dwMousePosition.Y
|
| 788 |
+
self.state = input.Event.MouseEvent.dwButtonState
|
| 789 |
+
elif input.EventType == WINDOW_BUFFER_SIZE_EVENT:
|
| 790 |
+
self.type = "Configure"
|
| 791 |
+
self.width = input.Event.WindowBufferSizeEvent.dwSize.X
|
| 792 |
+
self.height = input.Event.WindowBufferSizeEvent.dwSize.Y
|
| 793 |
+
elif input.EventType == FOCUS_EVENT:
|
| 794 |
+
if input.Event.FocusEvent.bSetFocus:
|
| 795 |
+
self.type = "FocusIn"
|
| 796 |
+
else:
|
| 797 |
+
self.type = "FocusOut"
|
| 798 |
+
elif input.EventType == MENU_EVENT:
|
| 799 |
+
self.type = "Menu"
|
| 800 |
+
self.state = input.Event.MenuEvent.dwCommandId
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def getconsole(buffer=1):
|
| 804 |
+
"""Get a console handle.
|
| 805 |
+
|
| 806 |
+
If buffer is non-zero, a new console buffer is allocated and
|
| 807 |
+
installed. Otherwise, this returns a handle to the current
|
| 808 |
+
console buffer"""
|
| 809 |
+
|
| 810 |
+
c = Console(buffer)
|
| 811 |
+
|
| 812 |
+
return c
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
# The following code uses ctypes to allow a Python callable to
|
| 816 |
+
# substitute for GNU readline within the Python interpreter. Calling
|
| 817 |
+
# raw_input or other functions that do input, inside your callable
|
| 818 |
+
# might be a bad idea, then again, it might work.
|
| 819 |
+
|
| 820 |
+
# The Python callable can raise EOFError or KeyboardInterrupt and
|
| 821 |
+
# these will be translated into the appropriate outputs from readline
|
| 822 |
+
# so that they will then be translated back!
|
| 823 |
+
|
| 824 |
+
# If the Python callable raises any other exception, a traceback will
|
| 825 |
+
# be printed and readline will appear to return an empty line.
|
| 826 |
+
|
| 827 |
+
# I use ctypes to create a C-callable from a Python wrapper that
|
| 828 |
+
# handles the exceptions and gets the result into the right form.
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
# the type for our C-callable wrapper
|
| 832 |
+
HOOKFUNC23 = CFUNCTYPE(c_char_p, c_void_p, c_void_p, c_char_p)
|
| 833 |
+
|
| 834 |
+
readline_hook = None # the python hook goes here
|
| 835 |
+
readline_ref = None # reference to the c-callable to keep it alive
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
def hook_wrapper_23(stdin, stdout, prompt):
|
| 839 |
+
"""Wrap a Python readline so it behaves like GNU readline."""
|
| 840 |
+
try:
|
| 841 |
+
# call the Python hook
|
| 842 |
+
res = ensure_str(readline_hook(prompt))
|
| 843 |
+
# make sure it returned the right sort of thing
|
| 844 |
+
if res and not isinstance(res, bytes):
|
| 845 |
+
raise TypeError("readline must return a string.")
|
| 846 |
+
except KeyboardInterrupt:
|
| 847 |
+
# GNU readline returns 0 on keyboard interrupt
|
| 848 |
+
return 0
|
| 849 |
+
except EOFError:
|
| 850 |
+
# It returns an empty string on EOF
|
| 851 |
+
res = ensure_str("")
|
| 852 |
+
except BaseException:
|
| 853 |
+
print("Readline internal error", file=sys.stderr)
|
| 854 |
+
traceback.print_exc()
|
| 855 |
+
res = ensure_str("\n")
|
| 856 |
+
# we have to make a copy because the caller expects to free the result
|
| 857 |
+
n = len(res)
|
| 858 |
+
p = Console.PyMem_Malloc(n + 1)
|
| 859 |
+
_strncpy(cast(p, c_char_p), res, n + 1)
|
| 860 |
+
return p
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def install_readline(hook):
|
| 864 |
+
"""Set up things for the interpreter to call
|
| 865 |
+
our function like GNU readline."""
|
| 866 |
+
global readline_hook, readline_ref
|
| 867 |
+
# save the hook so the wrapper can call it
|
| 868 |
+
readline_hook = hook
|
| 869 |
+
# get the address of PyOS_ReadlineFunctionPointer so we can update it
|
| 870 |
+
PyOS_RFP = c_void_p.from_address(
|
| 871 |
+
Console.GetProcAddress(
|
| 872 |
+
sys.dllhandle, "PyOS_ReadlineFunctionPointer".encode("ascii")
|
| 873 |
+
)
|
| 874 |
+
)
|
| 875 |
+
# save a reference to the generated C-callable so it doesn't go away
|
| 876 |
+
readline_ref = HOOKFUNC23(hook_wrapper_23)
|
| 877 |
+
# get the address of the function
|
| 878 |
+
func_start = c_void_p.from_address(addressof(readline_ref)).value
|
| 879 |
+
# write the function address into PyOS_ReadlineFunctionPointer
|
| 880 |
+
PyOS_RFP.value = func_start
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
if __name__ == "__main__":
|
| 884 |
+
import sys
|
| 885 |
+
import time
|
| 886 |
+
|
| 887 |
+
def p(char):
|
| 888 |
+
return chr(VkKeyScan(ord(char)) & 0xFF)
|
| 889 |
+
|
| 890 |
+
c = Console(0)
|
| 891 |
+
sys.stdout = c
|
| 892 |
+
sys.stderr = c
|
| 893 |
+
c.page()
|
| 894 |
+
print(p("d"), p("D"))
|
| 895 |
+
c.pos(5, 10)
|
| 896 |
+
c.write("hi there")
|
| 897 |
+
print("some printed output")
|
| 898 |
+
for i in range(10):
|
| 899 |
+
q = c.getkeypress()
|
| 900 |
+
print(q)
|
| 901 |
+
del c
|
python_embeded/Lib/site-packages/pyreadline3/console/console_attributes.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FOREGROUND_BLUE = 0x0001
|
| 2 |
+
FOREGROUND_GREEN = 0x0002
|
| 3 |
+
FOREGROUND_RED = 0x0004
|
| 4 |
+
FOREGROUND_INTENSITY = 0x0008
|
| 5 |
+
BACKGROUND_BLUE = 0x0010
|
| 6 |
+
BACKGROUND_GREEN = 0x0020
|
| 7 |
+
BACKGROUND_RED = 0x0040
|
| 8 |
+
BACKGROUND_INTENSITY = 0x0080
|
| 9 |
+
COMMON_LVB_LEADING_BYTE = 0x0100
|
| 10 |
+
COMMON_LVB_TRAILING_BYTE = 0x0200
|
| 11 |
+
COMMON_LVB_GRID_HORIZONTAL = 0x0400
|
| 12 |
+
COMMON_LVB_GRID_LVERTICAL = 0x0800
|
| 13 |
+
COMMON_LVB_GRID_RVERTICAL = 0x1000
|
| 14 |
+
COMMON_LVB_REVERSE_VIDEO = 0x2000
|
| 15 |
+
COMMON_LVB_UNDERSCORE = 0x4000
|
python_embeded/Lib/site-packages/pyreadline3/console/consolebase.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class baseconsole(object):
|
| 2 |
+
def __init__(self):
|
| 3 |
+
pass
|
| 4 |
+
|
| 5 |
+
def bell(self):
|
| 6 |
+
raise NotImplementedError
|
| 7 |
+
|
| 8 |
+
def pos(self, x=None, y=None):
|
| 9 |
+
"""Move or query the window cursor."""
|
| 10 |
+
raise NotImplementedError
|
| 11 |
+
|
| 12 |
+
def size(self):
|
| 13 |
+
raise NotImplementedError
|
| 14 |
+
|
| 15 |
+
def rectangle(self, rect, attr=None, fill=" "):
|
| 16 |
+
"""Fill Rectangle."""
|
| 17 |
+
raise NotImplementedError
|
| 18 |
+
|
| 19 |
+
def write_scrolling(self, text, attr=None):
|
| 20 |
+
"""write text at current cursor position while watching for scrolling.
|
| 21 |
+
|
| 22 |
+
If the window scrolls because you are at the bottom of the screen
|
| 23 |
+
buffer, all positions that you are storing will be shifted by the
|
| 24 |
+
scroll amount. For example, I remember the cursor position of the
|
| 25 |
+
prompt so that I can redraw the line but if the window scrolls,
|
| 26 |
+
the remembered position is off.
|
| 27 |
+
|
| 28 |
+
This variant of write tries to keep track of the cursor position
|
| 29 |
+
so that it will know when the screen buffer is scrolled. It
|
| 30 |
+
returns the number of lines that the buffer scrolled.
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
raise NotImplementedError
|
| 34 |
+
|
| 35 |
+
def getkeypress(self):
|
| 36 |
+
"""Return next key press event from the queue, ignoring others."""
|
| 37 |
+
raise NotImplementedError
|
| 38 |
+
|
| 39 |
+
def write(self, text):
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def page(self, attr=None, fill=" "):
|
| 43 |
+
"""Fill the entire screen."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def isatty(self):
|
| 47 |
+
return True
|
| 48 |
+
|
| 49 |
+
def flush(self):
|
| 50 |
+
pass
|
python_embeded/Lib/site-packages/pyreadline3/console/event.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Event(object):
|
| 2 |
+
"""Represent events from the console."""
|
| 3 |
+
|
| 4 |
+
def __init__(self, console, input):
|
| 5 |
+
pass
|
| 6 |
+
|
| 7 |
+
def __repr__(self):
|
| 8 |
+
"""Display an event for debugging."""
|
| 9 |
+
if self.type in ["KeyPress", "KeyRelease"]:
|
| 10 |
+
chr = self.char
|
| 11 |
+
if ord(chr) < ord("A"):
|
| 12 |
+
chr = "?"
|
| 13 |
+
s = "%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % (
|
| 14 |
+
self.type,
|
| 15 |
+
chr,
|
| 16 |
+
ord(self.char),
|
| 17 |
+
self.keysym,
|
| 18 |
+
self.keycode,
|
| 19 |
+
self.keycode,
|
| 20 |
+
self.state,
|
| 21 |
+
self.keyinfo,
|
| 22 |
+
)
|
| 23 |
+
elif self.type in ["Motion", "Button"]:
|
| 24 |
+
s = "%s x=%d y=%d state=%x" % (self.type, self.x, self.y, self.state)
|
| 25 |
+
elif self.type == "Configure":
|
| 26 |
+
s = "%s w=%d h=%d" % (self.type, self.width, self.height)
|
| 27 |
+
elif self.type in ["FocusIn", "FocusOut"]:
|
| 28 |
+
s = self.type
|
| 29 |
+
elif self.type == "Menu":
|
| 30 |
+
s = "%s state=%x" % (self.type, self.state)
|
| 31 |
+
else:
|
| 32 |
+
s = "unknown event type"
|
| 33 |
+
return s
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# def __str__(self):
|
| 37 |
+
# return "('%s',%s,%s,%s)"%(self.char,self.key,self.state,self.keyinfo)
|