repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
neo4j/neo4j-python-driver
tests/unit/test_driver.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from neo4j import ( BoltDriver, GraphDatabase, Neo4jDriver, TRUST_SYSTEM_CA_SIGNED_CERTIFICATES, TRUST_ALL_CERTIFICATES, ) from neo4j.api import WRITE_ACCESS from neo4j.exceptions import ConfigurationError @pytest.mark.parametrize("protocol", ("bolt://", "bolt+s://", "bolt+ssc://")) @pytest.mark.parametrize("host", ("localhost", "127.0.0.1", "[::1]", "[0:0:0:0:0:0:0:1]")) @pytest.mark.parametrize("port", (":1234", "", ":7687")) @pytest.mark.parametrize("auth_token", (("test", "test"), None)) def test_direct_driver_constructor(protocol, host, port, auth_token): uri = protocol + host + port driver = GraphDatabase.driver(uri, auth=auth_token) assert isinstance(driver, BoltDriver) @pytest.mark.parametrize("protocol", ("neo4j://", "neo4j+s://", "neo4j+ssc://")) @pytest.mark.parametrize("host", ("localhost", "127.0.0.1", "[::1]", "[0:0:0:0:0:0:0:1]")) @pytest.mark.parametrize("port", (":1234", "", ":7687")) @pytest.mark.parametrize("auth_token", (("test", "test"), None)) def test_routing_driver_constructor(protocol, host, port, auth_token): uri = protocol + host + port driver = GraphDatabase.driver(uri, auth=auth_token) assert isinstance(driver, Neo4jDriver) @pytest.mark.parametrize("test_uri", ( "bolt+ssc://127.0.0.1:9001", "bolt+s://127.0.0.1:9001", "bolt://127.0.0.1:9001", "neo4j+ssc://127.0.0.1:9001", "neo4j+s://127.0.0.1:9001", "neo4j://127.0.0.1:9001", )) @pytest.mark.parametrize( ("test_config", "expected_failure", "expected_failure_message"), ( ({"encrypted": False}, ConfigurationError, "The config settings"), ({"encrypted": True}, ConfigurationError, "The config settings"), ( {"encrypted": True, "trust": TRUST_ALL_CERTIFICATES}, ConfigurationError, "The config settings" ), ( {"trust": TRUST_ALL_CERTIFICATES}, ConfigurationError, "The config settings" ), ( {"trust": TRUST_SYSTEM_CA_SIGNED_CERTIFICATES}, ConfigurationError, "The config settings" ), ) ) def test_driver_config_error( test_uri, test_config, expected_failure, expected_failure_message ): if "+" in test_uri: # `+s` and `+ssc` are short hand syntax for not having to configure the # encryption behavior of the driver. Specifying both is invalid. with pytest.raises(expected_failure, match=expected_failure_message): GraphDatabase.driver(test_uri, **test_config) else: GraphDatabase.driver(test_uri, **test_config) @pytest.mark.parametrize("test_uri", ( "http://localhost:9001", "ftp://localhost:9001", "x://localhost:9001", )) def test_invalid_protocol(test_uri): with pytest.raises(ConfigurationError, match="scheme"): GraphDatabase.driver(test_uri) @pytest.mark.parametrize( ("test_config", "expected_failure", "expected_failure_message"), ( ({"trust": 1}, ConfigurationError, "The config setting `trust`"), ({"trust": True}, ConfigurationError, "The config setting `trust`"), ({"trust": None}, ConfigurationError, "The config setting `trust`"), ) ) def test_driver_trust_config_error( test_config, expected_failure, expected_failure_message ): with pytest.raises(expected_failure, match=expected_failure_message): GraphDatabase.driver("bolt://127.0.0.1:9001", **test_config) @pytest.mark.parametrize("uri", ( "bolt://127.0.0.1:9000", "neo4j://127.0.0.1:9000", )) def test_driver_opens_write_session_by_default(uri, mocker): driver = GraphDatabase.driver(uri) from neo4j.work.transaction import Transaction # we set a specific db, because else the driver would try to fetch a RT # to get hold of the actual home database (which won't work in this # unittest) with driver.session(database="foobar") as session: acquire_mock = mocker.patch.object(session._pool, "acquire", autospec=True) tx_begin_mock = mocker.patch.object(Transaction, "_begin", autospec=True) tx = session.begin_transaction() acquire_mock.assert_called_once_with( access_mode=WRITE_ACCESS, timeout=mocker.ANY, database=mocker.ANY, bookmarks=mocker.ANY ) tx_begin_mock.assert_called_once_with( tx, mocker.ANY, mocker.ANY, mocker.ANY, WRITE_ACCESS, mocker.ANY, mocker.ANY )
neo4j/neo4j-python-driver
tests/unit/test_addressing.py
<gh_stars>100-1000 #!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import unittest.mock as mock from socket import ( AF_INET, AF_INET6, ) from neo4j.addressing import ( Address, IPv4Address, IPv6Address, ) from neo4j import GraphDatabase mock_socket_ipv4 = mock.Mock() mock_socket_ipv4.getpeername = lambda: ("127.0.0.1", 7687) # (address, port) mock_socket_ipv6 = mock.Mock() mock_socket_ipv6.getpeername = lambda: ("[::1]", 7687, 0, 0) # (address, port, flow info, scope id) # python -m pytest tests/unit/test_addressing.py -s @pytest.mark.parametrize( "test_input, expected", [ (("127.0.0.1", 7687), {"family": AF_INET, "host": "127.0.0.1", "port": 7687, "str": "127.0.0.1:7687", "repr": "IPv4Address(('127.0.0.1', 7687))"}), (("localhost", 7687), {"family": AF_INET, "host": "localhost", "port": 7687, "str": "localhost:7687", "repr": "IPv4Address(('localhost', 7687))"}), ((None, None), {"family": AF_INET, "host": None, "port": None, "str": "None:None", "repr": "IPv4Address((None, None))"}), (("::1", 7687), {"family": AF_INET, "host": "::1", "port": 7687, "str": "::1:7687", "repr": "IPv4Address(('::1', 7687))"}), (("::1", 7687, 0, 0), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 0, 0))"}), (("::1", 7687, 1, 2), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 1, 2))"}), ((None, None, None, None), {"family": AF_INET6, "host": None, "port": None, "str": "[None]:None", "repr": "IPv6Address((None, None, None, None))"}), (Address(("127.0.0.1", 7687)), {"family": AF_INET, "host": "127.0.0.1", "port": 7687, "str": "127.0.0.1:7687", "repr": "IPv4Address(('127.0.0.1', 7687))"}), (Address(("::1", 7687, 1, 2)), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 1, 2))"}), ] ) def test_address_initialization(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_initialization address = Address(test_input) assert address.family == expected["family"] assert address.host == expected["host"] assert address.port == expected["port"] assert str(address) == expected["str"] assert repr(address) == expected["repr"] @pytest.mark.parametrize( "test_input", [ Address(("127.0.0.1", 7687)), Address(("127.0.0.1", 7687, 1, 2)), ] ) def test_address_init_with_address_object_returns_same_instance(test_input): # python -m pytest tests/unit/test_addressing.py -s -k test_address_init_with_address_object_returns_same_instance address = Address(test_input) assert address is test_input assert id(address) == id(test_input) @pytest.mark.parametrize( "test_input, expected", [ (("127.0.0.1",), ValueError), (("127.0.0.1", 7687, 0), ValueError), (("[::1]", 7687, 0), ValueError), (("[::1]", 7687, 0, 0, 0), ValueError), ] ) def test_address_initialization_with_incorrect_input(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_initialization_with_incorrect_input with pytest.raises(expected): address = Address(test_input) @pytest.mark.parametrize( "test_input, expected", [ (mock_socket_ipv4, ("127.0.0.1", 7687)), (mock_socket_ipv6, ("[::1]", 7687, 0, 0)) ] ) def test_address_from_socket(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_from_socket address = Address.from_socket(test_input) assert address == expected def test_address_from_socket_with_none(): # python -m pytest tests/unit/test_addressing.py -s -k test_address_from_socket_with_none with pytest.raises(AttributeError): address = Address.from_socket(None) @pytest.mark.parametrize( "test_input, expected", [ ("127.0.0.1:7687", ("127.0.0.1", 7687)), ("localhost:7687", ("localhost", 7687)), (":7687", ("localhost", 7687)), (":", ("localhost", 0)), ("", ("localhost", 0)), (":abcd", ("localhost", "abcd")), (" ", (" ", 0)), ] ) def test_address_parse_with_ipv4(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_parse_with_ipv4 parsed = Address.parse(test_input) assert parsed == expected @pytest.mark.parametrize( "test_input, expected", [ ("[::1]:7687", ("::1", 7687, 0, 0)), ("[::1]:abcd", ("::1", "abcd", 0, 0)), ("[::1]:", ("::1", 0, 0, 0)), ("[::1]", ("::1", 0, 0, 0)), ] ) def test_address_should_parse_ipv6(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_should_parse_ipv6 parsed = Address.parse(test_input) assert parsed == expected @pytest.mark.parametrize( "test_input, expected", [ (None, TypeError), (123, TypeError), (("127.0.0.1", 7687), TypeError), (("[::1]", 7687, 1, 2), TypeError), (Address(("127.0.0.1", 7687)), TypeError), ] ) def test_address_parse_with_invalid_input(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_parse_with_invalid_input with pytest.raises(expected): parsed = Address.parse(test_input) @pytest.mark.parametrize( "test_input, expected", [ (("localhost:7687 [::1]:7687",), 2), (("localhost:7687", "[::1]:7687"), 2), (("localhost:7687 localhost:7688", "[::1]:7687"), 3), (("localhost:7687 localhost:7687", "[::1]:7687"), 3), ] ) def test_address_parse_list(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_parse_list addresses = Address.parse_list(*test_input) assert len(addresses) == expected @pytest.mark.parametrize( "test_input, expected", [ (("localhost:7687", None), TypeError), (("localhost:7687", 123), TypeError), (("localhost:7687", ("127.0.0.1", 7687)), TypeError), (("localhost:7687", ("[::1]", 7687, 1, 2)), TypeError), (("localhost:7687", Address(("127.0.0.1", 7687))), TypeError), ] ) def test_address_parse_list_with_invalid_input(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_parse_list_with_invalid_input with pytest.raises(TypeError): addresses = Address.parse_list(*test_input) def test_address_resolve(): # python -m pytest tests/unit/test_addressing.py -s -k test_address_resolve address = Address(("127.0.0.1", 7687)) resolved = address.resolve() assert isinstance(resolved, Address) is False assert isinstance(resolved, list) is True assert len(resolved) == 1 assert resolved[0] == IPv4Address(('127.0.0.1', 7687)) def test_address_resolve_with_custom_resolver_none(): # python -m pytest tests/unit/test_addressing.py -s -k test_address_resolve_with_custom_resolver_none address = Address(("127.0.0.1", 7687)) resolved = address.resolve(resolver=None) assert isinstance(resolved, Address) is False assert isinstance(resolved, list) is True assert len(resolved) == 1 assert resolved[0] == IPv4Address(('127.0.0.1', 7687)) @pytest.mark.parametrize( "test_input, expected", [ (Address(("127.0.0.1", "abcd")), ValueError), (Address((None, None)), ValueError), ] ) def test_address_resolve_with_unresolvable_address(test_input, expected): # python -m pytest tests/unit/test_addressing.py -s -k test_address_resolve_with_unresolvable_address with pytest.raises(expected): test_input.resolve(resolver=None) def test_address_resolve_with_custom_resolver(): # python -m pytest tests/unit/test_addressing.py -s -k test_address_resolve_with_custom_resolver custom_resolver = lambda _: [("127.0.0.1", 7687), ("localhost", 1234)] address = Address(("127.0.0.1", 7687)) resolved = address.resolve(family=AF_INET, resolver=custom_resolver) assert isinstance(resolved, Address) is False assert isinstance(resolved, list) is True assert len(resolved) == 2 # IPv4 only assert resolved[0] == IPv4Address(('127.0.0.1', 7687)) assert resolved[1] == IPv4Address(('127.0.0.1', 1234)) def test_address_unresolve(): # python -m pytest tests/unit/test_addressing.py -s -k test_address_unresolve custom_resolved = [("127.0.0.1", 7687), ("localhost", 4321)] custom_resolver = lambda _: custom_resolved address = Address(("foobar", 1234)) unresolved = address.unresolved assert address.__class__ == unresolved.__class__ assert address == unresolved resolved = address.resolve(family=AF_INET, resolver=custom_resolver) custom_resolved = sorted(Address(a) for a in custom_resolved) unresolved = sorted(a.unresolved for a in resolved) assert custom_resolved == unresolved assert (list(map(lambda a: a.__class__, custom_resolved)) == list(map(lambda a: a.__class__, unresolved)))
neo4j/neo4j-python-driver
tests/unit/work/test_transaction.py
<filename>tests/unit/work/test_transaction.py #!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from uuid import uuid4 from unittest.mock import ( MagicMock, NonCallableMagicMock, ) import pytest from neo4j import ( Query, Transaction, ) from ._fake_connection import fake_connection @pytest.mark.parametrize(("explicit_commit", "close"), ( (False, False), (True, False), (True, True), )) def test_transaction_context_when_committing(mocker, fake_connection, explicit_commit, close): on_closed = MagicMock() on_error = MagicMock() tx = Transaction(fake_connection, 2, on_closed, on_error) mock_commit = mocker.patch.object(tx, "commit", wraps=tx.commit) mock_rollback = mocker.patch.object(tx, "rollback", wraps=tx.rollback) with tx as tx_: assert mock_commit.call_count == 0 assert mock_rollback.call_count == 0 assert tx is tx_ if explicit_commit: tx_.commit() mock_commit.assert_called_once_with() assert tx.closed() if close: tx_.close() assert tx_.closed() mock_commit.assert_called_once_with() assert mock_rollback.call_count == 0 assert tx_.closed() @pytest.mark.parametrize(("rollback", "close"), ( (True, False), (False, True), (True, True), )) def test_transaction_context_with_explicit_rollback(mocker, fake_connection, rollback, close): on_closed = MagicMock() on_error = MagicMock() tx = Transaction(fake_connection, 2, on_closed, on_error) mock_commit = mocker.patch.object(tx, "commit", wraps=tx.commit) mock_rollback = mocker.patch.object(tx, "rollback", wraps=tx.rollback) with tx as tx_: assert mock_commit.call_count == 0 assert mock_rollback.call_count == 0 assert tx is tx_ if rollback: tx_.rollback() mock_rollback.assert_called_once_with() assert tx_.closed() if close: tx_.close() mock_rollback.assert_called_once_with() assert tx_.closed() assert mock_commit.call_count == 0 mock_rollback.assert_called_once_with() assert tx_.closed() def test_transaction_context_calls_rollback_on_error(mocker, fake_connection): class OopsError(RuntimeError): pass on_closed = MagicMock() on_error = MagicMock() tx = Transaction(fake_connection, 2, on_closed, on_error) mock_commit = mocker.patch.object(tx, "commit", wraps=tx.commit) mock_rollback = mocker.patch.object(tx, "rollback", wraps=tx.rollback) with pytest.raises(OopsError): with tx as tx_: assert mock_commit.call_count == 0 assert mock_rollback.call_count == 0 assert tx is tx_ raise OopsError assert mock_commit.call_count == 0 mock_rollback.assert_called_once_with() assert tx_.closed() @pytest.mark.parametrize(("parameters", "error_type"), ( # maps must have string keys ({"x": {1: 'eins', 2: 'zwei', 3: 'drei'}}, TypeError), ({"x": {(1, 2): '1+2i', (2, 0): '2'}}, TypeError), ({"x": uuid4()}, TypeError), )) def test_transaction_run_with_invalid_parameters(fake_connection, parameters, error_type): on_closed = MagicMock() on_error = MagicMock() tx = Transaction(fake_connection, 2, on_closed, on_error) with pytest.raises(error_type): tx.run("RETURN $x", **parameters) def test_transaction_run_takes_no_query_object(fake_connection): on_closed = MagicMock() on_error = MagicMock() tx = Transaction(fake_connection, 2, on_closed, on_error) with pytest.raises(ValueError): tx.run(Query("RETURN 1")) def test_transaction_rollbacks_on_open_connections(fake_connection): tx = Transaction(fake_connection, 2, lambda *args, **kwargs: None, lambda *args, **kwargs: None) with tx as tx_: fake_connection.is_reset_mock.return_value = False fake_connection.is_reset_mock.reset_mock() tx_.rollback() fake_connection.is_reset_mock.assert_called_once() fake_connection.reset.assert_not_called() fake_connection.rollback.assert_called_once() def test_transaction_no_rollback_on_reset_connections(fake_connection): tx = Transaction(fake_connection, 2, lambda *args, **kwargs: None, lambda *args, **kwargs: None) with tx as tx_: fake_connection.is_reset_mock.return_value = True fake_connection.is_reset_mock.reset_mock() tx_.rollback() fake_connection.is_reset_mock.assert_called_once() fake_connection.reset.asset_not_called() fake_connection.rollback.asset_not_called() def test_transaction_no_rollback_on_closed_connections(fake_connection): tx = Transaction(fake_connection, 2, lambda *args, **kwargs: None, lambda *args, **kwargs: None) with tx as tx_: fake_connection.closed.return_value = True fake_connection.closed.reset_mock() fake_connection.is_reset_mock.reset_mock() tx_.rollback() fake_connection.closed.assert_called_once() fake_connection.is_reset_mock.asset_not_called() fake_connection.reset.asset_not_called() fake_connection.rollback.asset_not_called() def test_transaction_no_rollback_on_defunct_connections(fake_connection): tx = Transaction(fake_connection, 2, lambda *args, **kwargs: None, lambda *args, **kwargs: None) with tx as tx_: fake_connection.defunct.return_value = True fake_connection.defunct.reset_mock() fake_connection.is_reset_mock.reset_mock() tx_.rollback() fake_connection.defunct.assert_called_once() fake_connection.is_reset_mock.asset_not_called() fake_connection.reset.asset_not_called() fake_connection.rollback.asset_not_called()
neo4j/neo4j-python-driver
neo4j/api.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from urllib.parse import ( urlparse, parse_qs, ) from.exceptions import ( DriverError, ConfigurationError, ) from .meta import deprecated """ Base classes and helpers. """ READ_ACCESS = "READ" WRITE_ACCESS = "WRITE" DRIVER_BOLT = "DRIVER_BOLT" DRIVER_NEO4j = "DRIVER_NEO4J" SECURITY_TYPE_NOT_SECURE = "SECURITY_TYPE_NOT_SECURE" SECURITY_TYPE_SELF_SIGNED_CERTIFICATE = "SECURITY_TYPE_SELF_SIGNED_CERTIFICATE" SECURITY_TYPE_SECURE = "SECURITY_TYPE_SECURE" URI_SCHEME_BOLT = "bolt" URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE = "bolt+ssc" URI_SCHEME_BOLT_SECURE = "bolt+s" URI_SCHEME_NEO4J = "neo4j" URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE = "neo4j+ssc" URI_SCHEME_NEO4J_SECURE = "neo4j+s" URI_SCHEME_BOLT_ROUTING = "bolt+routing" TRUST_SYSTEM_CA_SIGNED_CERTIFICATES = "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" # Default TRUST_ALL_CERTIFICATES = "TRUST_ALL_CERTIFICATES" SYSTEM_DATABASE = "system" DEFAULT_DATABASE = None # Must be a non string hashable value # TODO: This class is not tested class Auth: """Container for auth details. :param scheme: specifies the type of authentication, examples: "basic", "kerberos" :type scheme: str :param principal: specifies who is being authenticated :type principal: str or None :param credentials: authenticates the principal :type credentials: str or None :param realm: specifies the authentication provider :type realm: str or None :param parameters: extra key word parameters passed along to the authentication provider :type parameters: Dict[str, Any] """ def __init__(self, scheme, principal, credentials, realm=None, **parameters): self.scheme = scheme # Neo4j servers pre 4.4 require the principal field to always be # present. Therefore, we transmit it even if it's an empty sting. if principal is not None: self.principal = principal if credentials: self.credentials = credentials if realm: self.realm = realm if parameters: self.parameters = parameters # For backwards compatibility AuthToken = Auth def basic_auth(user, password, realm=None): """Generate a basic auth token for a given user and password. This will set the scheme to "basic" for the auth token. :param user: user name, this will set the :type user: str :param password: <PASSWORD>, this will set the credentials :type password: str :param realm: specifies the authentication provider :type realm: str or None :return: auth token for use with :meth:`GraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("basic", user, password, realm) def kerberos_auth(base64_encoded_ticket): """Generate a kerberos auth token with the base64 encoded ticket. This will set the scheme to "kerberos" for the auth token. :param base64_encoded_ticket: a base64 encoded service ticket, this will set the credentials :type base64_encoded_ticket: str :return: auth token for use with :meth:`GraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("kerberos", "", base64_encoded_ticket) def bearer_auth(base64_encoded_token): """Generate an auth token for Single-Sign-On providers. This will set the scheme to "bearer" for the auth token. :param base64_encoded_token: a base64 encoded authentication token generated by a Single-Sign-On provider. :type base64_encoded_token: str :return: auth token for use with :meth:`GraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth("bearer", None, base64_encoded_token) def custom_auth(principal, credentials, realm, scheme, **parameters): """Generate a custom auth token. :param principal: specifies who is being authenticated :type principal: str or None :param credentials: authenticates the principal :type credentials: str or None :param realm: specifies the authentication provider :type realm: str or None :param scheme: specifies the type of authentication :type scheme: str or None :param parameters: extra key word parameters passed along to the authentication provider :type parameters: Dict[str, Any] :return: auth token for use with :meth:`GraphDatabase.driver` :rtype: :class:`neo4j.Auth` """ return Auth(scheme, principal, credentials, realm, **parameters) class Bookmark: """A Bookmark object contains an immutable list of bookmark string values. :param values: ASCII string values """ def __init__(self, *values): if values: bookmarks = [] for ix in values: try: if ix: ix.encode("ascii") bookmarks.append(ix) except UnicodeEncodeError as e: raise ValueError("The value {} is not ASCII".format(ix)) self._values = frozenset(bookmarks) else: self._values = frozenset() def __repr__(self): """ :return: repr string with sorted values """ return "<Bookmark values={{{}}}>".format(", ".join(["'{}'".format(ix) for ix in sorted(self._values)])) def __bool__(self): return bool(self._values) @property def values(self): """ :return: immutable list of bookmark string values :rtype: frozenset """ return self._values class ServerInfo: """ Represents a package of information relating to a Neo4j server. """ def __init__(self, address, protocol_version): self._address = address self._protocol_version = protocol_version self._metadata = {} @property def address(self): """ Network address of the remote server. """ return self._address @property def protocol_version(self): """ Bolt protocol version with which the remote server communicates. This is returned as a :class:`.Version` object, which itself extends a simple 2-tuple of (major, minor) integers. """ return self._protocol_version @property def agent(self): """ Server agent string by which the remote server identifies itself. """ return self._metadata.get("server") @property def connection_id(self): """ Unique identifier for the remote server connection. """ return self._metadata.get("connection_id") # TODO in 5.0: remove this method @deprecated("The version_info method is deprecated, please use " "ServerInfo.agent, ServerInfo.protocol_version, or " "call the dbms.components procedure instead") def version_info(self): """Return the server version if available. :return: Server Version or None :rtype: tuple .. deprecated:: 4.3 `version_info` will be removed in version 5.0. Use :meth:`~ServerInfo.agent`, :meth:`~ServerInfo.protocol_version`, or call the `dbms.components` procedure instead. """ if not self.agent: return None # Note: Confirm that the server agent string begins with "Neo4j/" and fail gracefully if not. # This is intended to help prevent drivers working for non-genuine Neo4j instances. prefix, _, value = self.agent.partition("/") try: assert prefix in ["Neo4j"] except AssertionError: raise DriverError("Server name does not start with Neo4j/") try: if self.protocol_version >= (4, 0): return self.protocol_version except TypeError: pass value = value.replace("-", ".").split(".") for i, v in enumerate(value): try: value[i] = int(v) except ValueError: pass return tuple(value) def update(self, metadata): """ Update server information with extra metadata. This is typically drawn from the metadata received after successful connection initialisation. """ self._metadata.update(metadata) class Version(tuple): def __new__(cls, *v): return super().__new__(cls, v) def __repr__(self): return "{}{}".format(self.__class__.__name__, super().__repr__()) def __str__(self): return ".".join(map(str, self)) def to_bytes(self): b = bytearray(4) for i, v in enumerate(self): if not 0 <= i < 2: raise ValueError("Too many version components") if isinstance(v, list): b[-i - 1] = int(v[0] % 0x100) b[-i - 2] = int((v[0] - v[-1]) % 0x100) else: b[-i - 1] = int(v % 0x100) return bytes(b) @classmethod def from_bytes(cls, b): b = bytearray(b) if len(b) != 4: raise ValueError("Byte representation must be exactly four bytes") if b[0] != 0 or b[1] != 0: raise ValueError("First two bytes must contain zero") return Version(b[-1], b[-2]) def parse_neo4j_uri(uri): parsed = urlparse(uri) if parsed.username: raise ConfigurationError("Username is not supported in the URI") if parsed.password: raise ConfigurationError("Password is not supported in the URI") if parsed.scheme == URI_SCHEME_BOLT_ROUTING: raise ConfigurationError("Uri scheme {!r} have been renamed. Use {!r}".format(parsed.scheme, URI_SCHEME_NEO4J)) elif parsed.scheme == URI_SCHEME_BOLT: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_NOT_SECURE elif parsed.scheme == URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_SELF_SIGNED_CERTIFICATE elif parsed.scheme == URI_SCHEME_BOLT_SECURE: driver_type = DRIVER_BOLT security_type = SECURITY_TYPE_SECURE elif parsed.scheme == URI_SCHEME_NEO4J: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_NOT_SECURE elif parsed.scheme == URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_SELF_SIGNED_CERTIFICATE elif parsed.scheme == URI_SCHEME_NEO4J_SECURE: driver_type = DRIVER_NEO4j security_type = SECURITY_TYPE_SECURE else: raise ConfigurationError("URI scheme {!r} is not supported. Supported URI schemes are {}. Examples: bolt://host[:port] or neo4j://host[:port][?routing_context]".format( parsed.scheme, [ URI_SCHEME_BOLT, URI_SCHEME_BOLT_SELF_SIGNED_CERTIFICATE, URI_SCHEME_BOLT_SECURE, URI_SCHEME_NEO4J, URI_SCHEME_NEO4J_SELF_SIGNED_CERTIFICATE, URI_SCHEME_NEO4J_SECURE ] )) return driver_type, security_type, parsed def check_access_mode(access_mode): if access_mode is None: return WRITE_ACCESS if access_mode not in (READ_ACCESS, WRITE_ACCESS): msg = "Unsupported access mode {}".format(access_mode) raise ConfigurationError(msg) return access_mode def parse_routing_context(query): """ Parse the query portion of a URI to generate a routing context dictionary. """ if not query: return {} context = {} parameters = parse_qs(query, True) for key in parameters: value_list = parameters[key] if len(value_list) != 1: raise ConfigurationError("Duplicated query parameters with key '%s', value '%s' found in query string '%s'" % (key, value_list, query)) value = value_list[0] if not value: raise ConfigurationError("Invalid parameters:'%s=%s' in query string '%s'." % (key, value, query)) context[key] = value return context
neo4j/neo4j-python-driver
tests/unit/io/test_neo4j_pool.py
<gh_stars>100-1000 #!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from unittest.mock import Mock import pytest from ..work import FakeConnection from neo4j import ( READ_ACCESS, WRITE_ACCESS, ) from neo4j.addressing import ResolvedAddress from neo4j.conf import ( PoolConfig, RoutingConfig, WorkspaceConfig ) from neo4j.io import Neo4jPool ROUTER_ADDRESS = ResolvedAddress(("1.2.3.1", 9001), host_name="host") READER_ADDRESS = ResolvedAddress(("1.2.3.1", 9002), host_name="host") WRITER_ADDRESS = ResolvedAddress(("1.2.3.1", 9003), host_name="host") @pytest.fixture() def opener(): def open_(addr, timeout): connection = FakeConnection() connection.addr = addr connection.timeout = timeout route_mock = Mock() route_mock.return_value = [{ "ttl": 1000, "servers": [ {"addresses": [str(ROUTER_ADDRESS)], "role": "ROUTE"}, {"addresses": [str(READER_ADDRESS)], "role": "READ"}, {"addresses": [str(WRITER_ADDRESS)], "role": "WRITE"}, ], }] connection.attach_mock(route_mock, "route") opener_.connections.append(connection) return connection opener_ = Mock() opener_.connections = [] opener_.side_effect = open_ return opener_ def test_acquires_new_routing_table_if_deleted(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx) assert pool.routing_tables.get("test_db") del pool.routing_tables["test_db"] cx = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx) assert pool.routing_tables.get("test_db") def test_acquires_new_routing_table_if_stale(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx) assert pool.routing_tables.get("test_db") old_value = pool.routing_tables["test_db"].last_updated_time pool.routing_tables["test_db"].ttl = 0 cx = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx) assert pool.routing_tables["test_db"].last_updated_time > old_value def test_removes_old_routing_table(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx = pool.acquire(READ_ACCESS, 30, "test_db1", None) pool.release(cx) assert pool.routing_tables.get("test_db1") cx = pool.acquire(READ_ACCESS, 30, "test_db2", None) pool.release(cx) assert pool.routing_tables.get("test_db2") old_value = pool.routing_tables["test_db1"].last_updated_time pool.routing_tables["test_db1"].ttl = 0 pool.routing_tables["test_db2"].ttl = \ -RoutingConfig.routing_table_purge_delay cx = pool.acquire(READ_ACCESS, 30, "test_db1", None) pool.release(cx) assert pool.routing_tables["test_db1"].last_updated_time > old_value assert "test_db2" not in pool.routing_tables @pytest.mark.parametrize("type_", ("r", "w")) def test_chooses_right_connection_type(opener, type_): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS if type_ == "r" else WRITE_ACCESS, 30, "test_db", None) pool.release(cx1) if type_ == "r": assert cx1.addr == READER_ADDRESS else: assert cx1.addr == WRITER_ADDRESS def test_reuses_connection(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx1) cx2 = pool.acquire(READ_ACCESS, 30, "test_db", None) assert cx1 is cx2 @pytest.mark.parametrize("break_on_close", (True, False)) def test_closes_stale_connections(opener, break_on_close): def break_connection(): pool.deactivate(cx1.addr) if cx_close_mock_side_effect: cx_close_mock_side_effect() pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx1) assert cx1 in pool.connections[cx1.addr] # simulate connection going stale (e.g. exceeding) and than breaking when # the pool tries to close the connection cx1.stale.return_value = True cx_close_mock = cx1.close if break_on_close: cx_close_mock_side_effect = cx_close_mock.side_effect cx_close_mock.side_effect = break_connection cx2 = pool.acquire(READ_ACCESS, 30, "test_db", None) pool.release(cx2) assert cx1.close.called_once() assert cx2 is not cx1 assert cx2.addr == cx1.addr assert cx1 not in pool.connections[cx1.addr] assert cx2 in pool.connections[cx2.addr] def test_release_resets_connections(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS, 30, "test_db", None) cx1.is_reset_mock.return_value = False cx1.is_reset_mock.reset_mock() pool.release(cx1) cx1.is_reset_mock.assert_called_once() cx1.reset.assert_called_once() def test_release_does_not_resets_closed_connections(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS, 30, "test_db", None) cx1.closed.return_value = True cx1.closed.reset_mock() cx1.is_reset_mock.reset_mock() pool.release(cx1) cx1.closed.assert_called_once() cx1.is_reset_mock.asset_not_called() cx1.reset.asset_not_called() def test_release_does_not_resets_defunct_connections(opener): pool = Neo4jPool(opener, PoolConfig(), WorkspaceConfig(), ROUTER_ADDRESS) cx1 = pool.acquire(READ_ACCESS, 30, "test_db", None) cx1.defunct.return_value = True cx1.defunct.reset_mock() cx1.is_reset_mock.reset_mock() pool.release(cx1) cx1.defunct.assert_called_once() cx1.is_reset_mock.asset_not_called() cx1.reset.asset_not_called()
Fethbita/flask-mongoengine
flask_mongoengine/sessions.py
"""MongoDB Session Interface""" import typing as t from datetime import datetime, timedelta import uuid from bson.tz_util import utc from flask.sessions import SessionInterface, SessionMixin from werkzeug.datastructures import CallbackDict # Type checking if t.TYPE_CHECKING: from flask.app import Flask from flask.wrappers import Request, Response __all__ = ("MongoEngineSession", "MongoEngineSessionInterface") class MongoEngineSession(CallbackDict, SessionMixin): def __init__(self, initial=None, sid=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.modified = False class MongoEngineSessionInterface(SessionInterface): """SessionInterface for mongoengine""" def __init__(self, db, collection="session"): """ The MongoSessionInterface :param db: The app's db eg: MongoEngine() :param collection: The session collection name defaults to "session" """ if not isinstance(collection, str): raise ValueError("Collection argument should be string") class DBSession(db.Document): sid = db.StringField(primary_key=True) data = db.DictField() expiration = db.DateTimeField() meta = { "allow_inheritance": False, "collection": collection, "indexes": [ { "fields": ["expiration"], "expireAfterSeconds": 60 * 60 * 24 * 7 * 31, } ], } self.cls = DBSession def get_expiration_time(self, app: "Flask", session: SessionMixin) -> datetime: now = datetime.utcnow().replace(tzinfo=utc) if session.permanent: return now + app.permanent_session_lifetime # Fallback to 1 day session ttl, if SESSION_TTL not set. return now + timedelta(**app.config.get("SESSION_TTL", {"days": 1})) def open_session(self, app: "Flask", request: "Request") -> MongoEngineSession: val = request.cookies.get(self.get_cookie_name(app)) if not val: return MongoEngineSession(sid=str(uuid.uuid4())) stored_session = self.cls.objects(sid=val).first() if not stored_session: return MongoEngineSession(sid=str(uuid.uuid4())) expiration = stored_session.expiration if not expiration.tzinfo: expiration = expiration.replace(tzinfo=utc) if expiration > datetime.utcnow().replace(tzinfo=utc): return MongoEngineSession( initial=stored_session.data, sid=stored_session.sid ) return MongoEngineSession(sid=str(uuid.uuid4())) def save_session( # type: ignore[override] self, app: "Flask", session: MongoEngineSession, response: "Response" ): name = self.get_cookie_name(app) domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) secure = self.get_cookie_secure(app) samesite = self.get_cookie_samesite(app) # If the session is modified to be empty, remove the cookie. # If the session is empty, return without setting the cookie. if not session: if session.modified: response.delete_cookie( name, domain=domain, path=path, secure=secure, samesite=samesite ) return # Add a "Vary: Cookie" header if the session was accessed at all. if session.accessed: response.vary.add("Cookie") if not self.should_set_cookie(app, session): return httponly = self.get_cookie_httponly(app) expires = self.get_expiration_time(app, session) if session.modified: self.cls(sid=session.sid, data=session, expiration=expires).save() response.set_cookie( key=name, value=session.sid, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite, )
vinnyotach7/RBAC-APP
constants.py
<gh_stars>0 from PyInquirer import prompt, Separator questions = [ { 'type': "input", "name": "userName", "message": "Enter a UserName", }, { 'type': 'checkbox', 'message': 'Select roles', 'name': 'roles', 'choices': [ Separator('= ROLES ='), { 'name': 'admin' }, { 'name': 'user' } ], 'validate': lambda answer: 'You must choose at least one role.' \ if len(answer) == 0 else True } ] viewQuestions = [ { 'type': "input", "name": "userName", "message": "Enter a UserName to view attached roles", } ] deleteQuestions = [ { 'type': "input", "name": "userName", "message": "Enter a UserName to be removed", }, { 'type': 'confirm', 'message': 'Do you want to continue?', 'name': 'continue', 'default': True, } ] loginQuestions = [ { 'type': "input", "name": "userName", "message": "Enter a UserName ", }, { 'type': "input", "name": "role", "message": "Enter a role to be used", }, ] introAdmin = """Enter view to view roles Enter add to add a User Enter delete to delete a user Enter login to login as another user""" introDeveloper = """Enter view to view roles Enter login to login as another user"""
vinnyotach7/RBAC-APP
entities/user.py
<reponame>vinnyotach7/RBAC-APP<filename>entities/user.py<gh_stars>0 class User(): def __init__(self,username,role): self.username = username self.role = role def get_username(self): return self.username def set_username(self,value): self.__username=value def get_roles(self): return self.role def set_roles(self,roles): self.roles=roles
vinnyotach7/RBAC-APP
entities/roles.py
<reponame>vinnyotach7/RBAC-APP<gh_stars>0 class Roles: def __init__(self,type,role): self.__validRole = ['User','Admin','Viewer'] @username.setter def username(self,type): if type not in self.__validRole: raise Exception('User type not allowed') #self.role=
vinnyotach7/RBAC-APP
main.py
<reponame>vinnyotach7/RBAC-APP from cmd import Cmd from BaseUser.createBaseUser import createBaseUser from entities.user import User from PyInquirer import prompt from examples import custom_style_2 from prompt_toolkit.validation import Validator, ValidationError from constants import questions,viewQuestions,deleteQuestions,loginQuestions,introAdmin,introDeveloper class MyPrompt(Cmd): __currentUser = [] __currentRole = [] prompt = '>>> ' intro = """Press 1 to login as admin Press 2 to login as developer""" def do_exit(self, inp): print("Bye") return True def begin(self): #user = self.__currentUser[0] userRole = self.__currentRole[0] print(userRole) if userRole != 'admin': print(introDeveloper) else: print(introAdmin) def help_exit(self): print('exit the application. Shorthand: x q Ctrl-D.') #add a user def do_add(self, inp): userRole = self.__currentRole[0] print("current role is",userRole) if userRole != 'admin': print("action not allowed") else: answers = prompt(questions, style=custom_style_2) createUser = createBaseUser() user = User(answers.get("userName"),answers.get("roles")) createUser.addUser(user) print("user {} added".format(answers.get("userName"))) return self.begin() #view a user def do_view(self, inp): answers = prompt(viewQuestions, style=custom_style_2) try: userRole = createBaseUser.userData[answers.get('userName')] except KeyError: print("Invalid username") return self.begin() print("user roles are '{}'".format(userRole)) #delete a user def do_delete(self, inp): #userRole = createBaseUser.userData[self.__currentUser[0]] createUser = createBaseUser() if self.__currentRole[0]!='admin': print("action not allowed") return self.begin() answers = prompt(deleteQuestions, style=custom_style_2) if(answers.get('continue') is True): resp = self.check_user_delete(answers.get('userName')) if(resp == False): print("cannot delete user") else: print("existing users are '{}'".format(createUser.userData)) del createBaseUser.userData[answers.get('userName')] print("Users after deletion '{}'".format(createUser.userData)) return self.begin() def do_login(self,inp): answers = prompt(loginQuestions, style=custom_style_2) checkUser = self.check_user_exists(answers.get('userName'),answers.get('role')) if(checkUser == True): print("You are now logged in as {} with role {}".format(answers.get('userName'),answers.get('role'))) self.__currentUser.clear() self.__currentRole.clear() self.__currentUser.append(answers.get('username')) self.__currentRole.append(answers.get('role')) return self.begin() def help_add(self): print("Add a new entry to the system.") def check_user_delete(self,username): #user = createBaseUser.userData[username] if username in ["user1","user2"]: return False return True def check_user_exists(self,username,role): try: userRole = createBaseUser.userData[username] except KeyError: print("Invalid username") return self.begin() if role not in userRole: print("User with role {} does not exist".format(role)) return self.begin() return True def default(self, inp): if inp == '1': self.__currentUser.append("user1") self.__currentRole.append('admin') print(introAdmin) elif inp == '2': self.__currentUser.append("user2") self.__currentRole.append('user') print(self.__currentUser) print(introDeveloper) elif inp == 'x' or inp == 'q': return self.do_exit(inp) else: print("sorry,I did not get that") return self.begin() #print("Default: {}".format(inp)) do_EOF = do_exit help_EOF = help_exit if __name__ == '__main__': createBaseUser.create() MyPrompt().cmdloop()
vinnyotach7/RBAC-APP
BaseUser/createBaseUser.py
<filename>BaseUser/createBaseUser.py from entities.user import User class createBaseUser: """def createBaseUser(self): user = {} user['User1']='Admin' return user""" superAdminActions = ['read','write','delete'] adminActions = ['read','write'] devActions = ['read'] userData = dict() #suserData = dict() @staticmethod def create(): roleAdmin = [] roleAdmin.append('admin') user1 = User("user1",roleAdmin) roleDev = [] roleDev.append('user') user2 = User("user2",roleDev) createBaseUser.userData[user1.get_username()]=user1.get_roles() createBaseUser.userData[user2.get_username()]=user2.get_roles() print(createBaseUser.userData) def addUser(self,user): if user.get_username() in createBaseUser.userData.keys(): print("user already exists") else: createBaseUser.userData[user.get_username()]=user.get_roles()
dominikheinisch/pybitbay
setup.py
<gh_stars>0 from setuptools import setup, find_packages setup( name="pybitbay", version="0.0.1", description="python api for bitbay cryptocurrency exchange", author="<NAME>", author_email="<EMAIL>", url="https://github.com/dominikheinisch/pybitbay", license='Apache 2.0', packages=find_packages("pybitbay"), install_requires=["pandas", "requests"], python_requires=">=3.6", )
dominikheinisch/pybitbay
test/test_bitbay.py
<reponame>dominikheinisch/pybitbay import pytest import pandas as pd from pybitbay import BitBayAPI TICKER = 'btcpln' JSON_DATA = [ {"date": 1396094988, "price": 4500.0, "type": "buy", "amount": 0.0129, "tid": "0"}, {"date": 1396096603, "price": 4400.0, "type": "sell", "amount": 0.011364, "tid": "1"}, ] COLUMNS = JSON_DATA[0].keys() EXPECTED_DF = pd.DataFrame( data=JSON_DATA, columns=COLUMNS ) class MockResponse: def json(self): return JSON_DATA class EmptyMockResponse: def json(self): return {} def test_BitBayAPI(mocker): mocker.patch('requests.Session.get', side_effect=[MockResponse(), EmptyMockResponse()]) trades = BitBayAPI().get_all_trades(ticker=TICKER) assert next(trades).equals(EXPECTED_DF) with pytest.raises(StopIteration): next(trades) def test_bitbay_public_api(): df = BitBayAPI().get_trades(ticker=TICKER, since=-1) assert list(COLUMNS) == df.columns.tolist() assert df[0:2].equals(EXPECTED_DF)
dominikheinisch/pybitbay
pybitbay/bitbay.py
import pandas as pd from requests import Session from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from typing import Generator class BitBayAPI: BASE_URL = 'https://bitbay.net/API/Public/' TRADES_SUFFIX = '/trades.json' SINCE_SUFFIX = '?since=' def __init__(self): retry_strategy = Retry( total=5, status_forcelist=[429, 500, 502, 503, 504], method_whitelist=['GET'], ) self._http = Session() self._http.mount( prefix='https://', adapter=HTTPAdapter(max_retries=retry_strategy) ) def get_all_trades(self, ticker: str, since: int = -1) -> Generator[pd.DataFrame, int, None]: ''' :param ticker: eg. 'btcpln' :param since: (first trade's id (tid) in a batch) - 1 :return: Generator[pd.DataFrame, int, None] ''' while not (df := self.get_trades(ticker, since)).empty: since += len(df) yield df def get_trades(self, ticker: str, since: int) -> pd.DataFrame: ''' :param ticker: eg. 'btcpln' :param since: first trade's id (tid) in a batch :return: pandas.DataFrame Index: RangeIndex Columns: Name: date, dtype: int64 Name: price, dtype: float64 Name: type, dtype: object Name: amount, dtype: float64 Name: tid, dtype: object ''' response = self._http.get( url=f'{self.BASE_URL}{ticker}{self.TRADES_SUFFIX}{self.SINCE_SUFFIX}{since}', timeout=3, ) return pd.json_normalize(response.json())
dominikheinisch/pybitbay
pybitbay/__init__.py
<reponame>dominikheinisch/pybitbay<gh_stars>0 from pybitbay.bitbay import BitBayAPI __all__ = ['BitBayAPI']
Narasimha-sai/eth-provider-benchmark
config.py
import sys from multiprocessing import Lock ITERATIONS = 457 DELAY = 5 VERBOSE = False STDIN = sys.stdin.fileno() LOCK = Lock()
Narasimha-sai/eth-provider-benchmark
provider_benchmark.py
from multiprocessing import Process from web3 import Web3 import argparse import random import log_consistency import pending_transactions import sys import config def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument('-i', action='store', dest='infura_api_key', help='test Infura with your unique API key') parser.add_argument('-a', action='store', dest='alchemy_api_key', help="test Alchemy with your unique API key") parser.add_argument('-c', '--cloudflare', action='store_true', help="test Cloudflare") parser.add_argument('-n', action='store', dest='node_http_instance', help="test a specific node with an http instance") parser.add_argument('-v', '--verbose', action='store_true', help="display progess of tests") net = parser.add_mutually_exclusive_group(required = True) net.add_argument('-mainnet', action='store_true', help="test on Mainnet") net.add_argument('-ropsten', action='store_true', help="test on Ropsten") connection = parser.add_mutually_exclusive_group(required = True) connection.add_argument('-websocket', action='store_true', help="test websocket") connection.add_argument('-http', action='store_true', help="test http") test = parser.add_mutually_exclusive_group(required=True) test.add_argument('-1', '--log_consistency', action='store_true', help="run test for log consistency") test.add_argument('-2', '--pending_transactions', action='store_true', help="run test for pending transactions") return parser.parse_args() def runTests(web3, company, tests): for test in tests: test (web3, company) def alchemy(tests, args): if args.websocket: if args.mainnet: web3 = Web3(Web3.WebsocketProvider("wss://eth-mainnet.ws.alchemyapi.io/ws/" + args.alchemy_api_key)) else: web3 = Web3(Web3.WebsocketProvider("wss://eth-ropsten.ws.alchemyapi.io/ws/" + args.alchemy_api_key)) else: if args.mainnet: web3 = Web3(Web3.HTTPProvider("https://eth-mainnet.alchemyapi.io/jsonrpc/" + args.alchemy_api_key)) else: web3 = Web3(Web3.HTTPProvider("https://eth-ropsten.alchemyapi.io/jsonrpc/" + args.alchemy_api_key)) runTests(web3, "Alchemy", tests) def infura(tests, args): if args.websocket: if args.mainnet: web3 = Web3(Web3.WebsocketProvider("wss://mainnet.infura.io/ws/v3/" + args.infura_api_key)) else: web3 = Web3(Web3.WebsocketProvider("wss://ropsten.infura.io/ws/v3/" + args.infura_api_key)) else: if args.mainnet: web3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/" + args.infura_api_key)) else: web3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/" + args.infura_api_key)) runTests(web3, "Infura", tests) def cloudflare(tests, args): if args.mainnet and args.http: web3 = Web3(Web3.HTTPProvider("https://cloudflare-eth.com")) runTests(web3, "Cloudflare", tests) def node(tests, args): if not args.websocket: web3 = Web3(Web3.HTTPProvider(args.node_http_instance)) runTests(web3, "ETH Node", tests) if __name__ == '__main__': args = parseArgs() config.VERBOSE = args.verbose if args.infura_api_key is None and args.alchemy_api_key is None and not args.cloudflare and args.node_http_instance is None: print ("provider_benchmark.py: error: must specify companies to test, use -h for help") sys.exit() tests = [] if args.log_consistency: tests.append(log_consistency.logTest) if args.pending_transactions: tests.append(pending_transactions.transactionsTest) threads = [] if args.infura_api_key: threads.append(Process(target=infura, args=(tests, args))) if args.alchemy_api_key: threads.append(Process(target=alchemy, args=(tests, args))) if args.cloudflare: threads.append(Process(target=cloudflare, args=(tests, args))) if args.node_http_instance: threads.append(Process(target=node, args=(tests, args))) for t in threads: t.start() for t in threads: t.join()
Narasimha-sai/eth-provider-benchmark
pending_transactions.py
import time import random import urllib, json from web3 import Web3 from multiprocessing import Process import provider_benchmark import eth_accountz import os import sys import config def transactionsTest(web3, company): transactionNotFound = 0 config.LOCK.acquire() sys.stdin = os.fdopen(config.STDIN) sendAddress = input("Enter an address to send transaction through " + company + " (must be distinct, do not repeat accross tests): ") sendPrivateKey = input("Enter the private key for that address: ") recieveAddress = input("Enter an address to recieve transaction through " + company + " (must be distinct, do not repeat accross tests): ") recievePrivateKey = input("Enter the private key for that address: ") config.LOCK.release() sendAccount = eth_accountz.Account(sendAddress, sendPrivateKey) recieveAccount = eth_accountz.Account(recieveAddress, recievePrivateKey) nonce = web3.eth.getTransactionCount(sendAccount.address) for i in range(config.ITERATIONS): signed_txn = web3.eth.account.signTransaction({ 'to': recieveAccount.address, 'gasPrice':web3.eth.gasPrice, 'nonce': nonce + i, 'gas': 100000, }, sendAccount.privateKey) try: txn = web3.eth.sendRawTransaction(signed_txn.rawTransaction) receipt = web3.eth.getTransaction(txn) except Exception as e: if config.VERBOSE: print (company, "gave the following error when sending then getting a transaction:", e) time.sleep(config.DELAY) continue if receipt is None: transactionNotFound += 1 if config.VERBOSE: print (company, "returned the following reciept:", receipt) time.sleep(config.DELAY) print (company, "failed to find pending transactions:", transactionNotFound/config.ITERATIONS * 100, "%")
Narasimha-sai/eth-provider-benchmark
log_consistency.py
<reponame>Narasimha-sai/eth-provider-benchmark<gh_stars>10-100 import time from web3 import Web3 import provider_benchmark import config def logTest(web3, company): methodInconsitency = 0 getLogByHashFailure = 0 latestBlockFailure = 0 logsDic = {} for i in range(config.ITERATIONS): latestBlock = web3.eth.getBlock('latest') if latestBlock is None: latestBlockFailure += 1 if config.VERBOSE: print (company, "couldn't get latest block") else: latestBlockHash = latestBlock.hash.hex() try: logByHash = web3.eth.getLogs({'blockHash': latestBlockHash}) except Exception as e: if config.VERBOSE: print (company, "gave the following error when trying to find logs for the latest block", latestBlock.number, "by blockHash:", e) getLogByHashFailure += 1 time.sleep(config.DELAY) continue if latestBlockHash in logsDic: if logsDic[latestBlockHash] != logByHash: methodInconsitency += 1 if config.VERBOSE: print (company, "gave a different log than previously reported for block", latestBlock) time.sleep(config.DELAY) continue else: logsDic[latestBlockHash] = logByHash if config.VERBOSE: print (company, "successfully found a log with", len(logByHash), "events for the latest block", latestBlock.number) time.sleep(config.DELAY) print (company, "returned a different log for the same latest block:", methodInconsitency/config.ITERATIONS * 100, "%") print (company, "failed to return the latest block:", latestBlockFailure/config.ITERATIONS * 100, "%") print (company, "failed to getLogs on the latest block queried by blockHash:", getLogByHashFailure/config.ITERATIONS * 100, "%")
Narasimha-sai/eth-provider-benchmark
eth_accountz.py
class Account: def __init__(self, address, privateKey): self.address = address self.privateKey = privateKey
TerrenceAm22/DS-Unit-3-Sprint-3-Productization-and-Cloud
Sprint Challenge 3 Unit 3/aq_dashboard.py
<gh_stars>0 """OpenAQ Air Quality Dashboard with Flask.""" from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy import openaq import requests """Create and configure an instance of the Flask application.""" APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' DB = SQLAlchemy(APP) api = openaq.OpenAQ() def aqmeasurements(city='Los Angeles', parameter='pm25'): status, body = api.measurements(city='Los Angeles', parameter='pm25') la_results = body['results'] date = [] for b in la_results: for x, y in b.items(): if x == 'date': date.append(y) utc = [] for c in date: for k, v in c.items(): if k == 'utc': utc.append(v) val = [] for d in la_results: for m, n in d.items(): if m == 'value': val.append(n) utc_value = list(zip(utc, val)) return utc_value @APP.route('/') def root(): hazard = Record.query.filter(Record.value >= 10).all() return str(hazard) class Record(DB.Model): id = DB.Column(DB.Integer, primary_key=True) datetime = DB.Column(DB.String(25)) value = DB.Column(DB.Float, nullable=False) def __repr__(self): return '< Date-time: {} - PM value: {} >'.format(self.datetime, self.value) @APP.route('/refresh') def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() utc_value = aqmeasurements(city='Los Angeles', parameter='pm25') for x in utc_value: db_record = Record(datetime=x[0], value=x[1]) DB.session.add(db_record) DB.session.commit() return 'Data refreshed!'
FlorianSchwendinger/pdfminer.six
tests/test_read_all.py
<reponame>FlorianSchwendinger/pdfminer.six #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 21 11:34:19 2020 @author: florian """ from pdfminer import pdf # Read the document doc = pdf.read_all("../samples/cars.pdf") doc # Get elements doc.list_elements() # By default all elments are returned as **DataFrame**. doc.get_metainfo() doc.get_text().head() doc.get_line() doc.get_rect() doc.get_curve() doc.get_figure() doc.get_textline().head() doc.get_textbox().head() doc.get_textgroup() doc.get_image() # But it is also possible the get the elemens as list of dictionaries. doc.get_metainfo("list") x = doc.get_text() pdf.group_blocks(x).head()
FlorianSchwendinger/pdfminer.six
tests/test_layout.py
<reponame>FlorianSchwendinger/pdfminer.six<filename>tests/test_layout.py import unittest from pdfminer.layout import LTLayoutContainer, LAParams, LTTextLineHorizontal class TestGroupTextLines(unittest.TestCase): def test_parent_with_wrong_bbox_returns_non_empty_neighbour_list(self): """ LTLayoutContainer.group_textlines() should return all the lines in a separate LTTextBoxes if they do not overlap. Even when the bounding box of the parent container does not contain all the lines. """ laparams = LAParams() layout = LTLayoutContainer((0, 0, 50, 50)) line1 = LTTextLineHorizontal(laparams.word_margin) line1.set_bbox((0, 0, 50, 5)) line2 = LTTextLineHorizontal(laparams.word_margin) line2.set_bbox((0, 50, 50, 55)) lines = [line1, line2] textboxes = list(layout.group_textlines(laparams, lines)) self.assertEqual(len(textboxes), 2)
FlorianSchwendinger/pdfminer.six
pdfminer/pdf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 21 08:46:25 2020 @author: florian This is copied from pdfmole (<https://github.com/FlorianSchwendinger/pdfmole>) from the file "pdfmole/inst/python/pdf2list.py". """ import os import json from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFLayoutAnalyzer from pdfminer.image import ImageWriter from pdfminer.layout import LAParams, LTPage, LTText, LTLine, LTRect, LTCurve, LTFigure, LTImage, \ LTChar, LTTextLine, LTTextBox, LTTextGroup, LTTextBoxVertical from pdfminer.utils import enc from pdfminer.pdfpage import PDFPage import pandas as pd class PDF2Converter(PDFLayoutAnalyzer): def __init__(self, rsrcmgr, codec='utf-8', pageno=1, laparams=None): PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams) self.codec = codec return class XML2Converter(PDF2Converter): def __init__(self, rsrcmgr, codec='utf-8', pageno=1, laparams=None, imagewriter=None, stripcontrol=False): PDF2Converter.__init__(self, rsrcmgr, codec=codec, pageno=pageno, laparams=laparams) self.imagewriter = imagewriter self.stripcontrol = stripcontrol self.doc = list() self.page = None return def receive_layout(self, ltpage): def show_group(item): if isinstance(item, LTTextGroup): self.page['textgroup'].append({'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]}) for child in item: show_group(child) return def render(item): if isinstance(item, LTPage): metainfo = {'pid': item.pageid, 'rotate': item.rotate, 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]} self.page = {'metainfo': metainfo, 'text': [], 'line': [], 'rect': [], 'curve': [], 'figure': [], 'textline': [], 'textbox': [], 'textgroup': [], 'image': []} for child in item: render(child) if item.groups is not None: for group in item.groups: show_group(group) self.doc.append(self.page) elif isinstance(item, LTLine): self.page['line'].append({'linewidth': item.linewidth, 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]}) elif isinstance(item, LTRect): self.page['rect'].append({'linewidth': item.linewidth, 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]}) elif isinstance(item, LTCurve): curve = {'linewidth': item.linewidth, 'pts': item.get_pts(), 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]} self.page['curve'].append(curve) elif isinstance(item, LTFigure): self.page['figure'].append({'name': item.name, 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]}) for child in item: render(child) elif isinstance(item, LTTextLine): self.page['textline'].append({'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]}) for child in item: render(child) elif isinstance(item, LTTextBox): wmode = 'vertical' if isinstance(item, LTTextBoxVertical) else 'horizontal' tb = {'id': item.index, 'wmode': wmode, 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]} self.page['textbox'].append(tb) for child in item: render(child) elif isinstance(item, LTChar): # bbox (x0,y0,x1,y1) # x0: the distance from the left of the page to the left edge of the box. # y0: the distance from the bottom of the page to the lower edge of the box. # x1: the distance from the left of the page to the right edge of the box. # y1: the distance from the bottom of the page to the upper edge of the box. txt = {'text': item.get_text(), 'font': enc(item.fontname), 'size': item.size, 'colorspace': item.ncs.name, 'color': json.dumps(item.graphicstate.ncolor), 'x0': item.bbox[0], 'y0': item.bbox[1], 'x1': item.bbox[2], 'y1': item.bbox[3]} self.page['text'].append(txt) elif isinstance(item, LTText): # LTText is the interface for things that have text. # LTAnno inherits from LTText. self.page['text'].append({'text': item.get_text()}) elif isinstance(item, LTImage): if self.imagewriter is not None: name = self.imagewriter.export_image(item) img = {'src': enc(name), 'width': item.width, 'height': item.height} self.page['image'].append(img) else: self.page['image'].append({'width': item.width, 'height': item.height}) else: assert False, str(('Unhandled', item)) return render(ltpage) return COL_NAMES = { 'metainfo': ['pid', 'rotate', 'x0', 'y0', 'x1', 'y1'], 'text': ['pid', 'block', 'text', 'font', 'size', 'colorspace', 'color', 'x0', 'y0', 'x1', 'y1'], 'line': ['pid', 'linewidth', 'x0', 'y0', 'x1', 'y1'], 'rect': ['pid', 'linewidth', 'x0', 'y0', 'x1', 'y1'], 'curve': ['pid', 'linewidth', 'pts', 'x0', 'y0', 'x1', 'y1'], 'figure': ['pid', 'name', 'x0', 'y0', 'x1', 'y1'], 'textline': ['pid', 'x0', 'y0', 'x1', 'y1'], 'textbox': ['pid', 'id', 'wmode', 'x0', 'y0', 'x1', 'y1'], 'textgroup': ['pid', 'x0', 'y0', 'x1', 'y1'], 'image': ['pid', 'src', 'width', 'height']} class PdfDoc: def __init__(self, doc): self.elements = ['metainfo', 'text', 'line', 'rect', 'curve', 'figure', 'textline', 'textbox', 'textgroup', 'image'] self.doc = {} for ele in self.elements: self.doc[ele] = list() for page in doc: if ele == 'metainfo': self.doc[ele].append(page[ele]) else: pid = page['metainfo']['pid'] for item in page[ele]: item['pid'] = pid self.doc[ele].append(item) def __repr__(self): if len(self.doc) == 1: s = "A pdf document with 1 page." else: s = "A pdf document with %i pages." % (len(self.doc), ) return s def __str__(self): return self.__repr__() def list_elements(self): return self.elements def check_dtype(self, dtype): if not dtype in ("list", "df"): raise ValueError("Unknown dtype, allowed values are 'list' and 'df'!") def __get_element(self, element, dtype="df"): self.check_dtype(dtype) if dtype == "list": return self.doc[element] else: df = pd.DataFrame(self.doc[element], columns=COL_NAMES[element]) return df def get_text(self, dtype="df"): self.check_dtype(dtype) if dtype == "list": return self.doc['text'] else: d = list() pid = -1 block = 0 for item in self.doc['text']: if "x0" in item.keys(): if pid != item['pid']: block += 1 item['block'] = block d.append(item) pid = item['pid'] else: block += 1 df = pd.DataFrame(self.doc['text'], columns=COL_NAMES['text']) return df def get_element(self, element, dtype="df"): return self.get_text(dtype) if element == "text" else self.__get_element(element, dtype) def get_metainfo(self, dtype="df"): return self.__get_element('metainfo', dtype) def get_line(self, dtype="df"): return self.__get_element('line', dtype) def get_rect(self, dtype="df"): return self.__get_element('rect', dtype) def get_curve(self, dtype="df"): return self.__get_element('curve', dtype) def get_figure(self, dtype="df"): return self.__get_element('figure', dtype) def get_textline(self, dtype="df"): return self.__get_element('textline', dtype) def get_textbox(self, dtype="df"): return self.__get_element('textbox', dtype) def get_textgroup(self, dtype="df"): return self.__get_element('textgroup', dtype) def get_image(self, dtype="df"): return self.__get_element('image', dtype) def read_all(pdffile, page_numbers=[], codec='utf-8', strip_control=False, password="", caching=True, maxpages=0, rotation=0, image_dir=None): if not (os.path.splitext(pdffile)[1] == ".pdf"): raise IOError("PDF-file expected got '%s'!" % (os.path.splitext(pdffile)[1], )) if not os.path.exists(pdffile): raise IOError("Could not find PDF-file '%s'!" % (pdffile, )) if image_dir is None: imagewriter = None else: if not os.path.exists(image_dir): os.mkdir(image_dir) imagewriter = ImageWriter(image_dir) rsrcmgr = PDFResourceManager(caching=caching) laparams = LAParams() device = XML2Converter(rsrcmgr, codec=codec, laparams=laparams, imagewriter=imagewriter, stripcontrol=strip_control) interpreter = PDFPageInterpreter(rsrcmgr, device) with open(pdffile, 'rb') as con: if (page_numbers is None) or (len(page_numbers) == 0): page_numbers = [i[0] for i in enumerate(PDFPage.get_pages(con))] for page in PDFPage.get_pages(con, page_numbers, maxpages=maxpages, password=password, caching=caching, check_extractable=True): page.rotate = (page.rotate + rotation) % 360 interpreter.process_page(page) return PdfDoc(device.doc) def group_blocks(x): def group_block(d): if d.shape[0] == 0: return None r1 = d.iloc[0] di = {'pid': r1['pid'], 'text': ''.join(d['text']), 'font': r1['font'], 'size': r1['size'], 'colorspace': r1['colorspace'], 'color': r1['color'], 'x0': d['x0'].min(), 'y0': d['y0'].min(), 'x1': d['x1'].max(), 'y1': d['y1'].max()} return di x = x.dropna(subset=['block']) x = x.astype({'block': int}) y = [group_block(df) for block_id, df in x.groupby('block', as_index=False)] return pd.DataFrame(y)
SynBioHub/Plugin-Visual-ProteinStructure
app.py
<gh_stars>0 from flask import Flask, request, abort import os import subprocess import sys import traceback import xml.etree.ElementTree as ET from flask.wrappers import Response sys.path.append("/usr/lib/python3/dist-packages") import pymol import urllib from prody import * app = Flask(__name__, static_url_path = "", static_folder = "./") @app.route("/status") def status(): return("The Visualisation Protein Structure Plugin Flask Server is up and running") @app.route("/evaluate", methods=["POST"]) def evaluate(): data = request.get_json(force=True) rdf_type = data['type'] # uses rdf types #accepted_types = {'Activity', 'Agent', 'Association', 'Attachment', # 'Collection', 'CombinatorialDerivation', 'Component', # 'ComponentDefinition', 'Cut', 'Experiment', # 'ExperimentalData', 'FunctionalComponent', # 'GenericLocation', 'Implementation', 'Interaction', # 'Location', 'MapsTo', 'Measure', 'Model', 'Module', # 'ModuleDefinition', 'Participation', 'Plan', 'Range', # 'Sequence', 'SequenceAnnotation', 'SequenceConstraint', # 'Usage', 'VariableComponent'} accepted_types = {'Component', 'ComponentDefinition'} acceptable = rdf_type in accepted_types if acceptable: return f'The type sent ({rdf_type}) is an accepted type', 200 else: return f'The type sent ({rdf_type}) is NOT an accepted type', 415 @app.route("/run", methods=["POST"]) def run(): plugin_ip = request.headers.get('host')#'127.0.0.1' print("plugin_ip: {}".format(plugin_ip), file=sys.stderr) data = request.get_json(force=True) print("RECEIVED: {}".format(data), file=sys.stderr) complete_sbol = data['complete_sbol'] instance_url = data['instanceUrl'] cwd = os.getcwd() filename = os.path.join(cwd, "result_template.html") data_dir = "/data" try: #subtest_sbol_url = complete_sbol.replace('public/igem/', 'download/sbol_').replace('/1/sbol','.xml') # This is temporary. #sbol_url = subtest_sbol_url sbol_url = complete_sbol print("Downloading SBOL file: {}".format(sbol_url), file=sys.stderr) urllib.request.urlretrieve(sbol_url, "sbol.xml") # Parse the SBOL xml to determine pdb id sbol_tree=ET.parse("sbol.xml") sbol_root=sbol_tree.getroot() print("Root = {}".format(sbol_root.tag), file=sys.stderr) print("Attrib = {}".format(sbol_root.attrib),file=sys.stderr) for sbol_child in sbol_root: if "Sequence" in sbol_child.tag: for sbol_child_child in sbol_child: if "elements" in sbol_child_child.tag: print("elements: {} - {}".format(sbol_child_child.tag, sbol_child_child.text),file=sys.stderr) sequence = sbol_child_child.text.lower() pdb_list_file = os.path.join(data_dir, "blast_pdb.txt") print("pdb_list_file: {}".format(pdb_list_file), file=sys.stderr) found_pdb_id = False if os.path.exists(pdb_list_file): f=open(pdb_list_file, 'r') for line in f: if sequence in line: print("Found: {}".format(line), file=sys.stderr) found_pdb_id = True pdb_match_line = line f.close() if found_pdb_id: pdb_id = pdb_match_line.strip().split(':')[-1] print("pdb_id: {}".format(pdb_id), file=sys.stderr) else: blast_record=blastPDB(sequence) best = blast_record.getBest() pdb_id = best['pdb_id'] f=open(pdb_list_file, 'a+') f.write(sequence + ":" + pdb_id + "\n") f.close() print("Retrieved PDB ID: {}".format(pdb_id), file=sys.stderr) protein_imagename = os.path.join(data_dir, "protein_"+pdb_id+".png") print("protein_imagename: {}".format(protein_imagename), file=sys.stderr) if not os.path.exists(protein_imagename): # Download the pdb file pdb_file_name = "protein_"+pdb_id+".pdb" pdb_url_base='https://www.ebi.ac.uk/pdbe/entry-files/download/pdb' pdb_file_url = pdb_url_base + pdb_id + '.ent'; print("Downloading pdb file: {}".format(pdb_file_url), file=sys.stderr) urllib.request.urlretrieve(pdb_file_url, pdb_file_name) # Check data directory size data_size = subprocess.check_output(['du','-sm', data_dir]).split()[0].decode('utf-8') print("data_size={}".format(data_size), file=sys.stderr) data_files = os.listdir(data_dir) png_files = [os.path.join(data_dir, x) for x in data_files if x.endswith('.png')] if len(png_files) > 0: oldest_png_file = min(png_files, key=os.path.getctime) print("Oldest PNG file: {}".format(oldest_png_file), file=sys.stderr) data_limit = 1024 # MiB if int(data_size) >= data_limit: print("Deleting oldest PNG file: {}".format(oldest_png_file), file=sys.stderr) os.remove(oldest_png_file) # Get the png image using pymol convert_to_png(pdb_id) print("Created PNG file!", file=sys.stderr) # protein_name = complete_sbol.replace(instance_url+'public/igem/', '').replace('/1/sbol', '') with open(filename, 'r') as htmlfile: result = htmlfile.read() result = result.replace("PLUGIN_IP", plugin_ip) result = result.replace("PROTEIN_IMAGEFILE", protein_imagename) print("Returning HTML: {}".format(result), file=sys.stderr) return result except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] lnum = exc_tb.tb_lineno abort(400, f'Exception is: {e}, exc_type: {exc_type}, exc_obj: {exc_obj}, fname: {fname}, line_number: {lnum}, traceback: {traceback.format_exc()}') def convert_to_png(pdb_id): data_dir = "/data" protein_imagename = os.path.join(data_dir, "protein_"+pdb_id+".png") pdb_file = "protein_"+pdb_id+".pdb" if not os.path.exists(protein_imagename): print("Converting PDB to PNG ... {}".format(protein_imagename), file=sys.stderr) pymol.pymol_argv = [ 'pymol', '-qc'] pdb_name = "protein_"+pdb_id+".pdb" pymol.cmd.load(pdb_file, pdb_name) pymol.cmd.disable("all") pymol.cmd.enable(pdb_name) pymol.cmd.png(protein_imagename) pymol.cmd.delete("all") os.remove(pdb_file)
khoih-prog/transformers
src/transformers/models/glpn/feature_extraction_glpn.py
<reponame>khoih-prog/transformers # coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Feature extractor class for GLPN.""" from typing import Optional, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...file_utils import TensorType from ...image_utils import ImageFeatureExtractionMixin, ImageInput, is_torch_tensor from ...utils import logging logger = logging.get_logger(__name__) class GLPNFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin): r""" Constructs a GLPN feature extractor. This feature extractor inherits from [`FeatureExtractionMixin`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the input based on certain `size_divisor`. size_divisor (`int` or `Tuple(int)`, *optional*, defaults to 32): Make sure the input is divisible by this value. Only has an effect if `do_resize` is set to `True`. resample (`int`, *optional*, defaults to `PIL.Image.BILINEAR`): An optional resampling filter. This can be one of `PIL.Image.NEAREST`, `PIL.Image.BOX`, `PIL.Image.BILINEAR`, `PIL.Image.HAMMING`, `PIL.Image.BICUBIC` or `PIL.Image.LANCZOS`. Only has an effect if `do_resize` is set to `True`. do_rescale (`bool`, *optional*, defaults to `True`): Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). """ model_input_names = ["pixel_values"] def __init__(self, do_resize=True, size_divisor=32, resample=Image.BILINEAR, do_rescale=True, **kwargs): super().__init__(**kwargs) self.do_resize = do_resize self.size_divisor = size_divisor self.resample = resample self.do_rescale = do_rescale def _resize(self, image, size_divisor, resample): if not isinstance(image, Image.Image): image = self.to_pil_image(image) width, height = image.size new_h, new_w = height // size_divisor * size_divisor, width // size_divisor * size_divisor image = self.resize(image, size=(new_w, new_h), resample=resample) return image def __call__( self, images: ImageInput, return_tensors: Optional[Union[str, TensorType]] = None, **kwargs ) -> BatchFeature: """ Main method to prepare for the model one or several image(s). <Tip warning={true}> NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass PIL images. </Tip> Args: images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a number of channels, H and W are image height and width. return_tensors (`str` or [`~file_utils.TensorType`], *optional*, defaults to `'np'`): If set, will return tensors of a particular framework. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields: - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height, width). """ # Input type checking for clearer error valid_images = False # Check that images has a valid type if isinstance(images, (Image.Image, np.ndarray)) or is_torch_tensor(images): valid_images = True elif isinstance(images, (list, tuple)): if len(images) == 0 or isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0]): valid_images = True if not valid_images: raise ValueError( "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), " "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)." ) is_batched = bool( isinstance(images, (list, tuple)) and (isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0])) ) if not is_batched: images = [images] # transformations (resizing + rescaling) if self.do_resize and self.size_divisor is not None: images = [ self._resize(image=image, size_divisor=self.size_divisor, resample=self.resample) for image in images ] if self.do_rescale: images = [self.to_numpy_array(image=image) for image in images] # return as BatchFeature data = {"pixel_values": images} encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors) return encoded_inputs
khoih-prog/transformers
src/transformers/models/resnet/modeling_resnet.py
<filename>src/transformers/models/resnet/modeling_resnet.py # coding=utf-8 # Copyright 2022 Microsoft Research, Inc. and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch ResNet model.""" from dataclasses import dataclass from typing import Optional, Tuple import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ImageClassifierOutput, ModelOutput from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_resnet import ResNetConfig logger = logging.get_logger(__name__) # General docstring _CONFIG_FOR_DOC = "ResNetConfig" _FEAT_EXTRACTOR_FOR_DOC = "AutoFeatureExtractor" # Base docstring _CHECKPOINT_FOR_DOC = "microsoft/resnet-50" _EXPECTED_OUTPUT_SHAPE = [1, 2048, 7, 7] # Image classification docstring _IMAGE_CLASS_CHECKPOINT = "microsoft/resnet-50" _IMAGE_CLASS_EXPECTED_OUTPUT = "tiger cat" RESNET_PRETRAINED_MODEL_ARCHIVE_LIST = [ "microsoft/resnet-50", # See all resnet models at https://huggingface.co/models?filter=resnet ] @dataclass class ResNetEncoderOutput(ModelOutput): """ ResNet encoder's output, with potential hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. """ last_hidden_state: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None @dataclass class ResNetModelOutput(ModelOutput): """ ResNet model's output, with potential hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, config.hidden_sizes[-1])`): The pooled last hidden state. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. """ last_hidden_state: torch.FloatTensor = None pooler_output: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None class ResNetConvLayer(nn.Sequential): def __init__( self, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, activation: str = "relu" ): super().__init__() self.convolution = nn.Conv2d( in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, bias=False ) self.normalization = nn.BatchNorm2d(out_channels) self.activation = ACT2FN[activation] if activation is not None else nn.Identity() class ResNetEmbeddings(nn.Sequential): """ ResNet Embedddings (stem) composed of a single aggressive convolution. """ def __init__(self, num_channels: int, out_channels: int, activation: str = "relu"): super().__init__() self.embedder = ResNetConvLayer(num_channels, out_channels, kernel_size=7, stride=2, activation=activation) self.pooler = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) class ResNetShortCut(nn.Sequential): """ ResNet shortcut, used to project the residual features to the correct size. If needed, it is also used to downsample the input using `stride=2`. """ def __init__(self, in_channels: int, out_channels: int, stride: int = 2): super().__init__() self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.normalization = nn.BatchNorm2d(out_channels) class ResNetBasicLayer(nn.Module): """ A classic ResNet's residual layer composed by a two `3x3` convolutions. """ def __init__(self, in_channels: int, out_channels: int, stride: int = 1, activation: str = "relu"): super().__init__() should_apply_shortcut = in_channels != out_channels or stride != 1 self.shortcut = ( ResNetShortCut(in_channels, out_channels, stride=stride) if should_apply_shortcut else nn.Identity() ) self.layer = nn.Sequential( ResNetConvLayer(in_channels, out_channels, stride=stride), ResNetConvLayer(out_channels, out_channels, activation=None), ) self.activation = ACT2FN[activation] def forward(self, hidden_state): residual = hidden_state hidden_state = self.layer(hidden_state) residual = self.shortcut(residual) hidden_state += residual hidden_state = self.activation(hidden_state) return hidden_state class ResNetBottleNeckLayer(nn.Module): """ A classic ResNet's bottleneck layer composed by a three `3x3` convolutions. The first `1x1` convolution reduces the input by a factor of `reduction` in order to make the second `3x3` convolution faster. The last `1x1` convolution remap the reduced features to `out_channels`. """ def __init__( self, in_channels: int, out_channels: int, stride: int = 1, activation: str = "relu", reduction: int = 4 ): super().__init__() should_apply_shortcut = in_channels != out_channels or stride != 1 reduces_channels = out_channels // reduction self.shortcut = ( ResNetShortCut(in_channels, out_channels, stride=stride) if should_apply_shortcut else nn.Identity() ) self.layer = nn.Sequential( ResNetConvLayer(in_channels, reduces_channels, kernel_size=1), ResNetConvLayer(reduces_channels, reduces_channels, stride=stride), ResNetConvLayer(reduces_channels, out_channels, kernel_size=1, activation=None), ) self.activation = ACT2FN[activation] def forward(self, hidden_state): residual = hidden_state hidden_state = self.layer(hidden_state) residual = self.shortcut(residual) hidden_state += residual hidden_state = self.activation(hidden_state) return hidden_state class ResNetStage(nn.Sequential): """ A ResNet stage composed by stacked layers. """ def __init__( self, config: ResNetConfig, in_channels: int, out_channels: int, stride: int = 2, depth: int = 2, ): super().__init__() layer = ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer self.layers = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(in_channels, out_channels, stride=stride, activation=config.hidden_act), *[layer(out_channels, out_channels, activation=config.hidden_act) for _ in range(depth - 1)], ) class ResNetEncoder(nn.Module): def __init__(self, config: ResNetConfig): super().__init__() self.stages = nn.ModuleList([]) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( config, config.embedding_size, config.hidden_sizes[0], stride=2 if config.downsample_in_first_stage else 1, depth=config.depths[0], ) ) in_out_channels = zip(config.hidden_sizes, config.hidden_sizes[1:]) for (in_channels, out_channels), depth in zip(in_out_channels, config.depths[1:]): self.stages.append(ResNetStage(config, in_channels, out_channels, depth=depth)) def forward( self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True ) -> ResNetEncoderOutput: hidden_states = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: hidden_states = hidden_states + (hidden_state,) hidden_state = stage_module(hidden_state) if output_hidden_states: hidden_states = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None) return ResNetEncoderOutput( last_hidden_state=hidden_state, hidden_states=hidden_states, ) class ResNetPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = ResNetConfig base_model_prefix = "resnet" main_input_name = "pixel_values" supports_gradient_checkpointing = True def _init_weights(self, module): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") elif isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, ResNetModel): module.gradient_checkpointing = value RESNET_START_DOCSTRING = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ RESNET_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoFeatureExtractor`]. See [`AutoFeatureExtractor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare ResNet model outputting raw features without any specific head on top.", RESNET_START_DOCSTRING, ) class ResNetModel(ResNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.config = config self.embedder = ResNetEmbeddings(config.num_channels, config.embedding_size, config.hidden_act) self.encoder = ResNetEncoder(config) self.pooler = nn.AdaptiveAvgPool2d((1, 1)) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(RESNET_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_FEAT_EXTRACTOR_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=ResNetModelOutput, config_class=_CONFIG_FOR_DOC, modality="vision", expected_output=_EXPECTED_OUTPUT_SHAPE, ) def forward( self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None ) -> ResNetModelOutput: output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict embedding_output = self.embedder(pixel_values) encoder_outputs = self.encoder( embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict ) last_hidden_state = encoder_outputs[0] pooled_output = self.pooler(last_hidden_state) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return ResNetModelOutput( last_hidden_state=last_hidden_state, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, ) @add_start_docstrings( """ ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """, RESNET_START_DOCSTRING, ) class ResNetForImageClassification(ResNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.resnet = ResNetModel(config) # classification head self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity(), ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(RESNET_INPUTS_DOCSTRING) @add_code_sample_docstrings( processor_class=_FEAT_EXTRACTOR_FOR_DOC, checkpoint=_IMAGE_CLASS_CHECKPOINT, output_type=ImageClassifierOutput, config_class=_CONFIG_FOR_DOC, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT, ) def forward( self, pixel_values: Tensor = None, labels: Tensor = None, output_hidden_states: bool = None, return_dict: bool = None, ) -> ImageClassifierOutput: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.resnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict) pooled_output = outputs.pooler_output if return_dict else outputs[1] logits = self.classifier(pooled_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
khoih-prog/transformers
src/transformers/models/realm/modeling_realm.py
# coding=utf-8 # Copyright 2022 The REALM authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch REALM model.""" import math import os from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from packaging import version from torch import nn from torch.nn import CrossEntropyLoss from ...activations import ACT2FN from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, MaskedLMOutput, ModelOutput, ) from ...modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from ...utils import logging from .configuration_realm import RealmConfig logger = logging.get_logger(__name__) _EMBEDDER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-embedder" _ENCODER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-encoder" _SCORER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-scorer" _CONFIG_FOR_DOC = "RealmConfig" _TOKENIZER_FOR_DOC = "RealmTokenizer" REALM_PRETRAINED_MODEL_ARCHIVE_LIST = [ "google/realm-cc-news-pretrained-embedder", "google/realm-cc-news-pretrained-encoder", "google/realm-cc-news-pretrained-scorer", "google/realm-cc-news-pretrained-openqa", "google/realm-orqa-nq-openqa", "google/realm-orqa-nq-reader", "google/realm-orqa-wq-openqa", "google/realm-orqa-wq-reader", # See all REALM models at https://huggingface.co/models?filter=realm ] def load_tf_weights_in_realm(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): if isinstance(model, RealmReader) and "reader" not in name: logger.info(f"Skipping {name} as it is not {model.__class__.__name__}'s parameter") continue # For pretrained openqa reader if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmForOpenQA): name = name.replace("bert/", "reader/realm/") name = name.replace("cls/", "reader/cls/") # For pretrained encoder if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmKnowledgeAugEncoder): name = name.replace("bert/", "realm/") # For finetuned reader if name.startswith("reader"): reader_prefix = "" if isinstance(model, RealmReader) else "reader/" name = name.replace("reader/module/bert/", f"{reader_prefix}realm/") name = name.replace("reader/module/cls/", f"{reader_prefix}cls/") name = name.replace("reader/dense/", f"{reader_prefix}qa_outputs/dense_intermediate/") name = name.replace("reader/dense_1/", f"{reader_prefix}qa_outputs/dense_output/") name = name.replace("reader/layer_normalization", f"{reader_prefix}qa_outputs/layer_normalization") # For embedder and scorer if name.startswith("module/module/module/"): # finetuned embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/" name = name.replace("module/module/module/module/bert/", f"{embedder_prefix}realm/") name = name.replace("module/module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/") name = name.replace("module/module/module/dense/", f"{embedder_prefix}cls/dense/") name = name.replace("module/module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/") name = name.replace("module/module/module/bert/", f"{embedder_prefix}realm/") name = name.replace("module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/") elif name.startswith("module/module/"): # pretrained embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/" name = name.replace("module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/") name = name.replace("module/module/dense/", f"{embedder_prefix}cls/dense/") name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info(f"Skipping {'/'.join(name)}") continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info(f"Skipping {'/'.join(name)}") continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) return model # Copied from transformers.models.bert.modeling_bert.BertEmbeddings with Bert->Realm class RealmEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) if version.parse(torch.__version__) > version.parse("1.6.0"): self.register_buffer( "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False, ) def forward( self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves # issue #5664 if token_type_ids is None: if hasattr(self, "token_type_ids"): buffered_token_type_ids = self.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + token_type_embeddings if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Realm class RealmSelfAttention(nn.Module): def __init__(self, config, position_embedding_type=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = position_embedding_type or getattr( config, "position_embedding_type", "absolute" ) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.is_decoder = config.is_decoder def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, output_attentions: Optional[bool] = False, ) -> Tuple: mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_layer = past_key_value[0] value_layer = past_key_value[1] attention_mask = encoder_attention_mask elif is_cross_attention: key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores(mixed_query_layer) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in RealmModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) if self.is_decoder: outputs = outputs + (past_key_value,) return outputs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Realm class RealmSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Realm class RealmAttention(nn.Module): def __init__(self, config, position_embedding_type=None): super().__init__() self.self = RealmSelfAttention(config, position_embedding_type=position_embedding_type) self.output = RealmSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, output_attentions: Optional[bool] = False, ) -> Tuple: self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Realm class RealmIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Realm class RealmOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Realm class RealmLayer(nn.Module): def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = RealmAttention(config) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: if not self.is_decoder: raise ValueError(f"{self} should be used as a decoder model if cross attention is added") self.crossattention = RealmAttention(config, position_embedding_type="absolute") self.intermediate = RealmIntermediate(config) self.output = RealmOutput(config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, output_attentions: Optional[bool] = False, ) -> Tuple: # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] # if decoder, the last output is tuple of self-attn cache if self.is_decoder: outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] else: outputs = self_attention_outputs[1:] # add self attentions if we output attention weights cross_attn_present_key_value = None if self.is_decoder and encoder_hidden_states is not None: if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" ) # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, cross_attn_past_key_value, output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights # add cross-attn cache to positions 3,4 of present_key_value tuple cross_attn_present_key_value = cross_attention_outputs[-1] present_key_value = present_key_value + cross_attn_present_key_value layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs # if decoder, return the attn key/values as the last output if self.is_decoder: outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Realm class RealmEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([RealmLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if self.gradient_checkpointing and self.training: if use_cache: logger.warning( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Realm class RealmPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output @dataclass class RealmEmbedderOutput(ModelOutput): """ Outputs of [`RealmEmbedder`] models. Args: projected_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`): Projected score. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ projected_score: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class RealmScorerOutput(ModelOutput): """ Outputs of [`RealmScorer`] models. Args: relevance_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates)`): The relevance score of document candidates (before softmax). query_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`): Query score derived from the query embedder. candidate_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates, config.retriever_proj_size)`): Candidate score derived from the embedder. """ relevance_score: torch.FloatTensor = None query_score: torch.FloatTensor = None candidate_score: torch.FloatTensor = None @dataclass class RealmReaderOutput(ModelOutput): """ Outputs of [`RealmReader`] models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided): Total loss. retriever_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided): Retriever loss. reader_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided): Reader loss. retriever_correct (`torch.BoolTensor` of shape `(config.searcher_beam_size,)`, *optional*): Whether or not an evidence block contains answer. reader_correct (`torch.BoolTensor` of shape `(config.reader_beam_size, num_candidates)`, *optional*): Whether or not a span candidate contains answer. block_idx (`torch.LongTensor` of shape `()`): The index of the retrieved evidence block in which the predicted answer is most likely. candidate (`torch.LongTensor` of shape `()`): The index of the retrieved span candidates in which the predicted answer is most likely. start_pos (`torch.IntTensor` of shape `()`): Predicted answer starting position in *RealmReader*'s inputs. end_pos: (`torch.IntTensor` of shape `()`): Predicted answer ending position in *RealmReader*'s inputs. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: torch.FloatTensor = None retriever_loss: torch.FloatTensor = None reader_loss: torch.FloatTensor = None retriever_correct: torch.BoolTensor = None reader_correct: torch.BoolTensor = None block_idx: torch.LongTensor = None candidate: torch.LongTensor = None start_pos: torch.int32 = None end_pos: torch.int32 = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None @dataclass class RealmForOpenQAOutput(ModelOutput): """ Outputs of [`RealmForOpenQA`] models. Args: reader_output (`dict`): Reader output. predicted_answer_ids (`torch.LongTensor` of shape `(answer_sequence_length)`): Predicted answer ids. """ reader_output: dict = None predicted_answer_ids: torch.LongTensor = None class RealmPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class RealmLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = RealmPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class RealmOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = RealmLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class RealmScorerProjection(nn.Module): def __init__(self, config): super().__init__() self.predictions = RealmLMPredictionHead(config) self.dense = nn.Linear(config.hidden_size, config.retriever_proj_size) self.LayerNorm = nn.LayerNorm(config.retriever_proj_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class RealmReaderProjection(nn.Module): def __init__(self, config): super().__init__() self.config = config self.dense_intermediate = nn.Linear(config.hidden_size, config.span_hidden_size * 2) self.dense_output = nn.Linear(config.span_hidden_size, 1) self.layer_normalization = nn.LayerNorm(config.span_hidden_size, eps=config.reader_layer_norm_eps) self.relu = nn.ReLU() def forward(self, hidden_states, block_mask): def span_candidates(masks): """ Generate span candidates. Args: masks: <bool> [num_retrievals, max_sequence_len] Returns: starts: <int32> [num_spans] ends: <int32> [num_spans] span_masks: <int32> [num_retrievals, num_spans] whether spans locate in evidence block. """ _, max_sequence_len = masks.shape def _spans_given_width(width): current_starts = torch.arange(max_sequence_len - width + 1, device=masks.device) current_ends = torch.arange(width - 1, max_sequence_len, device=masks.device) return current_starts, current_ends starts, ends = zip(*(_spans_given_width(w + 1) for w in range(self.config.max_span_width))) # [num_spans] starts = torch.cat(starts, 0) ends = torch.cat(ends, 0) # [num_retrievals, num_spans] start_masks = torch.index_select(masks, dim=-1, index=starts) end_masks = torch.index_select(masks, dim=-1, index=ends) span_masks = start_masks * end_masks return starts, ends, span_masks def mask_to_score(mask): return (1.0 - mask.type(torch.float32)) * -10000.0 # [reader_beam_size, max_sequence_len, span_hidden_size * 2] hidden_states = self.dense_intermediate(hidden_states) # [reader_beam_size, max_sequence_len, span_hidden_size] start_projection, end_projection = hidden_states.chunk(2, dim=-1) candidate_starts, candidate_ends, candidate_mask = span_candidates(block_mask) candidate_start_projections = torch.index_select(start_projection, dim=1, index=candidate_starts) candidate_end_projections = torch.index_select(end_projection, dim=1, index=candidate_ends) candidate_hidden = candidate_start_projections + candidate_end_projections # [reader_beam_size, num_candidates, span_hidden_size] candidate_hidden = self.relu(candidate_hidden) # [reader_beam_size, num_candidates, span_hidden_size] candidate_hidden = self.layer_normalization(candidate_hidden) # [reader_beam_size, num_candidates] reader_logits = self.dense_output(candidate_hidden).squeeze(-1) # [reader_beam_size, num_candidates] reader_logits += mask_to_score(candidate_mask) return reader_logits, candidate_starts, candidate_ends REALM_START_DOCSTRING = r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`RealmConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ REALM_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`RealmTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `({0})`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert *input_ids* indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ class RealmPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = RealmConfig load_tf_weights = load_tf_weights_in_realm base_model_prefix = "realm" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def _flatten_inputs(self, *inputs): """Flatten inputs' shape to (-1, input_shape[-1])""" flattened_inputs = [] for tensor in inputs: if tensor is None: flattened_inputs.append(None) else: input_shape = tensor.shape if len(input_shape) > 2: tensor = tensor.view((-1, input_shape[-1])) flattened_inputs.append(tensor) return flattened_inputs class RealmBertModel(RealmPreTrainedModel): """ Same as the original BertModel but remove docstrings. """ def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = RealmEmbeddings(config) self.encoder = RealmEncoder(config) self.pooler = RealmPooler(config) if add_pooling_layer else None # Weights initialization is mostly managed by other Realm models, # but we also have them initialized here to keep a consistency. self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") batch_size, seq_length = input_shape device = input_ids.device if input_ids is not None else inputs_embeds.device # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) if token_type_ids is None: if hasattr(self.embeddings, "token_type_ids"): buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) token_type_ids = buffered_token_type_ids_expanded else: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) @add_start_docstrings( "The embedder of REALM outputting projected score that will be used to calculate relevance score.", REALM_START_DOCSTRING, ) class RealmEmbedder(RealmPreTrainedModel): def __init__(self, config): super().__init__(config) self.realm = RealmBertModel(self.config) self.cls = RealmScorerProjection(self.config) self.post_init() def get_input_embeddings(self): return self.realm.embeddings.word_embeddings def set_input_embeddings(self, value): self.realm.embeddings.word_embeddings = value @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=RealmEmbedderOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" Returns: Example: ```python >>> from transformers import RealmTokenizer, RealmEmbedder >>> import torch >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-embedder") >>> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> projected_score = outputs.projected_score ``` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict realm_outputs = self.realm( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # [batch_size, hidden_size] pooler_output = realm_outputs[1] # [batch_size, retriever_proj_size] projected_score = self.cls(pooler_output) if not return_dict: return (projected_score,) + realm_outputs[2:4] else: return RealmEmbedderOutput( projected_score=projected_score, hidden_states=realm_outputs.hidden_states, attentions=realm_outputs.attentions, ) @add_start_docstrings( "The scorer of REALM outputting relevance scores representing the score of document candidates (before softmax).", REALM_START_DOCSTRING, ) class RealmScorer(RealmPreTrainedModel): r""" Args: query_embedder ([`RealmEmbedder`]): Embedder for input sequences. If not specified, it will use the same embedder as candidate sequences. """ def __init__(self, config, query_embedder=None): super().__init__(config) self.embedder = RealmEmbedder(self.config) self.query_embedder = query_embedder if query_embedder is not None else self.embedder self.post_init() @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=RealmScorerOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, candidate_input_ids=None, candidate_attention_mask=None, candidate_token_type_ids=None, candidate_inputs_embeds=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" candidate_input_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`): Indices of candidate input sequence tokens in the vocabulary. Indices can be obtained using [`RealmTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) candidate_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) candidate_token_type_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) candidate_inputs_embeds (`torch.FloatTensor` of shape `(batch_size * num_candidates, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `candidate_input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert *candidate_input_ids* indices into associated vectors than the model's internal embedding lookup matrix. Returns: Example: ```python >>> import torch >>> from transformers import RealmTokenizer, RealmScorer >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-scorer") >>> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=2) >>> # batch_size = 2, num_candidates = 2 >>> input_texts = ["How are you?", "What is the item in the picture?"] >>> candidates_texts = [["Hello world!", "Nice to meet you!"], ["A cute cat.", "An adorable dog."]] >>> inputs = tokenizer(input_texts, return_tensors="pt") >>> candidates_inputs = tokenizer.batch_encode_candidates(candidates_texts, max_length=10, return_tensors="pt") >>> outputs = model( ... **inputs, ... candidate_input_ids=candidates_inputs.input_ids, ... candidate_attention_mask=candidates_inputs.attention_mask, ... candidate_token_type_ids=candidates_inputs.token_type_ids, ... ) >>> relevance_score = outputs.relevance_score ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is None and inputs_embeds is None: raise ValueError("You have to specify either input_ids or input_embeds.") if candidate_input_ids is None and candidate_inputs_embeds is None: raise ValueError("You have to specify either candidate_input_ids or candidate_inputs_embeds.") query_outputs = self.query_embedder( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # [batch_size * num_candidates, candidate_seq_len] (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs( candidate_input_ids, candidate_attention_mask, candidate_token_type_ids ) candidate_outputs = self.embedder( flattened_input_ids, attention_mask=flattened_attention_mask, token_type_ids=flattened_token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=candidate_inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # [batch_size, retriever_proj_size] query_score = query_outputs[0] # [batch_size * num_candidates, retriever_proj_size] candidate_score = candidate_outputs[0] # [batch_size, num_candidates, retriever_proj_size] candidate_score = candidate_score.view(-1, self.config.num_candidates, self.config.retriever_proj_size) # [batch_size, num_candidates] relevance_score = torch.einsum("BD,BND->BN", query_score, candidate_score) if not return_dict: return relevance_score, query_score, candidate_score return RealmScorerOutput( relevance_score=relevance_score, query_score=query_score, candidate_score=candidate_score ) @add_start_docstrings( "The knowledge-augmented encoder of REALM outputting masked language model logits and marginal log-likelihood loss.", REALM_START_DOCSTRING, ) class RealmKnowledgeAugEncoder(RealmPreTrainedModel): def __init__(self, config): super().__init__(config) self.realm = RealmBertModel(self.config) self.cls = RealmOnlyMLMHead(self.config) self.post_init() def get_input_embeddings(self): return self.realm.embeddings.word_embeddings def set_input_embeddings(self, value): self.realm.embeddings.word_embeddings = value def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward( REALM_INPUTS_DOCSTRING.format("batch_size, num_candidates, sequence_length") ) @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, relevance_score=None, labels=None, mlm_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" relevance_score (`torch.FloatTensor` of shape `(batch_size, num_candidates)`, *optional*): Relevance score derived from RealmScorer, must be specified if you want to compute the masked language modeling loss. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` mlm_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid calculating joint loss on certain positions. If not specified, the loss will not be masked. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Returns: Example: ```python >>> import torch >>> from transformers import RealmTokenizer, RealmKnowledgeAugEncoder >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder") >>> model = RealmKnowledgeAugEncoder.from_pretrained( ... "google/realm-cc-news-pretrained-encoder", num_candidates=2 ... ) >>> # batch_size = 2, num_candidates = 2 >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]] >>> inputs = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt") >>> outputs = model(**inputs) >>> logits = outputs.logits ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs( input_ids, attention_mask, token_type_ids ) joint_outputs = self.realm( flattened_input_ids, attention_mask=flattened_attention_mask, token_type_ids=flattened_token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # [batch_size * num_candidates, joint_seq_len, hidden_size] joint_output = joint_outputs[0] # [batch_size * num_candidates, joint_seq_len, vocab_size] prediction_scores = self.cls(joint_output) # [batch_size, num_candidates] candidate_score = relevance_score masked_lm_loss = None if labels is not None: if candidate_score is None: raise ValueError( "You have to specify `relevance_score` when `labels` is specified in order to compute loss." ) batch_size, seq_length = labels.size() if mlm_mask is None: mlm_mask = torch.ones_like(labels, dtype=torch.float32) else: mlm_mask = mlm_mask.type(torch.float32) # Compute marginal log-likelihood loss_fct = CrossEntropyLoss(reduction="none") # -100 index = padding token # [batch_size * num_candidates * joint_seq_len, vocab_size] mlm_logits = prediction_scores.view(-1, self.config.vocab_size) # [batch_size * num_candidates * joint_seq_len] mlm_targets = labels.tile(1, self.config.num_candidates).view(-1) # [batch_size, num_candidates, joint_seq_len] masked_lm_log_prob = -loss_fct(mlm_logits, mlm_targets).view( batch_size, self.config.num_candidates, seq_length ) # [batch_size, num_candidates, 1] candidate_log_prob = candidate_score.log_softmax(-1).unsqueeze(-1) # [batch_size, num_candidates, joint_seq_len] joint_gold_log_prob = candidate_log_prob + masked_lm_log_prob # [batch_size, joint_seq_len] marginal_gold_log_probs = joint_gold_log_prob.logsumexp(1) # [] masked_lm_loss = -torch.nansum(torch.sum(marginal_gold_log_probs * mlm_mask) / torch.sum(mlm_mask)) if not return_dict: output = (prediction_scores,) + joint_outputs[2:4] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=joint_outputs.hidden_states, attentions=joint_outputs.attentions, ) @add_start_docstrings("The reader of REALM.", REALM_START_DOCSTRING) class RealmReader(RealmPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler", "cls"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.realm = RealmBertModel(config) self.cls = RealmOnlyMLMHead(config) self.qa_outputs = RealmReaderProjection(config) self.post_init() @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("reader_beam_size, sequence_length")) @replace_return_docstrings(output_type=RealmReaderOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, relevance_score=None, block_mask=None, start_positions=None, end_positions=None, has_answers=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" relevance_score (`torch.FloatTensor` of shape `(searcher_beam_size,)`, *optional*): Relevance score, which must be specified if you want to compute the logits and marginal log loss. block_mask (`torch.BoolTensor` of shape `(searcher_beam_size, sequence_length)`, *optional*): The mask of the evidence block, which must be specified if you want to compute the logits and marginal log loss. start_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. has_answers (`torch.BoolTensor` of shape `(searcher_beam_size,)`, *optional*): Whether or not the evidence block has answer(s). Returns: """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if relevance_score is None: raise ValueError("You have to specify `relevance_score` to calculate logits and loss.") if block_mask is None: raise ValueError("You have to specify `block_mask` to separate question block and evidence block.") if token_type_ids.size(1) < self.config.max_span_width: raise ValueError("The input sequence length must be greater than or equal to config.max_span_width.") outputs = self.realm( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # [reader_beam_size, joint_seq_len, hidden_size] sequence_output = outputs[0] # [reader_beam_size, num_candidates], [num_candidates], [num_candidates] reader_logits, candidate_starts, candidate_ends = self.qa_outputs( sequence_output, block_mask[0 : self.config.reader_beam_size] ) # [searcher_beam_size, 1] retriever_logits = torch.unsqueeze(relevance_score[0 : self.config.reader_beam_size], -1) # [reader_beam_size, num_candidates] reader_logits += retriever_logits # [] predicted_block_index = torch.argmax(torch.max(reader_logits, dim=1).values) # [] predicted_candidate = torch.argmax(torch.max(reader_logits, dim=0).values) # [1] predicted_start = torch.index_select(candidate_starts, dim=0, index=predicted_candidate) # [1] predicted_end = torch.index_select(candidate_ends, dim=0, index=predicted_candidate) total_loss = None retriever_loss = None reader_loss = None retriever_correct = None reader_correct = None if start_positions is not None and end_positions is not None and has_answers is not None: def compute_correct_candidates(candidate_starts, candidate_ends, gold_starts, gold_ends): """Compute correct span.""" # [reader_beam_size, num_answers, num_candidates] is_gold_start = torch.eq( torch.unsqueeze(torch.unsqueeze(candidate_starts, 0), 0), torch.unsqueeze(gold_starts, -1) ) is_gold_end = torch.eq( torch.unsqueeze(torch.unsqueeze(candidate_ends, 0), 0), torch.unsqueeze(gold_ends, -1) ) # [reader_beam_size, num_candidates] return torch.any(torch.logical_and(is_gold_start, is_gold_end), 1) def marginal_log_loss(logits, is_correct): """Loss based on the negative marginal log-likelihood.""" def mask_to_score(mask): return (1.0 - mask.type(torch.float32)) * -10000.0 # [] log_numerator = torch.logsumexp(logits + mask_to_score(is_correct), dim=-1) log_denominator = torch.logsumexp(logits, dim=-1) return log_denominator - log_numerator # sometimes the start/end positions are outside our model inputs, we ignore these terms # `-1` is reserved for no answer. ignored_index = sequence_output.size(1) start_positions = start_positions.clamp(-1, ignored_index) end_positions = end_positions.clamp(-1, ignored_index) retriever_correct = has_answers any_retriever_correct = torch.any(retriever_correct) reader_correct = compute_correct_candidates( candidate_starts=candidate_starts, candidate_ends=candidate_ends, gold_starts=start_positions[0 : self.config.reader_beam_size], gold_ends=end_positions[0 : self.config.reader_beam_size], ) any_reader_correct = torch.any(reader_correct) retriever_loss = marginal_log_loss(relevance_score, retriever_correct) reader_loss = marginal_log_loss(reader_logits.view(-1), reader_correct.view(-1)) retriever_loss *= any_retriever_correct.type(torch.float32) reader_loss *= any_reader_correct.type(torch.float32) total_loss = (retriever_loss + reader_loss).mean() if not return_dict: output = (predicted_block_index, predicted_candidate, predicted_start, predicted_end) + outputs[2:] return ( ((total_loss, retriever_loss, reader_loss, retriever_correct, reader_correct) + output) if total_loss is not None else output ) return RealmReaderOutput( loss=total_loss, retriever_loss=retriever_loss, reader_loss=reader_loss, retriever_correct=retriever_correct, reader_correct=reader_correct, block_idx=predicted_block_index, candidate=predicted_candidate, start_pos=predicted_start, end_pos=predicted_end, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) REALM_FOR_OPEN_QA_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`RealmTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token (should not be used in this model by design). [What are token type IDs?](../glossary#token-type-ids) answer_ids (`list` of shape `(num_answers, answer_length)`, *optional*): Answer ids for computing the marginal log-likelihood loss. Indices should be in `[-1, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-1` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "`RealmForOpenQA` for end-to-end open domain question answering.", REALM_START_DOCSTRING, ) class RealmForOpenQA(RealmPreTrainedModel): def __init__(self, config, retriever=None): super().__init__(config) self.embedder = RealmEmbedder(config) self.reader = RealmReader(config) self.register_buffer( "block_emb", torch.zeros(()).new_empty( size=(config.num_block_records, config.retriever_proj_size), dtype=torch.float32, device=torch.device("cpu"), ), ) self.retriever = retriever self.post_init() @property def searcher_beam_size(self): if self.training: return self.config.searcher_beam_size return self.config.reader_beam_size def block_embedding_to(self, device): """Send `self.block_emb` to a specific device. Args: device (`str` or `torch.device`): The device to which `self.block_emb` will be sent. """ self.block_emb = self.block_emb.to(device) @add_start_docstrings_to_model_forward(REALM_FOR_OPEN_QA_DOCSTRING.format("1, sequence_length")) @replace_return_docstrings(output_type=RealmForOpenQAOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids, attention_mask=None, token_type_ids=None, answer_ids=None, return_dict=None, ): r""" Returns: Example: ```python >>> import torch >>> from transformers import RealmForOpenQA, RealmRetriever, RealmTokenizer >>> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa") >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") >>> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa", retriever=retriever) >>> question = "Who is the pioneer in modern computer science?" >>> question_ids = tokenizer([question], return_tensors="pt") >>> answer_ids = tokenizer( ... ["alan mathison turing"], ... add_special_tokens=False, ... return_token_type_ids=False, ... return_attention_mask=False, >>> ).input_ids >>> reader_output, predicted_answer_ids = model(**question_ids, answer_ids=answer_ids, return_dict=False) >>> predicted_answer = tokenizer.decode(predicted_answer_ids) >>> loss = reader_output.loss ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and input_ids.shape[0] != 1: raise ValueError("The batch_size of the inputs must be 1.") question_outputs = self.embedder( input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, return_dict=True ) # [1, projection_size] question_projection = question_outputs[0] # CPU computation starts. # [1, block_emb_size] batch_scores = torch.einsum("BD,QD->QB", self.block_emb, question_projection.to(self.block_emb.device)) # [1, searcher_beam_size] _, retrieved_block_ids = torch.topk(batch_scores, k=self.searcher_beam_size, dim=-1) # [searcher_beam_size] retrieved_block_ids = retrieved_block_ids.squeeze() # [searcher_beam_size, projection_size] retrieved_block_emb = torch.index_select(self.block_emb, dim=0, index=retrieved_block_ids) # CPU computation ends. # Retrieve possible answers has_answers, start_pos, end_pos, concat_inputs = self.retriever( retrieved_block_ids.cpu(), input_ids, answer_ids, max_length=self.config.reader_seq_len ) concat_inputs = concat_inputs.to(self.reader.device) block_mask = concat_inputs.special_tokens_mask.type(torch.bool).to(device=self.reader.device) block_mask.logical_not_().logical_and_(concat_inputs.token_type_ids.type(torch.bool)) if has_answers is not None: has_answers = torch.tensor(has_answers, dtype=torch.bool, device=self.reader.device) start_pos = torch.tensor(start_pos, dtype=torch.long, device=self.reader.device) end_pos = torch.tensor(end_pos, dtype=torch.long, device=self.reader.device) # [searcher_beam_size] retrieved_logits = torch.einsum( "D,BD->B", question_projection.squeeze(), retrieved_block_emb.to(self.reader.device) ) reader_output = self.reader( input_ids=concat_inputs.input_ids[0 : self.config.reader_beam_size], attention_mask=concat_inputs.attention_mask[0 : self.config.reader_beam_size], token_type_ids=concat_inputs.token_type_ids[0 : self.config.reader_beam_size], relevance_score=retrieved_logits, block_mask=block_mask, has_answers=has_answers, start_positions=start_pos, end_positions=end_pos, return_dict=True, ) predicted_block = concat_inputs.input_ids[reader_output.block_idx] predicted_answer_ids = predicted_block[reader_output.start_pos : reader_output.end_pos + 1] if not return_dict: return reader_output, predicted_answer_ids return RealmForOpenQAOutput( reader_output=reader_output, predicted_answer_ids=predicted_answer_ids, )
soerenbnoergaard/impulseresponder
impulseresponder.py
import matplotlib matplotlib.use("TkAgg") import numpy as np import tkinter as tk import sounddevice as sd import matplotlib.pyplot as plt from scipy import signal from tkinter import filedialog from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg def main(): # imp = ImpulseResponderSimulation(48000) # imp.measure("prbs15") # imp.analyze(0.01) main_gui() def main_gui(): root = tk.Tk() root.title("Impulse Responder") Gui(root).pack(expand=True, fill=tk.BOTH) root.mainloop() class ImpulseResponderBase(object): def __init__(self, sample_rate_Hz): self.sample_rate_Hz = sample_rate_Hz self.x = None # Input self.y = None # Output self.h = None # Impulse response self.H = None # Frequency response self.t = None # Time axis self.f = None # Frequency axis def get_waveform_data(self, waveform_string): noise_function = { "prbs9": self.prbs9, "prbs15": self.prbs15, "prbs20": self.prbs20, }[waveform_string] length = self.get_prbs_length(waveform_string) return noise_function(length) def get_prbs_length(self, s): return { "prbs9": 2**9-1, "prbs15": 2**15-1, "prbs20": 2**20-1, }[s] def prbs_generic(self, num_bits, seed, field_width, newbit_function): mask = int("1" * field_width, 2) a = seed bits = [] for _ in range(num_bits): newbit = newbit_function(a) a = ((a << 1) | newbit) & mask bits.append(newbit * 2 - 1) # NRZ sequence return bits def prbs7(self, num_bits, seed=0x01): return self.prbs_generic(num_bits, seed, 7, lambda x: (((x >> 6) ^ (x >> 5)) & 1)) def prbs9(self, num_bits, seed=0x01): return self.prbs_generic(num_bits, seed, 9, lambda x: (((x >> 8) ^ (x >> 4)) & 1)) def prbs15(self, num_bits, seed=0x01): return self.prbs_generic(num_bits, seed, 15, lambda x: (((x >> 14) ^ (x >> 13)) & 1)) def prbs20(self, num_bits, seed=0x01): return self.prbs_generic(num_bits, seed, 20, lambda x: (((x >> 19) ^ (x >> 2)) & 1)) def prbs23(self, num_bits, seed=0x01): return self.prbs_generic(num_bits, seed, 23, lambda x: (((x >> 22) ^ (x >> 17)) & 1)) def analyze(self, impulse_response_length_s): # Estimate impulse response h = signal.correlate(self.y, self.x, "full") # h /= len(self.x) # TODO: Is this scaling correct? h = h[len(h)//2:] h = h[0:int(impulse_response_length_s * self.sample_rate_Hz)] t = np.linspace(0, impulse_response_length_s, len(h)) # Estimate frequency response H = np.fft.fft(h) H = H[0:len(H)//2] # H /= max(H) f = np.linspace(0, self.sample_rate_Hz/2, len(H)) # Store results self.h = h self.t = t self.H = H self.f = f class ImpulseResponderSimulation(ImpulseResponderBase): def measure(self, waveform_string): b, a = signal.cheby1(4, 10, 10_000 / (self.sample_rate_Hz/2)) x = self.get_waveform_data(waveform_string) y = signal.lfilter(b, a, x) # Store results self.x = x self.y = y class ImpulseResponderSoundcard(ImpulseResponderBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def measure(self, waveform_string): sd.default.device = "Scarlett 2i2 USB: Audio" sd.default.blocksize = 512 sd.default.samplerate = self.sample_rate_Hz sd.default.channels = 1 x = np.array(self.get_waveform_data(waveform_string), dtype=float) y = sd.playrec(np.hstack([ x, x, x, np.zeros(int(0.2 * self.sample_rate_Hz)), ])) sd.wait() y = y.T[0] y = y[len(y)//2:] # Locate x in y R = abs(signal.correlate(y, x, "valid")) start = np.argmax(R) y = y[start:start+len(x)] # Store results self.x = x self.y = y # ny = np.arange(len(y)) # nx = np.arange(len(x)) # plt.plot(ny, y) # plt.plot(nx + start, x) # plt.show() class Var(object): def __init__(self): self.sample_rate_Hz = tk.StringVar() self.waveform = tk.StringVar() self.impulse_response_length_s = tk.StringVar() class Gui(tk.Frame): def __init__(self, parent): self.parent = parent self.var = Var() self.parent.protocol("WM_DELETE_WINDOW", self.on_close) self.var.sample_rate_Hz.set("48000") self.var.waveform.set("prbs15") self.var.impulse_response_length_s.set("1") tk.Frame.__init__(self, parent) # FRAMES fr_A = tk.Frame(self) fr_B = tk.Frame(self) fr_A.pack(side=tk.TOP, expand=False, fill=tk.X) fr_B.pack(side=tk.TOP, expand=True, fill=tk.BOTH) fr_input = tk.LabelFrame(fr_A, text="Input") fr_output = tk.LabelFrame(fr_A, text="Output") fr_plot = tk.Frame(fr_B) fr_input.pack(side=tk.LEFT) fr_output.pack(side=tk.LEFT) fr_plot.pack(side=tk.TOP, expand=True, fill=tk.BOTH) # INPUT tk.Label(fr_input, text="Sample rate [Hz]").grid(row=0, column=0) tk.OptionMenu(fr_input, self.var.sample_rate_Hz, "48000", "44100", command=lambda x: self.on_update_input()).grid(row=0, column=1) tk.Label(fr_input, text="Waveform").grid(row=1, column=0) tk.OptionMenu(fr_input, self.var.waveform, "prbs9", "prbs15", "prbs20", command=lambda x: self.on_update_input()).grid(row=1, column=1) tk.Button(fr_input, text="Save WAV", command=self.on_input_save_wav).grid(row=2, column=0, columnspan=2, sticky=tk.W+tk.E) # OUTPUT tk.Button(fr_output, text="Measure", command=self.on_measure).grid(row=0, column=0, columnspan=2, sticky=tk.W+tk.E) tk.Label(fr_output, text="Impulse response").grid(row = 1, column=0, columnspan=2, sticky=tk.W+tk.E) tk.Label(fr_output, text="Length [s]").grid(row=2, column=0) e = tk.Entry(fr_output, textvariable=self.var.impulse_response_length_s) e.grid(row=2, column=1) e.bind("<Return>", lambda x: self.on_update_output()) tk.Button(fr_output, text="Save WAV", command=self.on_output_save_impulse_response_as_wav).grid(row=3, column=0, columnspan=2, sticky=tk.W+tk.E) # PLOT self.fig = plt.Figure(dpi=100) canvas = FigureCanvasTkAgg(self.fig, master=fr_plot) canvas.draw() canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) self.on_update_input() def on_close(self): self.parent.destroy() def on_measure(self): self.meas = ImpulseResponderSoundcard(float(self.var.sample_rate_Hz.get())) self.meas.measure(self.var.waveform.get()) self.on_update_output() def on_update_input(self): fs = float(self.var.sample_rate_Hz.get()) L = float(self.prbs_length(self.var.waveform.get())) self.var.impulse_response_length_s.set(str(L / fs)) def on_update_output(self): self.meas.analyze(float(self.var.impulse_response_length_s.get())) # Show results self.fig.clear() ax1 = self.fig.add_subplot(2, 1, 1) ax2 = self.fig.add_subplot(2, 1, 2) ax1.plot(self.meas.t, self.meas.h) ax2.semilogx(self.meas.f, 20*np.log10(abs(self.meas.H))) ax1.grid(True, "both", "both") ax2.grid(True, "both", "both") self.fig.tight_layout() self.fig.canvas.draw_idle() def on_input_save_wav(self): print("Not implemented yet") def on_output_save_recording_as_wav(self): print("Not implemented yet") def on_output_save_impulse_response_as_wav(self): print("Not implemented yet") def prbs_length(self, s): return { "prbs9": 2**9-1, "prbs15": 2**15-1, "prbs20": 2**20-1, }[s] if __name__ == "__main__": main()
KosukeKamiya/datadog-zabbix-check
checks.d/zabbix_metrics.py
try: from datadog_checks.base import AgentCheck import urllib.request import json except ImportError: from checks import AgentCheck __version__ = "1.0.0" class HelloCheck(AgentCheck): def request(self,zabbix_api,req_data): req_header = { 'Content-Type': 'application/json-rpc', } req = urllib.request.Request(zabbix_api, data=req_data.encode(), method='POST', headers=req_header) try: with urllib.request.urlopen(req) as response: body = json.loads(response.read()) headers = response.getheaders() status = response.getcode() return body except urllib.error.URLError as e: self.log.error('request error') return "Error" def login(self,zabbix_user,zabbix_pass,zabbix_api): req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'user.login', 'params': { 'user': zabbix_user, 'password': <PASSWORD> }, 'id': 1 }) response = self.request(zabbix_api,req_data) token = response.get('result') return token def logout(self, token,zabbix_api): req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'user.logout', 'params': {}, 'auth': token, 'id': 1 }) response = self.request(zabbix_api,req_data) return response def get_hosts(self,token,zabbix_api,hosts=None): if hosts is not None: req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'host.get', 'params': { 'filter':{ 'host': hosts }, 'output': [ 'hostid', 'host' ] }, 'auth': token, 'id': 1 }) else: req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'host.get', 'params': { 'output': [ 'hostid', 'host' ] }, 'auth': token, 'id': 1 }) response = self.request(zabbix_api,req_data) return response.get('result') def get_items(self,token,hostids,zabbix_api,items=None): if items is not None: req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'item.get', 'params': { 'hostids': hostids, 'filter': { 'name': items }, 'output': [ 'itemid', 'name', 'hostid', 'value_type' ] }, 'auth': token, 'id': 1 }) else: req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'item.get', 'params': { 'hostids': hostids, 'output': [ 'itemid', 'name', 'hostid', 'value_type' ] }, 'auth': token, 'id': 1 }) response = self.request(zabbix_api,req_data) return response.get('result') def get_history(self,token,hostid,itemid,value_type,zabbix_api): req_data = json.dumps({ 'jsonrpc': '2.0', 'method': 'history.get', 'params': { 'hostids': hostid, 'itemids': itemid, 'output': [ 'itemid', 'value' ], 'history': value_type, 'sortfield': 'clock', 'sortorder': 'DESC', 'limit': 1 }, 'auth': token, 'id': 1 }) response = self.request(zabbix_api,req_data) result = response.get('result') return result def check(self, instance): zabbix_user = instance.get('zabbix_user') zabbix_pass = instance.get('zabbix_password') zabbix_api = instance.get('zabbix_api') hosts = instance.get('hosts') metrics = instance.get('metrics') ## Get token token = self.login(zabbix_user,zabbix_pass,zabbix_api) self.log.debug(token) ## Get hosts if hosts is not None: zabbixhosts = self.get_hosts(token,zabbix_api,hosts) else: zabbixhosts = self.get_hosts(token,zabbix_api) hostdic = {} hostids = [] for host in zabbixhosts: hostdic[host['hostid']] = host['host'] hostids.append(host['hostid']) # Get items if metrics is not None: zabbixitems = self.get_items(token,hostids,zabbix_api,metrics) else: zabbixitems = self.get_items(token,hostids,zabbix_api) self.log.debug(zabbixitems) ## Get metrics value for item in zabbixitems: hostid=item['hostid'] itemid=item['itemid'] value_type=item['value_type'] history = self.get_history(token,hostid,itemid,value_type,zabbix_api) dd_metricname = 'custom.zabbix.' + item['name'].replace(' ','_') dd_metricvalue = history[0]['value'] dd_hostname = hostdic[hostid].replace(' ','_') self.gauge(dd_metricname, dd_metricvalue, tags=None, hostname=dd_hostname, device_name=None) # Revoke token result = self.logout(token,zabbix_api) self.log.debug(result)
thocoo/gamma-desk
gdesk/panels/imgview/spectrogram.py
<filename>gdesk/panels/imgview/spectrogram.py import sys import numpy as np from ... import gui def spectrogram(arr, vertical=False, plot=True): """ Calculates the fullnoise, whitenoise and whiteness. and plot a spectrogram. https://www.emva.org/wp-content/uploads/EMVA1288-3.1a.pdf :param np.ndarray arr: A 2 dimensional array :param bool vertical: Calculate in vertical direction :param bool plot: Plot and print :returns: fullnoise, whitenoise, whiteness :rtype: tuple(float, float, float) """ if vertical: return spectr_vert(arr, plot) else: return spectr_hori(arr, plot) def spectr_hori(arr, plot=True): """ Calculates the fullnoise, whitenoise and whiteness. and plot a horizontal spectrogram. :param np.ndarray arr: A 2 dimensional array :returns: fullnoise, whitenoise, whiteness :rtype: tuple(float, float, float) """ arr = arr.astype('double') ydim, xdim = arr.shape arr -= arr.mean() mag = abs(np.fft.fft(arr,axis=1)) / xdim ** 0.5 spr = (np.sum(mag**2,0) / ydim) ** 0.5 fullnoise = (np.sum(spr**2) / (xdim+1))** 0.5 whitenoise = np.median(spr) whiteness = (fullnoise / whitenoise) if plot: plt = gui.prepareplot() plt.figure() plt.grid(True) plt.title('Horizontal Spectrogram') plt.plot(spr) print("Fullnoise : %8.2f" % fullnoise) print("WhiteNoise : %8.2f" % whitenoise) print("The whiteness: %8.2f Ideal this is 1" % whiteness) plt.show() return fullnoise, whitenoise, whiteness def spectr_vert(arr, plot=True): """ Calculates the fullnoise, whitenoise and whiteness. and plot a vertical spectrogram. :param np.ndarray arr: A 2 dimensional array :returns: fullnoise, whitenoise, whiteness :rtype: tuple(float, float, float) """ arr = arr.astype('double') ydim, xdim = arr.shape arr -= arr.mean() mag = abs(np.fft.fft(arr,axis=0)) / ydim ** 0.5 spr = (np.sum(mag**2,1) / xdim) ** 0.5 fullnoise = (np.sum(spr**2) / (ydim+1))** 0.5 whitenoise = np.median(spr) whiteness = (fullnoise / whitenoise) if plot: plt = gui.prepareplot() plt.figure() plt.grid(True) plt.title('Vertical Spectrogram') plt.plot(spr) print("Fullnoise : %8.2f" % fullnoise) print("WhiteNoise : %8.2f" % whitenoise) print("The whiteness: %8.2f Ideal this is 1" % whiteness) plt.show() return fullnoise, whitenoise, whiteness
thocoo/gamma-desk
gdesk/panels/console/consoleproxy.py
<reponame>thocoo/gamma-desk import sys import threading from ...core.gui_proxy import GuiProxyBase, StaticGuiCall, gui from ...core.shellmod import Shell class ConsoleGuiProxy(GuiProxyBase): category = 'console' opens_with = ['.py'] def __init__(self): pass def attach(self, gui): gui.console = self gui.clc = self.clc return 'console' @StaticGuiCall def open(filepath): panel = gui.qapp.panels.selected('console') ConsoleGuiProxy._gui_execute_file(filepath, panel.panid) @StaticGuiCall def console(pandid=None, consoletype='thread'): """ :param str consoletype: 'main', 'thread', 'child', 'child-thread', 'process' """ if pandid is None: panel = gui.qapp.panels.selected('console') else: panel = gui.qapp.panels.select_or_new('console', pandid, consoletype) return panel.panid @StaticGuiCall def clc(): """Clear the Console Output""" # For now, jus take the active console # Note that this is not always correct # Should first search for the console of the current process and thread sys.stdout.flush() sys.stderr.flush() panel = gui.qapp.panels.selected('console') panel.stdio.stdOutputPanel.clear() @StaticGuiCall def text(): panel = gui.qapp.panels.selected('console') text = panel.stdio.stdOutputPanel.toPlainText() return text def set_mode(self, mode='input', panid=None): if panid is None: shell = Shell.instance ident = threading.get_ident() panid = shell.interpreters[ident].console_id return ConsoleGuiProxy._gui_set_console_mode(mode, panid) def show_me(self): shell = Shell.instance this_panid = shell.this_interpreter().console_id self.show(this_panid) @StaticGuiCall def show(panid): console = gui.qapp.panels['console'][panid] console.show_me() @StaticGuiCall def _gui_set_console_mode(mode='input', panid=None): console = gui.qapp.panels['console'][panid] old_mode = console.stdio.stdInputPanel.mode console.set_mode(mode) return old_mode @StaticGuiCall def release_side_thread(panid): task = gui.qapp.panels['console'][panid].task task.release_control() def execute_code(self, code_string, panid=None): shell = Shell.instance this_panid = shell.this_interpreter().console_id if panid is None or this_panid == panid: exec(code_string, shell.wsdict) else: ConsoleGuiProxy._gui_execute_code(code_string, panid) @StaticGuiCall def _gui_execute_code(code_string=None, panid=None): """ Execute code in ANOTHER console """ console = gui.qapp.panels.select_or_new('console', panid) console.stdio.stdInputPanel.execute_commands(code_string) def execute_file(self, filepath, panid=None): shell = Shell.instance this_panid = shell.this_interpreter().console_id if panid is None or this_panid == panid: shell.execfile(filepath, shell.wsdict) else: ConsoleGuiProxy._gui_execute_file(filepath) @StaticGuiCall def _gui_execute_file(filepath, panid=None): """ Execute a file in ANOTHER console """ console = gui.qapp.panels.select_or_new('console', panid) console.task.send_command(f"_ = shell.execfilews(r'{filepath}')") @StaticGuiCall def sync_paths(source_panid=0, target_panid=1): """ Syncing sys.path and the live paths from source to target. """ from ...core.shellmod import Shell source_task = gui.qapp.panels['console'][source_panid].task target_task = gui.qapp.panels['console'][target_panid].task sys_paths = source_task.call_func(Shell.get_sys_paths, wait=True) target_task.call_func(Shell.add_sys_paths, args=(sys_paths,)) live_paths = source_task.call_func(Shell.get_live_paths, wait=True) target_task.call_func(Shell.set_live_paths, args=(live_paths,)) @StaticGuiCall def child(init_caller, *args): panel = gui.qapp.panels.select_or_new('console', None, 'child') #panel.window().toggleStatOnTop(True) panel.task.wait_process_ready() panel.task.call_func(init_caller, args=args, callback=None) return panel.panid
thocoo/gamma-desk
gdesk/graphics/grid.py
<filename>gdesk/graphics/grid.py from qtpy import QtCore, QtGui, QtWidgets class yAxisLabel(QtWidgets.QGraphicsLineItem): def __init__(self, ticksX, ticksY, direction, parent=None, scene=None): super().__init__(parent=parent, scene=scene) self.direction = direction def createGrid(self): self.grid = [] pens = [] pens.append(QtGui.QPen(QtGui.QColor(159,159,159), 0, QtCore.Qt.SolidLine)) pens.append(QtGui.QPen(QtGui.QColor(191,191,191), 0, QtCore.Qt.DashLine)) pens.append(QtGui.QPen(QtGui.QColor(223,223,223), 0, QtCore.Qt.DotLine)) pens.append(QtGui.QPen(QtGui.QColor(159,159,159), 0, QtCore.Qt.SolidLine)) pens.append(QtGui.QPen(QtGui.QColor(191,191,191), 0, QtCore.Qt.DashLine)) pens.append(QtGui.QPen(QtGui.QColor(223,223,223), 0, QtCore.Qt.DotLine)) paths = [] for ticklevel in range(3): paths.append(QtGui.QPainterPath()) for i in self.ticksX[ticklevel][1]: if self.direction == 0: paths[-1].moveTo(i, self.startY) paths[-1].lineTo(i, self.stopY) else: paths[-1].moveTo(self.startY, i) paths[-1].lineTo(self.stopY, i) for ticklevel in range(3): paths.append(QtGui.QPainterPath()) for i in self.ticksY[ticklevel][1]: if self.direction == 0: paths[-1].moveTo(self.startX, i) paths[-1].lineTo(self.stopX, i) else: paths[-1].moveTo(i, self.startX) paths[-1].lineTo(i, self.stopX) for i in range(len(paths)): self.grid.append(QtWidgets.QGraphicsPathItem(paths[i])) self.grid[-1].setPen(pens[i]) self.grid[-1].setZValue(-2) self.scene.addItem(self.grid[-1])
thocoo/gamma-desk
gdesk/dicttree/node.py
# -*- coding: utf-8 -*- from PySide2 import QtGui, QtCore, QtXml class Node(object): def __init__(self, name, parent=None): self._name = name self._parent = parent self._children = [] self._value = None if parent is not None: parent.addChild(self) def typeInfo(self): return 'NODE' def addChild(self, child): self._children.append(child) def insertChild(self, position, child): if position < 0 or position > len(self._children): return False self._children.insert(position, child) child._parent = self return True def removeChild(self, position): if position < 0 or position > len(self._children): return False self._children.pop(position) child._parent = None return True def attrs(self): classes = self.__class__.__mro__ keyvalued = {} for cls in classes: for key, value in cls.__dict__.iteritems(): if isinstance(value, property): keyvalued[key] = value.fget(self) return keyvalued def to_xml(self): doc = QtXml.QDomDocument() node = doc.createElement(self.typeInfo()) doc.appendChild(node) for i in self._children: i._recurseXml(doc, node) return doc.toString(indent=4) def _recurse_xml(self, doc, parent): node = doc.createElement(self.typeInfo()) parent.appendChild(node) attrs = self.attrs().iteritems() for k, v in attrs: node.setAttribute(k, v) for child in self._children: child._recurse_xml(doc, node) def to_list(self): output = [] if self._children: for child in self._children: output += [self.name, child.to_list()] else: output += [self.name, self.value] return output def to_dict(self, d={}): for child in self._children: child._recurse_dict(d) return d def _recurse_dict(self, d): if self._children: d[self.name] = {} for child in self._children: child._recurse_dict(d[self.name]) else: d[self.name] = self.value def name(): def fget(self): return self._name def fset(self, value): self._name = value return locals() name = property(**name()) def value(): def fget(self): return self._value def fset(self, value): self._value = value return locals() value = property(**value()) def child(self, row): return self._children[row] def childCount(self): return len(self._children) def parent(self): return self._parent def row(self): if self._parent is not None: return self._parent._children.index(self) def log(self, tabLevel=-1): output = '' tabLevel += 1 for i in range(tabLevel): output += ' ' output += ''.join(('|----', self._name,' = ', '\n')) for child in self._children: output += child.log(tabLevel) tabLevel -= 1 output += '\n' return output def __repr__(self): return self.log() def data(self, column): if column == 0: return self.name elif column == 1: return self.value def setData(self, column, value): if column == 0: self.name = value if column == 1: self.value = value def resource(self): return None
thocoo/gamma-desk
gdesk/utils/funccom.py
"""Function tools.""" from types import CodeType, FunctionType def find_nested_func(parent, child_name, globs, closure=None): """ Find nested funcion. Return the function named <child_name> that is defined inside a <parent> function Returns None if nonexistent """ consts = parent.__code__.co_consts for item in consts: if isinstance(item, CodeType) and item.co_name == child_name: return FunctionType(item, globs, closure=closure)
thocoo/gamma-desk
gdesk/utils/__init__.py
<reponame>thocoo/gamma-desk<gh_stars>0 """A collections of utils.""" import sys from functools import reduce import numpy as np def new_id_using_keys(keys): """Find the lowest new id starting from already exisiting ids.""" keys = np.array(keys) if len(keys) == 0: return 1 keys.sort() np.diff(keys) gaps = np.where(np.diff(keys) > 1)[0] if len(gaps) > 0: key = keys[gaps[0]] + 1 else: key = keys[-1] + 1 return key def lazyf(template): """Do a f-string formating.""" frame = sys._getframe(1) result = eval('f"""' + template + '"""', frame.f_globals, frame.f_locals) return result def clip_values(dtype): """Get the lowest and highest clipvalue for a certain numpy data type.""" if dtype == 'uint8': low, high = 0, 255 elif dtype == 'int8': low, high = -127, 127 elif dtype == 'uint16': low, high = 0, 65535 elif dtype == 'int16': low, high = -32768, 32767 elif dtype == 'uint32': low, high = 0, 4294967295 elif dtype == 'int32': low, high = -2147483648, 2147483647 elif dtype in ['float', 'double']: low, high = 0, 1 else: raise AttributeError(f'clip values not defined for {dtype}') return low, high def clip_array(array, dtype): """Clip the array to clipvalues of dtype.""" if dtype in ['float16', 'float32', 'float64', 'float', 'double']: return array array = array.clip(*clip_values(dtype)).astype(dtype) return array def get_factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
thocoo/gamma-desk
gdesk/core/comm_nonduplex.py
<filename>gdesk/core/comm_nonduplex.py # My alternative for multiprocessing Queues # The original multiprocessing.Queues with locks can only be # initialized to a process by inheritance # The shared locks are the problem # Because there are no locks, to be save # only a single writer and reader can use this queue import os import threading import collections import multiprocessing import _multiprocessing from multiprocessing.connection import PipeConnection from multiprocessing.reduction import duplicate, steal_handle class NonDuplexQueue(object): def __init__(self): self.reader, self.writer = multiprocessing.Pipe(duplex=False) self._buffer = collections.deque() self._thread = None def steal_pipe(self, pid, read_handle, write_handle): read_handle = steal_handle(pid, read_handle) write_handle = steal_handle(pid, write_handle) reader = PipeConnection(read_handle, writable=False) writer = PipeConnection(write_handle, readable=False) return reader, writer def duplicate_pipe(self): read_handle = duplicate(self.reader._handle) write_handle = duplicate(self.writer._handle) return read_handle, write_handle def __getstate__(self): state = dict() state['pid'] = os.getpid() read_handle, write_handle = self.duplicate_pipe() state['read_handle'] = read_handle state['write_handle'] = write_handle return state def __setstate__(self, state): self.reader, self.writer = self.steal_pipe(state['pid'], state['read_handle'], state['write_handle']) self._buffer = collections.deque() self._thread = None def empty(self): return not self.reader.poll() def put(self, data): # The _notempty lock can not be pickled and shared # between processes (only by inheritance)! # So this function should be called after the this queue # has been setup between the 2 processes if self._thread is None: self._notempty = threading.Condition(threading.Lock()) self._thread = threading.Thread(target=self._feed, name='NonDuplexQueueFeed' ,daemon=True) self._thread.start() with self._notempty: self._buffer.append(data) self._notempty.notify() def get(self, timeout=None): if self.reader.poll(timeout): return self.reader.recv() else: raise RuntimeError('Queue is empty') def _feed(self): while True: with self._notempty: self._notempty.wait() try: while True: data = self._buffer.popleft() if data is sentinel: return self.writer.send(data) except IndexError: pass def close(self): self.put(sentinel)
thocoo/gamma-desk
gdesk/external/channel.py
import os import sys import threading import pathlib import pprint from multiprocessing import Process, Queue from .. import config, configure, gui configure(matplotlib={'backend':'svg'}) from .. import console from ..core.shellmod import Shell from ..core.tasks import ZmqQueues from ..core.tasks import CommQueues from ..core.watcher import CommandClient def python_executable(): executable = pathlib.Path(sys.executable) if executable.name == 'python.exe': #This is also correct for virtual env #Note that the os module is loaded from the master Python location #not the virtual env return str(executable) else: #In case of embeded python in on other executable (Canvas) #Base the python.exe location on the os module location executable = pathlib.Path(os.__file__).parent.parent / 'python.exe' return str(executable) def connect_to_gui(port=None, host='localhost', namespace=None, gui_redirect=True, as_server=False): """ Start Gamma Desk as a independend process and open a zmq communication channel This function start a new thread. :param int port: TCP port number to connect to (default 5998) :param str host: Hostname of ip address to connect to (default localhost) :param dict namespace: The namespace to use in the Gamma Desk console (Caller namespace by default) :param bool gui_redirect: Make the gui mapper accesible in this thread :param bool as_server: True -> This will be the zmq server (default False -> GD acts as server) Typical usage in a second Python process by the following command: >>> from gdesk.external import channel >>> channel.connect_to_gui() Connecting to a running GD instance at another computer >>> channel.connect_to_gui(5998, 'FFYBVR-L1.ad.onsemi.com') """ if namespace is None: namespace = sys._getframe(1).f_globals shell = Shell(namespace) if host not in ['localhost', '127.0.0.1']: config['image']['queue_array_shared_mem'] = False if port is None: ports = shell.get_watcher_ports() port = ports[-1] cmdclient = CommandClient(port, host) if as_server: print('Connecting as server') cqs = ZmqQueues() cqs.setup_as_server() cqs_config = cmdclient.send({'cmd': 'connect_zmq_process', 'args': (cqs.to_json(),)}, timeout=5000, retries=1) pprint.pprint(cqs_config) else: print('Connecting as client') cqs_config = cmdclient.send({'cmd': 'connect_zmq_process', 'args': ()}, timeout=5000, retries=1) pprint.pprint(cqs_config) cqs = ZmqQueues.from_json(cqs_config) cqs.setup_as_client(host) return init_gui(shell, cqs, gui_redirect, client=False) def start_gui_as_child(namespace=None, gui_redirect=True): """ Start Gamma Hawk as a child process and open a communication channel to a new thread in this process. :param dict workspace: The workspace to use in the Shell object :param bool gui_redirect: make the gui mapper accesible in this thread Typical usage in Canvas by the following command: from ghawk2.external.channel import start_ghawk_as_child; start_ghawk_as_child(globals()) """ if namespace is None: namespace = sys._getframe(1).f_globals shell = Shell(namespace) #CommQueues can only be send to other process by #spawn process inheritance cqs = CommQueues(Queue, process=True) start_gui(child=True, commqueues=cqs) return init_gui(shell, cqs, gui_redirect) def start_gui(child=False, commqueues=None, deamon=False): if child: #Start the Gui as a subprocess using the multiprocessing module #hack the executable in sys (for embeded Python) sys.executable = python_executable() proc_config = { 'default_perspective': 'base', 'init_command': {'cmd': 'connect_process', 'args': ()}} process = Process(target=console.run_as_child, args=((), proc_config, {'cqs': commqueues}), daemon=deamon) process.start() else: os.system(f'start {python_executable()} -m ghawk2') def init_gui(shell, commqueues, gui_redirect=True, client=True): name, tid = shell.new_interactive_thread(commqueues, client=client) if gui_redirect: gui.redirects[threading.get_ident()] = tid return tid
thocoo/gamma-desk
gdesk/panels/dialog/__init__.py
from .proxy import DialogGuiProxy
thocoo/gamma-desk
gdesk/core/gui_proxy.py
<reponame>thocoo/gamma-desk<filename>gdesk/core/gui_proxy.py<gh_stars>0 import sys import threading from multiprocessing import Queue import functools import importlib import types import pickle import logging import pathlib import time import numpy as np from ..utils.funccom import find_nested_func from ..utils.imconvert import qimage_to_ndarray from .conf import config try: #Only on Windows from ..utils.keypress import PressKey, ReleaseKey except: pass logger = logging.getLogger(__name__) if config.get('sphinx', False): #https://stackoverflow.com/questions/28366818/preserve-default-arguments-of-wrapped-decorated-python-function-in-sphinx-docume def wraps(original_func): wrap_decorator = functools.wraps(original_func) def re_wrapper(func): wrapper = wrap_decorator(func) poorman_sig = original_func.__code__.co_varnames[ :original_func.__code__.co_argcount] wrapper.__doc__ = "{} ({})\n\n{}".format ( original_func.__name__, ", ".join(poorman_sig), wrapper.__doc__) return wrapper return re_wrapper else: wraps = functools.wraps def StaticGuiCall(func): #Decorator for pushing the function call through a queue #func is the function of the decorated method, not the method itself? @staticmethod @wraps(func) def caller(*args, **kwargs): return gui.gui_call(func, *args, **kwargs) return caller class RedBull(object): def __init__(self, interval=60): self.interval = interval self.actives = [] self.timer_thread = None #Function Key 15 self.keycode = 0x7E def enable(self, interval=None): if len(self.actives) == 0: self.start(interval or self.interval) else: self.stop() self.start(interval or self.interval) def disable(self): self.stop() def start(self, interval): self.timer_thread = threading.Thread(target=self.loop, args=(interval,)) self.timer_thread.start() def stop(self): self.actives.clear() self.timer_thread = None def loop(self, interval): ident = threading.get_ident() self.actives.append(ident) while True: time.sleep(interval) if not ident in self.actives: break self.do() def do(self): PressKey(self.keycode) ReleaseKey(self.keycode) class GuiProxyBase(object): category = None @classmethod def derivedClasses(cls): l = [] for SubClass in cls.__subclasses__(): l.extend(SubClass.derivedClasses()) l.append((SubClass.category, SubClass)) if cls is GuiProxyBase: result = dict() for category, Cls in l: if not category in result.keys(): result[category] = [] result[category].append(Cls) return result else: return l @classmethod def menu(cls, action_names, *args, **kwargs): """ Call a certain menu item of the panel :param list action_names: Example ['File', 'New...'] :param ``*args``: Positional arguments of the menu call :param ``**kwargs``: Keyword arguments of the menu call """ return gui.menu_trigger(cls.category, None, action_names, *args, **kwargs) @classmethod def new(cls, paneltype=None, windowname=None, *args, **kwargs): return GuiProxyBase._new(cls.category, paneltype, windowname, *args, **kwargs) @StaticGuiCall def _new(category, paneltype=None, windowname=None, size=None, *args, **kwargs): return gui.qapp.panels.new(category, paneltype, windowname, size=size, *args, **kwargs) @classmethod def selected(cls): """ Return the panel id of the selected panel if this category. """ category = cls.category return GuiProxyBase._selected_panid_of_category(category) @StaticGuiCall def _selected_panid_of_category(category): return gui.qapp.panels.selected(category, panel=False) @classmethod def close(Cls, panid=-1): """ Close the selected panel of the category """ return Cls._close_panel_of_category(panid, Cls.category) @StaticGuiCall def _close_panel_of_category(panid, category): panel = gui.qapp.panels.selected(category, panid) if not panel is None: panel.close_panel() return True else: return False @classmethod def grab(cls): return cls._panel_grab(cls.category) @StaticGuiCall def _panel_grab(category): panel = gui.qapp.panels.selected(category) pixmap = panel.grab() image = pixmap.toImage() arr = qimage_to_ndarray(image) return arr #Note that a embeded function is also be static if closure is None STATIC = 1 #Embeded functions with closure not None ENCLOSED = 2 #Method on object METHOD = 4 class GuiProxy(object): """ Communication channel to the gui Master and Slave Across Procecess and Threads """ push_list = [] def __init__(self, qapp=None, master_call_queue=None, master_return_queue=None, process_ready_call=None): """ In case of multiprocessing, there is a gui instance at the master process for every child process and an instance at the child process :param qapp: None in case of child process :type qapp: QApplication or None :param bool process: True in case of multi processing :param multiprocessing.queue master_queue: The event queue from the master process """ self.hooks = dict() self.reg_obj = dict() self.proxies = dict() self.block = True self._qapp = qapp self.call_queue = master_call_queue self.return_queue = master_return_queue if not process_ready_call is None: self.set_func_hook(-2, process_ready_call) if not qapp is None: if not self.call_queue is None: self.pass_thread = threading.Thread(target=self._pass_to_eventloop, name=f'Handover-{id(self)}', daemon=True) self.pass_thread.start() self.redbull = RedBull() self.refresh_proxies() @property def qapp(self): """ The QApplication instance. Is only visible in the gui thread. """ #Hide it also for threads in the gui app which are not the main #User should not use it directly, only by gui_call if self.is_main(): return self._qapp else: return None def refresh_proxies(self): """ Add all currently imported Gui Proxies. :meta private: """ catclasses = GuiProxyBase.derivedClasses() for category, classes in catclasses.items(): proxy = classes[0]() name = proxy.attach(self) if not name is None: self.proxies[name] = proxy def set_func_hook(self, key, func): """ :meta private: """ self.hooks[key] = func def register_object(self, obj): #This is supposed to happen only in the gui thread id_obj = id(obj) self.reg_obj[id_obj] = [obj] + self.reg_obj.get(id_obj, []) return id_obj def retrieve_object(self, key): lst = self.reg_obj[key] func_id = lst.pop() if len(lst) == 0: self.reg_obj.pop(key) return func_id def is_main(self): return (not self._qapp is None and threading.currentThread().name == 'MainThread') def encode_func(self, func, register=False): if isinstance(func, (int, tuple)): #It is already encoded func_id = func elif isinstance(func, (types.FunctionType, type)): module = func.__module__ qualname = func.__qualname__ if func.__closure__ is None: func_id = STATIC, module, qualname else: closere_id = self.register_object(func.__closure__) func_id = ENCLOSED, module, qualname, closere_id elif isinstance(func, (types.MethodType, type)): module = func.__module__ qualname = func.__qualname__ self_key = self.register_object(func.__self__) func_id = METHOD, module, qualname, self_key else: raise AttributeError(f'Type of {func} is not valid') func_id = func.__name__ return func_id def decode_func(self, func_id): if isinstance(func_id, int): #For some limit cases, this a a quicker decoding #Used for stdout flushing and process_ready func = self.hooks[func_id] elif isinstance(func_id, tuple): lib = importlib.import_module(func_id[1]) attrs = func_id[2] parts = attrs.split('.') if func_id[0] in [STATIC, ENCLOSED]: tmp = lib closure = None if func_id[0] == STATIC else self.retrieve_object(func_id[3]) for i, attr in enumerate(parts): if attr == '<locals>': tmp = find_nested_func(tmp, parts[i+1], lib.__dict__, closure) break else: tmp = getattr(tmp, attr) func = tmp elif func_id[0] == METHOD: obj = self.retrieve_object(func_id[3]) tmp = lib for i, attr in enumerate(parts): tmp = getattr(tmp, attr) func = types.MethodType(tmp, obj) else: #already decoded, was not encoded func = func_id return func def gui_call(self, func, *args, **kwargs): if self.is_main(): func = self.decode_func(func) return func(*args, **kwargs) #return self._qapp.handover.send(self.block, func, *args, **kwargs) return self._call(func, *args, **kwargs) def _call(self, func, *args, **kwargs): return self._call_base(True, func, *args, **kwargs) def _call_no_wait(self, func, *args, **kwargs): return self._call_base(False, func, *args, **kwargs) def _call_base(self, wait, func, *args, **kwargs): if self.call_queue is None: #Multi Threading Child #Direct handover to eventloop func = self.decode_func(func) return self._qapp.handover.send(self.block, func, *args, **kwargs) else: #Multi Processing Child #Handover to Gui Process func = self.encode_func(func) if wait: self.call_queue.put((True, func, args, kwargs)) value = self.return_queue.get() return value else: self.call_queue.put((False, func, args, kwargs)) return None def _pass_to_eventloop(self): """ Receive func, args, kwargs from call_queue and handover to event loop. :meta private: """ while True: backval, func, args, kwargs = self.call_queue.get() func = self.decode_func(func) value = self._qapp.handover.send(True, func, *args, **kwargs) if backval: self.return_queue.put(value) @StaticGuiCall def get_panel_ids(category): """ Returns all current panal ids of a category. The last one is the selected one. :returns: current panal ids :rtype: list """ if category in gui.qapp.panels.keys(): return list(gui.qapp.panels[category].keys()) else: return [] @StaticGuiCall def load_layout(name='console'): gui.qapp.panels.restore_state_from_config(name) def show(self, *args, **argv): """ Shows a object in an suitable panel You can give more then one object to display, multiple viewers will be created. :param int select: selects which viewer shows the object (start with 1! 0 in GH1) negative numbers stands for last selected, or the selected before that, or before that """ objcount = len(args) panids = argv.get('select', range(-objcount, 0)) panid = None for obj, panid in zip(args, panids): if isinstance(obj, np.ndarray): self.img.select(panid) panid = self.img.show(obj) return panid @property def vs(self): """ The shared array on the current image viewer Note that the data is on shared memory. ``vs[:]`` or ``vs.ndarray`` to view it as a real numpy array """ try: return self.img.vs except: return None @property def vr(self): """ The roi sliced numpy array of the current image viewer """ try: return self.img.vr except: return None @StaticGuiCall def menu_trigger(category, pandid, action_names, *args, **kwargs): """ Trigger a menu action of a panel. :param str category: Example 'image' :param int id: Example 1 :param list action_names: Example ['File', 'New...'] """ try: action = gui.qapp.panels.get_menu_action(category, pandid, action_names) except KeyError: logger.error(f'Menu action {action_names} not found') return if len(args) == len(kwargs) == 0: action.setData(None) else: action.setData({'args':args, 'kwargs': kwargs}) retval = action.trigger() action.setData(None) return retval @StaticGuiCall def history(count=20): """ The command history :param int count: Show the last count elements :returns: Command history as list :rtype: list """ return gui.qapp.history.tail(count) @StaticGuiCall def push(obj): """ Push an object on the gui data stack :param object obj: A pickable object """ GuiProxy.push_list.append(obj) @StaticGuiCall def pull(): """ Pull and object from the gui data stack :returns: The object """ return GuiProxy.push_list.pop(0) @StaticGuiCall def exit(): """ Exit Gamma Hawk """ gui.qapp.quit() class GuiMap(object): gui_proxies = dict() redirects = dict() def __init__(self): pass @property def _gui_proxy(self): ident = threading.get_ident() ident = GuiMap.redirects.get(ident, ident) return GuiMap.gui_proxies.get(ident, None) def valid(self): return not self._gui_proxy is None def __dir__(self): return self._gui_proxy.__dir__() def __repr__(self): return self._gui_proxy.__repr__() def __str__(self): return self._gui_proxy.__str__() def __getattr__(self, attr): return getattr(self._gui_proxy, attr) def __setattr__(self, attr, value): return setattr(self._gui_proxy, attr, value) gui = GuiMap() def register_objects_in_ghawk2_init(): import gdesk gdesk.GuiMap = GuiMap gdesk.gui = gui gdesk.StaticGuiCall = StaticGuiCall
thocoo/gamma-desk
gdesk/gcore/qgc.py
<gh_stars>0 """The Garbage Collector timer in the Qt Event Loop.""" import gc import sys from qtpy.QtCore import QObject, QTimer class QGarbageCollector(QObject): """ Disable automatic garbage collection and instead collect manually. Timeout every INTERVAL milliseconds. This is done to ensure that garbage collection only happens in the GUI thread, as otherwise Qt can crash. """ INTERVAL = 5000 def __init__(self, parent, debug=False): """QGarbageCollector.""" QObject.__init__(self, parent) self.debug = debug self.timer = QTimer(self) self.timer.timeout.connect(self.check) self.threshold = gc.get_threshold() def enable(self): """Enable the timer.""" gc.disable() self.timer.start(self.INTERVAL) def disable(self): """Disable the timer.""" self.timer.stop() gc.enable() def check(self): """Do the garbage collection.""" cnt_0, cnt_1, cnt_2 = gc.get_count() if self.debug: sys.__stdout__.write('gc_check called: %d, %d, %d\n' % (cnt_0, cnt_1, cnt_2)) sys.__stdout__.flush() if cnt_0 > self.threshold[0]: num = gc.collect(0) if self.debug: sys.__stdout__.write('collecting gen 0, found: %d unreachable\n' % num) sys.__stdout__.flush() if cnt_1 > self.threshold[1]: num = gc.collect(1) if self.debug: sys.__stdout__.write('collecting gen 1, found: %d unreachable\n' % num) sys.__stdout__.flush() if cnt_2 > self.threshold[2]: num = gc.collect(2) if self.debug: sys.__stdout__.write('collecting gen 2, found: %d unreachable\n' % num) sys.__stdout__.flush()
thocoo/gamma-desk
gdesk/panels/imgview/quantiles.py
import numpy as np from .fasthist import hist2d stdquant = np.ndarray(13) stdquant[0] = (0.0000316712418331200) #-4 sdev stdquant[1] = (0.0013498980316301000) #-3 sdev stdquant[2] = (0.0227501319481792000) #-2 sdev stdquant[3] = (0.05) stdquant[4] = (0.1586552539314570000) #-1 sdev or lsdev stdquant[5] = (0.25) #first quartile stdquant[6] = (0.50) #median stdquant[7] = (0.75) #third quartile stdquant[8] = (0.8413447460685430000) #+1 sdev or usdev stdquant[9] = (0.95) stdquant[10] = (0.9772498680518210000) #+2 sdev stdquant[11] = (0.9986501019683700000) #+3 sdev stdquant[12] = (0.9999683287581670000) #+4 sdev def get_standard_quantiles(arr, bins=64, step=None, quantiles=None): hist, starts, stepsize = hist2d(arr, bins, step, plot=False) cumhist = np.cumsum(hist) if quantiles is None: quantiles = stdquant else: quantiles = np.array(quantiles) n = len(quantiles) npix = np.multiply.reduce(arr.shape) quantiles *= npix thresh = [0] * n #TO DO: speed up by using interpolation function of numpy for ind in range(n): thresh[ind] = starts[(cumhist < quantiles[ind]).sum()] return thresh def get_sigma_range(arr, sigma=1, bins=64, step=None): if sigma == 1: return get_standard_quantiles(arr, bins, step, (stdquant[4], stdquant[8])) elif sigma == 2: return get_standard_quantiles(arr, bins, step, (stdquant[2], stdquant[10])) elif sigma == 3: return get_standard_quantiles(arr, bins, step, (stdquant[1], stdquant[11])) elif sigma == 4: return get_standard_quantiles(arr, bins, step, (stdquant[0], stdquant[12])) def get_sigma_range_for_hist(starts, hist, sigma): cumhist = np.cumsum(hist) if sigma==1: quantiles = np.array((stdquant[4], stdquant[8])) elif sigma==2: quantiles = np.array((stdquant[2], stdquant[10])) elif sigma==3: quantiles = np.array((stdquant[1], stdquant[11])) elif sigma==4: quantiles = np.array((stdquant[0], stdquant[12])) n = len(quantiles) npix = cumhist[-1] quantiles *= npix thresh = [0] * n #TO DO: speed up by using interpolation function of numpy for ind in range(n): thresh[ind] = starts[(cumhist < quantiles[ind]).sum()] return thresh
thocoo/gamma-desk
gdesk/core/comm.py
<reponame>thocoo/gamma-desk import os import sys import queue import threading import collections import socket import json import multiprocessing import _multiprocessing import zmq zmq_context = zmq.Context() from .conf import config if sys.platform == 'win32': from .comm_nonduplex import NonDuplexQueue sentinel = object() class CommQueues(object): def __init__(self, QueueCls, process=False): self.host = 'localhost' self.flow_queue = QueueCls() self.return_queue = QueueCls() self.stdin_queue = QueueCls() self.stdout_queue = QueueCls() if process: self.gui_call_queue = QueueCls() self.gui_return_queue = QueueCls() else: self.gui_call_queue = None self.gui_return_queue = None def clear(self): while not self.flow_queue.empty(): self.flow_queue.get() while not self.stdout_queue.empty(): self.stdout_queue.get() while not self.return_queue.empty(): self.return_queue.get() if not self.gui_call_queue is None: while not self.gui_call_queue.empty(): self.gui_call_queue.get() if not self.gui_return_queue is None: while not self.gui_return_queue.empty(): self.gui_return_queue.get() def close(self): for q in [self.flow_queue, self.stdout_queue, self.return_queue, self.gui_call_queue, self.gui_return_queue]: if isinstance(q, NonDuplexQueue): q.close() class ZmqQueue(object): def __init__(self, port=None): self.port = port def setup_as_server(self): self.socket = zmq_context.socket(zmq.PAIR) self.port = self.socket.bind_to_random_port('tcp://*', min_port=config['zmq_queue_min_port'], max_port=config['zmq_queue_max_port'], max_tries=100) def setup_as_client(self, host='localhost'): self.socket = zmq_context.socket(zmq.PAIR) self.socket.connect(f"tcp://{host}:{self.port}") def __getstate__(self): state = dict() state['port'] = self.port return state def __setstate__(self, state): self.port = state['port'] def put(self, data): self.socket.send_pyobj(data, flags=zmq.NOBLOCK) def get(self, timeout=None): if not timeout is None: event = self.socket.poll(timeout*1000) if event == 0: raise queue.Empty() return self.socket.recv_pyobj() def empty(self): return self.socket.poll(0) == 0 class ZmqQueues(object): ports = { 'cmd': None, 'stdin': None, 'stdout': None, 'return': None, 'gui_call': None, 'gui_return': None, } def __init__(self, ports=None): if ports is None: ports = ZmqQueues.ports for queue_name, port in ports.items(): self.__dict__[f'{queue_name}_queue'] = ZmqQueue(port=port) def setup_host(self): self.hostname = socket.gethostname() hostname_ex, aliaslist, ipaddrlist = socket.gethostbyname_ex(self.hostname) self.hostname_ex = hostname_ex self.aliaslist = aliaslist self.ipaddrlist = ipaddrlist @classmethod def from_json(Cls, json_string): d0 = json.loads(json_string) d1 = d0['channel'] ports = dict() ports['cmd'] = d1['cmd'] ports['stdin'] = d1['stdin'] ports['stdout'] = d1['stdout'] ports['return'] = d1['return'] ports['gui_call'] = d1['gui_call'] ports['gui_return'] = d1['gui_return'] instance = Cls(ports) instance.hostname = d1['hostname'] instance.hostname_ex = d1['hostname_ex'] instance.aliaslist = d1['aliaslist'] instance.ipaddrlist = d1['ipaddrlist'] return instance def to_json(self): d0 = dict() d1 = d0['channel'] = dict() d1['method'] = 'zmq' d1['hostname'] = self.hostname d1['hostname_ex'] = self.hostname_ex d1['aliaslist'] = self.aliaslist d1['ipaddrlist'] = self.ipaddrlist d1['cmd'] = self.flow_queue.port d1['stdin'] = self.stdin_queue.port d1['stdout'] = self.stdout_queue.port d1['return'] = self.return_queue.port d1['gui_call'] = self.gui_call_queue.port d1['gui_return'] = self.gui_return_queue.port return json.dumps(d0) def setup_as_server(self): self.setup_host() self.flow_queue.setup_as_server() self.stdin_queue.setup_as_server() self.stdout_queue.setup_as_server() self.return_queue.setup_as_server() self.gui_call_queue.setup_as_server() self.gui_return_queue.setup_as_server() def setup_as_client(self, host=None): if host is None: self.host = 'localhost' else: self.host = host self.flow_queue.setup_as_client(self.host) self.stdin_queue.setup_as_client(self.host) self.stdout_queue.setup_as_client(self.host) self.return_queue.setup_as_client(self.host) self.gui_call_queue.setup_as_client(self.host) self.gui_return_queue.setup_as_client(self.host)
thocoo/gamma-desk
gdesk/dialogs/base.py
import ctypes import ctypes.wintypes from pathlib import Path from qtpy import QtCore, QtGui, QtWidgets from qtpy import PYSIDE, PYSIDE2, PYQT4, PYQT5 def using_pyside(): return PYSIDE or PYSIDE2 def using_pyqt(): return PYQT4 or PYQT5 LASTMAP = None class LASTINPUTINFO(ctypes.Structure): _fields_ = [ ('cbSize', ctypes.wintypes.UINT), ('dwTime', ctypes.wintypes.DWORD), ] PLASTINPUTINFO = ctypes.POINTER(LASTINPUTINFO) GetLastInputInfo = ctypes.windll.user32.GetLastInputInfo GetLastInputInfo.restype = ctypes.wintypes.BOOL GetLastInputInfo.argtypes = [PLASTINPUTINFO] def get_last_input_moment(): liinfo = LASTINPUTINFO() liinfo.cbSize = ctypes.sizeof(liinfo) GetLastInputInfo(ctypes.byref(liinfo)) return liinfo.dwTime class ExecTimeout: def __init__(self, dialog, timeout=None): self.dialog = dialog self.timer = QtCore.QTimer() self.timer.timeout.connect(self.check_user_input_and_close) self.timeout = timeout if not timeout is None: self.timer.start(timeout) def exec_(self): self.exec_user_input_moment = get_last_input_moment() self.dialog.exec_() self.timer.stop() def check_user_input_and_close(self): last_user_input_moment = get_last_input_moment() if self.exec_user_input_moment < last_user_input_moment: self.timer.stop() else: self.dialog.close() def getFile(filter='*.*', title='open', defaultFile=None, hideFilterDetails=False): global LASTMAP if not defaultFile is None: defaultDir = defaultFile else: defaultDir = LASTMAP #The HideNameFilterDetails option seems to be crashy #if the filter doesn't have the detailed form # Tagged Image Format (*.tif) #For example the filter *.* often crashes if the option is enabled #Maybe QT returns a buggy string as selectedFilter? if using_pyside(): if not hideFilterDetails: fileName, selectedFilter = QtWidgets.QFileDialog.getOpenFileName( caption = title, dir=defaultDir, filter=filter) else: fileName, selectedFilter = QtWidgets.QFileDialog.getOpenFileName( caption = title, dir=defaultDir, filter=filter, options=QtWidgets.QFileDialog.HideNameFilterDetails) elif using_pyqt(): if not hideFilterDetails: fileName, selectedFilter = QtWidgets.QFileDialog.getOpenFileNameAndFilter( caption = title, directory=defaultDir, filter=filter) else: fileName, selectedFilter = QtWidgets.QFileDialog.getOpenFileNameAndFilter( caption = title, directory=defaultDir, filter=filter, options=QtWidgets.QFileDialog.HideNameFilterDetails) LASTMAP = str(Path(fileName).parent) return fileName, selectedFilter def getFiles(filter='*.*', title='open', defaultFile=None, hideFilterDetails=False): global LASTMAP if not defaultFile is None: defaultDir = defaultFile else: defaultDir = LASTMAP #The HideNameFilterDetails option seems to be crashy #if the filter doesn't have the detailed form # Tagged Image Format (*.tif) #For example the filter *.* often crashes if the option is enabled #Maybe QT returns a buggy string as selectedFilter? if using_pyside(): if not hideFilterDetails: fileNames, selectedFilter = QtWidgets.QFileDialog.getOpenFileNames( caption = title, dir=defaultDir, filter=filter) else: fileNames, selectedFilter = QtWidgets.QFileDialog.getOpenFileNames( caption = title, dir=defaultDir, filter=filter, options=QtWidgets.QFileDialog.HideNameFilterDetails) elif using_pyqt(): if not hideFilterDetails: fileNames, selectedFilter = QtWidgets.QFileDialog.getOpenFileNamesAndFilter( caption = title, directory=defaultDir, filter=filter) else: fileNames, selectedFilter = QtWidgets.QFileDialog.getOpenFileNamesAndFilter( caption = title, directory=defaultDir, filter=filter, options=QtWidgets.QFileDialog.HideNameFilterDetails) LASTMAP = str(Path(fileNames[0]).parent) return fileNames, selectedFilter def putFile(filter='*.*', title='save', defaultFile=None, defaultFilter=''): global LASTMAP if not defaultFile is None: defaultDir = defaultFile else: defaultDir = LASTMAP if using_pyside(): fileName, selectedFilter = QtWidgets.QFileDialog.getSaveFileName( caption = title, filter = filter, dir = defaultDir, selectedFilter = defaultFilter) elif using_pyqt(): fileName, selectedFilter = QtWidgets.QFileDialog.getSaveFileNameAndFilter( caption = title, filter = filter, directory = defaultDir, selectedFilter = defaultFilter) LASTMAP = str(Path(fileName).parent) return fileName, selectedFilter def getMap(startPath=None, title='select a Directory'): global LASTMAP startPath = startPath or LASTMAP if using_pyside(): path = QtWidgets.QFileDialog.getExistingDirectory( caption=title, dir=startPath) elif using_pyqt(): path = QtWidgets.QFileDialog.getExistingDirectory( caption=title, directory=startPath) LASTMAP = path return path def getString(prompt, default='', title='Input', echo='Normal'): """ Show a popup-window to ask the user some textual input. Makes use of QtWidgets.QInputDialog.getText; see https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText :param str prompt: The explanation that is visible just above the text input field. :param str default: The text that is already present in the editable input field. :param str title: The name of the pop-window (shown in its title bar). :param str echo: 'Normal' for normal text entry; 'Password' for password entry. See http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum """ echo_mode = getattr(QtWidgets.QLineEdit.EchoMode, echo) return QtWidgets.QInputDialog.getText(None, title, prompt, echo=echo_mode, text=default)[0] def getStringTimeout(prompt, default='', title='Input', echo='Normal', timeout=10000): echo_mode = getattr(QtWidgets.QLineEdit.EchoMode, echo) dialog = QtWidgets.QInputDialog() dialog.setWindowTitle(title) dialog.setLabelText(prompt) dialog.setTextValue(default) retval = ExecTimeout(dialog, timeout).exec_() if retval == 0: return default return dialog.textValue() def selectFiles(filter='*.*', title='Select', defaultPath=None): filedialog = QtWidgets.QFileDialog() filedialog.setFileMode(QtWidgets.QFileDialog.FileMode.AnyFile) filedialog.setNameFilter(filter) if not defaultPath is None: defaultPath = Path(defaultPath) if defaultPath.is_file(): defaultDir = defaultPath.parent defaultFile = defaultPath.name elif defaultPath.is_dir(): defaultDir = defaultPath defaultFile = None else: defaultDir = None defaultFile = None if not defaultDir is None: filedialog.setDirectory(str(defaultDir)) if not defaultFile is None: filedialog.selectFile(str(defaultFile)) filedialog.setWindowTitle(title) #filedialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen) for btn in filedialog.findChildren(QtWidgets.QPushButton): if btn.text() == "&Open": btn.setText("Select") filedialog.exec_() return filedialog.selectedFiles() def getMultiString(prompt, default, title='Input', timeout=None): dlg = MultiString(prompt, default, title) ExecTimeout(dlg, timeout).exec_() return dlg.lns def messageBox(message, title='', icon='none'): icon = icon or 'none' icon = icon.lower() if icon == 'help': icon = QtWidgets.QMessageBox.Question elif icon == 'info': icon = QtWidgets.QMessageBox.Information elif icon == 'warn': icon = QtWidgets.QMessageBox.Warning elif icon == 'error': icon = QtWidgets.QMessageBox.Critical else: icon = QtWidgets.QMessageBox.NoIcon msgBox = QtWidgets.QMessageBox(icon, title, message) #msgBox.setText(message) #msgBox.setIcon(icon) msgBox.exec_() def questionBox(question, title=''): flags = QtWidgets.QMessageBox.question(None, title, question, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if flags == 16384: return True else: return False class MultiString(QtWidgets.QDialog): def __init__(self, prompt = [], default = [], title="Input"): super().__init__(None) self.initui(prompt, default, title) def initui(self, prompt, default, title="Input"): self.setWindowTitle(title) layout = QtWidgets.QVBoxLayout() self.edits = [] for [p,d] in zip(prompt, default): pw = QtWidgets.QLabel(p, self) dw = QtWidgets.QLineEdit(d, self) self.edits.append(dw) layout.addWidget(pw) layout.addWidget(dw) self.okbtn = QtWidgets.QPushButton('Ok') self.okbtn.clicked.connect(self.finish) layout.addWidget(self.okbtn) self.setLayout(layout) def finish(self): self.lns = [] for e in self.edits: self.lns.append(e.text()) self.close() class TopMessageBox(QtWidgets.QWidget): def __init__(self): super().__init__() self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
thocoo/gamma-desk
gdesk/panels/scriptwiz/proxy.py
from ...core.gui_proxy import GuiProxyBase, StaticGuiCall, gui class ScriptWizardProxy(GuiProxyBase): category = 'scriptwiz' def __init__(self): pass def attach(self, gui): gui.script = self @StaticGuiCall def open(templateFile): """ """ panel = gui.qapp.panels.select_or_new('scriptwiz') panel.openTemplate(templateFile)
thocoo/gamma-desk
gdesk/live/manage.py
# This module contains a script manager which implements Matlab like live scripting # Support call of scripts which can be automatic reloaded without leaving the Python interpreter # The user can modify code in a script file # These script files will be reloaded based on modify time stamps # New compiled code is direct available in current Python process import os, sys, traceback, time from pathlib import Path import functools def show_syntax_error(writer_call): """Display the syntax error that just occurred.""" type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb lines = traceback.format_exception_only(type, value) writer_call(''.join(lines)) def show_traceback(writer_call): """Display the exception that just occurred.""" try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(type, value)) finally: tblist = tb = None writer_call(''.join(lines)) def markUpdateCall(scm, ls_code, attr): func = getattr(ls_code.workspace, attr) @functools.wraps(func) def wrapped_caller(*args, **kwargs): scm.mark_for_update() error = ls_code.check_for_update() return func(*args, **kwargs) return wrapped_caller class LiveScriptModule(object): def __init__(self, script_manager, path, top=False): object.__setattr__(self, '__script_manager__', script_manager) object.__setattr__(self, '__path__', path) object.__setattr__(self, '__top__', top) @property def __wrapped__(self): ls_code = self.__script_manager__.ls_codes[self.__path__] error = ls_code.check_for_update() return ls_code.workspace def __getattr__(self, attr): if self.__top__: wrapped_attr = getattr(self.__wrapped__, attr) if callable(wrapped_attr): return markUpdateCall(self.__script_manager__, self.__script_manager__.ls_codes[self.__path__], attr) else: wrapped_attr = getattr(self.__wrapped__, attr) return wrapped_attr def __setattr__(self, attr, value): setattr(self.__wrapped__, attr, value) def __dir__(self): if self.__top__: self.__script_manager__.mark_for_update() return self.__wrapped__.__dir__() def __repr__(self): return f"<LiveScriptModule '{self.__path__}'>" @property def __doc__(self): return self.__wrapped__.__doc__ class LiveScriptTree(object): def __init__(self, script_manager, path, top=False, name=None): object.__setattr__(self, '__script_manager__', script_manager) object.__setattr__(self, '__path__', path) object.__setattr__(self, '__top__', top) object.__setattr__(self, '__name__', name) def __dir__(self): lst = [] lst = list(self.__dict__.keys()) lst.extend(list(type(self).__dict__.keys())) node = self.__path__ for file in node.glob('*'): lst.append(file.stem) return lst def __getattr__(self, attr): path = self.__path__ / attr qualname = f'{self.__name__}.{attr}' return self.__script_manager__.using_path(path, top=self.__top__, name=qualname) def __repr__(self): return f"<LiveScriptTree '{self.__path__}'>" class LiveScriptScan(object): def __init__(self, script_manager, top=False): object.__setattr__(self, '__script_manager__', script_manager) object.__setattr__(self, '__top__', top) object.__setattr__(self, '__name__', 'LiveScriptScan') def __dir__(self): lst = [] lst = list(self.__dict__.keys()) lst.extend(list(type(self).__dict__.keys())) paths = self.__script_manager__.path for path in paths: node = Path(path) for file in node.glob('*'): if file.is_dir(): lst.append(file.stem) elif file.suffix.lower() == '.py': lst.append(file.stem) return lst def __getattr__(self, attr): try: return self.__using__(attr) except KeyError: #Without this, Jypeter doesn't auto-complete #I don't know why raise AttributeError(attr) def __call__(self, modstr): return self.__using__(modstr) def __using__(self, modstr): self.__script_manager__.log(f'Calling {modstr}') if isinstance(self.__top__, str): top = sys._getframe(2).f_globals['__name__'] == self.__top__ else: top = self.__top__ return self.__script_manager__.using_modstr(modstr, top) def __repr__(self): return f"<LiveScriptScan '{self.__script_manager__.path}'>" class LsCode(object): def __init__(self, script_manager, path, name=None): self.script_manager = script_manager self.path = path self.name = 'unknown' if name is None else name self.load_modify = -1 self.code = None self.workspace = None self.ask_refresh = 0 def check_for_update(self): ls_code = self updated = None if not ls_code.ask_refresh == 0: if ls_code.ask_refresh == 1: updated = ls_code.update() elif ls_code.ask_refresh == 2: updated = ls_code.load() if not updated is None: if updated == 0: ls_code.ask_refresh = 0 self.script_manager.log(f'Updated {ls_code.path}') else: self.script_manager.warn(f'Failed to update {ls_code.path}') self.script_manager.warn(f'Error code {updated}') return updated def modify_time(self): return os.path.getmtime(str(self.path)) def update(self): if self.load_modify < self.modify_time(): ret = self.load() return ret else: return None def load(self): self.code = None self.workspace = None with open(str(self.path), 'r', encoding='utf-8') as fp: current_modify_stamp = self.modify_time() pycode = fp.read() try: codeobj = compile(pycode, str(self.path), 'exec') self.code = codeobj except: show_syntax_error(self.script_manager.write_syntax_err) return 1 self.workspace = LsWorkspace(self, str(self.path), self.name) try: exec(codeobj, self.workspace.__dict__, self.workspace.__dict__) except: show_traceback(self.script_manager.write_error) return 2 self.load_modify = current_modify_stamp self.script_manager.log(f'{self.path} loaded at {time.ctime(self.load_modify)}') return 0 class LsWorkspace(object): #Provide a namespace for each script file. def __init__(self, ls_code, file, name='unkown'): self.__file__ = file self.__ls_code__ = ls_code self.__name__ = name class LiveScriptManager(object): def __init__(self, workspace=None): # Add the search paths to self.path if workspace is None: workspace = dict() self.path = [] self.ls_codes = dict() self.workspace = workspace self.verbose = 3 def find_script(self, modstr='test'): """Search for the script in the path. Return the found path. """ modpath = modstr.replace('.', '/') result = [] for path in self.path: #It is note sure every path exists path = Path(path).absolute() if (path / modpath).with_suffix('.py').exists(): result.append(((path / modpath).with_suffix('.py'), 'file')) elif (path / modpath).is_dir(): result.append(((path / modpath), 'dir')) if len(result) == 0: raise KeyError(f'{modstr} not found') elif len(result) == 1: return result[0] else: self.warn(f'Multiple matches found for {modstr}') for path in result: self.warn(str(path[0])) return result[0] def append_path(self, path, resolve=True): path = Path(path).absolute() if resolve: try: path = path.resolve() except: print(f'Script path {path} not found') path = None if path is not None and str(path) not in self.path: self.path.append(str(path)) def load(self, path, name=None): self.ls_codes[str(path)] = LsCode(self, path, name) self.ls_codes[str(path)].load() def log(self, *msgs): if self.verbose > 4: print('<LiveScriptManager Log', *msgs, '>') def warn(self, *msgs): if self.verbose > 2: print('<LiveScriptManager Warning', *msgs, '>') def update_now(self, enforce=False): """ Reload the scripts in memory. If not enforced, load only scripts with more recent timestamps """ for ls_code in self.ls_codes.values(): if enforce: ret = ls_code.load() else: ret = ls_code.update() def mark_for_update(self, enforce=False): self.log('Marking all modules for update') mark = 2 if enforce else 1 for ls_code in self.ls_codes.values(): ls_code.ask_refresh = mark def using_modstr(self, modstr, top=False): """Load a script or make a ScriptTree. A ScripTree is used to link to a dir. The loading of a script is done at moment of attribute access. """ path, stype = self.find_script(modstr) return self.using_path(path, stype, top, modstr) def using_path(self, path, stype=None, top=False, name=None): if stype is None: if path.is_dir(): stype = 'dir' else: path = path.with_suffix('.py') stype = 'file' if path is None: raise ImportError(f'LiveScript {modstr} not found') if str(path) in self.ls_codes.keys(): return LiveScriptModule(self, str(path), top) if stype == 'file': self.load(path, name) return LiveScriptModule(self, str(path), top) elif stype == 'dir': return LiveScriptTree(self, path, top, name) def write_error(self, text): sys.stderr.write(text) def write_syntax_err(self, text): sys.stderr.write(text)
thocoo/gamma-desk
gdesk/ezdock/overlay.py
import collections import importlib import pprint import logging import pathlib from qtpy.QtWidgets import * from qtpy.QtCore import * from qtpy.QtGui import * from qtpy import QtCore, QtGui, QtWidgets from .. import gui, config from .laystruct import LayoutStruct from .dockwidgets import DockContainer, DockTab, DockTag respath = pathlib.Path(config['respath']) logger = logging.getLogger(__name__) class HoverButton(QPushButton): icons = dict() def __init__(self, caption, parent): if caption in HoverButton.icons.keys(): super().__init__('', parent) self.setIcon(HoverButton.icons[caption]) else: super().__init__(caption, parent) self.setAcceptDrops(True) @staticmethod def load_icons(): HoverButton.icons['T'] = QtGui.QIcon(str(respath / 'icons' / 'dock_tab.png')) HoverButton.icons['L'] = QtGui.QIcon(str(respath / 'icons' / 'dock_left.png')) HoverButton.icons['R'] = QtGui.QIcon(str(respath / 'icons' / 'dock_right.png')) HoverButton.icons['U'] = QtGui.QIcon(str(respath / 'icons' / 'dock_up.png')) HoverButton.icons['B'] = QtGui.QIcon(str(respath / 'icons' / 'dock_bottom.png')) def enterEvent(self, event): self.startPreview() def leaveEvent(self, event): self.endPreview() def dragEnterEvent(self, event): event.accept() self.startPreview() def dragLeaveEvent(self, event): self.endPreview() def startPreview(self): self.parent().active_rect_index = self.rect_id self.parent().repaint() def endPreview(self): self.parent().endPreview() def dropEvent(self, event): position = event.pos() event.setDropAction(Qt.MoveAction) event.accept() self.clicked.emit() class DockOverlay(QWidget): def __init__(self, parent, tool=False): self.tool = tool if self.tool: super().__init__(parent=None) self.container = parent self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint) self.setAttribute(Qt.WA_NoSystemBackground) self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowOpacity(1) else: super().__init__(parent=parent) self.container = parent palette = QPalette(self.palette()) palette.setColor(palette.Background, Qt.transparent) self.setPalette(palette) #self.setMouseTracking(True) #self.rects = [] self.active_rect_index = None self.hide() #font = QtWidgets.QApplication.instance().font() fontmetric = QtGui.QFontMetrics(self.font()) fontheight = fontmetric.height() btnsize = int(round(fontheight * 2.5)) // 2 * 2 #Size parameters of the buttons self.btnw = btnsize self.btnh = btnsize self.btnb = btnsize // 2 + 2 self.btnc = btnsize + 2 @property def ezm(self): return self.container.manager def show_and_insert(self, window, insert_node): self.insert_window = window self.insert_node = insert_node container = self.container self.match_geometry(container) self.get_dock_and_button_positions(container) self.show() def find_best_fit(self, lower_container, upper_container): self.match_geometry(lower_container) rects = self.get_dock_positions(lower_container) pos = self.mapFromGlobal(upper_container.mapToGlobal(upper_container.pos())) x, y = pos.x(), pos.y() w, h = upper_container.width(), upper_container.height() diffs = [] for tags_rect in rects: tags, rect = tags_rect caption, panqualid, btnpos = tags rx, ry, rw, rh = rect[0], rect[1], rect[2], rect[3] diff = sum(((rx - x)**2 , (ry - y)**2, (rx + rw - x - w)**2, (ry - y)**2, (rx - x)**2 , (ry + rh - y - h)**2, (rx + rw - x - w)**2, (ry + rh - y - h)**2)) diffs.append((len(diffs), diff)) diffs = sorted(diffs, key= lambda item: item[1]) lowest = diffs[0][0] return rects[lowest] def get_dock_and_button_positions(self, container): self.rects = self.get_dock_positions(container) self.buttons = [] w, h = self.btnw, self.btnh for index, tags_rect in enumerate(self.rects): tags, rect = tags_rect caption, panqualid, pos = tags button = HoverButton(caption, self) button.setGeometry(pos[0]- w//2, pos[1]- h//2, w, h) button.clicked.connect(self.endOverlay) button.rect_id = index self.buttons.append(button) def get_dock_positions(self, container): rects = [] spaceb = self.btnb spacec = self.btnc geo = self.geometry() w, h = geo.width(), geo.height() rects.append((('U', ('top', None), (w/2, spaceb )), (0, 0 , w, h/3))) rects.append((('B', ('bottom', None), (w/2, h-spaceb)), (0, 2*h/3, w, h/3))) rects.append((('L', ('left', None), (spaceb, h/2 )), (0, 0, w/3, h ))) rects.append((('R', ('right', None), (w-spaceb,h/2 )), (2*w/3, 0, w/3, h ))) panelrects = self.get_panel_positions(container) for panel, rect in panelrects: panqualid = (panel.category, panel.panid) pos = self.mapFromGlobal(QtCore.QPoint(rect[0], rect[1])) posx = pos.x() posy = pos.y() w, h = rect[2], rect[3] xc, yc = posx + w/2, posy + h/2 rects.append((('T', ('tab', panqualid), (xc, yc )), (posx, posy, w, h))) rects.append((('U', ('top', panqualid), (xc, yc-spacec)), (posx, posy, w, h/2))) rects.append((('B', ('bottom', panqualid), (xc, yc+spacec)), (posx, posy + h/2, w, h/2))) rects.append((('L', ('left', panqualid), (xc-spacec, yc)), (posx, posy, w/2, h))) rects.append((('R', ('right', panqualid), (xc+spacec, yc)), (posx + w/2, posy, w/2, h))) return rects def get_panel_positions(self, container): rects = [] for cat, panid in container.panelIds: panel = gui.qapp.panels[cat][panid] #TO DO: if panel is part of scrollarea, it is possible # that the panel is not completly visible # So take the visible part. But how? if not panel.isVisible(): continue pos = panel.mapToGlobal(panel.pos()) rect = (panel, (pos.x(), pos.y(), panel.width(), panel.height())) rects.append(rect) return rects def match_geometry(self, window): if self.tool: geo = window.geometry() pos = window.mapToGlobal(geo.topLeft()) self.setGeometry(pos.x(), pos.y(), geo.width(), geo.height()) else: geo = window.geometry() w, h = geo.width(), geo.height() self.setGeometry(0, 0, w, h) def endOverlay(self): if not self.active_rect_index is None: tags, rect = self.rects[self.active_rect_index] caption, panqualid, pos = tags self.ezm.hide_overlays() self.place_node(*panqualid) def endPreview(self): self.active_rect_index = None self.repaint() def mousePressEvent(self, event): self.ezm.hide_overlays() geo = self.insert_window.geometry() geo.moveTo(QCursor.pos()) self.insert_window.setGeometry(geo) self.insert_window.show() def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 127))) if not self.active_rect_index is None: position, rect = self.rects[self.active_rect_index] painter.fillRect(*rect, QBrush(QColor(0, 255, 0, 127))) painter.setPen(QPen(Qt.NoPen)) def place_node(self, relative_pos, refpanqualid): ls = self.container.get_layout_struct() ls.compact() ls.insert_branch(self.insert_node, relative_pos, refpanqualid) #ls.compact() self.insert_window.container.update_layout(LayoutStruct()) self.container.update_layout(ls)
thocoo/gamma-desk
gdesk/ezdock/ezdock.py
<reponame>thocoo/gamma-desk<gh_stars>0 import collections import importlib import pprint import logging import sys from qtpy.QtWidgets import * from qtpy.QtCore import * from qtpy.QtGui import * from qtpy import QtCore, QtGui from .. import gui from ..panels.base import BasePanel from .laystruct import LayoutStruct from .dockwidgets import DockContainer, DockTab, DockTag from .overlay import DockOverlay, HoverButton from ..utils.z_order import get_z_values logger = logging.getLogger(__name__) class DockManager(object): def __init__(self, panels, qapp): self.panels = panels self.qapp = qapp self.containers = dict() self.layoutstructs = dict() self.overlays = [] self.newWindow = lambda name, parentName: gui.qapp.newWindow(name, parentName) self.deleteWindow = lambda w: gui.qapp.deleteWindow(w) self.perspectives = collections.OrderedDict() self.bindGroups = dict() HoverButton.load_icons() def new_container(self, parent=None, name='main'): container = DockContainer(self, parent, name) self.containers[name] = container return container def add_button_to_bindgroup(self, category, panid, button): if not category in self.bindGroups.keys(): self.bindGroups[category] = QButtonGroup(self.qapp) #If old button can still exist #PySide2 doesn't seem to overwrite it, so remove it first existingButton = self.bindGroups[category].button(panid) if not existingButton is None: self.bindGroups[category].removeButton(existingButton) self.bindGroups[category].addButton(button, panid) def detach_all(self): for category, panels in self.panels.items(): for panid, panel in panels.items(): panel.detach() for name, container in self.containers.items(): container.compact() def get_container(self, category, panid): for container in self.containers.values(): if (category, panid) in container.panelIds: return container return None def get_layout_struct_from_containers(self): self.layoutstructs.clear() for name, container in self.containers.items(): self.layoutstructs[name] = container.get_layout_struct() return self.layoutstructs def show_overlays(self, window, insert_node, allWindows=True): if allWindows: for container in self.containers.values(): if not container.isVisible() or container.parent() is window: continue overlay = DockOverlay(container, tool=False) overlay.show_and_insert(window, insert_node) self.overlays.append(overlay) else: container = window.parent().container overlay = DockOverlay(container, tool=False) overlay.show_and_insert(window, insert_node) self.overlays.append(overlay) return len(self.overlays) def drop_in(self, container, hide=True, allWindows=False): window = container.parent() if window.parent() is None: allWindows = True if hide: window.hide() layout = container.get_layout_struct() layout.compact() self.show_overlays(window, layout.root, allWindows) def distribute(self): for container in self.containers.values(): container.distribute() def hide_overlays(self): for overlay in self.overlays: overlay.hide() overlay.deleteLater() self.overlays.clear() def new_window_on_panel(self, panel, parentName=None): layout = LayoutStruct() layout.root = {'type': 'panel', 'category': panel.category, 'id': panel.panid} return self.new_window_using_layout(layout, panel.width(), panel.height(), parentName=parentName) def new_window_using_layout(self, layout, width=640, height=480, parentName=None): w = self.newWindow(None, parentName) geo = w.geometry() geo.setWidth(width) geo.setHeight(height) w.setGeometry(geo) layout.compact() w.container.update_layout(layout) w.show() return w def get_perspective(self): perspective = dict() perspective['panels'] = [] perspective['windows'] = [] for category in self.panels.keys(): for panid, panel in self.panels[category].items(): panelinfo = dict() panelinfo['id'] = panid panelinfo['category'] = category panelinfo['module'] = type(panel).__module__ panelinfo['qualname'] = type(panel).__qualname__ #panelinfo['basewindow'] = panel.baseWindowName panelinfo['title'] = panel.windowTitle() bindings = [] for bindcategory, bindpanid in panel.bindings: binding = dict() binding['category'] = bindcategory binding['id'] = bindpanid bindings.append(binding) panelinfo['bindings'] = bindings perspective['panels'].append(panelinfo) for name, container in self.containers.items(): #window = container.parent() ls = container.get_layout_struct() ls.compact() visible = container.parent().isVisible() perspective['windows'].append({'name': name, 'docks': ls.root, 'visible': visible}) return perspective def set_perspective(self, perspective): self.detach_all() panels = perspective['panels'] #Create panels for panelinfo in panels: category = panelinfo['category'] panid = panelinfo['id'] module = panelinfo['module'] qualname = panelinfo['qualname'] #base_window_name = panelinfo['basewindow'] id_exists = self.panels.id_exists(category, panid) tmp = importlib.import_module(module) for attr in qualname.split('.'): tmp = getattr(tmp, attr) Cls = tmp if id_exists: panel = self.panels[category][panid] if isinstance(panel, Cls): continue else: # Delete of this existing panel # Or keep reference to it in some old_panels dictionary? # So the user can still decide what to do with it # What to do with the panid, rename it available id not used in this perspective? # What to do with the bindings # Or just remap the conflicting panid to a fresh panid logger.warn(f'Panel {category} {panid} already exists but is of wrong class {type(panel)}') persp_cat_panids = set(tmppanel['id'] for tmppanel in panels if tmppanel['category'] == category) exist_cat_panids = set(self.panels[category].keys()) logger.debug(f'Perspective panids of {category}: {persp_cat_panids}') logger.debug(f'Existing panids of {category}: {exist_cat_panids}') continue panel = self.panels.new_panel(Cls, None, panid, floating=True) #Setup of bindings for panelinfo in panels: category = panelinfo['category'] panid = panelinfo['id'] panel = self.panels[category][panid] for binding in panelinfo['bindings']: bindcategory = binding['category'] bindpanid = binding['id'] panel.addBindingTo(bindcategory, bindpanid) for window in perspective['windows']: ls = LayoutStruct() ls.root = window["docks"] visible = window.get('visible', True) #container = self.qapp.windows['main'].container winname = window['name'] if winname in self.qapp.windows.keys(): window = self.qapp.windows[winname] else: window = self.newWindow(None, None) window.container.update_layout(ls) if visible: window.show() window.raise_() else: window.hide() #Put all the floating pannels together in tabs and one seperate window floating_panels = [] floating_panels = [] for category in self.panels.keys(): for panid, panel in self.panels[category].items(): if panel.parent() is None: node = {'type': 'panel', 'category': category, 'id': panid} floating_panels.append(node) if len(floating_panels) > 0: layout = LayoutStruct() layout.root = dict() layout.root['type'] = 'layout' layout.root['category'] = 'tab' layout.root['id'] = 1 layout.root['items'] = floating_panels win = self.new_window_using_layout(layout) win.hide() gui.qapp.deleteEmptyWindows(True) self.panels.reselect_all()
thocoo/gamma-desk
gdesk/utils/ticks.py
import numpy as np def getOptimalMinimumSpacing(minVal, maxVal, scale=1): dif = abs(maxVal - minVal) if dif == 0: return 0 size = dif * scale # decide optimal minor tick spacing in pixels (this is just aesthetics) pixelSpacing = np.log(size+10) * 5 #pixelSpacing = np.log(size+10) * 2 optimalTickCount = size / pixelSpacing if optimalTickCount < 1: optimalTickCount = 1 # optimal minor tick spacing minimumSpacing = dif / optimalTickCount return minimumSpacing * scale def tickSpacing(minimumSpacing=1, noDecimals=False): """Return values describing the desired spacing and offset of ticks. This method is called whenever the axis needs to be redrawn and is a good method to override in subclasses that require control over tick locations. The return value must be a list of three tuples:: [ (major tick spacing, offset), (minor tick spacing, offset), (micro tick spacing, offset), ... ] """ # the largest power-of-10 spacing which is smaller than optimal p10unit = 10 ** np.floor(np.log10(minimumSpacing)) if noDecimals and p10unit < 1: return [5, 1, 1] # (5, 0), # (1, 0), # (1, 0) # ] microInternals = np.array([0.2, 0.4, 1., 2.]) * p10unit minorInternals = np.array([1., 2., 5., 10.]) * p10unit majorInternals = np.array([2., 4., 10., 20.]) * p10unit # Determine major/minor tick spacings which flank the optimal spacing. minorIndex = 3 while minorInternals[minorIndex-1] > minimumSpacing: minorIndex -= 1 # return [ # (majorInternals[minorIndex], 0), # (minorInternals[minorIndex], 0), # (microInternals[minorIndex], 0)] return [majorInternals[minorIndex], minorInternals[minorIndex], microInternals[minorIndex]] def tickValues(minVal, maxVal, scale, minimumSpacing=None, noDecimals=False): """ Return the values and spacing of ticks to draw:: [ (spacing, [major ticks]), (spacing, [minor ticks]), ... ] By default, this method calls tickSpacing to determine the correct tick locations. This is a good method to override in subclasses. """ minVal, maxVal = sorted((minVal, maxVal)) if minimumSpacing == None: minimumSpacing = getOptimalMinimumSpacing(minVal, maxVal, scale) ticks = [] tickLevels = tickSpacing(minimumSpacing / scale, noDecimals) allValues = np.array([]) # for i in range(len(tickLevels)): # spacing, offset = tickLevels[i] offset = 0 for spacing in tickLevels: # determine starting tick start = (np.ceil((minVal-offset) / spacing) * spacing) + offset # determine number of ticks num = int((maxVal-start) / spacing) + 1 values = np.arange(num) * spacing + start # remove any ticks that were present in higher levels # we assume here that if the difference between a tick value and a previously seen tick value # is less than spacing/100, then they are 'equal' and we can ignore the new tick. values = list(filter(lambda x: all(np.abs(allValues-x) > spacing*0.01), values) ) allValues = np.concatenate([allValues, values]) scaledSpacing = spacing * scale ticks.append((scaledSpacing, values)) return ticks class Ticks: def __init__(self, minVal, maxVal, scale, minimumSpacing=None, noDecimals=False): if minimumSpacing == None: self.minimumSpacing = getOptimalMinimumSpacing(minVal, maxVal, scale) else: self.minimumSpacing = minimumSpacing self.noDecimals = noDecimals self.values = [] self.pop_values = [] #to be removed from scene self.push_values = [] #to be added to scene self.update(minVal, maxVal, scale) def update(self, minVal, maxVal, scale): self.spacings = tickSpacing(self.minimumSpacing / scale, self.noDecimals) values = [] self.pop_values = [] #to be removed from scene self.push_values = [] #to be added to scene allValues = np.array([]) #for i in range(len(self.tickLevels)): for spacing in self.spacings: #spacing, offset = self.tickLevels[i] # determine starting tick start = np.ceil(minVal / spacing) # determine number of ticks end = np.floor(maxVal / spacing) + 1 val = np.arange(start, end) * spacing # remove any ticks that were present in higher levels # we assume here that if the difference between a tick value and a previously seen tick value # is less than spacing/100, then they are 'equal' and we can ignore the new tick. val = list(filter(lambda x: all(np.abs(allValues-x) > spacing*0.01), val) ) allValues = np.concatenate([allValues, val]) scaledSpacing = spacing * scale values.append((scaledSpacing, val)) if self.values != []: for i in range(len(values)): old_scaled_spacing, old_values = self.values[i] new_scaled_spacing, new_values = values[i] push_mask = np.in1d(new_values, old_values, invert = True) pop_mask = np.in1d(old_values, new_values, invert = True) self.push_values.append(np.array(new_values)[push_mask]) self.pop_values.append(np.array(old_values)[pop_mask]) else: self.push_values.append(values[0][1]) self.push_values.append(values[1][1]) self.push_values.append(values[2][1]) # if len(self.push_values) != 0: # print('push', self.push_values) # if len(self.pop_values) != 0: # print('pop', self.pop_values) self.values = values
thocoo/gamma-desk
gdesk/dialogs/editpaths.py
<filename>gdesk/dialogs/editpaths.py import re import fnmatch import pathlib from qtpy import QtCore, QtGui, QtWidgets from .base import getMap class PathList(QtWidgets.QListWidget): def __init__(self, parent, paths): super().__init__(parent=parent) for item in paths: list_item = QtWidgets.QListWidgetItem(str(item)) list_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.addItem(list_item) class EditPaths(QtWidgets.QDialog): def __init__(self, paths): super().__init__(None) self.initgui(paths) def initgui(self, paths): self.paths = paths self.selectionlist = PathList(self, paths) self.addPathBtn = QtWidgets.QPushButton('Add', self) self.addPathBtn.clicked.connect(self.add) self.editPathBtn = QtWidgets.QPushButton('Edit', self) self.editPathBtn.clicked.connect(self.edit) self.delPathBtn = QtWidgets.QPushButton('Delete', self) self.delPathBtn.clicked.connect(self.delete) self.okBtn = QtWidgets.QPushButton('Ok', self) self.okBtn.clicked.connect(self.ok) self.cancelBtn = QtWidgets.QPushButton('Cancel', self) self.cancelBtn.clicked.connect(self.cancel) layout = QtWidgets.QVBoxLayout() hlayout = QtWidgets.QHBoxLayout() hlayout.addWidget(self.addPathBtn) hlayout.addWidget(self.editPathBtn) hlayout.addWidget(self.delPathBtn) layout.addLayout(hlayout) hlayout = QtWidgets.QHBoxLayout() layout.addLayout(hlayout) layout.addWidget(self.selectionlist) hlayout = QtWidgets.QHBoxLayout() hlayout.addWidget(self.okBtn) hlayout.addWidget(self.cancelBtn) layout.addLayout(hlayout) self.setLayout(layout) def add(self): path = pathlib.Path(getMap()) item = QtWidgets.QListWidgetItem(str(path)) item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.selectionlist.addItem(item) def edit(self): for item in self.selectionlist.selectedItems(): path = item.text() path = pathlib.Path(getMap(path)) item.setText(path) def delete(self): for item in self.selectionlist.selectedItems(): self.selectionlist.takeItem(self.selectionlist.row(item)) def ok(self): self.updatePaths() self.done(QtWidgets.QDialog.DialogCode.Accepted) def cancel(self): self.done(QtWidgets.QDialog.DialogCode.Rejected) def updatePaths(self): self.paths.clear() for index in range(self.selectionlist.count()): item = self.selectionlist.item(index) self.paths.append(item.text())
thocoo/gamma-desk
gdesk/widgets/thumbs.py
from qtpy import QtCore, QtGui, QtWidgets from qtpy.QtCore import Qt class Thumbs(QtWidgets.QListWidget): def __init__(self, parent): super().__init__(parent=parent) #self.setViewMode(QtWidgets.QListWidget.IconMode) self.setViewMode(QtWidgets.QListWidget.ListMode) self.setIconSize(QtCore.QSize(256, 256)) self.setResizeMode(QtWidgets.QListWidget.Adjust) def addQImage(self, qimg, title): pixmap = QtGui.QPixmap(qimg) self.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(pixmap), title))
thocoo/gamma-desk
gdesk/live/__version__.py
from .. import __version__, __version_info__ VERSION_INFO = __version__ VERSION = __version_info__
thocoo/gamma-desk
gdesk/panels/imgview/roi.py
# -*- coding: latin-1 -*- #------------------------------------------------------------------------------- # Name: imageport.roi # Purpose: Region of Interest # # Author: <NAME> # # Created: 01/08/2014 # Copyright: (c) <NAME> 2014 # Licence: <your licence> #------------------------------------------------------------------------------- from qtpy import QtCore, QtGui, QtWidgets from ... import config AUTO_APPLY = False class SelRoiWidget(QtWidgets.QWidget): """ Selection widget of a region of interest. """ roiChanged = QtCore.Signal() roiRemoved = QtCore.Signal() def __init__(self, parent=None): #width and height are the dimensions of the image (not the roi) super().__init__(parent=parent) self.phase = 0 self.solidColor = QtCore.Qt.white self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.newPhase) self.timer.setSingleShot(True) self.setMouseTracking(True) # is this timer also active when roi isn't visible ??? self.initProps() self.initUI() self.hide() def initUI(self): self.scaleCursor = QtGui.QCursor(QtCore.Qt.SizeAllCursor) self.fillColor = QtGui.QColor(*config['roi color']) self.dashColor = QtGui.QColor(*config['roi color']) self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, False) self.get_context_menu = lambda: None @property def vd(self): return self.parent().vd @property def selroi(self): return self.vd.selroi def initProps(self): self.dragSliceStartX = self.selroi.xr.start self.dragSliceStartY = self.selroi.yr.start self.dragStartX = 0 self.dragStartY = 0 self.mouseRightWasDown = False self.mouseMidWasDown = False self.mouseDoubleClicked = False self.overscan = 5 self.createState = False def selectAll(self): self.selroi.reset() self.selroi.update_statistics() self.recalcGeometry() def newPhase(self): self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, True) self.phase = (self.phase + 1) % 8 #self.parent().setUpdatesEnabled(False) #self.setUpdatesEnabled(True) #self.blockSignals(True) self.repaint(0,self.overscan,self.width(),1) self.repaint(self.overscan,0,1,self.height()) self.repaint(0,self.height()-self.overscan-1,self.width(),1) self.repaint(self.width()-self.overscan-1,0,1,self.height()) self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, False) #self.update() #self.parent().blockSignals(False) self.timer.start(100) #self.parent().setUpdatesEnabled(True) def setStartEndPoints(self, startX, startY, endX, endY): startX = int(round(startX)) startY = int(round(startY)) endX = int(round(endX)) endY = int(round(endY)) if (startX > endX) and (startY > endY): pass else: if startY > endY: startY = endY if startX > endX: startX = endX self.selroi.xr.start = startX self.selroi.xr.stop = endX + 1 self.selroi.yr.start = startY self.selroi.yr.stop = endY + 1 self.clip() def clip(self): self.selroi.ensure_rising() self.selroi.clip() self.selroi.update_statistics() self.recalcGeometry() def asSliceTupple(self): return (slice(self.selroi.xr.start, self.selroi.xr.stop), \ slice(self.selroi.yr.start, self.selroi.yr.stop)) def recalcGeometry(self): x0 = round((self.selroi.xr.start - self.parent().dispOffsetX) * self.parent().zoomValue) y0 = round((self.selroi.yr.start - self.parent().dispOffsetY) * self.parent().zoomValue) x1 = round((self.selroi.xr.stop - self.parent().dispOffsetX) * self.parent().zoomValue) y1 = round((self.selroi.yr.stop - self.parent().dispOffsetY) * self.parent().zoomValue) width = max(abs(x1 - x0),1) height = max(abs(y1 - y0),1) self.setGeometry(min(x0,x1)-self.overscan, min(y0,y1)-self.overscan, width+2*self.overscan, height+2*self.overscan) def mousePressEvent(self, event): if (event.buttons() == QtCore.Qt.RightButton) and \ not self.createState: #check if we are not doing setStartEndPoints self.createState = True self.edgePosition = self.checkNearEdge(event) self.setCursorShape(self.edgePosition) self.dragStartX = event.globalX() self.dragStartY = event.globalY() self.dragSliceStartX = self.selroi.xr.start self.dragSliceStartY = self.selroi.yr.start self.dragSliceEndX = self.selroi.xr.stop self.dragSliceEndY = self.selroi.yr.stop self.mouseRightWasDown = True self.repaint() elif (event.buttons() == QtCore.Qt.MidButton): self.dragStartX = event.globalX() self.dragStartY = event.globalY() self.mouseMidWasDown = True #propagated up the parent widget event.ignore() else: #propagated up the parent widget event.ignore() def checkNearEdge(self, event): x = event.pos().x() y = event.pos().y() (x0, y0, x1, y1) = self.getRelativeCoord() if abs(x0 - x1) <= 10: hori = 1 elif abs(x0 - x) < 5: hori = 0 elif abs(x1 - x) < 5: hori = 2 else: hori = 1 if abs(y0 - y1) <= 10: vert = 1 elif abs(y0 - y) < 5: vert = 0 elif abs(y1 - y) < 5: vert = 2 else: vert = 1 return vert * 3 + hori def setCursorShape(self, edgePosition): if edgePosition in (0, 8): self.setCursor(QtCore.Qt.SizeFDiagCursor) elif edgePosition in (1, 7): self.setCursor(QtCore.Qt.SizeVerCursor) elif edgePosition in (2, 6): self.setCursor(QtCore.Qt.SizeBDiagCursor) elif edgePosition in (3, 5): self.setCursor(QtCore.Qt.SizeHorCursor) elif edgePosition == 4: self.setCursor(QtCore.Qt.SizeAllCursor) def getMouseShifts(self, event, manhattan=False): if manhattan: if abs(self.dragStartX - event.globalX()) > abs(self.dragStartY - event.globalY()): self.dragEndX = event.globalX() self.dragEndY = self.dragStartY else: self.dragEndX = self.dragStartX self.dragEndY = event.globalY() else: self.dragEndX = event.globalX() self.dragEndY = event.globalY() shiftX = round((self.dragEndX - self.dragStartX) / self.parent().zoomValue) shiftY = round((self.dragEndY - self.dragStartY) / self.parent().zoomValue) return (shiftX, shiftY) def mouseMoveEvent(self, event): if event.buttons() == QtCore.Qt.RightButton: if event.modifiers() & QtCore.Qt.ShiftModifier: shiftX, shiftY = self.getMouseShifts(event, manhattan=True) else: shiftX, shiftY = self.getMouseShifts(event, manhattan=False) if self.edgePosition == 0: self.setStartEndPoints(self.dragSliceStartX + shiftX, self.dragSliceStartY + shiftY,\ self.dragSliceEndX -1, self.dragSliceEndY -1) elif self.edgePosition == 1: self.setStartEndPoints(self.dragSliceStartX, self.dragSliceStartY + shiftY,\ self.dragSliceEndX -1, self.dragSliceEndY -1) elif self.edgePosition == 2: self.setStartEndPoints(self.dragSliceStartX, self.dragSliceStartY + shiftY,\ self.dragSliceEndX + shiftX - 1, self.dragSliceEndY -1) elif self.edgePosition == 3: self.setStartEndPoints(self.dragSliceStartX + shiftX, self.dragSliceStartY,\ self.dragSliceEndX - 1, self.dragSliceEndY -1) elif self.edgePosition == 4: #moving #limiting the shift to the borders of the image if (self.dragSliceStartX + shiftX) < 0: shiftX = - self.dragSliceStartX if (self.dragSliceEndX + shiftX - 1) >= self.selroi.xr.maxstop: shiftX = self.selroi.xr.maxstop - self.dragSliceEndX if (self.dragSliceStartY + shiftY) < 0: shiftY = - self.dragSliceStartY if (self.dragSliceEndY + shiftY - 1) >= self.selroi.yr.maxstop: shiftY = self.selroi.yr.maxstop - self.dragSliceEndY self.setStartEndPoints(self.dragSliceStartX + shiftX, self.dragSliceStartY + shiftY,\ self.dragSliceEndX + shiftX - 1, self.dragSliceEndY + shiftY - 1) elif self.edgePosition == 5: self.setStartEndPoints(self.dragSliceStartX, self.dragSliceStartY,\ self.dragSliceEndX + shiftX - 1, self.dragSliceEndY -1) elif self.edgePosition == 6: self.setStartEndPoints(self.dragSliceStartX + shiftX, self.dragSliceStartY,\ self.dragSliceEndX - 1, self.dragSliceEndY + shiftY - 1) elif self.edgePosition == 7: self.setStartEndPoints(self.dragSliceStartX, self.dragSliceStartY,\ self.dragSliceEndX - 1, self.dragSliceEndY + shiftY - 1) elif self.edgePosition == 8: self.setStartEndPoints(self.dragSliceStartX, self.dragSliceStartY,\ self.dragSliceEndX + shiftX - 1, self.dragSliceEndY + shiftY - 1) self.repaint() else: event.ignore() def mouseReleaseEvent(self, event): self.createState = False contextMenu = self.get_context_menu() if self.mouseRightWasDown: self.mouseRightWasDown = False shiftX, shiftY = self.getMouseShifts(event) if (shiftX == 0) and (shiftY == 0): pos = QtGui.QCursor.pos() pos.setX(pos.x() - 10) pos.setY(pos.y() - 10) if not contextMenu is None: contextMenu.exec_(pos) #return None #self.parent().myContextMenuEvent(event) else: self.clip() if AUTO_APPLY: self.applyRoi() self.roiChanged.emit() if self.mouseMidWasDown: self.mouseMidWasDown = False shiftX, shiftY = self.getMouseShifts(event) if (shiftX == 0) and (shiftY == 0): self.parent().zoomAuto() self.unsetCursor() self.repaint() event.ignore() def release_creation(self): self.createState = False self.clip() if AUTO_APPLY: self.applyRoi() self.roiChanged.emit() self.repaint() def hideRoi(self): self.selroi.reset() if AUTO_APPLY: self.applyRoi() self.hide() self.unsetCursor() self.roiRemoved.emit() self.repaint() def applyRoi(self): self.parent().vd.applyroi() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawRoi(qp) qp.end() def getRelativeCoord(self): x0 = self.overscan y0 = self.overscan x1 = self.size().width()-1-self.overscan y1 = self.size().height()-1-self.overscan return (x0, y0, x1, y1) def drawRoi(self, qp): pensolid = QtGui.QPen(self.solidColor, 1, QtCore.Qt.SolidLine) pendash = QtGui.QPen(self.dashColor, 1, QtCore.Qt.CustomDashLine) ## pendash.setDashPattern([3, 3, 1, 5, 3, 3, 5, 1]) pendash.setDashPattern([4,4]) x0 = self.overscan y0 = self.overscan #max-> keep is visible even if it is smaller then 1x1 x1 = max(self.size().width() - 1 - self.overscan, x0 + 1) y1 = max(self.size().height() - 1 - self.overscan, y0 + 1) pendash.setDashOffset(8-self.phase) polygonRect = QtGui.QPolygon() polygonNe = QtGui.QPolygon() polygonSw = QtGui.QPolygon() polygonRect << QtCore.QPoint(x0, y0) << QtCore.QPoint(x1, y0)\ << QtCore.QPoint(x1, y1) << QtCore.QPoint(x0, y1) polygonNe << QtCore.QPoint(x0, y0) << QtCore.QPoint(x1, y0)\ << QtCore.QPoint(x1, y1) polygonSw << QtCore.QPoint(x0, y0) << QtCore.QPoint(x0, y1)\ << QtCore.QPoint(x1, y1) if self.createState: self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, False) qp.setOpacity(0.25) qp.fillRect(x0, y0, x1-x0+1, y1-y0+1, self.fillColor) qp.setOpacity(0.5) else: qp.setOpacity(1.0) self.timer.start(100) qp.setPen(pensolid) qp.drawPolygon(polygonRect) qp.setPen(pendash) qp.drawPolyline(polygonNe) qp.drawPolyline(polygonSw) #self.parent().blockSignals(False)
thocoo/gamma-desk
gdesk/core/shellmod.py
import sys import os import threading import multiprocessing import builtins import logging import traceback import queue import subprocess import pprint import shlex import json import psutil import inspect import shlex from pathlib import Path from . import stdinout from .interpreter import QueueInterpreter from .stdinout import ProcessStdInput from .gui_proxy import gui from .conf import config from .history import LogDir from ..utils.names import DictStruct from ..rectable import RecordTable from ..live import use, manager if config['console']['completer'] == 'native': from rlcompleter import Completer else: from ..live.completer import Completer here = Path(__file__).absolute().parent logger = logging.getLogger(__name__) class Shell(object): instance = None def __init__(self, workspace=None): self.wsdict = dict() if workspace is None else workspace self.ws = DictStruct(self.wsdict) Shell.instance = self self.wsdict['shell'] = self self.wsdict['gui'] = gui self.wsdict['use'] = use self.wsdict['__name__'] = '__main__' self.redirect_stdout() self.redirect_input() self.comp = Completer(self.wsdict) self.interpreters = dict() self.logdir = LogDir(config['path_log']) def redirect_stdout(self): if not config['debug']['skip_main_stdout_redirect']: current_stdout = sys.stdout sys.stdout = self.stdout = stdinout.StdOutRouter() sys.stdout.backup_stream = current_stdout stdinout.enable_ghstream_handler() if not config['debug']['skip_main_stderr_redirect']: current_stderr = sys.stderr sys.stderr = self.stderr = stdinout.StdErrRouter() sys.stderr.backup_stream = current_stderr def get_watcher_ports(self): lock_files = self.logdir.get_active_lock_files() lock_files = sorted(lock_files, key=os.path.getmtime) ports = [] for lock_file in lock_files: info_file = lock_file.parent / 'cmdserver.json' if not info_file.exists(): continue with open(str(info_file), 'r') as fp: content = json.load(fp) ports.append(content['port']) return ports @property def _qapp(self): from qtpy.QtWidgets import QApplication return QApplication.instance() def redirect_input(self): #ProcessStdInput is missing some function #to be a good overwrite of sys.stdin. But it is not needed to overwrite sys.stdin #Only, overwriting builtins.input is good enough #(original input function doesn't seem to be compatible with ProcessStdInput) self.stdin = ProcessStdInput() self.__input__ = builtins.input builtins.input = self.input sys.displayhook = sys.__displayhook__ def restore_stdout(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ #The following is used to customize the repr functionaility #It also stores to _ sys.displayhook = sys.__displayhook__ def restore_input(self): builtins.input = self.__input__ def info(self): """ Print info about the current process """ prc = psutil.Process(os.getpid()) pyprc = multiprocessing.current_process() print(f'name: {prc.name()}') print(f'pname: {pyprc.name}') print(f'exe: {prc.exe()}') print(f'argv: {sys.argv}') print(f'cwd: {prc.cwd()}') print(f'pid: {prc.pid}') print(f'ppid: {prc.ppid()}') print(f'mem rss: {prc.memory_info().rss}') print(f'#threads: {prc.num_threads()}') this_thread = threading.currentThread() print(f'thread name: {this_thread.name}') print(f'tid: {this_thread.ident}') def this_interpreter(self): """ Return the interpreter related to this thread. """ tid = threading.get_ident() #TO DO, support for other threads which are not in a console ? # what about the stdout of these threads return self.interpreters.get(tid, None) def edit_file(self, filename, lineno=0): """ Edit the file with an external editor at a certain lineno. """ editorExecutable = Path(config['texteditor']) if not editorExecutable.exists(): logger.error(f"{editorExecutable} doesn't exist") return if editorExecutable.name == 'notepad++.exe': # supply line number argument os.spawnl(os.P_NOWAIT, editorExecutable, '"' + str(editorExecutable) + '"', '-n%d'%lineno, '"{0}"'.format(filename)) else: os.spawnl(os.P_NOWAIT, editorExecutable, '"' + str(editorExecutable) + '"', '"{0}"'.format(filename)) def edit_dbase(self, filename): """ Edit a SQLite file with an external editor. """ executable = config['dbbrowser'] os.spawnl(os.P_NOWAIT, executable, '"' + executable + '"', '"{0}"'.format(filename)) def edit(self, object): """ Edit source file of object with external editor :param objects: object from which the source code will be opened in an editor :return: None """ object_type_name = type(object).__name__ if object_type_name == 'ImageDataManager': self.edit_dbase(object.fullpath) return (filename, lineno) = self.getcodefile(object) if not filename is None: logger.info('opening "%s" with editor at line %d' % (filename, lineno)) self.edit_file(filename, lineno) else: logger.warn('Could not find the file for object') def getcodefile(self, object): """ Find out which source or compiled file an object was defined in. """ fi = None lineno = 0 if hasattr(object, 'ls_code'): #it is a script callable code = object.func.__code__ fi = code.co_filename lineno = code.co_firstlineno elif hasattr(object, '__func__'): code = object.__func__.__code__ fi = code.co_filename lineno = code.co_firstlineno else: if hasattr(object, '__wrapped__'): object = object.__wrapped__ try: fi = inspect.getsourcefile(object) except: fi = None if fi is None: fi = inspect.getsourcefile(type(object)) if hasattr(object, '__code__'): try: lineno = object.__code__.co_firstlineno except: lineno = 1 else: try: lineno = inspect.getlineno(object) except AttributeError: lineno = 1 return (fi, lineno) @staticmethod def new_interactive_thread(cqs, guiproxy=None, client=True, console_id=None): shell = Shell.instance if client and type(cqs).__name__ == 'ZmqQueues': cqs.setup_as_client() thread = threading.Thread(target=QueueInterpreter.create_and_interact, args=(shell, cqs, guiproxy, console_id), name='Interact',daemon=True) thread.start() return (thread.name, thread.ident) def popen(self, commands, shell=True, stdin=True): #https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/ if isinstance(commands, str): commands = shlex.split(commands) def output_reader(proc): for line in iter(proc.stdout.readline, b''): sys.stdout.write(line.decode('utf-8')) sys.stdout.flush() print(f'{commands[0]}: stdout ended') #sys.stdout.redirects.pop(threading.get_ident()) def stderr_reader(proc): for line in iter(lambda: proc.stderr.read(1), b''): sys.stderr.write(line.decode('utf-8')) sys.stderr.flush() print(f'{commands[0]}: stderr ended') #sys.stderr.redirects.pop(threading.get_ident()) if stdin: process = subprocess.Popen(commands, stdin=subprocess.PIPE, stdout= subprocess.PIPE, stderr= subprocess.PIPE, shell=shell) else: process = subprocess.Popen(commands, stdout= subprocess.PIPE, stderr= subprocess.PIPE, shell=shell) stdout_thread = threading.Thread(target=output_reader, args=(process,)) stdout_thread.start() stderr_thread = threading.Thread(target=stderr_reader, args=(process,)) stderr_thread.start() sys.stdout.copy_to_thread(stdout_thread.ident) sys.stderr.copy_to_thread(stderr_thread.ident) while True: cmd = input('') if cmd == '': break process.stdin.write(cmd.encode() + '\n'.encode()) process.stdin.flush() process.stdin.close() process.terminate() def pty(self, command='cmd', cwd=None, textmode='ansi'): """ Setup a virtual terminal. Stdout of the executing process live printed. textmode = 'ansi' or 'raw' """ from winpty import PtyProcess #install pywinpty #The orginal terminal is killed or hidden? #logging.root.handlers[0] becomes invalid? if isinstance(logging.root.handlers[0], logging.StreamHandler): logging.root.handlers.pop(0) #WINPTY_SHOW_CONSOLE to 1 os.environ['WINPTY_SHOW_CONSOLE'] = '1' #proc = PtyProcess.spawn(command, cwd=cwd) proc = PtyProcess.spawn(command) def output_reader(proc): #PTYESC = '\033]' while proc.isalive(): text = proc.readline() sys.stdout._write_mode(text, textmode) stdout_thread = threading.Thread(target=output_reader, args=(proc,)) stdout_thread.start() sys.stdout.copy_to_thread(stdout_thread.ident) while proc.isalive(): try: cmd = input('', timeout=1) proc.write(cmd + '\r\n') except queue.Empty: pass # def ipython(self): # from IPython.terminal.embed import InteractiveShellEmbed # ishell = InteractiveShellEmbed() # stdout_back = sys.stdout # ishell.interact() # sys.stdout = stdout_back # def jupyter(self, rundir=''): # JUPYTER_DATA_DIR = str(here.parent / 'external' / 'jupyter' / 'data') # logger.info(f'JUPYTER_DATA_DIR: {JUPYTER_DATA_DIR}') # os.environ['JUPYTER_DATA_DIR'] = JUPYTER_DATA_DIR # os.system(f'start {sys.executable} -m jupyterlab --notebook-dir="{rundir}"') def pprint(self, var): """ Do a `pretty print <https://docs.python.org/3.8/library/pprint.html>`_ of var. The user can also use `var!!` to call this function. """ pprint.pprint(var) def magic(self, cmd): """ Magic commands like in IPython. """ cmd, *args = shlex.split(cmd) if cmd == 'cd': os.chdir(args[0]) elif cmd == 'pwd': print(Path('.').resolve()) elif cmd in ['ls', 'dir']: self.popen('dir') elif cmd == 'tb': traceback.print_last() elif cmd == 'info': self.info() elif cmd == 'who': tbl = RecordTable(['name', 'repr', 'str']) for key in list(self.wsdict.keys()): if key.startswith('_'): continue obj = self.wsdict[key] tbl.add_row((key, repr(obj), str(obj))) print(tbl) def start_in_this_thread(self, cqs, console_id=None): QueueInterpreter.create_and_interact(self, cqs, None, console_id) @staticmethod def get_completer_data(text, max=1000, wild=False): shell = Shell.instance items = [] for state in range(max): if shell.comp.complete.__func__.__code__.co_argcount == 3: #The Python Original rlcompleter item = shell.comp.complete(text, state) else: item = shell.comp.complete(text, state, wild) if item is None: break items.append(item) return items def input(self, message='', timeout=None): ident = threading.get_ident() if ident in self.interpreters.keys(): if gui.is_main(): return gui.inputdlg(message) else: prior_console_mode = gui.console.set_mode('input') print(message, end='') mode, args, callback = self.stdin.read(timeout=timeout) gui.console.set_mode(prior_console_mode) return args[0] else: return self.__input__(message) def execfile(self, filepath, globals=None, locals=None): """ Execute a Python file """ filepath = str(Path(filepath).absolute()) source = open(filepath, 'r').read() code = compile(source, filepath, 'exec') exec(code, globals, locals) def execfilews(self, filepath, wsname='__execfilews__'): """ Execute a Python file in a new workspace. Place the workspace in shell """ filepath = str(Path(filepath).absolute()) ws = dict() ws['__file__'] = filepath self.execfile(filepath, ws) self.wsdict[wsname] = ws return ws @staticmethod def set_logger_level(level=20): root = logging.getLogger() root.setLevel(level) for handler in root.handlers: handler.setLevel(level) @staticmethod def get_sys_paths(customs_only=True): """ List the sys.paths. :param bool customs_only: List only paths not part of the python.exe directory. """ base = Path(sys.executable).parent custom_paths = [] for path in sys.path: path = Path(path) if customs_only: if base in path.parents: continue elif base == path: continue elif path == Path('.'): continue custom_paths.append(str(path)) return custom_paths @staticmethod def set_sys_paths(new_sys_paths): """ Set new content for sys.path. """ sys.path.clear() sys.path.extend(new_sys_paths) print(f'The new paths are {sys.path}') @staticmethod def add_sys_paths(sys_paths): for path in sys_paths: if not path in sys.path: sys.path.append(path) @staticmethod def get_live_paths(): #from ..live import manager return manager.path.copy() @staticmethod def set_live_paths(new_live_paths): #from ..live import manager manager.path.clear() manager.path.extend(new_live_paths) print(f'The new live paths are {manager.path}')
thocoo/gamma-desk
gdesk/dialogs/filterlist.py
import re import fnmatch from qtpy import QtCore, QtGui, QtWidgets class SelectionList(QtWidgets.QListWidget): def __init__(self, parent): super().__init__(parent=parent) class FilterList(QtWidgets.QDialog): def __init__(self, items, multiple=True, filter='*'): super().__init__(None) self.initgui(items, multiple, filter) def initgui(self, items, multiple, filter): self.selectionlist = SelectionList(self) self.items = items self.changeSelectStateAllBtn = QtWidgets.QPushButton('Check none', self) self.changeSelectStateAllBtn.clicked.connect(self.toggleCheckStateAll) self.filter = QtWidgets.QLineEdit(filter, self) self.useregexpr = QtWidgets.QCheckBox('RegExp', self) self.addSelectByFilterBtn = QtWidgets.QPushButton('Add', self) self.addSelectByFilterBtn.clicked.connect(self.addSelectByFilter) self.removeSelectByFilterBtn = QtWidgets.QPushButton('Remove', self) self.removeSelectByFilterBtn.clicked.connect(self.removeSelectByFilter) if not multiple: self.changeSelectStateAllBtn.hide() self.filter.hide() self.useregexpr.hide() self.addSelectByFilterBtn.hide() self.removeSelectByFilterBtn.hide() self.okBtn = QtWidgets.QPushButton('Ok', self) self.okBtn.clicked.connect(self.ok) self.cancelBtn = QtWidgets.QPushButton('Cancel', self) self.cancelBtn.clicked.connect(self.cancel) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.changeSelectStateAllBtn) layout.addWidget(self.filter) hlayout = QtWidgets.QHBoxLayout() layout.addLayout(hlayout) hlayout.addWidget(self.useregexpr) hlayout.addWidget(self.addSelectByFilterBtn) hlayout.addWidget(self.removeSelectByFilterBtn) layout.addWidget(self.selectionlist) hlayout = QtWidgets.QHBoxLayout() layout.addLayout(hlayout) hlayout.addWidget(self.okBtn) hlayout.addWidget(self.cancelBtn) self.setLayout(layout) for item in self.items: list_item = QtWidgets.QListWidgetItem(str(item)) if multiple: list_item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) else: list_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.selectionlist.addItem(list_item) def checkedItems(self): selection = [] for i in range(self.selectionlist.count()): uiitem = self.selectionlist.item(i) if uiitem.checkState() == QtCore.Qt.Checked: selection.append(self.items[i]) return selection def selectedItem(self): for i in range(self.selectionlist.count()): uiitem = self.selectionlist.item(i) if uiitem.isSelected(): return self.items[i] return None def selectItem(self, item): for i in range(self.selectionlist.count()): selection_item = self.selectionlist.item(i) if self.items[i] == item: selection_item.setSelected(True) self.selectionlist.scrollToItem(selection_item) return def toggleCheckStateAll(self): if self.changeSelectStateAllBtn.text() == 'Check all': state = True self.changeSelectStateAllBtn.setText('Check none') self.checkAll(state) elif self.changeSelectStateAllBtn.text() == 'Check none': state = False self.changeSelectStateAllBtn.setText('Check all') self.checkAll(state) def addSelectByFilter(self): use_regexp = self.useregexpr.isChecked() self.checkItemsFilterMatch(self.filter.text(), append=True, remove=False, use_regexp=use_regexp) def removeSelectByFilter(self): use_regexp = self.useregexpr.isChecked() self.checkItemsFilterMatch(self.filter.text(), append=False, remove=True, use_regexp=use_regexp) def checkItems(self, items_to_select): for i in range(self.selectionlist.count()): selection_item = self.selectionlist.item(i) if self.items[i] in items_to_select: selection_item.setCheckState(QtCore.Qt.Checked) else: selection_item.setCheckState(QtCore.Qt.Unchecked) def checkItemsRe(self, pattern, append=True, remove=True): self.checkItemsFilterMatch(pattern, append, remove, use_regexp=True) def checkItemsFilterMatch(self, pattern, append=True, remove=True, use_regexp=False): def matches_fn(item): return fnmatch.fnmatch(item, pattern) def matches_regexp(item): return not re.match(pattern, str(item)) is None if use_regexp: matchfunc = matches_regexp else: matchfunc = matches_fn for i in range(self.selectionlist.count()): selection_item = self.selectionlist.item(i) item = self.items[i] matches = matchfunc(item) #checked = selection_item.getChecked() if append and remove: if matches: selection_item.setCheckState(QtCore.Qt.Checked) else: selection_item.setCheckState(QtCore.Qt.Unchecked) elif append: if matches: selection_item.setCheckState(QtCore.Qt.Checked) elif remove: if matches: selection_item.setCheckState(QtCore.Qt.Unchecked) def checkAll(self, state=True): if state: newstate = QtCore.Qt.Checked else: newstate = QtCore.Qt.Unchecked for i in range(self.selectionlist.count()): item = self.selectionlist.item(i) item.setCheckState(newstate) def ok(self): self.done(QtWidgets.QDialog.DialogCode.Accepted) def cancel(self): self.done(QtWidgets.QDialog.DialogCode.Rejected)
thocoo/gamma-desk
gdesk/rectable/__init__.py
from .base import RecordTable
thocoo/gamma-desk
gdesk/panels/imgview/demosaic.py
<gh_stars>0 import numpy as np from scipy.ndimage.filters import convolve #https://github.com/colour-science def as_float_array(array): return array.astype('double') def masks_CFA_Bayer(shape, pattern='RGGB'): """ Returns the *Bayer* CFA red, green and blue masks for given pattern. Parameters ---------- shape : array_like Dimensions of the *Bayer* CFA. pattern : unicode, optional **{'RGGB', 'BGGR', 'GRBG', 'GBRG'}**, Arrangement of the colour filters on the pixel array. Returns ------- tuple *Bayer* CFA red, green and blue masks. Examples -------- >>> from pprint import pprint >>> shape = (3, 3) >>> pprint(masks_CFA_Bayer(shape)) (array([[ True, False, True], [False, False, False], [ True, False, True]], dtype=bool), array([[False, True, False], [ True, False, True], [False, True, False]], dtype=bool), array([[False, False, False], [False, True, False], [False, False, False]], dtype=bool)) >>> pprint(masks_CFA_Bayer(shape, 'BGGR')) (array([[False, False, False], [False, True, False], [False, False, False]], dtype=bool), array([[False, True, False], [ True, False, True], [False, True, False]], dtype=bool), array([[ True, False, True], [False, False, False], [ True, False, True]], dtype=bool)) """ pattern = pattern.upper() channels = dict((channel, np.zeros(shape)) for channel in 'RGB') for channel, (y, x) in zip(pattern, [(0, 0), (0, 1), (1, 0), (1, 1)]): channels[channel][y::2, x::2] = 1 return tuple(channels[c].astype(bool) for c in 'RGB') def bayer_split(array, pattern='RGGB'): assert array.ndim == 2 original_type = array.dtype R_m, G_m, B_m = masks_CFA_Bayer(array.shape, pattern) R = array * R_m G = array * G_m B = array * B_m procarr = np.ndarray(list(array.shape) + [3], original_type) procarr[:,:,0] = R procarr[:,:,1] = G procarr[:,:,2] = B return procarr def demosaicing_CFA_Bayer_bilinear(CFA, pattern='RGGB'): """ Returns the demosaiced *RGB* colourspace array from given *Bayer* CFA using bilinear interpolation. Parameters ---------- CFA : array_like *Bayer* CFA. pattern : unicode, optional **{'RGGB', 'BGGR', 'GRBG', 'GBRG'}**, Arrangement of the colour filters on the pixel array. Returns ------- ndarray *RGB* colourspace array. Notes ----- - The definition output is not clipped in range [0, 1] : this allows for direct HDRI / radiance image generation on *Bayer* CFA data and post demosaicing of the high dynamic range data as showcased in this `Jupyter Notebook <https://github.com/colour-science/colour-hdri/\ blob/develop/colour_hdri/examples/\ examples_merge_from_raw_files_with_post_demosaicing.ipynb>`__. References ---------- :cite:`Losson2010c` Examples -------- >>> import numpy as np >>> CFA = np.array( ... [[0.30980393, 0.36078432, 0.30588236, 0.3764706], ... [0.35686275, 0.39607844, 0.36078432, 0.40000001]]) >>> demosaicing_CFA_Bayer_bilinear(CFA) array([[[ 0.69705884, 0.17941177, 0.09901961], [ 0.46176472, 0.4509804 , 0.19803922], [ 0.45882354, 0.27450981, 0.19901961], [ 0.22941177, 0.5647059 , 0.30000001]], <BLANKLINE> [[ 0.23235295, 0.53529412, 0.29705883], [ 0.15392157, 0.26960785, 0.59411766], [ 0.15294118, 0.4509804 , 0.59705884], [ 0.07647059, 0.18431373, 0.90000002]]]) >>> CFA = np.array( ... [[0.3764706, 0.360784320, 0.40784314, 0.3764706], ... [0.35686275, 0.30980393, 0.36078432, 0.29803923]]) >>> demosaicing_CFA_Bayer_bilinear(CFA, 'BGGR') array([[[ 0.07745098, 0.17941177, 0.84705885], [ 0.15490197, 0.4509804 , 0.5882353 ], [ 0.15196079, 0.27450981, 0.61176471], [ 0.22352942, 0.5647059 , 0.30588235]], <BLANKLINE> [[ 0.23235295, 0.53529412, 0.28235295], [ 0.4647059 , 0.26960785, 0.19607843], [ 0.45588237, 0.4509804 , 0.20392157], [ 0.67058827, 0.18431373, 0.10196078]]]) """ original_type = CFA.dtype CFA = as_float_array(CFA) R_m, G_m, B_m = masks_CFA_Bayer(CFA.shape, pattern) H_G = np.array( [[0, 1, 0], [1, 4, 1], [0, 1, 0]], 'double') / 4 # yapf: disable H_RB = np.array( [[1, 2, 1], [2, 4, 2], [1, 2, 1]], 'double') / 4 # yapf: disable R = convolve(CFA * R_m, H_RB) G = convolve(CFA * G_m, H_G) B = convolve(CFA * B_m, H_RB) procarr = np.ndarray(list(CFA.shape) + [3], original_type) procarr[:,:,0] = R procarr[:,:,1] = G procarr[:,:,2] = B return procarr
thocoo/gamma-desk
gdesk/panels/levels/__init__.py
<reponame>thocoo/gamma-desk from ... import config if config['qapp']: from .panel import LevelsPanel
thocoo/gamma-desk
gdesk/utils/imconvert.py
<filename>gdesk/utils/imconvert.py import numpy as np from qtpy import PYSIDE, PYSIDE2, PYQT4, PYQT5 from qtpy import QtGui, QtCore from .shared import SharedArray try: from .numba_func import map_values_mono, map_values_rgbswap, map_values_rgb, nb_float_offset_gain_gamma_8bit has_numba = True except: has_numba = False if has_numba: use_numba = True else: use_numba = False colormaps = ['grey', 'clip', 'turbo', 'jet', 'invert', 'hot', 'cold'] turbo_colormap_data = [ [0.18995,0.07176,0.23217],[0.19483,0.08339,0.26149],[0.19956,0.09498,0.29024],[0.20415,0.10652,0.31844], [0.20860,0.11802,0.34607],[0.21291,0.12947,0.37314],[0.21708,0.14087,0.39964],[0.22111,0.15223,0.42558], [0.22500,0.16354,0.45096],[0.22875,0.17481,0.47578],[0.23236,0.18603,0.50004],[0.23582,0.19720,0.52373], [0.23915,0.20833,0.54686],[0.24234,0.21941,0.56942],[0.24539,0.23044,0.59142],[0.24830,0.24143,0.61286], [0.25107,0.25237,0.63374],[0.25369,0.26327,0.65406],[0.25618,0.27412,0.67381],[0.25853,0.28492,0.69300], [0.26074,0.29568,0.71162],[0.26280,0.30639,0.72968],[0.26473,0.31706,0.74718],[0.26652,0.32768,0.76412], [0.26816,0.33825,0.78050],[0.26967,0.34878,0.79631],[0.27103,0.35926,0.81156],[0.27226,0.36970,0.82624], [0.27334,0.38008,0.84037],[0.27429,0.39043,0.85393],[0.27509,0.40072,0.86692],[0.27576,0.41097,0.87936], [0.27628,0.42118,0.89123],[0.27667,0.43134,0.90254],[0.27691,0.44145,0.91328],[0.27701,0.45152,0.92347], [0.27698,0.46153,0.93309],[0.27680,0.47151,0.94214],[0.27648,0.48144,0.95064],[0.27603,0.49132,0.95857], [0.27543,0.50115,0.96594],[0.27469,0.51094,0.97275],[0.27381,0.52069,0.97899],[0.27273,0.53040,0.98461], [0.27106,0.54015,0.98930],[0.26878,0.54995,0.99303],[0.26592,0.55979,0.99583],[0.26252,0.56967,0.99773], [0.25862,0.57958,0.99876],[0.25425,0.58950,0.99896],[0.24946,0.59943,0.99835],[0.24427,0.60937,0.99697], [0.23874,0.61931,0.99485],[0.23288,0.62923,0.99202],[0.22676,0.63913,0.98851],[0.22039,0.64901,0.98436], [0.21382,0.65886,0.97959],[0.20708,0.66866,0.97423],[0.20021,0.67842,0.96833],[0.19326,0.68812,0.96190], [0.18625,0.69775,0.95498],[0.17923,0.70732,0.94761],[0.17223,0.71680,0.93981],[0.16529,0.72620,0.93161], [0.15844,0.73551,0.92305],[0.15173,0.74472,0.91416],[0.14519,0.75381,0.90496],[0.13886,0.76279,0.89550], [0.13278,0.77165,0.88580],[0.12698,0.78037,0.87590],[0.12151,0.78896,0.86581],[0.11639,0.79740,0.85559], [0.11167,0.80569,0.84525],[0.10738,0.81381,0.83484],[0.10357,0.82177,0.82437],[0.10026,0.82955,0.81389], [0.09750,0.83714,0.80342],[0.09532,0.84455,0.79299],[0.09377,0.85175,0.78264],[0.09287,0.85875,0.77240], [0.09267,0.86554,0.76230],[0.09320,0.87211,0.75237],[0.09451,0.87844,0.74265],[0.09662,0.88454,0.73316], [0.09958,0.89040,0.72393],[0.10342,0.89600,0.71500],[0.10815,0.90142,0.70599],[0.11374,0.90673,0.69651], [0.12014,0.91193,0.68660],[0.12733,0.91701,0.67627],[0.13526,0.92197,0.66556],[0.14391,0.92680,0.65448], [0.15323,0.93151,0.64308],[0.16319,0.93609,0.63137],[0.17377,0.94053,0.61938],[0.18491,0.94484,0.60713], [0.19659,0.94901,0.59466],[0.20877,0.95304,0.58199],[0.22142,0.95692,0.56914],[0.23449,0.96065,0.55614], [0.24797,0.96423,0.54303],[0.26180,0.96765,0.52981],[0.27597,0.97092,0.51653],[0.29042,0.97403,0.50321], [0.30513,0.97697,0.48987],[0.32006,0.97974,0.47654],[0.33517,0.98234,0.46325],[0.35043,0.98477,0.45002], [0.36581,0.98702,0.43688],[0.38127,0.98909,0.42386],[0.39678,0.99098,0.41098],[0.41229,0.99268,0.39826], [0.42778,0.99419,0.38575],[0.44321,0.99551,0.37345],[0.45854,0.99663,0.36140],[0.47375,0.99755,0.34963], [0.48879,0.99828,0.33816],[0.50362,0.99879,0.32701],[0.51822,0.99910,0.31622],[0.53255,0.99919,0.30581], [0.54658,0.99907,0.29581],[0.56026,0.99873,0.28623],[0.57357,0.99817,0.27712],[0.58646,0.99739,0.26849], [0.59891,0.99638,0.26038],[0.61088,0.99514,0.25280],[0.62233,0.99366,0.24579],[0.63323,0.99195,0.23937], [0.64362,0.98999,0.23356],[0.65394,0.98775,0.22835],[0.66428,0.98524,0.22370],[0.67462,0.98246,0.21960], [0.68494,0.97941,0.21602],[0.69525,0.97610,0.21294],[0.70553,0.97255,0.21032],[0.71577,0.96875,0.20815], [0.72596,0.96470,0.20640],[0.73610,0.96043,0.20504],[0.74617,0.95593,0.20406],[0.75617,0.95121,0.20343], [0.76608,0.94627,0.20311],[0.77591,0.94113,0.20310],[0.78563,0.93579,0.20336],[0.79524,0.93025,0.20386], [0.80473,0.92452,0.20459],[0.81410,0.91861,0.20552],[0.82333,0.91253,0.20663],[0.83241,0.90627,0.20788], [0.84133,0.89986,0.20926],[0.85010,0.89328,0.21074],[0.85868,0.88655,0.21230],[0.86709,0.87968,0.21391], [0.87530,0.87267,0.21555],[0.88331,0.86553,0.21719],[0.89112,0.85826,0.21880],[0.89870,0.85087,0.22038], [0.90605,0.84337,0.22188],[0.91317,0.83576,0.22328],[0.92004,0.82806,0.22456],[0.92666,0.82025,0.22570], [0.93301,0.81236,0.22667],[0.93909,0.80439,0.22744],[0.94489,0.79634,0.22800],[0.95039,0.78823,0.22831], [0.95560,0.78005,0.22836],[0.96049,0.77181,0.22811],[0.96507,0.76352,0.22754],[0.96931,0.75519,0.22663], [0.97323,0.74682,0.22536],[0.97679,0.73842,0.22369],[0.98000,0.73000,0.22161],[0.98289,0.72140,0.21918], [0.98549,0.71250,0.21650],[0.98781,0.70330,0.21358],[0.98986,0.69382,0.21043],[0.99163,0.68408,0.20706], [0.99314,0.67408,0.20348],[0.99438,0.66386,0.19971],[0.99535,0.65341,0.19577],[0.99607,0.64277,0.19165], [0.99654,0.63193,0.18738],[0.99675,0.62093,0.18297],[0.99672,0.60977,0.17842],[0.99644,0.59846,0.17376], [0.99593,0.58703,0.16899],[0.99517,0.57549,0.16412],[0.99419,0.56386,0.15918],[0.99297,0.55214,0.15417], [0.99153,0.54036,0.14910],[0.98987,0.52854,0.14398],[0.98799,0.51667,0.13883],[0.98590,0.50479,0.13367], [0.98360,0.49291,0.12849],[0.98108,0.48104,0.12332],[0.97837,0.46920,0.11817],[0.97545,0.45740,0.11305], [0.97234,0.44565,0.10797],[0.96904,0.43399,0.10294],[0.96555,0.42241,0.09798],[0.96187,0.41093,0.09310], [0.95801,0.39958,0.08831],[0.95398,0.38836,0.08362],[0.94977,0.37729,0.07905],[0.94538,0.36638,0.07461], [0.94084,0.35566,0.07031],[0.93612,0.34513,0.06616],[0.93125,0.33482,0.06218],[0.92623,0.32473,0.05837], [0.92105,0.31489,0.05475],[0.91572,0.30530,0.05134],[0.91024,0.29599,0.04814],[0.90463,0.28696,0.04516], [0.89888,0.27824,0.04243],[0.89298,0.26981,0.03993],[0.88691,0.26152,0.03753],[0.88066,0.25334,0.03521], [0.87422,0.24526,0.03297],[0.86760,0.23730,0.03082],[0.86079,0.22945,0.02875],[0.85380,0.22170,0.02677], [0.84662,0.21407,0.02487],[0.83926,0.20654,0.02305],[0.83172,0.19912,0.02131],[0.82399,0.19182,0.01966], [0.81608,0.18462,0.01809],[0.80799,0.17753,0.01660],[0.79971,0.17055,0.01520],[0.79125,0.16368,0.01387], [0.78260,0.15693,0.01264],[0.77377,0.15028,0.01148],[0.76476,0.14374,0.01041],[0.75556,0.13731,0.00942], [0.74617,0.13098,0.00851],[0.73661,0.12477,0.00769],[0.72686,0.11867,0.00695],[0.71692,0.11268,0.00629], [0.70680,0.10680,0.00571],[0.69650,0.10102,0.00522],[0.68602,0.09536,0.00481],[0.67535,0.08980,0.00449], [0.66449,0.08436,0.00424],[0.65345,0.07902,0.00408],[0.64223,0.07380,0.00401],[0.63082,0.06868,0.00401], [0.61923,0.06367,0.00410],[0.60746,0.05878,0.00427],[0.59550,0.05399,0.00453],[0.58336,0.04931,0.00486], [0.57103,0.04474,0.00529],[0.55852,0.04028,0.00579],[0.54583,0.03593,0.00638],[0.53295,0.03169,0.00705], [0.51989,0.02756,0.00780],[0.50664,0.02354,0.00863],[0.49321,0.01963,0.00955],[0.47960,0.01583,0.01055]] # The look-up table contains 256 entries. Each entry is a floating point sRGB triplet. def using_pyside(): return PYSIDE or PYSIDE2 def using_pyqt(): return PYQT4 or PYQT5 def natural_range(dtype): if dtype in ['uint8', 'int8']: return 256 elif dtype in ['uint16', 'int16']: return 65536 elif dtype in ['uint32', 'int32']: #return 4294967296 return 1 elif dtype in ['uint64', 'int64']: #return 18446744073709551616 return 1 elif dtype in ['float16', 'float32', 'float64']: return 1 else: raise TypeError('dtype %s not supported to display' % str(statbuff.dtype)) def integer_limits(integer): return np.iinfo(integer).min, np.iinfo(integer).max def make_map8(dtype='uint16', offset=0, gain=1, gamma=1): natrange = natural_range(dtype) #astype('uint8') rounds down ! if dtype in ['uint8', 'uint16']: if gamma == 1: return ((np.arange(natrange, dtype='double') - offset) * gain * 256 / natrange).clip(0, 255).astype('uint8') else: temp = ((np.arange(natrange, dtype='double') - offset) * gain * 256 / natrange) return (temp ** gamma * 255 ** (1-gamma)).clip(0, 255).astype('uint8') elif dtype in ['int8', 'int16']: halfrange = natrange // 2 if gamma == 1: positives = ((np.arange(halfrange, dtype='double') - offset) * gain * 256 / natrange).clip(0, 255).astype('uint8') negatives = ((np.arange(-halfrange, 0, dtype='double') - offset) * gain * 256 / natrange).clip(0, 255).astype('uint8') return np.r_[positives, negatives] else: positives = (np.arange(halfrange, dtype='double') - offset) * gain * 256 / natrange positives = (positives ** gamma * 255 ** (1-gamma)).clip(0, 255).astype('uint8') negatives = (np.arange(-halfrange, 0, dtype='double') - offset) * gain * 256 / natrange negatives = (negatives ** gamma * 255 ** (1-gamma)).clip(0, 255).astype('uint8') return np.r_[positives, negatives] def qimage_to_ndarray(qimg, dtype=None): if qimg.depth() == 8 and qimg.format() == QtGui.QImage.Format_Indexed8: qimg_canvas = QtGui.QImage(qimg.width(), qimg.height(), QtGui.QImage.Format_RGB888) qp = QtGui.QPainter() qp.begin(qimg_canvas) qp.drawImage(0, 0, qimg) qp.end() qimg = qimg_canvas z = qimg.depth() // 8 if using_pyside(): memview = qimg.bits() #on pyside image.bits() return an memoryview elif using_pyqt(): ptr = qimg.bits() #on pyqt, it is a sip.voidptr ptr.setsize(qimg.height() * qimg.width() * z) memview = ptr if qimg.depth() == 8: arr = np.array(memview, 'uint8').reshape((qimg.height(), qimg.width())) if not dtype is None: return arr.astype(dtype) else: return arr.copy() elif qimg.depth() == 24: arr = np.array(memview, 'uint8').reshape((qimg.height(), qimg.width(), z)) if not dtype is None: return arr[:,:,:].astype(dtype) else: return arr[:,:,:].copy() elif qimg.depth() == 32: arr = np.array(memview, 'uint8').reshape((qimg.height(), qimg.width(), z)) if not dtype is None: return arr[:,:,2::-1].astype(dtype) else: return arr[:,:,2::-1].copy() else: raise ValueError("Can't handle the depth %d" % qimg.depth()) def get_height_width_channels(array): ndim = array.ndim shape = array.shape dtype = array.dtype if ndim == 1: width = shape[0] channels = height = 1 elif ndim == 2: height, width = shape channels = 1 elif ndim == 3: height, width, channels = shape return height, width, channels def float_offset_gain_gamma_8bit(array, offset=0, gain=1, gamma=1): if gamma == 1: return ((array - offset) * (gain * 256)).clip(0, 255).astype('uint8') else: temp = ((array - offset) * (gain * 256)) return (temp ** gamma * 255 ** (1-gamma)).clip(0, 255).astype('uint8') def process_ndarray_to_qimage_8bit(array, offset=0, gain=1, color_table_name=None, refer=False, shared=False, gamma=1): h, w, c = get_height_width_channels(array) shape = (h, w) if c == 1 else (h, w, c) if shared: result = SharedArray(shape, 'uint8') processed = result.ndarray else: result = np.ndarray(shape, 'uint8') processed = result if array.dtype in ['int8', 'uint8']: if array.dtype == 'uint8' and offset == 0 and gain == 1 and gamma == 1: if c == 4: processed[:,:,0] = array[:,:,2] processed[:,:,1] = array[:,:,1] processed[:,:,2] = array[:,:,0] processed[:,:,3] = array[:,:,3] else: processed[:] = array else: map8 = make_map8(array.dtype, offset, gain, gamma) if use_numba: if c == 1: map_values_mono(array, processed, map8) elif c == 3: map_values_rgb(array, processed, map8) elif c == 4: map_values_rgbswap(array, processed, map8) else: processed[:] = np.take(map8, array) elif array.dtype in ['int16', 'uint16']: if array.dtype == 'uint16' and offset == 0 and gain == 1 and gamma == 1: # >> Rounds down ! if c == 1: processed[:] = array >> 8 elif c == 3: processed[:] = array >> 8 elif c == 4: processed[:,:,0] = array[:,:,2] >> 8 processed[:,:,1] = array[:,:,1] >> 8 processed[:,:,2] = array[:,:,0] >> 8 processed[:,:,3] = array[:,:,3] >> 8 else: map8 = make_map8(array.dtype, offset, gain, gamma) if use_numba: if c == 1: map_values_mono(array, processed, map8) elif c == 3: map_values_rgb(array, processed, map8) elif c == 4: map_values_rgbswap(array, processed, map8) else: if c in [1, 3]: processed[:] = np.take(map8, array) elif c == 4: processed[:,:,0] = np.take(map8, array[:,:,2]) processed[:,:,1] = np.take(map8, array[:,:,1]) processed[:,:,2] = np.take(map8, array[:,:,0]) processed[:,:,3] = array[:,:,3] >> 8 elif array.dtype in ['int32', 'uint32', 'float16', 'float32', 'float64']: if has_numba: convertor = nb_float_offset_gain_gamma_8bit else: convertor = float_offset_gain_gamma_8bit if c == 1: processed[:] = convertor(array, offset, gain, gamma) elif c == 3: processed[:,:,0] = convertor(array[:,:,0], offset, gain, gamma) processed[:,:,1] = convertor(array[:,:,1], offset, gain, gamma) processed[:,:,2] = convertor(array[:,:,2], offset, gain, gamma) elif c == 4: processed[:,:,0] = convertor(array[:,:,2], offset, gain, gamma) processed[:,:,1] = convertor(array[:,:,1], offset, gain, gamma) processed[:,:,2] = convertor(array[:,:,0], offset, gain, gamma) processed[:,:,3] = array[:,:,3] >> 8 color_table = None if color_table_name is None or color_table_name in ['grey', 'gray'] else make_color_table(color_table_name) qimg = ndarray_to_qimage(processed, color_table) if not refer: #The current image buffer of qimg is refered to ndarray processed #So don't delete processed object or copy qimg return qimg.copy() else: return result, qimg def color_table_preview_qimg(name, height=32): arr = np.ones((height,1), 'uint8').dot(np.arange(256, dtype='uint8').reshape(1,256)) return process_ndarray_to_qimage_8bit(arr, 0, 1, color_table_name=name) def make_color_table(name): #8bit table = list() # Note that the order in QT is BGRA # Blue is the lowest byte # Alpha is the highest byte bBase = 1 gBase = 1 << 8 rBase = 1 << 16 aBase = 1 << 24 if name in ('grey', 'gray'): a = 255 for i in range(0, 256): b = g = r = i table.append(a*aBase + b*bBase + g * gBase + r * rBase) elif name == 'clip': a = 255 table.append(255 * aBase + 255 * bBase + 0 * gBase + 0 * rBase) for i in range(1, 255): b = g = r = i table.append(a*aBase + b*bBase + g * gBase + r * rBase) table.append(255 * aBase + 127 * bBase + 127 * gBase + 255 * rBase) elif name == 'mask': table.append(0) for i in range(1, 256): table.append(255 * aBase + 0 * bBase + 0 * gBase + 255 * rBase) elif name == 'jet': a = 255 for i in range(0, 256): r = min(max(383 - round(abs(i-191) * 4), 0), 255) g = min(max(383 - round(abs(i-127) * 4), 0), 255) b = min(max(383 - round(abs(i-63) * 4), 0), 255) table.append(a*aBase + b*bBase + g * gBase + r * rBase) elif name == 'invert': a = 255 for i in range(0,256): b = 255 - i g = 255 - i r = 255 - i table.append(a*aBase + b*bBase + g * gBase + r * rBase) elif name == 'hot': a = 255 for i in range(0,256): b = min(max( i * 5 - 1020, 0),255) g = min(max( round(i * 2.5) - 255, 0),255) r = min(max( round(i * 2.5), 0),255) table.append(a*aBase + b*bBase + g * gBase + r * rBase) elif name == 'cold': a = 255 for i in range(0,256): r = min(max( i * 5 - 1020, 0),255) g = min(max( round(i * 2.5) - 255, 0),255) b = min(max( round(i * 2.5), 0),255) table.append(a*aBase + b*bBase + g * gBase + r * rBase) elif name == 'turbo': a = 255 for i in range(0,256): r, g, b = [min(max(0, int(c*255)), 255) for c in turbo_colormap_data[i]] table.append(a*aBase + r*rBase + g*gBase + b*bBase ) return table def ndarray_to_qimage(array, color_table=None): ndim = array.ndim shape = array.shape dtype = array.dtype #Format_RGB888: Byte order in Red, Green, Blue #Format_ARGB32: Byte order in Blue, Green, Red, Alpha if ndim == 1: width = shape[0] channels = height = 1 elif ndim == 2: height, width = shape channels = 1 elif ndim == 3: height, width, channels = shape else: raise AttributeError(f'ndim {ndim} not supported') if dtype in ['bool', 'int8', 'uint8']: memview = memoryview(array) if channels == 1: if color_table is None: qimg = QtGui.QImage(memview, width, height, width, QtGui.QImage.Format_Grayscale8) else: qimg = QtGui.QImage(memview, width, height, width, QtGui.QImage.Format_Indexed8) qimg.setColorTable(color_table) elif channels == 3: qimg = QtGui.QImage(memview, width, height, width * 3, QtGui.QImage.Format_RGB888) elif channels == 4: qimg = QtGui.QImage(memview, width, height, width * 4, QtGui.QImage.Format_ARGB32) else: raise AttributeError(f'To many channels {channels}') elif dtype in ['int16', 'uint16']: memview = memoryview(array) if channels == 1: qimg = QtGui.QImage(memview, width, height, width, QtGui.QImage.Format_Indexed8) elif channels == 3: qimg = QtGui.QImage(memview, width, height, width * 3, QtGui.QImage.Format_RGB888) elif channels == 4: qimg = QImage(self.memview, width, height, width * 4, QImage.Format_ARGB32) elif dtype in ['float32', 'float64']: pass else: raise TypeError(f'type {dtype} not supported') return qimg
thocoo/gamma-desk
gdesk/graphics/view.py
<filename>gdesk/graphics/view.py from qtpy import QtCore, QtGui, QtWidgets QtSignal = QtCore.Signal from .point import Point #Point = QtCore.QPointF class SceneView(QtWidgets.QGraphicsView): scaled = QtSignal(bool, bool) scale_ended = QtSignal(bool, bool) translated = QtSignal(bool, bool) translate_ended = QtSignal(bool, bool) zoom_full = QtSignal() def __init__(self, parent): super().__init__(parent) #self.setMouseTracking(True) #self.setInteractive(False) #self.useOpenGL(True) self.setCacheMode(self.CacheBackground) self.scale = [1, 1] self.center = [0, 0] self.fixScaleX = False self.fixScaleY = False self.lastMousePos = None self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFrameShape(QtWidgets.QFrame.NoFrame) self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor) self.setResizeAnchor(QtWidgets.QGraphicsView.NoAnchor) self.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.freeze_y0 = False self.old_view_rect = None # self.restore_view_rect_timer = QtCore.QTimer() # self.restore_view_rect_timer.timeout.connect(self.restore_view_rect) # self.restore_view_rect_timer.setSingleShot(True) self.updateMatrix() def useOpenGL(self, b=True): if b: from PySide2 import QtOpenGL v = QtOpenGL.QGLWidget() else: v = QtWidgets.QWidget() self.setViewport(v) # def restore_view_rect(self): # x0, y0, x1, y1 = self.old_view_rect # self.setXLimits(x0, x1, 0,0) # self.setYLimits(y0, y1, 0,0) # self.old_view_rect = None # self.scaled.emit(True, True) def setRange(self, scene_width, scene_height): self.scale[0] = self.width() / scene_width self.scale[1] = self.height() / scene_height self.updateMatrix() def updateMatrix(self, propagate=True): #t = self.transform() self.limitRefreshRange() self.setTransform(QtGui.QTransform(\ self.scale[0], 0 , 0,\ 0 , self.scale[1], 0,\ 0 , 0 , 1)) self.centerOn(*self.center) self.viewport().update() def translate(self, dx, dy): self.center = [self.center[0] +dx, self.center[1] + dy] self.updateMatrix() def limitRefreshRange(self): self.range = QtCore.QRectF() self.range.setWidth((self.width() + 20)/ self.scale[0]) self.range.setHeight((self.height() + 20) / self.scale[1]) self.range.moveCenter(QtCore.QPointF(*self.center)) self.setSceneRect(self.range) def setXPosScale(self, pos, scale): self.scale[0] = scale self.center[0] = pos + self.width() / 2.0 / scale self.limitRefreshRange() t = self.transform() self.setTransform(QtGui.QTransform(\ scale, 0 , 0,\ 0 , t.m22(), 0,\ 0 , 0 , 1)) self.centerOn(*self.center) def setXLimits(self, low, high, left_border=0, right_border=0): self.scale[0] = (self.width() - left_border - right_border)/ (high - low) self.center[0] = (low - left_border / self.scale[0] + high) / 2 self.limitRefreshRange() self.updateMatrix() def setYPosScale(self, pos, scale): self.scale[1] = scale self.center[1] = pos + self.height() / 2.0 / scale self.limitRefreshRange() t = self.transform() self.setTransform(QtGui.QTransform(\ t.m11(), 0 , 0,\ 0 , scale, 0,\ 0 , 0 , 1)) self.centerOn(*self.center) def setYLimits(self, low, high, bottom_border=0, top_border=0): self.scale[1] = (self.height() - bottom_border - top_border) / (low - high) self.center[1] = (low + bottom_border / self.scale[1] + high) / 2 self.limitRefreshRange() self.updateMatrix() def wheelEvent(self, ev): #QtWidgets.QGraphicsView.wheelEvent(self, ev) if not self.fixScaleX and (self.fixScaleY or self.freeze_y0): self.scale[0] = self.scale[0] * 1.001 ** ev.delta() self.updateMatrix() self.scale_ended.emit(True, False) elif self.fixScaleX and not self.fixScaleY: self.scale[1] = self.scale[1] * 1.001 ** ev.delta() self.updateMatrix() self.scale_ended.emit(False, True) else: self.scale[0] = self.scale[0] * 1.001 ** ev.delta() self.scale[1] = self.scale[1] * 1.001 ** ev.delta() self.updateMatrix() self.scale_ended.emit(True, True) def pixelSize(self): """Return vector with the length and width of one view pixel in scene coordinates""" p0 = Point(0,0) p1 = Point(1,1) tr = self.transform().inverted()[0] p01 = tr.map(p0) p11 = tr.map(p1) return Point(p11 - p01) def mousePressEvent(self, ev): self.lastMousePos = Point(ev.pos()) self.lastPressButton = ev.button() super().mousePressEvent(ev) #print('mouse press x:%d y:%d' % (self.lastMousePos[0], self.lastMousePos[1])) def mouseDoubleClickEvent(self, ev): self.zoom_full.emit() def mouseMoveEvent(self, ev): super().mouseMoveEvent(ev) if hasattr(self.scene(), 'moving_indicators') and self.scene().moving_indicators: self.scene().moving_indicators = False return if self.lastMousePos is None: self.lastMousePos = Point(ev.pos()) delta = Point(ev.pos()) - self.lastMousePos self.lastMousePos = Point(ev.pos()) if ev.buttons() in [QtCore.Qt.LeftButton]: #if ev.buttons() in [QtCore.Qt.MidButton, QtCore.Qt.RightButton]: px = self.pixelSize() tr = -delta * px movex, movey = True, True if self.fixScaleX: tr[0] = 0 movex = False if self.fixScaleY or self.freeze_y0: tr[1] = 0 movey = False self.translate(tr[0], tr[1]) self.translated.emit(movex, movey) elif ev.buttons() in [QtCore.Qt.RightButton]: if not self.freeze_y0: px = self.pixelSize() self.scale[0] = self.scale[0] * 1.01 ** delta[0] self.scale[1] = self.scale[1] * 1.01 ** delta[1] self.updateMatrix() self.scaled.emit(True, True) elif self.freeze_y0: scale_x = 1.01 ** (-delta[0]) scale_y = 1.01 ** delta[1] x0, y0, x1, y1 = self.viewRectCoord() cx = (x1 + x0) / 2 rx = (x1 - x0) / 2 x0 = cx - rx * scale_x x1 = cx + rx * scale_x self.setXLimits(x0, x1, 0, 0) y0 = y0 * scale_y y1 = y1 * scale_y self.setYLimits(y0, y1, 0, 0) self.scaled.emit(True, True) def viewRectCoord(self): #return the currently visible window in view coord xc, yc = self.center x0 = xc - self.width() / abs(self.scale[0]) / 2 y0 = yc - self.height() / abs(self.scale[1]) / 2 x1 = xc + self.width() / abs(self.scale[0]) / 2 y1 = yc + self.height() / abs(self.scale[1]) / 2 return x0, y0, x1, y1 def refresh(self): self.viewport().update() def resizeEvent(self, ev): # if self.old_view_rect is None: # self.old_view_rect = x0, y0, x1, y1 = self.viewRectCoord() # self.restore_view_rect_timer.start(500) self.updateMatrix()
thocoo/gamma-desk
gdesk/panels/cmdhist/panel.py
from qtpy import QtCore, QtGui, QtWidgets from ...dialogs.formlayout import fedit from ...panels.base import BasePanel from ... import gui class CmdHistTableModel(QtCore.QAbstractTableModel): def __init__(self): super().__init__() def rowCount(self, index): for row in gui.qapp.history.execfetch('SELECT COUNT() FROM CMDHIST'): count = row[0] return count def columnCount(self, index): return 2 def data(self, index, role): if role == QtCore.Qt.DisplayRole: rownr, colnr = index.row(), index.column() for row in gui.qapp.history.execfetch(f'SELECT TIME, CMD FROM CMDHIST LIMIT {rownr}, 1'): value = row[colnr] return str(value) class CmdHistTableView(QtWidgets.QTableView): def __init__(self): super().__init__() def getSelectedCommands(self): selmodel = self.selectionModel() lines = [] for index in selmodel.selectedIndexes(): text = self.model().data(index, QtCore.Qt.DisplayRole) lines.append(text) return '\n'.join(lines) def mouseDoubleClickEvent(self, event): text = self.getSelectedCommands() console = gui.qapp.panels.selected('console') if not text.endswith('\n'): text += '\n' console.stdio.stdInputPanel.addText(text) class CmdHistPanel(BasePanel): panelCategory = 'cmdhist' panelShortName = 'basic' userVisible = True def __init__(self, parent, panid): super().__init__(parent, panid, type(self).panelCategory) self.initMenu() self.model = CmdHistTableModel() self.cmdhistview = CmdHistTableView() self.cmdhistview.setModel(self.model) self.setCentralWidget(self.cmdhistview) self.statusBar().hide() def initMenu(self): self.fileMenu = self.menuBar().addMenu("&File") self.addMenuItem(self.fileMenu, 'Close', self.close_panel, statusTip="Close this levels panel", icon = 'cross.png') self.viewMenu = self.menuBar().addMenu("&View") self.addMenuItem(self.viewMenu, 'Reset', self.reset) self.addMenuItem(self.viewMenu, 'Refresh', self.refresh) self.addMenuItem(self.viewMenu, 'Paste stdin', self.pasteStdin) self.addBaseMenu() def reset(self): self.model.reset() def refresh(self): self.cmdhistview.repaint() def pasteStdin(self): text = self.cmdhistview.getSelectedCommands() console = gui.qapp.panels.selected('console') console.stdio.stdInputPanel.setPlainText(text)
thocoo/gamma-desk
gdesk/core/stdinout.py
import io import sys import threading import time import logging from logging.handlers import RotatingFileHandler from logging import StreamHandler, Handler from queue import Queue from .conf import config from .gui_proxy import gui sentinel = object() logger = logging.getLogger(__name__) streamhandler = None ESC = '\033[' RED_PREFIX = ESC + '38;5;9m' RED_SUFFIX = ESC + '0m' LOG_PREFIX = '\033[48;5;7mLOG\033[0m ' DEBUG_PREFIX = ESC + '38;5;6m' DEBUG_SUFFIX = ESC + '0m' INFO_PREFIX = ESC + '38;5;12m' INFO_SUFFIX = ESC + '0m' WARNING_PREFIX = ESC + '38;5;13m' WARNING_SUFFIX = ESC + '0m' ERROR_PREFIX = ESC + '38;5;9m' ERROR_SUFFIX = ESC + '0m' CRITICAL_PREFIX = ESC + '38;5;5m' CRITICAL_SUFFIX = ESC + '0m' if config.get('qapp', False): filehandler = RotatingFileHandler(f'stderr.log', maxBytes=1024*1024, encoding='UTF-8',backupCount=5) filehandler.setLevel(config.get('logging_level_logfile', 'DEBUG')) logging.root.addHandler(filehandler) class StreamRouter(object): ''' Pass the calls to a threading dependent stream ''' def __init__(self): self.streams = dict() self.backup_stream = sys.__stdout__ @property def stream(self): ident = threading.get_ident() if ident in self.streams.keys(): return self.streams[ident] else: return self.backup_stream def route_stream(self, stream, ident=None): if ident is None: ident = threading.get_ident() self.streams[ident] = stream def unregister(self, ident=None): if ident is None: ident = threading.get_ident() self.streams.pop(ident) def copy_to_thread(self, to_tid, from_tid=None): from_tid = from_tid or threading.get_ident() self.streams[to_tid] = self.streams[from_tid] def __getattr__(self, attr): return getattr(self.stream, attr) def __dir__(self): return dir(self.stream) class StdOutRouter(StreamRouter): def __init__(self): super().__init__() self.backup_stream = sys.__stdout__ class StdErrRouter(StreamRouter): def __init__(self): super().__init__() self.backup_stream = sys.__stderr__ class GhStreamHandler(Handler): def __init__(self, stream): super().__init__() self.stream = stream self.set_name('ghstream') def setStream(self, stream): self.stream.flush() self.stream = stream def emit(self, record): text = self.format(record) if record.levelno <= logging.DEBUG: self.stream.write(f'{LOG_PREFIX}{DEBUG_PREFIX}{text}{DEBUG_SUFFIX}\n') elif record.levelno <= logging.INFO: self.stream.write(f'{LOG_PREFIX}{INFO_PREFIX}{text}{INFO_SUFFIX}\n') elif record.levelno <= logging.WARNING: self.stream.write(f'{LOG_PREFIX}{WARNING_PREFIX}{text}{WARNING_SUFFIX}\n') elif record.levelno <= logging.ERROR: self.stream.write(f'{LOG_PREFIX}{ERROR_PREFIX}{text}{ERROR_SUFFIX}\n') elif record.levelno <= logging.CRITICAL: self.stream.write(f'{LOG_PREFIX}{CRITICAL_PREFIX}{text}{CRITICAL_SUFFIX}\n') else: self.stream.write(f'LOG {text}') try: if record.levelno >= logging.WARNING: gui.console.show_me() except: pass class PopupHandler(Handler): def emit(self, record): #Do not popup outside the main gui thread #Should it not be better to test console thread ? #Otherwise, errors in Qt Threads, will not popup if gui.qapp is None: return text = self.format(record) if record.levelno == logging.ERROR: gui.dialog.msgbox(text, 'Error', 'error') elif record.levelno == logging.CRITICAL: gui.dialog.msgbox(text, 'Critical', 'error') def enable_ghstream_handler(): global streamhandler streamhandler = GhStreamHandler(sys.stdout) streamhandler.setLevel(config.get('logging_level_console', 'WARNING')) logging.root.addHandler(streamhandler) class FlushReducer(object): def __init__(self, flusher): self.q = Queue() self.flusher = flusher self.thread = threading.Thread(target=self.reduce, name='FlushReducer', daemon=True) self.thread.start() def __call__(self): self.q.put(1) def reduce(self): while True: t = self.q.get() if t is sentinel: return time.sleep(0.01) self.q.queue.clear() self.flusher() def close(self): #wait on an empty queue while not self.q.empty(): time.sleep(0.01) self.q.put(sentinel) class FlushPipeStream(io.TextIOBase): def __init__(self, streamqueue, flusher): self.streamqueue = streamqueue self.flusher = FlushReducer(flusher) def write(self, text): self._write_mode(text, config['stdoutmode']) def ansi(self, text): self._write_mode(text, 'ansi') def _write_mode(self, text, mode, prefix='', suffix=''): if mode == 'ansi': text = f'{prefix}{text}{suffix}' self.streamqueue.put((mode, text)) self.flush() def flush(self): self.flusher() class ErrLogStream(io.TextIOBase): def __init__(self): self.line_cache = '' def write(self, text): self.line_cache += text if text.endswith('\n'): logger.error(self.line_cache.rstrip('\n')) self.line_cache = '' class ProcessStdInput(io.TextIOBase): stdin_queues = dict() def __init__(self, stdin_queue=None): self.stdin_queue = stdin_queue def close(self): pass def read(self, timeout=None): ident = threading.get_ident() if ident in ProcessStdInput.stdin_queues.keys(): text = ProcessStdInput.stdin_queues[ident].get(timeout=timeout) return text else: return sys.__stdin__.read()
thocoo/gamma-desk
gdesk/utils/keypress.py
<gh_stars>0 import ctypes from ctypes import wintypes import time user32 = ctypes.WinDLL('user32', use_last_error=True) INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 INPUT_HARDWARE = 2 KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENTF_UNICODE = 0x0004 KEYEVENTF_SCANCODE = 0x0008 MAPVK_VK_TO_VSC = 0 # msdn.microsoft.com/en-us/library/dd375731 VK_TAB = 0x09 VK_MENU = 0x12 VK_F15 = 0x7E # C struct definitions wintypes.ULONG_PTR = wintypes.WPARAM class MOUSEINPUT(ctypes.Structure): _fields_ = (("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", wintypes.ULONG_PTR)) class KEYBDINPUT(ctypes.Structure): _fields_ = (("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", wintypes.ULONG_PTR)) def __init__(self, *args, **kwds): super(KEYBDINPUT, self).__init__(*args, **kwds) # some programs use the scan code even if KEYEVENTF_SCANCODE # isn't set in dwFflags, so attempt to map the correct code. if not self.dwFlags & KEYEVENTF_UNICODE: self.wScan = user32.MapVirtualKeyExW(self.wVk, MAPVK_VK_TO_VSC, 0) class HARDWAREINPUT(ctypes.Structure): _fields_ = (("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)) class INPUT(ctypes.Structure): class _INPUT(ctypes.Union): _fields_ = (("ki", KEYBDINPUT), ("mi", MOUSEINPUT), ("hi", HARDWAREINPUT)) _anonymous_ = ("_input",) _fields_ = (("type", wintypes.DWORD), ("_input", _INPUT)) LPINPUT = ctypes.POINTER(INPUT) def _check_count(result, func, args): if result == 0: raise ctypes.WinError(ctypes.get_last_error()) return args user32.SendInput.errcheck = _check_count user32.SendInput.argtypes = (wintypes.UINT, # nInputs LPINPUT, # pInputs ctypes.c_int) # cbSize # Functions def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) try: user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) except: # [WinError 5] Access is denied. # Can happen when current session is locked # by for example switching to other users pass def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode, dwFlags=KEYEVENTF_KEYUP)) try: user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) except: # [WinError 5] Access is denied. # Can happen when current session is locked # by for example switching to other users pass def red_bulling(interval = 60): """ Press F-15 every interval seconds """ import time print('Red bulling started') while True: time.sleep(interval) PressKey(0x7E) ReleaseKey(0x7E) if __name__ == "__main__": red_bulling()
thocoo/gamma-desk
gdesk/ezdock/boxes.py
<reponame>thocoo/gamma-desk from qtpy import QtWidgets, QtCore, QtGui from qtpy.QtCore import Qt from .docks import DockBase class AreaSplitterHandle(QtWidgets.QSplitterHandle): def mouseDoubleClickEvent(self, event): self.parent().distributeWidgets() class DockBox(QtWidgets.QSplitter, DockBase): SplitArea = 0 PinArea = 1 ScrollArea = 2 def __init__(self, orientation): QtWidgets.QSplitter.__init__(self, orientation) pal = self.palette() if orientation == Qt.Horizontal: pal.setColor(QtGui.QPalette.Background, QtGui.QColor(192,224,192)) elif orientation == Qt.Vertical: pal.setColor(QtGui.QPalette.Background, QtGui.QColor(192,192,224)) self.setPalette(pal) self.pinarea = PinnedBox(orientation) self.scrollarea = ScrollBox(orientation) super().addWidget(self.pinarea) super().addWidget(self.scrollarea) self.collapsed = False self.scrollarea.hide() def createHandle(self): return AreaSplitterHandle(self.orientation(), self) def addWidget(self, widget, area=PinArea, title=None): if area == DockBox.PinArea: self.pinarea.addWidget(widget) elif area == DockBox.ScrollArea: if self.scrollarea.count() == 0: self.scrollarea.show() self.setSizes([4,1], DockBox.SplitArea) self.scrollarea.addWidget(widget) def count(self, area=PinArea): if area == DockBox.SplitArea: return super().count() elif area == DockBox.PinArea: return self.pinarea.count() elif area == DockBox.ScrollArea: return self.scrollarea.count() def moveToOtherArea(self, widget, area=None): if area is None: area_widget = widget.parent() while not isinstance(area_widget, (PinnedBox, ScrollBox)): area_widget = area_widget.parent() if isinstance(area_widget, PinnedBox): area = DockBox.ScrollArea elif isinstance(area_widget, ScrollBox): area = DockBox.PinArea if area == DockBox.ScrollArea: self.addWidget(widget, area=DockBox.ScrollArea) elif area == DockBox.PinArea: self.scrollarea.removeWidget(widget) self.addWidget(widget, area=DockBox.PinArea) def distributeWidgets(self): sizes = self.pinarea.sizes() newsize = sum(sizes) // self.pinarea.count() sizes = [newsize] * self.pinarea.count() self.pinarea.setSizes(sizes) def setSizes(self, sizes, area=PinArea): if area == DockBox.SplitArea: super().setSizes(sizes) elif area == DockBox.PinArea: self.pinarea.setSizes(sizes) elif area == DockBox.ScrollArea: self.scrollarea.growbox.setSizes(sizes) def sizes(self, area=PinArea): if area == DockBox.SplitArea: return super().sizes() elif area == DockBox.PinArea: return self.pinarea.sizes() elif area == DockBox.ScrollArea: return self.scrollarea.growbox.sizes() def currentIndex(self): return self.pinarea.currentIndex() def widget(self, index, area=PinArea): if area == DockBox.PinArea: return self.pinarea.widget(index) elif area == DockBox.ScrollArea: return self.scrollarea.growbox.widget(index) def show(self): self.pinarea.show() if self.scrollarea.count() > 0: self.scrollarea.show() else: self.scrollarea.hide() self.scrollarea.growbox.show() for pos in range(self.count(DockBox.PinArea)): widget = self.widget(pos, DockBox.PinArea) widget.show() for pos in range(self.count(DockBox.ScrollArea)): widget = self.widget(pos, DockBox.ScrollArea) widget.show() super().show() def setCurrentIndex(self, index): self.pinarea.setCurrentIndex(index) class DockVBox(DockBox): def __init__(self): super().__init__(Qt.Vertical) class DockHBox(DockBox): def __init__(self): super().__init__(Qt.Horizontal) class PinnedSplitterHandle(QtWidgets.QSplitterHandle): def mouseDoubleClickEvent(self, event): self.parent().distributeWidgets(self) class PinnedBox(QtWidgets.QSplitter): def __init__(self, orientation): QtWidgets.QSplitter.__init__(self, orientation) pal = self.palette() pal.setColor(QtGui.QPalette.Background, QtGui.QColor(192,192,192)) self.setPalette(pal) self.atLeastOnePanel = True def collapse(self, widget): if self.atLeastOnePanel: not_collapsed_widgets = [self.widget(pos) for pos in range(self.count()) if not self.widget(pos).collapsed] if not widget.collapsed and len(not_collapsed_widgets) == 1: widget.topleftbtn.setChecked(False) return widget.collapseVertical() def moveToOtherArea(self, widget): self.parent().moveToOtherArea(widget, DockBox.ScrollArea) def createHandle(self): return PinnedSplitterHandle(self.orientation(), self) def distributeWidgets(self, handle): pos = self.indexOf(handle) sizes = self.sizes() newsize = sum(sizes[pos-1:pos+1]) // 2 sizes[pos-1] = newsize sizes[pos] = newsize self.setSizes(sizes) class SplitterHandle(QtWidgets.QWidget): def __init__(self, orientation, space=5): super().__init__() self._orientation = orientation if orientation == Qt.Vertical: self.setCursor(QtGui.QCursor(QtCore.Qt.SplitVCursor)) self.setFixedHeight(space) elif orientation == Qt.Horizontal: self.setCursor(QtGui.QCursor(QtCore.Qt.SplitHCursor)) self.setFixedWidth(space) def orientation(self): return self._orientation def mouseDoubleClickEvent(self, event): self.parent().distributeWidgets(self) def mouseMoveEvent(self, event): pos = self.parent().indexOf(self) - 1 if self.orientation() == Qt.Vertical: delta = event.pos().y() self.parent().changeWidgetSize(pos, delta, delta=True) elif self.orientation() == Qt.Horizontal: delta = event.pos().x() self.parent().changeWidgetSize(pos, delta, delta=True) class SplitBox(QtWidgets.QWidget): def __init__(self, orientation): super().__init__() self._orientation = orientation self.widgets = [] self.handles = [None] self.space = 5 if orientation == Qt.Vertical: layout = QtWidgets.QVBoxLayout() self.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) elif orientation == Qt.Horizontal: layout = QtWidgets.QHBoxLayout() self.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) layout.setContentsMargins(0,0,0,0) layout.setSpacing(0) self.setLayout(layout) self.atLeastOnePanel = False def orientation(self): return self._orientation def addWidget(self, widget): if self.orientation() == Qt.Vertical: sizes = self.sizes() + [widget.height()] elif self.orientation() == Qt.Horizontal: sizes = self.sizes() + [widget.width()] self.widgets.append(widget) self.layout().addWidget(widget) handle = SplitterHandle(self.orientation(), self.space) self.handles.append(handle) self.layout().addWidget(handle) self.layout().setStretch(self.layout().count()-1, self.space) self.setSizes(sizes) def insertWidget(self, pos, widget): if self.orientation() == Qt.Vertical: prefered_height = widget.height() sizes = self.sizes() sizes.insert(pos, prefered_height) elif self.orientation() == Qt.Horizontal: prefered_width = widget.width() sizes = self.sizes() sizes.insert(pos, prefered_width) self.widgets.insert(pos, widget) self.layout().insertWidget(pos*2, widget) handle = SplitterHandle(self.orientation(), self.space) self.handles.insert(pos+1, handle) self.layout().insertWidget(pos*2+1, handle) self.layout().setStretch(pos*2+1, self.space) self.setSizes(sizes) def resizeWidget(self, widget, size): if isinstance(widget, int): pos = widget else: pos = self.indexOf(widget) sizes = self.sizes() sizes[pos] = size self.setSizes(sizes) def removeWidget(self, widget): if isinstance(widget, int): pos = widget else: pos = self.indexOf(widget) sizes = self.sizes() sizes.pop(pos) widget = self.widgets.pop(pos) self.layout().removeWidget(widget) handle = self.handles.pop(pos+1) self.layout().removeWidget(handle) widget.setParent(None) handle.setParent(None) self.setSizes(sizes) return widget def count(self): return len(self.widgets) def widget(self, index): return self.widgets[index] def indexOf(self, widget): try: return self.widgets.index(widget) except ValueError: pass try: return self.handles.index(widget) except ValueError: pass return None def distributeWidgets(self, handle): pos = self.indexOf(handle) sizes = self.sizes() cmo = self.count() if pos == cmo: sizes = [sum(sizes[:cmo]) // cmo] * cmo else: newsize = sum(sizes[pos-1:pos+1]) // 2 sizes[pos-1] = newsize sizes[pos] = newsize self.setSizes(sizes) def collapse(self, widget): if self.atLeastOnePanel: not_collapsed_widgets = [self.widget(pos) for pos in range(self.count()) if not self.widget(pos).collapsed] if not widget.collapsed and len(not_collapsed_widgets) == 1: widget.topleftbtn.setChecked(False) return widget.collapseVertical() def sizes(self): if self.orientation() == Qt.Vertical: return [widget.height() for widget in self.widgets] elif self.orientation() == Qt.Horizontal: return [widget.width() for widget in self.widgets] #return self.stretches() def stretches(self): return [self.layout().stretch(index) for index in range(self.count()*2)] def setSizes(self, sizes): total_size = sum(sizes) + self.space * self.count() # print(f'Sizes: Stretches: {self.stretches()}') # print(f' Old: {self.sizes()}') # print(f' New: {sizes} Total: {total_size}') if self.orientation() == Qt.Vertical: self.setFixedHeight(total_size) elif self.orientation() == Qt.Horizontal: self.setFixedWidth(total_size) for (i, stretch) in zip(range(self.count()), sizes): self.layout().setStretch(i*2, stretch) # QtWidgets.QApplication.instance().processEvents() # print(f' Eff: {self.sizes()}') # QtWidgets.QApplication.instance().processEvents() def changeWidgetSize(self, pos_or_widget, size, delta=False, fixed=False): """ Set the widget at pos to size. Adapt the size of the splitbox so no other widgets resizes """ sizes = self.sizes() if isinstance(pos_or_widget, int): pos = pos_or_widget widget = self.widget(pos) else: pos = self.indexOf(pos_or_widget) widget = pos_or_widget if self.orientation() == Qt.Vertical: widget_height = sizes[pos] if delta: size = widget_height + size new_widget_height = max(size, widget.minimumHeight()) sizes[pos] = new_widget_height if fixed: widget.setFixedHeight(size) elif self.orientation() == Qt.Horizontal: widget_width = sizes[pos] if delta: size = widget_width + size new_widget_width = max(size, widget.minimumWidth()) sizes[pos] = new_widget_width if fixed: widget.setFixedWidth(size) self.setSizes(sizes) class ScrollBox(QtWidgets.QScrollArea): def __init__(self, orientation): QtWidgets.QScrollArea.__init__(self) self.setWidgetResizable(True) if orientation == Qt.Vertical: self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) elif orientation == Qt.Horizontal: self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) pal = self.palette() pal.setColor(QtGui.QPalette.Background, QtGui.QColor(160,200,224)) self.setPalette(pal) self.growbox = SplitBox(orientation) self.setWidget(self.growbox) def addWidget(self, widget): self.growbox.addWidget(widget) def removeWidget(self, widget): self.growbox.removeWidget(widget) def count(self): return self.growbox.count()
thocoo/gamma-desk
gdesk/gcore/guiapp.py
<filename>gdesk/gcore/guiapp.py<gh_stars>0 import threading import sys, os import ctypes import logging import textwrap import pathlib import mmap import struct import threading import psutil from multiprocessing.connection import Pipe from multiprocessing.reduction import duplicate from qtpy import QtGui, QtWidgets, QtCore from qtpy.QtWidgets import QApplication, QShortcut, QDesktopWidget from qtpy.QtGui import QIcon, QKeySequence from qtpy.QtCore import Qt from .. import gui, config, PROGNAME from ..core.history import History from ..core.watcher import CommandServer from ..utils import new_id_using_keys from ..utils.namedmutex import NamedMutex from .qgc import QGarbageCollector from .threadcom import HandOver from .utils import getMenuAction, relax_menu_text, relax_menu_trace from ..panels.window import MainWindow from ..panels.panels import Panels from ..panels.base import thisPanel from ..dialogs.main import MainDialog here = pathlib.Path(__file__).parent respath = pathlib.Path(config['respath']) logger = logging.getLogger(__name__) class WaitCursorContext(object): def __init__(self, qapp, message=None): self.qapp = qapp self.message = message self.window = self.qapp.activeWindow() if not self.window in self.qapp.windows.values(): self.window = None def __enter__(self): self.qapp.setOverrideCursor(QtCore.Qt.WaitCursor) if not self.message is None: #TO DO, bring this to the relevant window status bar #self.qapp.panels['console'][0].addText(f'{self.message}\n') logger.info(self.message) if not self.window is None: self.window.statusBar().showMessage(self.message) self.qapp.processEvents() def __exit__(self, exc_type, exc, exc_tb): self.qapp.restoreOverrideCursor() self.qapp.processEvents() if not self.window is None: self.window.statusBar().clearMessage() class GuiApplication(QApplication): lastWindowId = 0 def __init__(self, shell, argv): self.shell = shell super().__init__(argv) self.windows = dict() self.panels = Panels(self) self.panelsDialog = MainDialog(self.panels) self.appIcon = QIcon(str(respath / 'logo' / 'logo_32px.png')) self.setWindowIcon(self.appIcon) self.handover = HandOver(self) self.history = History(self.shell.logdir.logpath) self.setFont(QtGui.QFont('MS Shell Dlg 2', pointSize=config['console']['fontsize'])) if os.name == 'nt': # This is needed to display the app icon on the taskbar on Windows 7 myappid = f'{PROGNAME}' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) self.gc = QGarbageCollector(self) self.gc.enable() self.selected_group = dict() self.radio_group = dict() self.bindicon = QtGui.QIcon() self.bindicon.addFile(str(respath / 'icons' / 'bind_12px.png'), state=QIcon.On) self.bindicon.addFile(str(respath / 'icons' / 'broken_12px.png'), state=QIcon.Off) self.resizeicon = QtGui.QIcon() self.resizeicon.addFile(str(respath / 'icons' / 'arrow_down_8px.png'), state=QIcon.Off) self.resizeicon.addFile(str(respath / 'icons' / 'arrow_right_8px.png'), state=QIcon.On) self.panelsDialog.showMinimized() self.focusChanged.connect(self.checkPanelActive) self.menuCallShortCuts = dict() def setShortCuts(self): for layid in range(1,10): self.setShortCut(f"{config['shortcuts']['layout']['prefix']}{layid}", lambda layid=layid: self.panels.restore_state_from_config(layid)) self.setPanelsDialogShortCut(config['shortcuts']['help'], ['Help', 'Help']) self.setPanelsDialogShortCut(config['shortcuts']['instance info'], ['Help', 'Instance Info']) self.setPanelsDialogShortCut(config['shortcuts']['panel preview'], ['Panel', 'Previews...']) self.setPanelsDialogShortCut(config['shortcuts']['window preview'], ['Window', 'Previews...']) self.setShortCut(config['shortcuts']['new panel'], lambda : self.showNewPanelDialog()) for keySequence, menuCallParams in config["shortcutmenu"].items(): for category, action_names in menuCallParams.items(): if not category in self.menuCallShortCuts.keys(): self.menuCallShortCuts[category] = dict() self.menuCallShortCuts[category][relax_menu_trace(action_names)] = keySequence self.setShortCut(keySequence, lambda keySequence=keySequence: self.menuShortCutCall(keySequence)) def setShortCut(self, keySequence, func): sc = QShortcut(QKeySequence(keySequence), self.panelsDialog, func) sc.setContext(Qt.ApplicationShortcut) def setPanelsDialogShortCut(self, keySequence, menuTrace): menuTrace = relax_menu_trace(menuTrace) def caller(): action = getMenuAction(self.panelsDialog.menuBar(), menuTrace) action.trigger() action = getMenuAction(self.panelsDialog.menuBar(), menuTrace) action.setText(f'{action.text()}\t{keySequence}') self.setShortCut(keySequence, caller) def menuShortCutCall(self, keySequence): shortCutParams = config["shortcutmenu"][keySequence] if len(shortCutParams) == 1: category, action_names = next(iter(shortCutParams.items())) panid = None else: category, panid, action_names = None, None, None for category in reversed(self.panels.keys()): panids = list(self.panels[category].keys()) if len(panids) == 0: continue if category in shortCutParams.keys(): for panid in reversed(panids): panel = self.panels[category][panid] if panel.window() == self.activeWindow(): action_names = shortCutParams[category] break if not action_names is None: break else: category = None if category is None: return elif category == 'window': window = self.activeWindow() action = getMenuAction(window.windowMenu, action_names) action.trigger() else: action = self.panels.get_menu_action(category, panid, action_names) if not action is None: action.trigger() def checkPanelActive(self, old, new): #This function is probably more called then needed ! logger.debug(f'focus changed from {old} to {new}') if new is None: return try: panel = thisPanel(new) if panel is None: return logger.debug(f'Selecting panel {panel.category}#{panel.panid}') panel.select() except Exception as ex: #Do not print any error message in the gui #It would emit focusChanged and lead to infinite loop sys.__stdout__.write(str(ex)) sys.__stdout__.flush() @property def mainWindow(self): return self.windows['main'] def showDialog(self): self.panelsDialog.refresh() self.panelsDialog.exec_(self.activeWindow()) def showNewPanelDialog(self): self.panelsDialog.newMenu.exec_(QtGui.QCursor.pos()) def closePanel(self): window = self.activeWindow() panel = self.panels[window.activeCategory][window.activePanId] panel.close_panel() def newWindow(self, name=None, parentName=None): if name is None: keys = [eval(k.split(' ')[1]) for k in self.windows.keys() if k.startswith('window ')] key = new_id_using_keys(keys) name = f'window {key}' self.windows[name] = window = MainWindow(self, name, parentName) return window def getActiveWindow(self): for winname, window in self.windows.items(): if window.isActiveWindow(): return window def cycleTagLevel(self): self.getActiveWindow().cycle_tag_level() def toggleFullScreen(self): self.getActiveWindow().fullScreen() def toggleMenuStatusbar(self): self.getActiveWindow().toggleMenuStatusbar() def toggleShortCuts(self): self.panelsDialog.setVisible(not self.panelsDialog.isVisible()) def deleteWindow(self, window): if isinstance(window, str): winname = window else: winname = window.name window = self.windows.pop(winname) container = self.panels.ezm.containers.pop(winname) window.deleteLater() def deleteEmptyWindows(self, check=False): for winname in list(self.windows.keys()): if winname == 'main': continue window = self.windows[winname] if window.container.is_empty(check): self.deleteWindow(winname) def waitCursor(self, message=None): return WaitCursorContext(self, message) def hideWindow(self, window=None): if not window is None: window.hide() #Close if no window visible visibles = [win.isVisible() for win in self.windows.values()] if sum(visibles) == 0: self.panelsDialog.showNormal() def eventloop(shell, init_code=None, init_file=None, console_id=0, pictures=None): """ The GUI Process and Thread running the eventloop """ shell.logdir.find_log_path() qapp = GuiApplication(shell, sys.argv) qapp.setShortCuts() qapp.newWindow('main') #To run in a new thread but on the same gui process #panid = qapp.mainWindow.newThread() qapp.mainWindow.show() desktopGeometry = QDesktopWidget().availableGeometry() qapp.mainWindow.resize(int(desktopGeometry.width()*3/5), int(desktopGeometry.height()*3/5)) qtRectangle = qapp.mainWindow.frameGeometry() centerPoint = desktopGeometry.center() qtRectangle.moveCenter(centerPoint) qapp.mainWindow.move(qtRectangle.topLeft()) # Make sure the gui proxy for the main thread is created qapp.panels.restore_state_from_config('base') # if not config['debug']['skip_restore_perspective']: # if config['default_perspective'] != 'base': # qapp.panels.restore_state_from_config(config['default_perspective']) qapp.processEvents() qapp.cmdserver = CommandServer(shell) if not init_file is None: cmd = {'cmd': 'execute_file', 'args': (init_file, console_id)} qapp.cmdserver.cmd_queue.put(cmd) if not init_code is None: cmd = {'cmd': 'execute_code', 'args': (init_code, console_id)} qapp.cmdserver.cmd_queue.put(cmd) if not pictures is None: cmd = {'cmd': 'open_images', 'args': pictures} qapp.cmdserver.cmd_queue.put(cmd) cmd = config.get('init_command') qapp.cmdserver.cmd_queue.put(cmd) qapp.cmdserver.start_queue_loop(qapp) qapp.cmdserver.start(qapp) exit_code = qapp.exec_() #Kill all the children parent = psutil.Process(os.getpid()) for child in parent.children(recursive=True): child.kill() from pylab import plt plt.close('all') sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ print(f'Exiting {PROGNAME}. Releasing lock.') shell.logdir.release_lock_file()
thocoo/gamma-desk
gdesk/utils/numba_func.py
import numpy as np import numba @numba.njit(cache=True) def bincount2d(array, minlength=65536): hist = np.bincount(array.ravel(), minlength=minlength) return hist @numba.njit(parallel=True, cache=True) def map_values_mono(source, target, mapvector): length = len(source) for i in numba.prange(length): value = source[i] target[i] = mapvector[value] @numba.njit(parallel=True, cache=True) def map_values_rgb(source, target, mapvector): height, width, channels = source.shape for i in numba.prange(height): for j in numba.prange(width): target[i,j,0] = mapvector[source[i,j,0]] target[i,j,1] = mapvector[source[i,j,1]] target[i,j,2] = mapvector[source[i,j,2]] @numba.njit(parallel=True, cache=True) def map_values_rgbswap(source, target, mapvector): height, width, channels = source.shape for i in numba.prange(height): for j in numba.prange(width): target[i,j,2] = mapvector[source[i,j,0]] target[i,j,1] = mapvector[source[i,j,1]] target[i,j,0] = mapvector[source[i,j,2]] target[i,j,3] = 255 @numba.njit(parallel=True, cache=True) def get_min_max(source): return source.min(), source.max() def nb_float_offset_gain_gamma_8bit(array, offset=0, gain=1, gamma=1): procarr = np.ndarray(array.shape, 'uint8') nb_float_offset_gain_gamma_loop(array, procarr, offset, gain, gamma * 1.0) return procarr @numba.njit(parallel=True, cache=True) def nb_float_offset_gain_gamma_loop(source, target, offset=0, gain=1, gamma=1): height, width = source.shape gscale = 255 ** (1 - gamma) for i in numba.prange(height): for j in numba.prange(width): tmp = (source[i,j] - offset) * (gain * 256) if gamma == 1.0: if tmp < 0: target[i,j] = 0 elif tmp > 255: target[i,j] = 255 else: target[i,j] = tmp else: tmp2 = tmp ** gamma * gscale if tmp2 < 0: target[i,j] = 0 elif tmp2 > 255: target[i,j] = 255 else: target[i,j] = tmp2
thocoo/gamma-desk
gdesk/utils/z_order.py
import ctypes GW_HWNDNEXT = 2 def get_windows(): '''Returns windows in z-order (top first)''' user32 = ctypes.windll.user32 lst = [] top = user32.GetTopWindow(None) if not top: return lst lst.append(top) while True: next = user32.GetWindow(lst[-1], GW_HWNDNEXT) if not next: break lst.append(next) return lst def get_z_values(*windows): """ Order these window in z order Top window first and lowest z value returns a list of [(z, window), ...] """ all_winids_zorder = get_windows() zorder = ((all_winids_zorder.index(window.winId()), window) for window in windows if window.winId() in all_winids_zorder) return sorted(zorder, key = lambda item: item[0])
thocoo/gamma-desk
gdesk/panels/imgview/fasthist.py
import sys import math import logging import numpy as np try: from ...utils import numba_func has_numba = True except: has_numba = False logger = logging.getLogger(__name__) def is_integer_num(n): if isinstance(n, int): return True if isinstance(n, float): return n.is_integer() return False def natural_range(dtype): if dtype in ['uint8', 'int8']: return 256 elif dtype in ['uint16', 'int16']: return 65536 elif dtype in ['uint32', 'int32']: return 4294967296 elif dtype in ['uint64', 'int64']: return 18446744073709551616 elif dtype in ['float16', 'float32', 'float64']: return 1 else: raise TypeError('dtype %s not supported to display' % str(statbuff.dtype)) def get_map16(dtype='float64', offset=0, gain=1): natrange = natural_range(dtype) return ((np.arange(natrange) - offset) * gain * 65536 / natrange).clip(0, 65536).astype('uint16') def hist2d(array, bins=64, step=None, low=None, high=None, pow2snap=True, plot=False, use_numba=True): if array.dtype in ['int8', 'uint8', 'int16', 'uint16']: assert pow2snap hist, starts, stepsize = hist16bit(array, bins, step, low, high, use_numba=True) return hist, starts, stepsize elif array.dtype in ['float16', 'float32', 'float64']: hist, starts, stepsize = histfloat(array, bins, step, low, high, pow2snap) return hist, starts, stepsize if plot: plt.bar(starts + stepsize/2, hist, stepsize) plt.grid() plt.xlabel('value [DN]') plt.ylabel('count') return hist, starts, stepsize def hist16bit(array, bins=64, step=None, low=None, high=None, use_numba=True): """ stepsize should be power of 2 array should be 8 or 16 bit integer """ if array.dtype == 'uint8': length = 256 offset = 0 elif array.dtype == 'int8': length = 256 offset = 128 elif array.dtype == 'uint16': length = 65536 offset = 0 elif array.dtype == 'int16': length = 65536 offset = 32768 if array.dtype in ['uint8', 'uint16']: if use_numba and has_numba: hist = numba_func.bincount2d(array, length) else: if use_numba: logger.warning('Numba is not available') hist = np.bincount(array.ravel(), minlength=length) elif array.dtype in ['int8', 'int16']: if array.dtype == 'int8': unsigned_array = array.view('uint8') else: unsigned_array = array.view('uint16') if use_numba and has_numba: hist = numba_func.bincount2d(unsigned_array, length) else: if use_numba: logger.warning('Numba is not available') hist = np.bincount(unsigned_array.ravel(), minlength=length) hist = np.r_[hist[len(hist)//2:], hist[:len(hist)//2]] non_zeros_indices = np.argwhere(hist > 0) min_index = non_zeros_indices[0][0] max_index = non_zeros_indices[-1][0] first_edge = min_index if low is None else low last_edge = max_index if high is None else high if step is None: if first_edge == last_edge: stepsize = max((last_edge - first_edge) / (bins-1), 1) else: stepsize = 1 else: stepsize = step stepsize = max(2**math.floor(np.log2(stepsize)), 1) if stepsize > 1: hist = hist.reshape(length // stepsize, stepsize).sum(1) non_zeros_indices = np.argwhere(hist > 0) min_index = non_zeros_indices[0][0] max_index = non_zeros_indices[-1][0] first_edge = min_index last_edge = max_index starts = np.arange(first_edge, last_edge+1) * stepsize - offset return hist[min_index:max_index+1], starts, stepsize def histfloat(array, bins=64, step=None, low=None, high=None, pow2snap=True, use_numba=True): if (low is None or high is None): if use_numba: minimum, maximum = numba_func.get_min_max(array) else: minimum, maximum = array.min(), array.max() first_edge = minimum if low is None else low last_edge = maximum if high is None else high if first_edge == last_edge: first_edge -= 0.5 last_edge += 0.5 if step is None: stepsize = (last_edge - first_edge) / (bins-1) else: stepsize = step if pow2snap: stepsize = 2**math.floor(np.log2(stepsize)) bins = min(math.ceil((last_edge - first_edge) / stepsize), 65536) starts = first_edge + np.arange(bins) * stepsize offset = first_edge if not len(starts) <= 65536: logger.warning(f'To many bins {len(starts)} is larger then 65536') logger.warning(f'first_edge: {first_edge}; last_edge: {last_edge}; stepsize: {stepsize}') starts = starts[:65536] #TO DO, clipping is only needed if values are outside the bins #This means that minimum and maximum should always be calculated if (offset != 0) and (stepsize != 1): array16bit = ((array - offset) / stepsize).clip(0, 65535).astype('uint16') elif (stepsize != 1): array16bit = (array / stepsize).clip(0, 65535).astype('uint16') elif (offset != 0): array16bit = (array - offset).clip(0, 65535).astype('uint16') else: array16bit = array.clip(0, 65535).astype('uint16') if use_numba and has_numba: hist = numba_func.bincount2d(array16bit, 65536)[:len(starts)] else: hist = np.bincount2d(array16bit, minlength=65536)[:len(starts)] return hist, starts, stepsize
thocoo/gamma-desk
gdesk/graphics/functions.py
import struct import numpy as np from qtpy import QtCore, QtGui Colors = { 'b': (0,0,255,255), 'g': (0,255,0,255), 'r': (255,0,0,255), 'c': (0,255,255,255), 'm': (255,0,255,255), 'y': (255,255,0,255), 'k': (0,0,0,255), 'w': (255,255,255,255), } def intColor(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255, **kargs): """ Creates a QColor from a single index. Useful for stepping through a predefined list of colors. The argument *index* determines which color from the set will be returned. All other arguments determine what the set of predefined colors will be Colors are chosen by cycling across hues while varying the value (brightness). By default, this selects from a list of 9 hues.""" hues = int(hues) values = int(values) ind = int(index) % (hues * values) indh = ind % hues indv = ind / hues if values > 1: v = minValue + indv * ((maxValue-minValue) / (values-1)) else: v = maxValue h = minHue + (indh * (maxHue-minHue)) / hues c = QtGui.QColor() c.setHsv(h, sat, v) c.setAlpha(alpha) return c def mkColor(*args): """ Convenience function for constructing QColor from a variety of argument types. Accepted arguments are: ================ ================================================ 'c' one of: r, g, b, c, m, y, k, w R, G, B, [A] integers 0-255 (R, G, B, [A]) tuple of integers 0-255 float greyscale, 0.0-1.0 int see :func:`intColor() <pyqtgraph.intColor>` (int, hues) see :func:`intColor() <pyqtgraph.intColor>` "RGB" hexadecimal strings; may begin with '#' "RGBA" "RRGGBB" "RRGGBBAA" QColor QColor instance; makes a copy. ================ ================================================ """ err = 'Not sure how to make a color from "%s"' % str(args) if len(args) == 1: if isinstance(args[0], QtGui.QColor): return QtGui.QColor(args[0]) elif isinstance(args[0], float): r = g = b = int(args[0] * 255) a = 255 #elif isinstance(args[0], basestring): elif isinstance(args[0], str): c = args[0] if c[0] == '#': c = c[1:] if len(c) == 1: (r, g, b, a) = Colors[c] if len(c) == 3: r = int(c[0]*2, 16) g = int(c[1]*2, 16) b = int(c[2]*2, 16) a = 255 elif len(c) == 4: r = int(c[0]*2, 16) g = int(c[1]*2, 16) b = int(c[2]*2, 16) a = int(c[3]*2, 16) elif len(c) == 6: r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) a = 255 elif len(c) == 8: r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) a = int(c[6:8], 16) elif hasattr(args[0], '__len__'): if len(args[0]) == 3: (r, g, b) = args[0] a = 255 elif len(args[0]) == 4: (r, g, b, a) = args[0] elif len(args[0]) == 2: return intColor(*args[0]) else: raise Exception(err) elif type(args[0]) == int: return intColor(args[0]) else: raise Exception(err) elif len(args) == 3: (r, g, b) = args a = 255 elif len(args) == 4: (r, g, b, a) = args else: raise Exception(err) args = [r,g,b,a] #args = [0 if np.isnan(a) or np.isinf(a) else a for a in args] args = list(map(int, args)) return QtGui.QColor(*args) def mkBrush(*args, **kwds): """ | Convenience function for constructing Brush. | This function always constructs a solid brush and accepts the same arguments as :func:`mkColor() <pyqtgraph.mkColor>` | Calling mkBrush(None) returns an invisible brush. """ if 'color' in kwds: color = kwds['color'] elif len(args) == 1: arg = args[0] if arg is None: return QtGui.QBrush(QtCore.Qt.NoBrush) elif isinstance(arg, QtGui.QBrush): return QtGui.QBrush(arg) else: color = arg elif len(args) > 1: color = args return QtGui.QBrush(mkColor(color)) def arrayToQPath(x, y, connect='all'): """Convert an array of x,y coordinats to QPainterPath as efficiently as possible. The *connect* argument may be 'all', indicating that each point should be connected to the next; 'pairs', indicating that each pair of points should be connected, or an array of int32 values (0 or 1) indicating connections. """ #CODE IS COPIED FROM PYQTGRAPH ## Create all vertices in path. The method used below creates a binary format so that all ## vertices can be read in at once. This binary format may change in future versions of Qt, ## so the original (slower) method is left here for emergencies: #path.moveTo(x[0], y[0]) #if connect == 'all': #for i in range(1, y.shape[0]): #path.lineTo(x[i], y[i]) #elif connect == 'pairs': #for i in range(1, y.shape[0]): #if i%2 == 0: #path.lineTo(x[i], y[i]) #else: #path.moveTo(x[i], y[i]) #elif isinstance(connect, np.ndarray): #for i in range(1, y.shape[0]): #if connect[i] == 1: #path.lineTo(x[i], y[i]) #else: #path.moveTo(x[i], y[i]) #else: #raise Exception('connect argument must be "all", "pairs", or array') ## Speed this up using >> operator ## Format is: ## numVerts(i4) 0(i4) ## x(f8) y(f8) 0(i4) <-- 0 means this vertex does not connect ## x(f8) y(f8) 1(i4) <-- 1 means this vertex connects to the previous vertex ## ... ## 0(i4) ## ## All values are big endian--pack using struct.pack('>d') or struct.pack('>i') path = QtGui.QPainterPath() #profiler = debug.Profiler() n = x.shape[0] # create empty array, pad with extra space on either end arr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')]) # write first two integers #profiler('allocate empty') byteview = arr.view(dtype=np.ubyte) byteview[:12] = 0 byteview.data[12:20] = struct.pack('>ii', n, 0) #profiler('pack header') # Fill array with vertex values arr[1:-1]['x'] = x arr[1:-1]['y'] = y # decide which points are connected by lines #I replaced eq function by == if connect == 'all': arr[1:-1]['c'] = 1 elif connect == 'pairs': arr[1:-1]['c'][::2] = 1 arr[1:-1]['c'][1::2] = 0 elif connect == 'finite': arr[1:-1]['c'] = np.isfinite(x) & np.isfinite(y) elif isinstance(connect, np.ndarray): arr[1:-1]['c'] = connect else: raise Exception('connect argument must be "all", "pairs", "finite", or array') #profiler('fill array') # write last 0 lastInd = 20*(n+1) byteview.data[lastInd:lastInd+4] = struct.pack('>i', 0) #profiler('footer') # create datastream object and stream into path ## Avoiding this method because QByteArray(str) leaks memory in PySide #buf = QtCore.QByteArray(arr.data[12:lastInd+4]) # I think one unnecessary copy happens here path.strn = byteview.data[12:lastInd+4] # make sure data doesn't run away try: buf = QtCore.QByteArray.fromRawData(path.strn) except TypeError: buf = QtCore.QByteArray(bytes(path.strn)) #profiler('create buffer') ds = QtCore.QDataStream(buf) ds >> path #profiler('load') return path
thocoo/gamma-desk
gdesk/panels/scriptwiz/examples/example_01/template.py
# https://palletsprojects.com/p/jinja/ # Jinja2 is a full-featured template engine for Python # Using it here to template Python code def func1(): grabs = len(idminst.grabber.keys()) {% for row in tabulated_items -%} print('{{row.name}}', '{{row.value}}') {% endfor %} def main(caller_argument): print('{{single_line_text}}') print("""{{multi_line_text}}""") print('{{some_file}}')
thocoo/gamma-desk
gdesk/dialogs/colormap.py
from qtpy import QtGui, QtWidgets, QtCore from ..widgets.thumbs import Thumbs from ..utils import imconvert class ColorMapDialog(QtWidgets.QDialog): def __init__(self): super().__init__() colormaps = imconvert.colormaps self.thumbs = Thumbs(self) for cm_name in colormaps: qimg = imconvert.color_table_preview_qimg(cm_name) self.thumbs.addQImage(qimg, cm_name) self.vbox = QtWidgets.QVBoxLayout(self) self.setLayout(self.vbox) self.vbox.addWidget(self.thumbs) self.okBtn = QtWidgets.QPushButton('Ok') self.okBtn.clicked.connect(self.ok) self.vbox.addWidget(self.okBtn) self.cm_name = None def ok(self): items = self.thumbs.selectedItems() if len(items) > 0: self.cm_name = items[0].text() else: self.cm_name = None self.accept()
thocoo/gamma-desk
gdesk/utils/names.py
""" Provide OrderedStruct and DictStruct classes. Also, provide two utility functions: current_code_path() and force2bytes(). """ import os, sys import collections from pathlib import Path def current_code_path(): """ Return the path of the caller's source code file. If the caller is the shell (interactive scripting), None is returned. :return: Path object or None. Example: # works only when used from a .py file, not when used # in a shell (on standard input): from iskutil.names import current_code_path folder = current_code_path().parent # in a shell this is what happens: current_code_path() is None >>> True """ # ensure that pathlib is available if Path is None: raise ImportError("Could not import pathlib; you need to use Python version v >= 3.4 or install a discrete pathlib module (e.g. pathlib2)") frame = sys._getframe(1) code_path = Path(frame.f_code.co_filename) if code_path.name == '<input>': # this code did not come from a .py file, but from standard # input; we don't have a valid Path to that return None return code_path.resolve() class OrderedStruct: """ Object that mimics a classic structure type for holding data and retains the order of the elements. You can think of this as an ordered DictStruct, but the name is 'OrderedStruct' because that is shorter ;-) All the methods of the dict class are supported, but they will return their values NOT ordered. Instead, call _keys(), _values(), _items() and friends prepended with an underscore. Usage: .. code :: Python os = OrderedStruct(a=20) os.b = 'new attribute b' [key_value for key_value in os] >>> [('a', 20), ('b', 'new attribute b')] """ def __init__(self, *args, **argv): if not argv is None: self.__dict__ = argv self.__keyorder__ = list(argv.keys()) else: self.__keyorder__ = [] def _keys(self): """ Alternative for the standard dict.keys() which *does* return elements in order. """ for key in self.__dict__.keys(): if not key.startswith('__'): yield key def _values(self): """ Alternative for the standard dict.values() which *does* return elements in order. """ for key in self._keys(): if not key.startswith('__'): yield self.__dict__[key] def _items(self): """ Alternative for the standard dict.items() which *does* return elements in order. """ for key in self._keys(): if not key.startswith('__'): yield (key, self.__dict__[key]) def __repr__(self): """ Return string reperesentation of the OrderedStruct. """ return "OrderedStruct(keys=['{}'])".format( "','".join(k for k in self.__keyorder__ if not k.startswith('_')) ) def __str__(self): """ Human-readable representation of the OrderedStruct. """ s = '' for key in self.__keyorder__: s += '%s: %s\n' % (key, getattr(self, key)) return s[:-1] def __setattr__(self, name, val): if name in ['__dict__', '__keyorder__']: object.__setattr__(self, name, val) elif not name == '__keyorder__': self.__dict__[name] = val if not name in self.__keyorder__: self.__keyorder__.append(name) def __delattr__(self, name): index = self.__keyorder__.index(name) self.__keyorder__.pop(index) self.__dict__.pop(name) def __add__(self, other): """ Return an OrderedStruct which is the superset of the current and the given OrderedStruct. """ if not isinstance(other, OrderedStruct): raise ValueError("Operation '+=' (__iadd__) is only defined for other OrderedStruct instances") result = OrderedStruct() result.__keyorder__ = self.__keyorder__.copy() result.__dict__.update(self.__dict__) return result.__iadd__(other) def __iadd__(self, other): """ Extend the current OrderedStruct by updating the current values with the values from the given OrderedStruct. """ if not isinstance(other, OrderedStruct): raise ValueError("Operation '+=' (__iadd__) is only defined for other OrderedStruct instances") keyorderbackup = self.__keyorder__.copy() self.__dict__.update(other.__dict__) #note that this update will overwrite self.__keyorder__ self.__keyorder__ = keyorderbackup for key in other.__keyorder__: if not key in self.__keyorder__: self.__keyorder__.append(key) return self def __iter__(self): """ Return all keys in the OrderedDict. """ for key in self.__keyorder__: yield key, self.__dict__[key] def __getitem__(self, index): return self.__dict__[self.__keyorder__[index]] def __getattr__(self, name): """ Get the value of any attribute name in the internal dictionary. This exposes the dict methods themselves as well, such as keys(), items(), get(), clear(), update(), ... . If the name is not present in the dictionary, raise AttributeError. That makes it compatible to hasattr(), which only catches AttributeErrors, but not KeyErrors. Note: this method returns 'None' for all attribute names which start with double underscore. This breaks hasattr(), which will return True for *any* such attributename. """ if name[0:2] == '__': return None return getattr(self.__dict__, name) def __contains__(self, key): """ Check if the DictStruct contains the given key. The main purpose of implementing this is speed: if it is missing, the 'in' operator will to an iteration over all the elements instead of just using the hash lookup. """ return key in self.__dict__ def __getstate__(self): target = dict() for key, item in self.__dict__.items(): target[key] = item return target def __setstate__(self, state): for key, item in state.items(): self.__dict__[key] = item class DictStruct(object): """ Object that mimics a classic structure type for holding data. You can consider it to be a dict with all the key/value pairs as object attributes, making it easier to do auto-completion on. Regular dict methods such as keys(), values() and get() are all present. Usage: .. code :: Python from iskutil.names import DictStruct d = DictStruct(x=50) d.a = 'new attribute a on first level' d.b = 508 print(d.a, d.b) """ def __init__(self, dictionary=None): '''dictionary: use the existing dictionary for this class''' if not dictionary is None: self.__dict__ = dictionary def __repr__(self): """ Return string reperesentation of the DictStruct. """ return "DictStruct(keys=['{}'])".format( "','".join(k for k in self.keys()) ) def __str__(self): s = '' for key, val in self.__dict__.items(): s += '%s: %s\n' % (key, str(val)) return s[:-1] def __getattr__(self, name): """ Get the value of any attribute name in the internal dictionary. This exposes the dict methods themselves as well, such as keys(), items(), get(), clear(), update(), ... If the name is not present in the dictionary, raise AttributeError. That makes it compatible to hasattr(), which only catches AttributeErrors, but not KeyErrors. Note: this method returns 'None' for all attribute names which start with double underscore. This breaks hasattr(), which will return True for *any* such attributename. """ if name[0:2] == '__': raise AttributeError(name) return getattr(self.__dict__, name) def __iadd__(self, other): """ Extend the current DictStruct by updating the current values with the values from the given DictStruct. """ if not isinstance(other, DictStruct): raise ValueError("Operation '+=' (__iadd__) is only defined for other DictStruct instances") self.__dict__.update(other.__dict__) return self def __iter__(self): """ Allow to loop over all keys in the DictStruct. Ignore keys which start with an underscore. """ keys = list(self.__dict__.keys()) for key in keys: if not key.startswith('_'): yield key def _clear(self, keys): """ Remove the given keys (or key) from the DictStruct. This is a public function, but starts with an underscore to avoid it showing up in auto-complete, where you expect only the *content* of the DictStruct to appear. Usage: ds._clear(['a', 'b', 'x']) ds._clear('my_var') """ # we expect a list; convert a single string to a list if isinstance(keys, str): keys = [keys] for key in list(keys): del self.__dict__[key] def __getitem__(self, key): """ Get the given item using obj[angle_bracket] syntax. Is essentially the same as using obj.direct_access. """ return self.__dict__[key] def __setitem__(self, key, value): """ Set the given item using obj[angle_bracket] syntax. Is essentially the same as using obj.direct_access. """ self.__dict__[key] = value def __delitem__(self, key): """ Remove the given item from the dictstruct. Is an alternative to _clear(). """ del self.__dict__[key] def __contains__(self, key): """ Check if the DictStruct contains the given key. The main purpose of implementing this is speed: if it is missing, the 'in' operator will to an iteration over all the elements instead of just using the hash lookup. """ return key in self.__dict__ def addprop(inst, name, getter, setter=None, doc=None): cls = type(inst) if not hasattr(cls, '__perinstance'): cls = type(cls.__name__, (cls,), {}) cls.__perinstance = True inst.__class__ = cls #not sure this is needed ! setattr(cls, name, property(getter, setter, doc)) def fromfilename(fileName): '''parse a filename to a valid identifier extension is removed ''' basename = os.path.basename(fileName) (rootname, ext) = os.path.splitext(basename) rootname = rootname.replace(' ','_') varname = '' ch = rootname[0] if ch.isdigit(): varname += 'x' + ch elif ch.isidentifier(): varname += ch else: varname += 'x' + hex(ord(ch)) for i in range(1, len(rootname)): ch = rootname[i] if ch.isidentifier() or ch.isdigit(): varname += ch else: varname += hex(ord(ch)) if not varname.isidentifier(): raise Exception('could not parse to valid identifier') return varname def find_names(obj): #return the list of names refering to the object # #http://pythonic.pocoo.org/2009/5/30/finding-objects-names import gc, sys #Well, since the names of all locals are known at compile-time, Python optimizes function locals, #putting them into an array instead of a dictionary, which speeds up access tremendously. #But there is a way to get at the locals in a dictionary, namely the locals() function. #There must be some way to get Python to create it for us! #This is best done accessing the frame object's f_locals attribute which creates and caches this dictionary, #and that can be used to create dict references to all locals if the whole chain #of currently executed frames is traversed, as the first for loop does. # #next lines are needed to find names of compiled objects #not needed for life objects #frame = sys._getframe() #for frame in iter(lambda: frame.f_back, None): # frame.f_locals #========= result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.items(): if v is obj: result.append(k) return result def force2bytes(s): """ Convert the given string to bytes by encoding it. If the given argument is not a string (already bytes?), then return it verbatim. :param s: Data to encode in bytes, or any other object. :return: Bytes-encoded variant of the string, or the given argument verbatim. """ if isinstance(s, str): return s.encode() else: return s
thocoo/gamma-desk
gdesk/rectable/utils.py
import numpy as np from .base import RecordTable def compare(table1, table2, value_column_name, index_column_name=None): if index_column_name is None: valcol1 = table1.sa[value_column_name] valcol2 = table2.sa[value_column_name] difflocs = np.where(valcol1 != valcol2) difftable = RecordTable() difftable.add_column('value1', data=valcol1[difflocs]) difftable.add_column('value2', data=valcol2[difflocs]) else: ind1 = table1.sa[index_column_name] ind2 = table2.sa[index_column_name] valcol1 = table1.colnames.index(value_column_name) valcol2 = table2.colnames.index(value_column_name) locs1 = dict(zip(ind1, range(len(ind1)))) locs2 = dict(zip(ind2, range(len(ind2)))) indices = sorted(set(ind1).union(set(ind2))) difftable = RecordTable(['index', 'value1', 'value2']) for ind in indices: loc1 = locs1.get(ind, None) loc2 = locs2.get(ind, None) rec1 = None if loc1 is None else table1[loc1] rec2 = None if loc2 is None else table2[loc2] if rec1[valcol1] != rec2[valcol2]: difftable.add_row((ind, rec1[valcol1], rec2[valcol2])) return difftable
thocoo/gamma-desk
gdesk/gcore/utils.py
""" Small utils directly related to QT """ import collections from pathlib import Path from qtpy import QtWidgets from .. import config respath = Path(config['respath']) def relax_menu_text(text): """Remove any &, lower case, stop at first \\t""" tmp = text.replace('&', '').lower() tabind = tmp.find('\t') if tabind > 0: tmp = tmp[:tabind] return tmp.strip() def relax_menu_trace(menutrace): """relax_menu_text on every string of menutrace""" return tuple(relax_menu_text(item) for item in menutrace) def getMenuTrace(menu): """Return the current menu location as a list of strings""" menutrace = [menu.title().strip('&')] scan_action = menu.menuAction() while not scan_action is None: aw = scan_action.associatedWidgets() if len(aw) > 0 and isinstance(aw[0], QtWidgets.QMenu): menu = aw[0] menutrace.append(menu.title().strip('&')) scan_action = menu.menuAction() else: break return menutrace[::-1] def getMenuAction(menubar, menutrace): """Locate the action in a menubar""" actions = menubar.actions() action = None menutrace = relax_menu_trace(menutrace) for check_action_name in menutrace: for action in actions: action_name = action.text() action_name = relax_menu_text(action_name) if action_name == check_action_name: menu = action.menu() if not menu is None: #Cause showEvent which is sometimes used to refresh the menu content menu.show() actions = action.menu().actions() menu.hide() else: actions = [] break else: raise KeyError(f'Action part "{check_action_name}" not found') return action class ActionArguments(object): def __init__(self, qwidget): self.qwidget = qwidget self.args = collections.OrderedDict() def __setitem__(self, key, value): self.args[key] = value def __getitem__(self, key): return self.args[key] def isNotSet(self): return self.qwidget.sender().data() is None def __enter__(self): return self def __exit__(self, *args, **kwargs): arguments = self.qwidget.sender().data() or {} self.args.update(dict(zip(self.args.keys(), arguments.get('args', [])))) self.args.update(arguments.get('kwargs', {}))
thocoo/gamma-desk
gdesk/panels/imgview/operation.py
import os import time import collections from pathlib import Path import types from collections.abc import Iterable import queue import logging import numpy as np logger = logging.getLogger(__name__) from ... import config, gui if config.get('qapp', False): #only import qt stuff if process is gui from ...panels import CheckMenu from ...dialogs.formlayout import fedit else: #fake it CheckMenu = object # The nested functions are still callable # from a non qt process from .blueprint import make_thumbnail class OperationMenu(CheckMenu): def __init__(self, name, parentMenu=None, basePanel=None): super().__init__(name, parentMenu) basePanel.addMenuItem(self, 'Sum', self.sum, statusTip="Sum of 2 images", icon='image_add') basePanel.addMenuItem(self, 'Subtraction', self.subtraction, statusTip="Subtraction of 2 images", icon='image_delete') basePanel.addMenuItem(self, 'Difference', self.difference, statusTip="Difference of 2 images") basePanel.addMenuItem(self, 'Multiply', self.multiply, statusTip="Multiply of 2 images") basePanel.addMenuItem(self, 'Maximum', self.maximum, statusTip="Element-wise maximum of pixels of 2 images") basePanel.addMenuItem(self, 'Minumum', self.minimum, statusTip="Element-wise minimum of 2 images") def sum(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Sum') if results is None: return image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs dtype1 = image1.dtype dtype2 = image2.dtype if dtype1 == dtype2 == 'uint8': image3 = image1.astype('uint16') + image2.astype('uint16') elif dtype1 == dtype2 == 'uint16': image3 = image1.astype('uint32') + image2.astype('uint32') else: image3 = image1.astype('double') + image2.astype('double') pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id)) def subtraction(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Offset", 0), ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Subtraction') if results is None: return offset, image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid, offset): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs dtype1 = image1.dtype dtype2 = image2.dtype if dtype1 == dtype2 == 'uint8': image3 = (image1.astype('int16') - image2.astype('int16') + offset) elif dtype1 == dtype2 == 'uint16': image3 = (image1.astype('int32') - image2.astype('int32') + offset) else: image3 = image1.astype('double') - image2.astype('double') + offset pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id, offset)) def difference(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Difference') if results is None: return image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs dtype1 = image1.dtype dtype2 = image2.dtype if dtype1 == dtype2 == 'uint8': image3 = np.abs(image1.astype('int16') - image2.astype('int16')).clip(0, 2**8-1).astype('uint8') elif dtype1 == dtype2 == 'uint16': image3 = np.abs(image1.astype('int32') - image2.astype('int32')).clip(0, 2**16-1).astype('uint16') else: image3 = np.abs(image1.astype('double') - image2.astype('double')) pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id)) def multiply(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Multiply') if results is None: return image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs dtype1 = image1.dtype dtype2 = image2.dtype if dtype1 == dtype2 == 'uint8': image3 = image1.astype('uint16') * image2.astype('uint16') elif dtype1 == dtype2 == 'uint16': image3 = image1.astype('uint32') * image2.astype('uint32') pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id)) def maximum(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Multiply') if results is None: return image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs image3 = np.maximum(image1, image2) pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id)) def minimum(self): imviewers = dict() for imviewid in sorted(gui.qapp.panels['image'].keys()): imviewers[f'image#{imviewid}'] = imviewid imviewidkeys = list(imviewers.keys()) form = [ ("Image 1", [1] + imviewidkeys), ("Image 2", [2] + imviewidkeys)] results = fedit(form, title='Multiply') if results is None: return image1_ind, image2_ind = results image1_id = imviewers[imviewidkeys[image1_ind-1]] image2_id = imviewers[imviewidkeys[image2_ind-1]] def console_run(image1_pid, image2_pid): gui.img.select(image1_pid) image1 = gui.vs gui.img.select(image2_pid) image2 = gui.vs image3 = np.minimum(image1, image2) pid = gui.img.new() gui.img.select(pid) gui.img.show(image3) panel = gui.qapp.panels.selected('console') panel.task.call_func(console_run, args=(image1_id, image2_id))
thocoo/gamma-desk
gdesk/console.py
""" Gamma Desk interface to the DOS console """ import sys import os import logging import argparse from pathlib import Path from . import __release__, refer_shell_instance from . import configure, config, DOC_HTML, PROGNAME from .core import conf logger = logging.getLogger(__name__) boot_handler = logging.StreamHandler(sys.stdout) boot_handler.set_name('boot') logging.root.addHandler(boot_handler) MODNAME = '.'.join(globals()['__name__'].split('.')[:-1]) PATH_SEPERATOR = ';' if sys.platform == 'win32' else ':' HEADER = f"{PROGNAME} {__release__}" HEADER += '\n' + len(HEADER) * '=' + '\n' HEADER += DOC_HTML + '\n' EPILOG = f"""\ Examples -------- {MODNAME} -i init_file.py {MODNAME} -c config_file.??? """ def argparser(): """ Make the ArgumentParser instance """ parser = argparse.ArgumentParser(description=HEADER, prog=f'python -m {MODNAME}', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=EPILOG) parser.add_argument("-c", "--config_file", help="Use this configuration file") parser.add_argument("-i", "--init_file", help="Run this init file in console 1") parser.add_argument("-d", "--debug", action='store_true', help="Set logging level to debug") parser.add_argument("pictures", nargs='*', help="Image file to load") return parser def argexec(argv=None, **config_kwargs): """ Configure and start the eventloop """ bootpath = Path('.').resolve() print(f'Bootpath: {bootpath}') parser = argparser() args = parser.parse_args(argv) if args.debug: config_kwargs['logging_level'] = 'DEBUG' logging.root.setLevel(config_kwargs['logging_level']) config_kwargs['qapp'] = True if args.config_file: config_kwargs['path_config_files'] = [args.config_file] if args.init_file: config_kwargs['init_file'] = args.init_file configure(**config_kwargs) # Configure has to be done before import other modules from .core.shellmod import Shell shell = Shell() refer_shell_instance(shell) watcher_ports = shell.get_watcher_ports() pics = [bootpath / p for p in args.pictures] if len(watcher_ports) > 0: if args.pictures: from gdesk.core.watcher import CommandClient cmd = {'cmd': 'open_images', 'args': pics} cmdclient = CommandClient(watcher_ports[0], 'localhost') cmdclient.send(cmd) return from .gcore.guiapp import eventloop eventloop(shell, init_file=config['init_file'], pictures=pics) return shell def run_as_child(console_args, config_kwargs, config_objects): """ Top level function to start as child process """ #Note that auto unpickling of received arguments can have caused a configarion to be execed #The configuration was triggered by the Process code on decode this function pointer conf.config_objects.update(config_objects) #Allow reconfiguring conf.config.clear() conf.configured = False print(config_kwargs) argexec(console_args, **config_kwargs) def is_imported_by_child_process(): """ Detect whenever this module is imported by multiprocessing.spawn """ frame = sys._getframe() while not frame is None: module_name = frame.f_globals['__name__'] if module_name == 'multiprocessing.spawn': return True frame = frame.f_back return False def restart(): # in case of started with -m gdesk and extra arguments # sys.argv: # ['c:\\users\\thomas.cools\\projects\\gamma-desk\\git\\gdesk\\__main__.py', '-c', '..\\setup\\gdconf.json'] # in case of started with \scripts\gdesk.exe and extra arguments # ['C:\\Users\\thomas.cools\\AppData\\Local\\Programs\\Python\\venv\\os10a10\\Scripts\\gdesk', '-c', '../setup/gdconf.json'] # extra_arguments = sys.argv[1:] os.execlp(sys.executable, 'python', '-m', 'gdesk', *extra_arguments) if is_imported_by_child_process(): configure(qapp=True)
thocoo/gamma-desk
gdesk/core/conf.py
import os import sys import time import collections from pathlib import Path import json import importlib import copy import re import logging logger = logging.getLogger(__name__) global config config = dict() config_objects = dict() configured = False here = Path(__file__).parent.absolute() FIRST_CONFIG_FILE = here.parent / 'config' / 'defaults.json' REQUIRED = [ ('numpy', 'numpy'), ('matplotlib', 'matplotlib'), ('PySide2', 'PySide2'), ('qtpy', 'qtpy'), ('psutil', 'psutil'), ('numba', 'numba'), ('pyzmq', 'zmq'), ('gdesk', 'gdesk'), ] PATHPATTERN = re.compile('path_\w*') def deep_update(source, overrides): """ Update a nested dictionary or similar mapping. Modify ``source`` in place. """ for key, value in overrides.items(): if isinstance(value, collections.Mapping) and value: returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] if PATHPATTERN.match(str(key)) or key in ['respath']: if not source[key] is None: if isinstance(source[key], list): source[key] = [os.path.expandvars(val) for val in source[key]] else: source[key] = os.path.expandvars(source[key]) return source def deep_diff(dict1, dict2): """ Difference of nested dictionary or similar mapping. """ common_keys = set(dict1.keys()).intersection(set(dict2.keys())) dict2_keys_only = set(dict2.keys()).difference(set(dict1.keys())) result = dict((key, dict2[key]) for key in dict2_keys_only) for key in common_keys: value1 = dict1[key] value2 = dict2[key] if isinstance(value1, collections.Mapping): assert isinstance(value2, collections.Mapping) value = deep_diff(value1, value2) if len(value) > 0: result[key] = value elif value1 != value2: result[key] = value2 return result def list_packages(packages): for (package, base) in packages: found = importlib.util.find_spec(base) if found is None: logger.debug(f'{package}:\n NOT FOUND') else: modified = os.path.getmtime(found.origin) modified_str = time.strftime('%Y-%b-%d %H:%M:%S',time.gmtime(modified)) origin = Path(found.origin) install_dir = origin.parent.parent logger.debug(f'{package}:\n {origin.parent}\n {origin.name}: {modified_str}') for path in install_dir.glob(f'{package}*.dist-info'): logger.debug(f' dist-info: {path.stem}') def configure(**overwrites): global configured if configured: name = sys._getframe(1).f_globals['__name__'] if not name in ['gdesk.core.tasks']: logging.warning(f'configure unexpected called from {name} but already configured, no reconfiguring done') return else: configured = True os.environ['GDESKROOT'] = str(here.parent.absolute()) config_file = FIRST_CONFIG_FILE print(f'Loading config: {config_file}') deep_update(config, load_config(config_file)) prior_config_file = None config_files = overwrites.get('path_config_files', None) or config.get('path_config_files', []) #if not isinstance(config_files, list): config_files = [config_files] while len(config_files) > 0: print(f'config_files: {config_files}') next_config_file = config_files.pop(0) config_file = Path(next_config_file).expanduser() if not config_file.exists(): logger.warn(f'Configfile not found: {config_file}') continue print(f'Loading config: {config_file}') deep_update(config, load_config(config_file)) prior_config_file = config_file config_files = config.get('path_config_files', []) deep_update(config, overwrites) os.environ['QT_API'] = config['qt_api'] logging.root.setLevel(config['logging_level']) if config['debug'].get('list_packages', False): list_packages(REQUIRED) #TO DO: import register_objects_in_ghawk2_init #from ghawk2.core.gui_proxy import register_objects_in_ghawk2_init #register_objects_in_ghawk2_init() # Importing matplotlib takes some time ! # It also imports numpy import matplotlib matplotlib.use(config['matplotlib']['backend']) #This will also call the backend module #Which import ..panels.matplot import pylab #Configure and register plugins for panel_class_module in config["panel_class_modules"]: exec(f'import {panel_class_module}') def save_config_json(path=None): current_config = copy.deepcopy(config) current_config['qapp'] = False current_config['next_config_file'] = None save_config = not_defaults(current_config) with open(path, 'w') as fp: json.dump(save_config, fp, indent=2) def load_config(path): config_file = Path(path) if config_file.suffix in ['.cpy']: config_dict = eval(open(config_file).read()) elif config_file.suffix in ['.json']: config_dict = load_config_json(config_file) return config_dict def load_config_json(path=None): with open(path, 'r') as fp: loaded_config = json.load(fp) return loaded_config def not_defaults(current_config): defaults = {} deep_update(defaults, load_config(FIRST_CONFIG_FILE)) return deep_diff(defaults, current_config)
thocoo/gamma-desk
gdesk/panels/console/consolepanel.py
import os import textwrap import psutil import time import logging from pathlib import Path from qtpy import QtCore, QtGui, QtWidgets from qtpy.QtCore import Qt, QTimer, QSize from qtpy.QtGui import QFont, QFontMetrics, QTextCursor, QTextOption, QPainter, QTextCharFormat from qtpy.QtWidgets import (QAction, QMainWindow, QPlainTextEdit, QSplitter, QVBoxLayout, QLineEdit, QLabel, QMessageBox, QTextEdit, QWidget, QStyle, QStyleFactory, QApplication, QCompleter, QComboBox) from ... import config, gui from ...core import tasks from ...core.shellmod import Shell from ...panels.base import BasePanel, selectThisPanel, CheckMenu from ...dialogs.formlayout import fedit from ...dialogs.base import messageBox from ...dialogs.editpaths import EditPaths from ...utils.syntax_light import analyze_python, ansi_highlight from ...utils.ansi_code_processor import QtAnsiCodeProcessor from ...gcore.utils import getMenuAction from ...core import stdinout respath = Path(config['respath']) logger = logging.getLogger(__name__) MAXCHARPERLINE = 10000 #Only for ansi mode #PREFIXWIDTH = 30 # width of the left side line numbers ANSI_ESCAPE_SYNTAX_HIGHLIGHT = { 'comment': ('\033[38;5;2m', '\033[39m'), 'string': ('\033[38;5;8m', '\033[39m'), 'docstring': ('\033[38;5;208m', '\033[39m'), 'keyword': ('\033[38;5;12m', '\033[39m'), 'builtin': ('\033[38;5;6m', '\033[39m'), 'definition': ('\033[38;5;12m', '\033[39m'), 'defname': ('\033[38;5;13m', '\033[39m'), 'operator': ('\033[38;5;4m', '\033[39m'), } ESC = '\033[' ERROR_PREFIX = ESC + '38;5;9m' ERROR_SUFFIX = ESC + '0m' class LineNumberArea(QWidget): def __init__(self, textEditor): QWidget.__init__(self, textEditor) self.textEditor=textEditor self.prefix_color = Qt.lightGray self.prefix_font_color = Qt.black self.update_font() self._firstlinecode = [' >>> '] self.blinks = [':',' '] self.painter = QPainter() self.promptTimer = QTimer(self) self.promptTimer.timeout.connect(self.nextPrompt) self.profile_start = time.monotonic() self.profile_threshold = 10 self.profile_enabled = False def start_profiling(self): self.profile_start = time.monotonic() self.profile_enabled = True def stop_profiling(self): self.profile_enabled = False def update_font(self): self.setFont(self.textEditor.font()) self.fontmetric = QFontMetrics(self.textEditor.font()) self.prefixwidth = self.fontmetric.width('12345') self.prefixheight = self.fontmetric.height() self.setFixedWidth(self.prefixwidth) self.textEditor.setViewportMargins(self.prefixwidth, 0, 0, 0) def set_firstlinecode(self, prefices): self._firstlinecode = prefices if len(self._firstlinecode) > 1: self.promptTimer.start(500) else: self.promptTimer.stop() def get_firstlinecode(self): if self.profile_enabled: elapsed = time.monotonic() - self.profile_start if elapsed > self.profile_threshold: if elapsed >= 3600: profile = time.strftime("%H:%M", time.gmtime(elapsed)) else: profile = time.strftime("%M:%S", time.gmtime(elapsed)) return profile[:-3] + self.blinks[0] + profile[-2:] return self._firstlinecode[0] firstlinecode = property(get_firstlinecode, set_firstlinecode) def nextPrompt(self): self._firstlinecode = self._firstlinecode[1:] + self._firstlinecode[:1] self.blinks = self.blinks[1:] + self.blinks[:1] self.repaint() def paintEvent(self, event): cursor = self.textEditor.cursorForPosition(self.textEditor.viewport().pos()) painter = self.painter try: painter.begin(self) painter.fillRect(event.rect(), self.prefix_color) for i in range(100): blockNumber = cursor.block().blockNumber() if blockNumber == 0: code = self.firstlinecode else: code = str(blockNumber + 1) painter.setPen(self.prefix_font_color) y = self.textEditor.cursorRect(cursor).y() + self.textEditor.viewport().pos().y() - 2 painter.drawText(0, y, self.prefixwidth, self.prefixheight, Qt.AlignRight, code) if y > event.rect().bottom(): break if not cursor.block().next().isValid(): break cursor.movePosition(cursor.NextBlock) finally: painter.end() def sizeHint(self): return QSize(self.prefixwidth, 0) class StdInputPanel(QPlainTextEdit): def __init__(self, parent, task, outputPanel): super().__init__(parent = parent) self.task = task self.outputPanel = outputPanel self.qapp = QApplication.instance() self.prior_cmd_id = None self.hist_prefix = None self.configure(config) self.lineNumberArea=LineNumberArea(self) #self.setFocusPolicy(Qt.StrongFocus) self.styles = dict() self.styles['interprete'] = "background-color:white;" self.styles['wait'] = "background-color:#DDBBBB;" self.styles['running'] = "background-color:#FFFFE0;" self.styles['input'] = "background-color:#BBBBDD;" self.styles['ended'] = "background-color:#EFEFEF;" self.setMinimumHeight(32) self.mode = 'interprete' self.heightHint = 100 def configure(self, config): console_font = QFont('Consolas', pointSize=config['console']['fontsize']) self.setFont(console_font) if config['console']['wrap']: self.setWordWrapMode(QTextOption.WordWrap) else: self.setWordWrapMode(QTextOption.NoWrap) self.setUndoRedoEnabled(True) def sizeHint(self): return QtCore.QSize(200, self.heightHint) def resizeEvent(self, event): super().resizeEvent(event) rect=self.contentsRect() self.lineNumberArea.setGeometry(rect.x(),rect.y(), self.lineNumberArea.prefixwidth, rect.height()) def keyPressEvent(self, event): self.lineNumberArea.update(0, 0, self.lineNumberArea.width(), self.lineNumberArea.height()) #Is the enter pressed on numeric keypad or on the base keypad key_enter = (event.key() == Qt.Key_Return) or \ (event.key() == Qt.Key_Enter) #left or right shift modifiers = event.nativeModifiers() key_shift = modifiers & 1 == 1 or modifiers & 16 == 16 #left or right ctrl key_ctrl = modifiers & 2 == 2 or modifiers & 32 == 32 if not event.key() in [Qt.Key_Up, Qt.Key_Down]: self.prior_cmd_id = None self.hist_prefix = None if key_enter: if key_ctrl: self.execute_commands() elif key_shift: self.textCursor().insertBlock() else: if self.blockCount() == 1: self.execute_commands() else: if self.lastLineIsEmpty(): self.execute_commands() else: self.textCursor().insertBlock() elif event.key() == Qt.Key_Tab: if key_ctrl or key_shift: self.startAutoCompleter(wild=True) else: self.startAutoCompleter() elif event.key() == Qt.Key_Up and self.textCursor().block().blockNumber() == 0: if self.hist_prefix is None: self.hist_prefix = self.toPlainText() self.prior_cmd_id, cmd = self.qapp.history.retrievecmd(self.hist_prefix, self.prior_cmd_id, distinct=True, back=True, prefix=not key_ctrl) self.setPlainText(cmd) self.moveCursorToEndOfBlock() elif event.key() == Qt.Key_Down and self.textCursor().block().blockNumber() == (self.blockCount()-1): if self.hist_prefix is None: self.hist_prefix = self.toPlainText() self.prior_cmd_id, cmd = self.qapp.history.retrievecmd(self.hist_prefix, self.prior_cmd_id, distinct=True, back=False, prefix=not key_ctrl) self.setPlainText(cmd) self.moveCursorToEndOfDoc() else: super().keyPressEvent(event) def lastLineIsEmpty(self): self.cursor=self.textCursor() if self.cursor.block().blockNumber() != (self.blockCount() - 1): return False self.cursor.movePosition(self.cursor.EndOfLine, self.cursor.KeepAnchor) curdocpos = self.cursor.position() self.cursor.movePosition(self.cursor.StartOfLine, self.cursor.KeepAnchor) startlinepos = self.cursor.position() return curdocpos == startlinepos def startAutoCompleter(self, wild=False): #delims = ' \t\n\\"\'`@$><=;|&{(' delims = ' \t\n`@$><=;|&{(' current_text = self.toPlainText() try: pos = min(current_text[::-1].index(c) for c in delims if c in current_text) part = current_text[-pos:] except: pos = len(current_text) if pos == 0: self.insertText(' ') return self.keep, self.part = current_text[:-pos], current_text[-pos:] self.outputPanel.addText(f'{self.part}*\n') max_items = config['console']['max_complete'] self.task.call_func(Shell.get_completer_data, (self.part, max_items, wild), self.response_to_autocomplete) def moveCursorToEndOfBlock(self): cursor=self.textCursor() cursor.movePosition(cursor.EndOfBlock) self.setTextCursor(cursor) def moveCursorToEndOfDoc(self): cursor=self.textCursor() cursor.movePosition(cursor.End) self.setTextCursor(cursor) def execute_commands(self, cmd=None): if cmd is None: cmd = self.toPlainText() if self.mode in ['interprete', 'running']: cmd = textwrap.dedent(cmd) histcmd = cmd if cmd.startswith('%'): cmd = 'shell.magic(r"""' + cmd[1:]+ '""")' elif cmd.startswith('!!'): cmd = 'shell.popen(r"""' + cmd[2:] + '""", shell=False)' elif cmd.startswith('!'): cmd = 'shell.popen(r"""' + cmd[1:] + '""", shell=True)' elif cmd.endswith('??'): cmd = 'shell.edit(' + cmd[:-2] + ')' elif cmd.endswith('?'): histcmd = cmd cmd = 'help(' + cmd[:-1] + ')' elif cmd.endswith('!!'): cmd = 'shell.pprint(' + cmd[:-2] + ')' elif cmd.endswith('!'): cmd = 'print(' + cmd[:-1] + ')' if cmd.count('\n') == 0: prefix = '\033[48;5;7m>>>\033[0m \033[1m' suffix = '\033[0m\n' else: prefix = '\033[48;5;7m>>>\n\033[0m\033[1m' suffix = '\033[0m\n\033[48;5;7m<<<\033[0m\n' try: cmdecho = ansi_highlight(analyze_python(cmd), colors=ANSI_ESCAPE_SYNTAX_HIGHLIGHT) except: cmdecho = cmd self.outputPanel.addAnsiText(prefix + cmdecho + suffix) self.qapp.history.logcmd(histcmd) self.task.send_command(cmd, self.retval_ready) #self.set_mode('running') self.clear() elif self.mode == 'input': if cmd.count('\n') == 0: prefix = '\033[48;5;7m>?\033[0m \033[1m' suffix = '\033[0m\n' else: prefix = '\033[48;5;7m>?\n\033[0m\033[1m' suffix = '\033[0m\n\033[48;5;7m?<\033[0m\n' self.outputPanel.addAnsiText(prefix + cmd + suffix) self.task.send_input(cmd) self.clear() def retval_ready(self, mode, error_code, result): if mode == 'interprete': if error_code == 1: self.outputPanel.addAnsiText(f'\033[38;5;9msyntax error: {result}\033[0m\n') elif error_code == 2: self.outputPanel.addAnsiText(f'\033[38;5;9mincomplete error: {result}\033[0m\n') self.setPlainText(result + '\n') self.moveCursorToEndOfDoc() self.set_mode('interprete') def set_mode(self, mode='interprete'): if mode == 'wait': self.setStyleSheet(self.styles[mode]) self.mode = mode self.lineNumberArea.firstlinecode = [' ... ', ' ...', ' ..', ' .', ' ', '. ', '.. ', '... '] self.lineNumberArea.start_profiling() self.setReadOnly(True) if mode == 'running': self.setStyleSheet(self.styles[mode]) self.mode = mode self.lineNumberArea.firstlinecode = [' ... ', ' ...', ' ..', ' .', ' ', '. ', '.. ', '... '] self.lineNumberArea.start_profiling() self.setReadOnly(False) elif mode == 'interprete': self.setStyleSheet(self.styles[mode]) self.mode = mode self.lineNumberArea.firstlinecode = [' >>> '] self.lineNumberArea.stop_profiling() self.setReadOnly(False) elif mode == 'input': self.setStyleSheet(self.styles[mode]) self.mode = mode self.lineNumberArea.firstlinecode = ['>? ', ' >?'] self.lineNumberArea.stop_profiling() self.setReadOnly(False) elif mode == 'ended': self.outputPanel.setStyleSheet(self.styles[mode]) self.hide() self.mode = mode self.lineNumberArea.firstlinecode = ['Ended'] self.lineNumberArea.stop_profiling() self.setReadOnly(True) self.lineNumberArea.update() def response_to_autocomplete(self, tag, error_code, items): if len(items) == 0: return if len(items) == 1: self.setPlainText(self.keep + items[0]) self.moveCursorToEndOfDoc() else: for item in items: self.outputPanel.addText(f'{item}\n') commonprefix = os.path.commonprefix(items) if commonprefix != self.part: self.setPlainText(self.keep + commonprefix) self.moveCursorToEndOfDoc() def wheelEvent(self, event): modifiers = event.modifiers() #key_ctrl = modifiers & 2 == 2 or modifiers & 32 == 32 key_ctrl = modifiers & Qt.ControlModifier #key_ctrl = True #print(modifiers) if key_ctrl and event.delta() < 0: font = self.font() font.setPointSize(font.pointSize()-1) self.setFont(font) elif key_ctrl and event.delta() > 0: font = self.font() font.setPointSize(font.pointSize()+1) self.setFont(font) self.lineNumberArea.update_font() if not key_ctrl: super().wheelEvent(event) def replaceSelected(self, text): cursor = self.textCursor() start = cursor.selectionStart() end = cursor.selectionEnd() if cursor.hasSelection(): cursor.insertText(text) #end = cursor.position() end = start + len(text) #QTextCursor.KeepAnchor cursor.setPosition(start) cursor.setPosition(end, QTextCursor.KeepAnchor) self.setTextCursor(cursor) def insertText(self, text): cursor=self.textCursor() cursor.insertText(text) def addText(self, text): cursor=self.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.moveCursor(QTextCursor.End) class StdPlainOutputPanel(QPlainTextEdit): def __init__(self, parent, stdout_queue): super().__init__(parent = parent) self.stdout_queue = stdout_queue self.setReadOnly(True) self._ansi_processor = None self.auto_scroll = True self.configure(config) @property def panel(self): return self.parent().parent().parent() def configure(self, config): console_font = QFont('Consolas', pointSize=config['console']['fontsize']) self.setFont(console_font) if config['console']['wrap']: self.setWordWrapMode(QTextOption.WordWrap) else: self.setWordWrapMode(QTextOption.NoWrap) self.setMaximumBlockCount(config['console']['maxblockcount']) def flush(self): text = '' while not self.stdout_queue.empty(): data = self.stdout_queue.get() if isinstance(data, tuple): ttype, content = data else: ttype = 'raw' content = data text += content if not text == '': if ttype == 'raw': self.addText(text) elif ttype == 'error': self.addAnsiText(f'{ERROR_PREFIX}{text}{ERROR_SUFFIX}') self.panel.show_me() elif ttype == 'ansi': self.addAnsiText(text) #Some bug, reset format to normal #self.addAnsiText('\n') def addText(self, text): cursor=self.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) if self.auto_scroll: self.moveCursor(QTextCursor.End) def addAnsiText(self, text): cursor = self.textCursor() cursor.movePosition(QTextCursor.End) self._insert_ansi_escape_text(cursor, text) if self.auto_scroll: self.moveCursor(QTextCursor.End) def _insert_ansi_escape_text(self, cursor, text): cursor.beginEditBlock() if self._ansi_processor == None: self._ansi_processor = QtAnsiCodeProcessor() for substring in self._ansi_processor.split_string(text): for act in self._ansi_processor.actions: # Unlike real terminal emulators, we don't distinguish # between the screen and the scrollback buffer. A screen # erase request clears everything. if act.action == 'erase' and act.area == 'screen': cursor.select(QTextCursor.Document) cursor.removeSelectedText() # Simulate a form feed by scrolling just past the last line. elif act.action == 'scroll' and act.unit == 'page': cursor.insertText('\n') cursor.endEditBlock() self._set_top_cursor(cursor) cursor.joinPreviousEditBlock() cursor.deletePreviousChar() elif act.action == 'carriage-return': cursor.movePosition( cursor.StartOfLine, cursor.KeepAnchor) elif act.action == 'beep': gui.qapp.beep() elif act.action == 'backspace': cursor.movePosition( cursor.PreviousCharacter, cursor.KeepAnchor) elif act.action == 'newline': cursor.movePosition(cursor.EndOfLine) elif act.action == 'set-title': self.panel.long_title = act.title format = self._ansi_processor.get_format() # This doesn't seem to work with special characters # backspace seems to disable the output, no recovery selection = cursor.selectedText() if len(selection) == 0: if substring is None: pass elif len(substring) > MAXCHARPERLINE: cursor.insertText(substring[:MAXCHARPERLINE] + "...%d chars not displayed" % (len(substring) - MAXCHARPERLINE), format) else: cursor.insertText(substring, format) elif substring is not None: # BS and CR are treated as a change in print # position, rather than a backwards character # deletion for output equivalence with (I)Python # terminal. if len(substring) >= len(selection): cursor.insertText(substring, format) else: old_text = selection[len(substring):] cursor.insertText(substring + old_text, format) cursor.movePosition(cursor.PreviousCharacter, cursor.KeepAnchor, len(old_text)) cursor.setBlockCharFormat(QTextCharFormat()) cursor.endEditBlock() class StdioFrame(QWidget): """ A Window with standard input and output panels For threads and processes. """ def __init__(self, parent, title, task): super().__init__(parent=parent) self.task = task self.setWindowTitle(title) self.stdOutputPanel = StdPlainOutputPanel(self, task.stdout_queue) self.stdInputPanel = StdInputPanel(self, task, self.stdOutputPanel) task.set_flusher(self.stdOutputPanel.flush) splitter = QSplitter(Qt.Vertical, self) splitter.addWidget(self.stdOutputPanel) splitter.addWidget(self.stdInputPanel) vbox = QVBoxLayout() self.setLayout(vbox) vbox.setContentsMargins(0, 0, 0, 0) vbox.addWidget(splitter) def keyPressEvent(self, event): pass class WrapCaller(object): def __init__(self, caller, *args, **kwargs): self.caller = caller self.args = args self.kwargs = kwargs def __call__(self): self.caller(*self.args, **self.kwargs) class RecentMenu(QtWidgets.QMenu): def __init__(self, parent=None): super().__init__('Recent', parent) self.panel = self.parent() def showEvent(self, event): self.initactions() def initactions(self): self.clear() self.actions = [] for rowid, timestamp, path in gui.qapp.history.yield_recent_paths(category='console'): action = QtWidgets.QAction(path, self) action.triggered.connect(WrapCaller(self.panel.openFile, path)) self.addAction(action) self.actions.append(action) class Console(BasePanel): panelCategory = 'console' userVisible = False classIconFile = str(respath / 'icons' / 'px16' / 'application_xp_terminal.png') def __init__(self, parent, panid, task): super().__init__(parent, panid, 'console') self.stdio = StdioFrame(self, '', task) task.console = self self.setCentralWidget(self.stdio) self.createMenus() self.createStatusBar() self.stdio.stdOutputPanel.flush() self.setFocusPolicy(Qt.StrongFocus) self.timer = QTimer(self) self.timer.timeout.connect(self.updateProcessInfo) self.timer.start(config['system info period']) @property def task(self): return self.stdio.task def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") #self.executionMenu = self.menuBar().addMenu("&Execution") self.executionMenu = CheckMenu("&Execution", self.menuBar()) self.menuBar().addMenu(self.executionMenu) self.addMenuItem(self.fileMenu, "Open File", self.openFileDialog, statusTip="Open a file", icon = 'folder_vertical_document.png') self.addMenuItem(self.fileMenu, 'New Thread', self.newThread) self.fileMenu.addMenu(RecentMenu(self)) self.addMenuItem(self.fileMenu, "Close", self.close_panel, statusTip = "Close this Thread", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'cross.png'))) traceMenu = QtWidgets.QMenu('tracing') traceMenu.addAction(QAction("Enable Tracing", self, triggered=lambda: self.task.set_tracing(True), statusTip="Enable Tracing, needed for sync breaks")) traceMenu.addAction(QAction("Disable Tracing", self, triggered=lambda: self.task.set_tracing(False), statusTip="Disable Tracing")) self.addMenuItem(traceMenu, "Enable Timeit", lambda: self.task.set_timeit(True), statusTip="Show elapsed time report at end of execution", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'time_red.png'))) traceMenu.addAction(QAction("Disable Timeit", self, triggered=lambda: self.task.set_timeit(False), statusTip="Disable Timeit")) traceMenu.addAction(QAction("Enable profiling", self, triggered=lambda: self.task.enable_profiling(), statusTip="One time profiling of the next command")) traceMenu.addAction(QAction("Toggle Inspect", self, triggered=lambda: self.task.flow('toggle_inspect'))) self.executionMenu.addMenu(traceMenu) self.addMenuItem(self.executionMenu, 'Check Flow Alive', self.checkAlive, statusTip="Check if the flow loop is still alive") self.addMenuItem(self.executionMenu, 'Print Trace', self.stdio.task.print_trace, statusTip="Print the trace of the current execution frame") self.addMenuItem(self.executionMenu, 'Print Locals', self.stdio.task.print_locals, statusTip="Print the locals of the current namespace") self.addMenuItem(self.executionMenu, 'Sync Break', self.syncBreak, statusTip="Send a synchronous break, tracing should be active", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'cog_stop.png'))) self.addMenuItem(self.executionMenu, 'Async Break', self.asyncBreak, statusTip="Send a asynchronous break", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'cog_stop.png'))) self.addMenuItem(self.executionMenu, 'System Exit Thread', self.stdio.task.system_exit, statusTip="System Exit") self.executionMenu.addSeparator() # self.addMenuItem(self.executionMenu, 'Pause Process', self.suspendResumeProcess, # statusTip="Suspend this windows process") self.addMenuItem(self.executionMenu, 'Kill Process', self.killProcess, statusTip="Kill this Python Process and its threads", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'scull.png'))) self.viewMenu = CheckMenu("&View", self.menuBar()) self.menuBar().addMenu(self.viewMenu) logLevelMenu = CheckMenu('Log Level', self.viewMenu) self.addMenuItem(logLevelMenu, 'Debug', lambda: self.setLogLevel('DEBUG'), checkcall=lambda: self.isLogLevel('DEBUG')) self.addMenuItem(logLevelMenu, 'Info', lambda: self.setLogLevel('INFO'), checkcall=lambda: self.isLogLevel('INFO')) self.addMenuItem(logLevelMenu, 'Warning', lambda: self.setLogLevel('WARNING'), checkcall=lambda: self.isLogLevel('WARNING')) self.addMenuItem(logLevelMenu, 'Error', lambda: self.setLogLevel('ERROR'), checkcall=lambda: self.isLogLevel('ERROR')) self.addMenuItem(logLevelMenu, 'Critical', lambda: self.setLogLevel('CRITICAL'), checkcall=lambda: self.isLogLevel('CRITICAL')) self.addMenuItem(self.viewMenu, 'input', self.toggleInputVisible, checkcall=lambda: self.stdio.stdInputPanel.isVisible()) self.addMenuItem(self.viewMenu, 'Auto Scroll', self.toggleAutoScroll, checkcall=lambda: self.stdio.stdOutputPanel.auto_scroll) self.addMenuItem(self.viewMenu, 'Clear', self.clear) scripMenu = self.menuBar().addMenu("&Script") self.addMenuItem(scripMenu, 'Edit sys.path...', self.editSysPaths, statusTip="Edit the search path used to import Python packages", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'application_view_list.png'))) self.addMenuItem(scripMenu, 'Edit Live paths...', self.editLivePaths, statusTip="Edit the search path used to import user live scripts", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'script_gear.png'))) self.addBaseMenu() def createStatusBar(self): self.tasktype = QLabel('') self.pid = QLabel('Pid:0') self.pname = QLabel('Name:') self.tid = QLabel('Tid:0') self.pmem = QLabel('Mem:') self.statusBar().addWidget(self.tasktype,1) self.statusBar().addWidget(self.pid,1) self.statusBar().addWidget(self.pname,1) self.statusBar().addWidget(self.tid,1) self.statusBar().addWidget(self.pmem,1) def refresh_pid_tid(self): self.pid.setText(f'Pid:{self.stdio.task.process_id}') self.tid.setText(f'Tid:{self.stdio.task.thread_id}') self.long_title = f'{self.short_title} Pid {self.stdio.task.process_id} Tid {self.stdio.task.thread_id}' def updateProcessInfo(self): if self.stdio.task.process_id == -1: return try: proc = psutil.Process(self.stdio.task.process_id) except: return self.tasktype.setText(f'{self.stdio.task.tasktype}') self.pname.setText(f'Name:{proc.name()}') self.tid.setText(f'Tid:{self.stdio.task.thread_id}/{proc.num_threads()}') self.pmem.setText(f'Mem:{proc.memory_full_info().rss / 1024 / 1024:.4g} MB') def set_mode(self, mode): self.stdio.stdInputPanel.set_mode(mode) def newThread(self): self.duplicate() def checkAlive(self): def response(mode, error_code, result): messageBox(f'Mode: {mode}\nError Code: {error_code}\nResult: {result}', 'Info', 'Info') self.stdio.task.flow_alive(response, 5) def suspendResumeProcess(self): proc = psutil.Process(self.stdio.task.process_id) if proc.status() == 'running': proc.suspend() elif proc.status() == 'stopped': proc.resume() def killProcess(self): proc = psutil.Process(self.stdio.task.process_id) mem = proc.memory_full_info().rss / 1024 / 1024 if gui.dialog.question(f'Kill this following Process?\nExecutable: {proc.exe()}\nProcess id: {proc.pid} Cpu: {proc.cpu_percent(0.1)}% Mem: {mem:.4g}MB'): self.stdio.task.kill() def syncBreak(self): self.stdio.task.sync_break() def asyncBreak(self): self.stdio.task.async_break() def exec_cmd(self, cmd): self.stdio.stdInputPanel.execute_commands(cmd) def exec_file(self): cmd = """exec(open(gui.getfilename('*.py'),'r').read())""" self.exec_cmd(cmd) def openFileDialog(self): filepath = gui.dialog.getfilename('*.*') self.openFile(filepath) def openFile(self, filepath): filepath = Path(filepath) for proxyname, proxy in gui.proxies.items(): if filepath.suffix.lower() in proxy.opens_with: #cmd = f"""exec(open(r'{filepath}', 'r').read())""" #self.exec_cmd(cmd) proxy.open(filepath) break else: logger.error(f'Suffix {filepath.suffix} of {filepath.name} not registered') return gui.qapp.history.storepath(str(filepath), category='console') def addText(self, text): self.stdio.stdOutputPanel.addText(text) def editSysPaths(self): task = self.stdio.task def callback(mode, error_code, result): paths = result.copy() dialog_code = EditPaths(paths).exec_() result = task.call_func(Shell.set_sys_paths, args=(paths,)) result = task.call_func(Shell.get_sys_paths, args=(False,), callback=callback) def editLivePaths(self): task = self.stdio.task def callback(mode, error_code, result): paths = result.copy() dialog_code = EditPaths(paths).exec_() result = task.call_func(Shell.set_live_paths, args=(paths,)) result = task.call_func(Shell.get_live_paths, callback=callback) def setLogLevel(self, level): task = self.stdio.task def setProcessLogLevel(level): stdinout.streamhandler.setLevel(level) task.call_func(setProcessLogLevel, args=(level,), queue='flow') def isLogLevel(self, levelname): task = self.stdio.task def getProcessLogLevel(): level = stdinout.streamhandler.level return level level = task.call_func(getProcessLogLevel, queue='flow', wait=True) return logging.getLevelName(level) == levelname def toggleInputVisible(self): if self.stdio.stdInputPanel.isVisible(): self.stdio.stdInputPanel.hide() else: self.stdio.stdInputPanel.show() def toggleAutoScroll(self): self.stdio.stdOutputPanel.auto_scroll = not self.stdio.stdOutputPanel.auto_scroll def clear(self): self.stdio.stdOutputPanel.clear() def close_panel(self): try: self.stdio.task.system_exit() finally: self.stdio.task.unregister() super().close_panel() class MainThreadConsole(Console): panelShortName = 'main' userVisible = False def __init__(self, mainWindow, panid): shell = QApplication.instance().shell task = tasks.ThreadTask(shell, new_thread=False) super().__init__(mainWindow, panid, task) task.panid = self.panid task.start() self.stdio.stdInputPanel.styles['interprete'] = "background-color:#CBE9FF;" self.stdio.stdInputPanel.set_mode('interprete') self.stdio.stdInputPanel.heightHint = 0 self.stdio.stdInputPanel.setPlainText('# Reserved for debugging only') self.stdio.stdInputPanel.hide() self.executionMenu.setEnabled(False) getMenuAction(self.menuBar(), ['File', 'Close']).setEnabled(False) def duplicate(self, floating=False): newpanel = gui.qapp.panels.new_panel(SubThreadConsole, None, None, floating=floating) return newpanel def close_panel(self): pass class SubThreadConsole(Console): panelShortName = 'thread' userVisible = True def __init__(self, mainWindow, panid): shell = QApplication.instance().shell task = tasks.ThreadTask(shell, new_thread=True) super().__init__(mainWindow, panid, task) task.panid = self.panid task.start() class ChildProcessConsole(Console): panelShortName = 'child' userVisible = True def __init__(self, mainWindow, panid, cqs=None): shell = QApplication.instance().shell task = tasks.ProcessTask(shell, cqs) super().__init__(mainWindow, panid, task) task.panid = self.panid task.start() def duplicate(self, floating=False): newpanel = gui.qapp.panels.new_panel(ChildThreadConsole, None, None, floating=floating, kwargs={'parent_pid': self.task.process_id}) return newpanel class ChildThreadConsole(Console): panelShortName = 'child-thread' userVisible = True def __init__(self, mainWindow, panid, parent_pid=None): if parent_pid is None: pids = [str(pid) for pid in tasks.PROCESSES.keys()][1:] qtypes = ['zmq', 'pipe'] form = [('Process Id', [1] + pids), ('Queue Type', [1] + qtypes)] (ind0, ind1) = fedit(form) pid = int(pids[ind0-1]) queue_type = qtypes[ind1-1] else: pid = parent_pid queue_type = 'zmq' master = next(iter(tasks.PROCESSES[pid].values())) shell = QApplication.instance().shell task = tasks.ProcessThreadTask(shell, master, queue_type) super().__init__(mainWindow, panid, task) task.panid = self.panid task.start() def duplicate(self, floating=False): newpanel = gui.qapp.panels.new_panel(ChildThreadConsole, None, None, floating=floating, kwargs={'parent_pid': self.task.process_id}) return newpanel
thocoo/gamma-desk
gdesk/panels/html/__init__.py
<gh_stars>0 from .proxy import HtmlGuiProxy from ... import config if config['qapp']: from .panel import HtmlPanel
thocoo/gamma-desk
gdesk/ezdock/laystruct.py
import logging logger = logging.getLogger(__name__) class LayoutStruct(object): def __init__(self): self.root = dict() self.tabblock = True #Don't split inside tabs, go back one level def insert_panel(self, panel, relation='right', to_panel=None, size=100): category, panid = panel new_node = {'type': 'panel', 'category': category, 'id': panid} self.insert_panel_tree(self.root, new_node, relation, to_panel, size) def insert_branch(self, branch, relation='right', to_panel=None, size=100): self.insert_panel_tree(self.root, branch, relation, to_panel, size) def is_empty(self): def node_is_empty(node): if len(node.keys()) == 0: return True elif node['type'] == 'panel': return False for node in node.get('items', []): if not node_is_empty(node): return False return True return node_is_empty(self.root) def pop_node(self, nodetype='layout', category='tab', node_id=None): def check_node(subnode): if subnode['type'] == nodetype and \ subnode['category'] == category and \ subnode.get('id', None) == node_id: return True else: return False if check_node(self.root): poped_node = self.root self.root = dict() l = LayoutStruct() l.root = poped_node return l if not 'items' in self.root.keys(): return None def pop_node_brach(node): #print(f'node: {node}') found_index = None poped_node = None for index, subnode in enumerate(node['items']): if check_node(subnode): found_index = index break elif poped_node is None and subnode['type'] != 'panel': poped_node = pop_node_brach(subnode) if poped_node is None and not found_index is None: poped_node = node['items'].pop(found_index) if 'sizes' in node.keys(): pinned_size = len(node['sizes']) if found_index < pinned_size: #In the pinned area node['sizes'].pop(found_index) else: #In the scroll area node['scroll'].pop(found_index-pinned_size) #print(f'poped_node: {poped_node}') return poped_node poped_root = pop_node_brach(self.root) l = LayoutStruct() l.root = poped_root return l def insert_panel_tree(self, node, new_node, relation, to_panel=None, size=100): """ Relation is either: 'left', 'right', 'top', 'bottom' or 'tab' """ if not to_panel is None and not node['type'] == 'panel': top = False to_category, to_panid = to_panel item_index = None found_deeper = False for index, item in enumerate(node['items']): if item['type'] == 'panel': if item['category'] == to_category and item['id'] == to_panid: item_index = index else: found_deeper = self.insert_panel_tree(item, new_node, relation, to_panel, size) if found_deeper: item_index = index else: top = True if relation in ['left', 'top']: item_index = 0 elif relation in ['right', 'bottom']: if node['type'] == 'panel': #probably as top level single panel item_index = -1 else: item_index = len(node['items']) - 1 elif relation in ['tab']: item_index = -1 #Will not be used if not item_index is None: if relation in ['tab']: if not node['category'] == 'tab': if top: self.root = {'type': 'layout', 'category': 'tab', 'items': [node]} self.insert_panel_tree(self.root, new_node, relation, to_panel, size) else: subnode = node['items'][item_index] node['items'][item_index] = {'type': 'layout', 'category': 'tab', 'items': [subnode]} self.insert_panel_tree(node['items'][item_index], new_node, relation, to_panel, size) else: node['items'].append(new_node) else: if relation in ['left', 'right']: boxtype = 'hbox' elif relation in ['top', 'bottom']: boxtype = 'vbox' if not node['category'] == boxtype: if top: #insert a box at top level self.root = {'type': 'layout', 'category': boxtype, 'items': [node], 'sizes': [size]} self.insert_panel_tree(self.root, new_node, relation, to_panel, size) elif self.tabblock and node['category'] == 'tab': #Go back one level return True else: #insert a box at this level subnode = node['items'][item_index] node['items'][item_index] = {'type': 'layout', 'category': boxtype, 'items': [subnode], 'sizes': [size]} self.insert_panel_tree(node['items'][item_index], new_node, relation, to_panel, size) elif node['category'] == boxtype: #Add the item to the current hbox first_scroll_index = len(node['sizes']) if relation in ['left', 'top']: if item_index < first_scroll_index: node['items'].insert(item_index, new_node) node['sizes'].insert(item_index, size) else: node['items'].insert(item_index, new_node) node['scroll'].insert(item_index-first_scroll_index, size) elif relation in ['right', 'bottom']: if item_index < first_scroll_index: node['items'].insert(item_index+1, new_node) node['sizes'].insert(item_index+1, size) else: node['items'].insert(item_index+1, new_node) node['scroll'].insert(item_index-first_scroll_index+1, size) def compact(self): if not 'items' in self.root.keys(): return self.compact_branch(self.root) if len(self.root['items']) == 0: self.root = dict() self.root['type'] = 'layout' self.root['category'] = 'hbox' self.root['items'] = [] self.root['sizes'] = [] elif len(self.root['items']) == 1: self.root = self.root['items'][0] def compact_branch(self, node): zero_items = [] for index, subnode in enumerate(node['items']): if subnode['type'] == 'panel': continue self.compact_branch(subnode) if len(subnode['items']) == 0: zero_items.append(subnode) elif len(subnode['items']) == 1: node['items'][index] = subnode['items'][0] for item in zero_items: node['items'].remove(item) def distribute(self): def distribute_branch(node): if node['type'] == 'panel': return if 'sizes' in node.keys(): mean = sum(node['sizes']) / len(node['sizes']) node['sizes'] = len(node['sizes']) * [mean] for subnode in node['items']: distribute_branch(subnode) distribute_branch(self.root) def show(self): print(self.describe()) def describe(self): if self.root.get('type', None) == None: return lines = LayoutStruct.show_branch(self.root) return '\n'.join(lines) @staticmethod def show_branch(node, prefix=''): lines = [] if node['type'] == 'panel': lines.append(f"{prefix}{node['category']}#{node['id']}") elif node['category'] in ['tab', 'tag']: tabid = node.get('id', None) active = node.get('active', '') lines.append(f"{prefix}{node['type']} {node['category']} {tabid} {active}") for subnode in node['items']: lines.extend(LayoutStruct.show_branch(subnode, prefix + ' ')) else: tabid = node.get('id', None) lines.append(f"{prefix}{node['type']} {node['category']} {tabid} {node['sizes']}") for subnode in node['items']: lines.extend(LayoutStruct.show_branch(subnode, prefix + ' ')) return lines
thocoo/gamma-desk
gdesk/panels/matplot/plotproxy.py
import pickle import pylab from ...core.gui_proxy import GuiProxyBase, StaticGuiCall, gui class FigureBox(object): def __init__(self, figure): self.figure = figure def __getstate__(self): state = dict() mgr = self.figure.canvas.manager self.figure.canvas.manager = None state['figure'] = pickle.dumps(self.figure) self.figure.canvas.manager = mgr return state def __setstate__(self, state): self.figure = pickle.loads(state['figure']) class PlotProxy(object): def __init__(self, gui): self.gui = gui def __dir__(self): return dir(pylab) def __getattr__(self, attr): func = getattr(pylab, attr) return lambda *args, **kwargs: self.gui.gui_call(func, *args, **kwargs) class PlotGuiProxy(GuiProxyBase): category = 'plot' def __init__(self): pass def attach(self, gui): gui.plot = self gui.prepareplot = self.prepareplot self.plx = PlotProxy(gui) def show(self, figure=None, hold=False): import matplotlib.pyplot as plt from matplotlib.figure import Figure if not gui._qapp is None: if figure is None: plt.show() else: plt.figure(figure.number) plt.show() return if figure is None: figure = plt.gcf() assert isinstance(figure, Figure) return self.show_figure_box(FigureBox(figure), hold) def prepareplot(self): return self.plx @StaticGuiCall def select(panid=-1, args=()): """ If panid < 0, -1: select the active panel, -2: selected before that, ... panid == None: new panel panid >= 0: select the panel if exists, otherwise a new with that number """ panel = gui.qapp.panels.select_or_new('plot', panid, 'basic', args=args) return panel.panid @StaticGuiCall def restore_gcf_set_active(): from . import plotpanel plotpanel.restore_gcf_set_active() @StaticGuiCall def new(figure_id=None): """ Create a new figure. Links to pylab.figure """ import matplotlib.pyplot as plt fig = plt.figure(figure_id) return fig, fig.number def xy(self, *args, **kwargs): if not kwargs.get('hold', False): self.plx.figure() if 'hold' in kwargs.keys(): kwargs.pop('hold') self.plx.plot(*args, **kwargs) self.plx.show() @StaticGuiCall def show_figure_box(figurebox, hold=False): """ Display the figure in the figurebox. The figure has to be added to the current pyplot backend. :param bool hold: Replace the figure in the current selected panel by the new figure """ #unpickling a figure will call show when interactive is on #But this will be on the backend of the pickling process #All callbacks related to gui calls where removed by the pickling # from ...matplotbe import new_figure_manager_given_figure import matplotlib.pyplot as plt import matplotlib._pylab_helpers as pylab_helpers fig = figurebox.figure def make_active(event): pylab_helpers.Gcf.set_active(mgr) if False: #Creating a new figure manager allnums = plt.get_fignums() num = max(allnums) + 1 if allnums else 1 mgr = new_figure_manager_given_figure(num, fig) mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event', make_active) pylab_helpers.Gcf.set_active(mgr) fig = mgr.canvas.figure fig.number = num mgr.show() else: #Use the current figure mamaner and plot panel # Try to replace the figure on the current plot panel with this new figure from ...matplotbe import FigureCanvasGh2 panids = gui.get_panel_ids('plot') if not hold or len(panids) == 0: ignore, num = PlotGuiProxy.new() else: num = panids[-1] plotpanel = gui.qapp.panels['plot'][num] fig.number = num plotpanel.showNewFigure(fig) #Hack to call the correct set_active #Note that Gcf.set_active() is mapped to panel.select() in plotpanel.py mgr = fig.canvas.manager mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event', make_active) plotpanel.show() # I don't get the interactive update working # After a function lik grid(), xlabel(), .. # the stale property is set to True # This should trigger the call of stale_callback on the figure (=Artist) # or stall_callback on the axis object #Configure stale call backs #The hierarchy of the figure can be type of figure dependend try: from matplotlib.pyplot import _auto_draw_if_interactive from matplotlib.figure import _stale_figure_callback from matplotlib.artist import _stale_axes_callback fig.stale_callback = _auto_draw_if_interactive for ax in fig.axes: ax.stale_callback = _stale_figure_callback ax.xaxis.stale_callback = _stale_axes_callback ax.yaxis.stale_callback = _stale_axes_callback except: logger.error('Could not configure all interactive callbacks') return num @StaticGuiCall def save(file): """ Save the selected figure to a file """ import matplotlib.pyplot as plt plt.savefig(file)
thocoo/gamma-desk
gdesk/panels/imgview/imgdata.py
import pathlib import collections import queue import threading import math from qtpy import QtGui, QtCore from qtpy.QtGui import QImage import numpy as np from ... import gui, config from ...utils.shared import SharedArray from ...utils import imconvert from .dimensions import DimRanges from . import fasthist here = pathlib.Path(__file__).absolute().parent try: from .numba_func import map_values_mono, map_values_rgbswap, map_values_rgb has_numba = True except: has_numba = False #https://doc.qt.io/qtforpython-5.12/PySide2/QtGui/QPainter.html#composition-modes COMPMODE = dict() COMPMODE['sourceover'] = QtGui.QPainter.CompositionMode_SourceOver COMPMODE['plus'] = QtGui.QPainter.CompositionMode_Plus COMPMODE['multiply'] = QtGui.QPainter.CompositionMode_Multiply COMPMODE['screen'] = QtGui.QPainter.CompositionMode_Screen COMPMODE['overlay'] = QtGui.QPainter.CompositionMode_Overlay COMPMODE['darken'] = QtGui.QPainter.CompositionMode_Darken COMPMODE['lighten'] = QtGui.QPainter.CompositionMode_Lighten class SelectRoi(DimRanges): """ Selection widget range data. """ def __init__(self, height, width, update_statistics_func=None): DimRanges.__init__(self, (height, width)) self.update_statistics_func = update_statistics_func @property def yr(self): return self.rngs[0] @property def xr(self): return self.rngs[1] def ensure_rising(self): for rng in self.rngs: if rng.start > rng.stop: rng.start, rng.stop = rng.stop, rng.start def copy(self): s = SelectRoi(self.rngs[0].maxstop, self.rngs[1].maxstop) s.inherite(self) return s def update_statistics(self): if not self.update_statistics_func is None: self.update_statistics_func() class ImageStatistics(object): def __init__(self): self._cache = dict() self.arr2d = None def attach_arr2d(self, arr2d): self.arr2d = arr2d self.clear() @property def dtype(self): return self.arr2d.dtype def clear(self): self._cache.clear() def step_for_bins(self, bins): if self.dtype in ['float16', 'float32', 'float64']: return math.ceil(65536 / bins) if len(self._cache.keys()) == 0: self.calc_histogram() hist1 = self._cache['hist'] return math.ceil(len(hist1) / bins) def histogram(self, step=1): if len(self._cache.keys()) == 0: self.calc_histogram() hist1 = self._cache['hist'] if step > 1: bins = len(hist1) // step left = len(hist1) % step tmp = hist1[:step*bins] if left > 0: hist = np.r_[tmp.reshape(bins, step).sum(1), hist1[step*bins:].sum()] else: hist = tmp.reshape(bins, step).sum(1) return hist else: return hist1 def starts(self, step=1): if len(self._cache.keys()) == 0: self.calc_histogram() starts1 = self._cache['starts'] if step > 1: return starts1[::step] else: return starts1 def calc_histogram(self, bins=None, step=None): if self.dtype in ['int8', 'uint8', 'int16', 'uint16']: hist, starts, stepsize = fasthist.hist16bit(self.arr2d, bins=None, step=1, use_numba=True) elif self.dtype in ['int32', 'uint32', 'float16', 'float32', 'float64']: hist, starts, stepsize = fasthist.histfloat(self.arr2d, bins=65536, step=None, pow2snap=False, use_numba=True) self._cache['hist'] = hist self._cache['starts'] = starts self._cache['stepsize'] = stepsize @property def bins(self): return len(self.starts()) def stepsize(self, step): return self._cache['stepsize'] * step def n(self): return self.arr2d.shape[0] * self.arr2d.shape[1] def sum(self): return (self.histogram() * self.starts()).sum() def mean(self): return self.sum() / self.n() def sumsq(self): return (self.histogram() * self.starts()**2).sum() def min(self): non_zeros_indices = np.argwhere(self.histogram() > 0) min_index = non_zeros_indices[0][0] max_index = non_zeros_indices[-1][0] return self.starts()[min_index] def max(self): non_zeros_indices = np.argwhere(self.histogram() > 0) max_index = non_zeros_indices[-1][0] return self.starts()[max_index] def std(self): n = self.n() result = ((self.sumsq() - ((self.sum() * 1.0) ** 2) / n) / (n - 1)) ** 0.5 return result class ImageData(object): def __init__(self): self.qimg = None self.map8 = None self.sharray = None self.imghist = ArrayHistory(config['image'].get("history_size", 500e6)) arr = np.ones((1,1),'uint8') * 128 self.selroi = SelectRoi(1, 1, self.update_roi_statistics) self.chanstats = dict() self.show_array(arr) self.layers = collections.OrderedDict() def load_by_qt(self, path): self.qimg = QImage(str(path)) def show_array(self, array=None, black=0, white=256, colormap=None, gamma=1, log=True): with gui.qapp.waitCursor(): threadcount = config['image']['threads'] use_numba = config['image']['numba'] and has_numba if array is None: #offset and gain adjust of current viewer array = self.sharray shape = array.shape dtype = array.dtype # for stat in self.chanstats.values(): # stat.clear() else: if log and not self.sharray is None: self.imghist.push(self.sharray) if isinstance(array, SharedArray): self.sharray = array shape = array.shape dtype = array.dtype else: shape = array.shape dtype = array.dtype self.sharray = SharedArray(shape, dtype) self.sharray[:] = array self.chanstats.clear() if len(shape) == 2: self.chanstats['K'] = ImageStatistics() self.chanstats['K'].attach_arr2d(self.sharray.ndarray) self.chanstats['RK'] = ImageStatistics() self.update_roi_statistics() else: self.chanstats['R'] = ImageStatistics() self.chanstats['G'] = ImageStatistics() self.chanstats['B'] = ImageStatistics() self.chanstats['R'].attach_arr2d(self.sharray.ndarray[:,:,0]) self.chanstats['G'].attach_arr2d(self.sharray.ndarray[:,:,1]) self.chanstats['B'].attach_arr2d(self.sharray.ndarray[:,:,2]) self.chanstats['RR'] = ImageStatistics() self.chanstats['RG'] = ImageStatistics() self.chanstats['RB'] = ImageStatistics() self.update_roi_statistics() height, width, *ignore = shape self.height, self.width = height, width if self.selroi.isfullrange(): self.selroi.xr.maxstop = width self.selroi.yr.maxstop = height self.selroi.reset() else: self.selroi.xr.maxstop = width self.selroi.yr.maxstop = height self.selroi.clip() natrange = imconvert.natural_range(self.sharray.dtype) gain = natrange / (white - black) self.array8bit, self.qimg = imconvert.process_ndarray_to_qimage_8bit( self.sharray.ndarray, black, gain, colormap, refer=True, shared=config["image"].get("qimg_shared_mem", False), gamma=gamma) def get_natural_range(self): return imconvert.natural_range(self.sharray.dtype) def set_mask(self, array=None, composition='sourceover'): self.set_layer('mask', array, composition) def set_layer(self, name, array=None, composition='sourceover'): if array is None: if name in self.layers.keys(): self.layers.pop(name) return assert array.ndim == 2 assert array.dtype in ['uint8', 'bool'] height, width = array.shape compmode = COMPMODE[composition.lower()] qimage = QImage(memoryview(array), width, height, width, QImage.Format_Indexed8) qimage.setColorTable(imconvert.make_color_table('mask')) self.layers[name] = {'array': array, 'qimage': qimage, 'composition': compmode} def update_roi_statistics(self): slices = self.selroi.getslices() clr_slices = {'RK': slices, 'RR': (slices[0], slices[1], 0), 'RG': (slices[0], slices[1], 1), 'RB': (slices[0], slices[1], 2)} for clr, chanstat in self.chanstats.items(): if not clr in clr_slices.keys(): continue chanstat.attach_arr2d(self.sharray[clr_slices[clr]]) def update_array8bit_by_slices(self, slices): def takemap(source_slice, target_slice): self.array8bit[target_slice] = np.take(self.map8, self.sharray.ndarray[source_slice]) threads = [] for (source_slice, target_slice) in slices: threads.append(threading.Thread(target=takemap, args=(source_slice, target_slice))) for thread in threads: thread.start() for thread in threads: thread.join() @property def statarr(self): return self.sharray.ndarray def get_number_of_bytes(self): nbytes = 0 nbytes += self.sharray.ndarray.nbytes nbytes += self.array8bit.nbytes return nbytes class ArrayHistory(object): def __init__(self, max_size=4): self.max_size = max_size self.prior_arrays = [] self.next_arrays = [] def push(self, array): overflow = self.reduce_size_to_max_byte_size(array.size) if overflow < 0: self.prior_arrays.append(array) self.next_arrays.clear() def reduce_size_to_max_byte_size(self, add_size=0): current_size = add_size for arr in self.prior_arrays: current_size += arr.size overflow = current_size - self.max_size while overflow > 0 and len(self.prior_arrays) > 0: array = self.prior_arrays.pop(0) overflow -= array.size return overflow def prior(self, current_array): array = self.prior_arrays.pop(-1) self.next_arrays.append(current_array) return array def next(self, current_array): array = self.next_arrays.pop(-1) self.prior_arrays.append(current_array) return array def __len__(self): return len(self.prior_arrays) + len(self.next_arrays) def prior_length(self): return len(self.prior_arrays) def next_length(self): return len(self.next_arrays) def clear(self): self.stack.clear()
thocoo/gamma-desk
gdesk/live/__main__.py
<reponame>thocoo/gamma-desk from . import console if __name__ in ["__main__", "__mp_main__"]: ws = console.argexec()
thocoo/gamma-desk
gdesk/panels/html/proxy.py
<filename>gdesk/panels/html/proxy.py from ...core.gui_proxy import GuiProxyBase, StaticGuiCall, gui class HtmlGuiProxy(GuiProxyBase): category = 'html' def __init__(self): pass def attach(self, gui): gui.html = self @StaticGuiCall def show(html_content): #Note that the size of content is limited panel = gui.qapp.panels.selected('html') if panel is None: panel = gui.qapp.panels.select_or_new('html') panel.webview.setHtml(html_content) @StaticGuiCall def load_url(url): panel = gui.qapp.panels.selected('html') if panel is None: panel = gui.qapp.panels.select_or_new('html') panel.webview.load(url)
thocoo/gamma-desk
test/start_gdesk_as_child.py
<filename>test/start_gdesk_as_child.py import sys import pprint if __name__ == '__main__': pprint.pprint(sys.path) from gdesk.external import channel channel.start_gui_as_child()
thocoo/gamma-desk
gdesk/panels/cmdhist/proxy.py
from ...core.gui_proxy import GuiProxyBase, StaticGuiCall, gui class CmdHistGuiProxy(GuiProxyBase): category = 'cmdhist' def __init__(self): pass def attach(self, gui): gui.cmdhist = self
thocoo/gamma-desk
gdesk/panels/imgview/proxy.py
<filename>gdesk/panels/imgview/proxy.py import platform import numpy as np import logging from pathlib import Path logger = logging.getLogger(__name__) from ...core.gui_proxy import GuiProxyBase, StaticGuiCall from ... import gui, config from ...utils.shared import SharedArray class ImageGuiProxy(GuiProxyBase): category = 'image' opens_with = ['.tif', '.png', '.gif'] def __init__(self): pass def attach(self, gui): gui.img = self # Properties are defined on gui gui.set_roi = self.set_roi gui.set_roi_slices = self.set_roi_slices gui.get_roi = self.get_roi gui.get_roi_slices = self.get_roi_slices gui.jump_to = self.jump_to gui.zoom_fit = self.zoom_fit gui.zoom_full = self.zoom_full gui.zoom_region = self.zoom_region gui.get_clipboard_image = self.get_clipboard_image return 'img' @StaticGuiCall def new(cmap=None, viewtype='image-profile', title=None, size=None, empty=True): panel = GuiProxyBase._new('image', viewtype, size=size, empty=empty) if not cmap is None: panel.colormap = cmap if not title is None: panel.long_title = title return panel.panid @StaticGuiCall def open(filepath, new=False): if new: ImageGuiProxy.new() panel = gui.qapp.panels.selected('image') else: panel = gui.qapp.panels.selected('image') if panel is None: panel = gui.qapp.panels.select_or_new('image', defaulttype = 'image-profile', empty=True) panel.openImage(filepath) window = panel.get_container().parent() window.raise_() gui.qapp.processEvents() return panel.panid @StaticGuiCall def get_clipboard_image(): from ...utils.imconvert import qimage_to_ndarray cb = gui.qapp.clipboard() md = cb.mimeData() qimg = md.imageData() if qimg is None: logger.error('No image data on clipboard') return arr = qimage_to_ndarray(qimg) return arr @StaticGuiCall def select(panid=-1): """ Select or create an image panel with id image_id or auto id """ panel = gui.qapp.panels.select_or_new('image', panid, defaulttype='image-profile') return panel.panid def show(self, array, cmap=None): """ Show array in the image viewer. :param ndarray array: :param str cmap: 'grey', 'jet' or 'turbo' """ if config['image']['queue_array_shared_mem']: sharr = SharedArray(array.shape, array.dtype) sharr[:] = array return ImageGuiProxy.show_array(sharr, cmap) else: return ImageGuiProxy.show_array(array, cmap) @StaticGuiCall def show_array(array=None, cmap=None): panel = gui.qapp.panels.selected('image') if not cmap is None: panel.colormap = cmap panel.show_array(array) return panel.panid @StaticGuiCall def show_mask(array=None, composition='sourceover'): panel = gui.qapp.panels.selected('image') panel.imviewer.imgdata.set_mask(array, composition) panel.imviewer.refresh() def refresh(self): ImageGuiProxy.show_array() @StaticGuiCall def cmap(cmap): ImageGuiProxy.show_array(None, cmap) @property def vs(self): shared = config['image']['queue_array_shared_mem'] if shared: return self.get_image_view_source(True).ndarray else: return self.get_image_view_source(False) @property def vr(self): return self.get_image_view_region() @property def buff(self): return self.get_image_view_buffer() @StaticGuiCall def get_image_view_source(shared=True): panel = gui.qapp.panels.selected('image') if panel is None: return if shared: return panel.sharray else: return panel.sharray.ndarray def get_image_view_region(self): slices = self.get_roi_slices() if slices is None: return None vs = self.get_image_view_source() if vs is None: return return vs[slices] @StaticGuiCall def get_image_view_buffer(): panel = gui.qapp.panels.selected('image') if panel is None: return None return panel.imviewer.imgdata.array8bit @StaticGuiCall def repaint(): panel = gui.qapp.panels.selected('image') panel.imviewer.refresh() @StaticGuiCall def set_range(black, white): panel = gui.qapp.panels.selected('image') panel.changeBlackWhite(black, white) @StaticGuiCall def set_offset_gain(offset=0, gain=1, gamma=1, as_default=False): panel = gui.qapp.panels.selected('image') panel.changeOffsetGain(offset, gain, gamma) if as_default: panel.setCurrentOffsetGainAsDefault() @staticmethod def read_raw(data, width, height, depth=1, dtype='uint8', offset=0, byteswap=False): if isinstance(data, (str, Path)): fp = open(data, 'br') data = fp.read() fp.close() dtype = np.dtype(dtype) leftover = len(data) - (width * height * dtype.itemsize + offset) if leftover > 0: print('Too much data found (%d bytes too many)' % leftover) elif leftover < 0: print('Not enough data found (missing %d bytes)' % (-leftover)) arr = np.ndarray(shape=(height, width), dtype=dtype, buffer=data[offset:]) if byteswap: arr = arr.byteswap() return arr @staticmethod def close_all(): while ImageGuiProxy.close(): pass @StaticGuiCall def zoom_fit(): """ Zoom the image to fitting the image viewer area. Snap on the default zooming values. """ panel = gui.qapp.panels.selected('image') panel.zoomFit() @StaticGuiCall def zoom_full(): """ Zoom the image to fully fitting the image viewer area. """ panel = gui.qapp.panels.selected('image') panel.zoomFull() @StaticGuiCall def zoom_region(x, y, width, height): """ Zoom the image to a certain region. """ panel = gui.qapp.panels.selected('image') panel.zoomToRegion(x, y, width, height) @StaticGuiCall def jump_to(x, y): """ Select a certain pixel and zoom to it """ panel = gui.qapp.panels.selected('image') panel.jumpTo(x, y) @StaticGuiCall def set_roi_slices(slices, yonfirst=True): """ Set the region of interest on the current viewport. :param tuple slices: Tuple of slices accross the dimensions. :param bool yonfirst: True if first slice is the y direction. """ panel = gui.qapp.panels.selected('image') roi = panel.imviewer.roi selroi = panel.imviewer.imgdata.selroi if yonfirst: selroi.xr.setfromslice(slices[1]) selroi.yr.setfromslice(slices[0]) else: selroi.xr.setfromslice(slices[0]) selroi.yr.setfromslice(slices[1]) roi.clip() roi.show() roi.roiChanged.emit() @StaticGuiCall def set_roi(x0, y0, width=1, height=1): """ Set the region of interest on the current viewport. :param int x0: first column of the roi :param int y0: first row of the roi :param int width: width of the roi :param int height: height of the roi """ panel = gui.qapp.panels.selected('image') roi = panel.imviewer.roi roi.setStartEndPoints(x0, y0, x0 + width - 1, y0 + height - 1) roi.show() roi.roiChanged.emit() @StaticGuiCall def get_roi_slices(): """ Get the current region of interest as a tupple of slice objects """ panel = gui.qapp.panels.selected('image') if panel is None: return return panel.imviewer.imgdata.selroi.getslices() @StaticGuiCall def get_roi(): """ Get the region of interest of the current viewport as a tuple of integers. :return tuple(int, int, int, int): x0, y0, width, height. """ slices = ImageGuiProxy.get_roi_slices() x0 = slices[1].start width = slices[1].stop - x0 y0 = slices[0].start height = slices[0].stop - y0 return x0, y0, width, height @property def vr(self): slices = self.get_roi_slices() return self.vs[slices] @staticmethod def mirror_x(): print('mirror_x started') arr = gui.vs.copy() arr = arr[:,::-1] gui.img.new() gui.img.show(arr) print('mirror_x ended') @staticmethod def high_pass_current_image(): logger.error('Not implemented') @staticmethod def get_distance(): import math print('Select first point: ', end='') p1 = ImageGuiProxy.get_selected_pixel() print(p1) print('Select second point: ', end='') p2 = ImageGuiProxy.get_selected_pixel() print(p2) delta = (p2[0] - p1[0], p2[1] - p1[1]) print(f'delta xy: {delta}') print(f'delta r: {(delta[0]**2 + delta[1]**2) ** 0.5:.5g}') if delta[0] == 0: print(f'angle r: {90}') else: print(f'angle r: {math.atan(delta[1]/delta[0]) * 180 / 3.141592:.5g}') @staticmethod def get_selected_pixel(): ImageGuiProxy._push_selected_pixel_queue(True) pixel = input() return eval(pixel) @StaticGuiCall def _push_selected_pixel_queue(enable=True): panel = gui.qapp.panels.selected('image') panel.imviewer.push_selected_pixel = enable
thocoo/gamma-desk
gdesk/dialogs/about.py
""" The About window of this GUI """ import pathlib from qtpy import QtGui, QtWidgets from qtpy.QtCore import Qt from .. import config, __version__, __release__, PROGNAME respath = pathlib.Path(config['respath']) class TextEditLinks(QtWidgets.QTextBrowser): """ QTextBrowser used to show clickable links """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setOpenExternalLinks(True) def addLink(self, address, text): """addLink""" self.append(f'<a href="{address}">{text}</a>') def addMail(self, mail_address, text): """addMail""" self.append(f'<a href="mailto:{mail_address}">{text}</a>') class AboutScreen(QtWidgets.QDialog): """ The About window """ def __init__(self): super().__init__() self.initUI() def initUI(self): """ Init the GUI items on this widget """ self.setMinimumWidth(500) self.setMinimumHeight(400) self.setWindowTitle('About') self.setWindowFlags(Qt.WindowStaysOnTopHint) logopixmap = QtGui.QPixmap(str(respath / 'logo' / 'logo_128px.png')) logo = QtWidgets.QLabel() logo.setPixmap(logopixmap) message = f"""<center><h2>{PROGNAME}</h2> <p>Version {__release__}</p> """ cont = TextEditLinks(self) cont.setReadOnly(True) cont.append(message) cont.addLink("http://www.apache.org/licenses/LICENSE-2.0", "www.apache.org/licenses/LICENSE-2.0") cont.addLink("http://www.fatcow.com/free-icons", "www.fatcow.com/free-icons") cont.addMail("<EMAIL>", "<EMAIL>") hboxlogo = QtWidgets.QHBoxLayout() hboxlogo.addWidget(logo) hboxlogo.addWidget(cont) okButton = QtWidgets.QPushButton("OK") hboxbut = QtWidgets.QHBoxLayout() hboxbut.addStretch(1) hboxbut.addWidget(okButton) vbox = QtWidgets.QVBoxLayout() vbox.addLayout(hboxlogo) vbox.addLayout(hboxbut) self.setLayout(vbox) okButton.clicked.connect(self.close) self.show()
thocoo/gamma-desk
gdesk/panels/cmdhist/__init__.py
<reponame>thocoo/gamma-desk<gh_stars>0 from .proxy import CmdHistGuiProxy from ... import config if config['qapp']: from .panel import CmdHistPanel
thocoo/gamma-desk
gdesk/core/interpreter.py
<gh_stars>0 import sys import io import os import traceback import queue import ctypes import time import threading import multiprocessing import builtins import psutil import logging import inspect import cProfile import pstats from queue import Queue from codeop import CommandCompiler from datetime import timedelta from pathlib import Path import psutil from .conf import config from . import stdinout from .stdinout import ProcessStdInput from .gui_proxy import GuiProxy, GuiMap, gui logger = logging.getLogger(__file__) class SyncBreaked(Exception): pass class QueueInterpreter(object): def __init__(self, shell, cqs, gui_proxy=None, console_id=None): self.shell = shell self.cqs = cqs this_process = multiprocessing.current_process() this_thread = threading.currentThread() self.thread_id = thread_id = this_thread.ident self.console_id = console_id self.enable_trace = True self.breakable = False self.break_sent = False self.stop = False self.timeit = False self.enable_inspect = False self.enable_profile = False self.profile_sortby = 'cumulative' self.control_thread = None if gui_proxy is None: self.gui_proxy = GuiProxy(None, cqs.gui_call_queue, cqs.gui_return_queue) else: self.gui_proxy = gui_proxy self.register_thread(thread_id, cqs) self.interpreter = Interpreter(self.shell.wsdict, thread_id) self.shell.interpreters[self.thread_id] = self callbackargs = ('process', 0, (os.getpid(), this_thread.name, threading.get_ident())) self.gui_proxy._call(-2, *callbackargs) print(f'{sys.executable}') print(f'Python {".".join(str(v) for v in sys.version_info)}') print(os.getcwd()) print(f'{this_process.name} [{os.getpid()}] {this_thread.name} [{threading.get_ident()}]') def register_thread(self, tid, cqs): self.stdout = stdinout.FlushPipeStream(cqs.stdout_queue, lambda: self.gui_proxy._call_no_wait(-1)) self.shell.stdout.route_stream(self.stdout, tid) self.stderr = stdinout.ErrLogStream() self.shell.stderr.route_stream(self.stderr, tid) ProcessStdInput.stdin_queues[tid] = cqs.stdin_queue GuiMap.gui_proxies[tid] = self.gui_proxy def unregister_thread(self): tid = self.thread_id self.shell.stdout.streams.pop(tid) self.shell.stderr.streams.pop(tid) self.shell.interpreters.pop(tid) ProcessStdInput.stdin_queues.pop(tid) GuiMap.gui_proxies.pop(tid) @staticmethod def create_and_interact(shell, cqs, gui_proxy=None, console_id=None): try: queuedinter = QueueInterpreter(shell, cqs, gui_proxy, console_id) queuedinter.interact() finally: sys.__stdout__.write(f'End of create_and_interact\n') sys.__stdout__.flush() def interact(self): self.control_thread = threading.Thread(target=self.control_loop, name=f'control_thread{self.thread_id}', daemon=True) self.control_thread.start() self.commandLoop() def control_loop(self): flowcode = 1 self.shell.stdout.route_stream(self.stdout) try: while flowcode == 1: flowcode = self.control() finally: self.shell.stdout.unregister() sys.__stdout__.write(f'Exiting control loop of thread {self.thread_id}\n') sys.__stdout__.flush() def commandLoop(self): flowcode = 1 try: while flowcode == 1: flowcode = self.execute() finally: self.unregister_thread() sys.__stdout__.write(f'Exiting command loop of thread {self.thread_id}\n') sys.__stdout__.flush() def system_tracer(self, *args): if self.enable_trace and self.stop: raise SyncBreaked('Breaked by system tracer') return None def get_current_trace(self, back=50): lines = '' for frame in self.interpreter.get_code_frames(back): fi = inspect.getframeinfo(frame) file_position = ' File "%s", line %d, in %s\n' % (fi.filename, fi.lineno, fi.function) file_code = '' try: for line in fi.code_context: file_code += line except: pass lines = file_position + file_code + lines return lines def get_current_locals(self, back=5): lines = '' for frame in self.interpreter.get_code_frames(back): for key, val in frame.f_locals.items(): if key.startswith('_'): continue lines += f'{key}: {val}\n' return lines def set_console_mode(self, mode): #if not self.console_id is None: gui.console.set_mode(mode, self.console_id) def control(self): cqs = self.cqs interpreter = self.interpreter gui_proxy = self.gui_proxy while True: try: mode, args, callback = cqs.flow_queue.get() break except KeyboardInterrupt: pass if mode == 'flow': cmd, *cargs = args if cmd == 'heartbeat': callbackargs = (mode, 0, 'heartbeat') retvalue = 1 elif cmd == 'set_tracing': self.enable_trace = cargs[0] callbackargs = (mode, 0, f'Enable Trace: {self.enable_trace}') retvalue = 1 elif cmd == 'set_timeit': self.timeit = cargs[0] callbackargs = (mode, 0, f'Enable Time It: {self.timeit}') retvalue = 1 elif cmd == 'enable_profiling': self.enable_profile = True callbackargs = (mode, 0, f'Enable profiling') retvalue = 1 elif cmd == 'toggle_inspect': self.enable_inspect = not self.enable_inspect callbackargs = (mode, 0, f'enable_inspect={self.enable_inspect}') retvalue = 1 elif cmd == 'trace': print(self.get_current_trace()) callbackargs = (mode, 0, 'Trace printed') retvalue = 1 elif cmd == 'locals': print(self.get_current_locals()) callbackargs = (mode, 0, 'Locals printed') retvalue = 1 elif cmd == 'sync_break': if not threading.currentThread().ident == self.thread_id and self.enable_trace: self.stop = True callbackargs = (mode, 0, 'Thread is asked to stop') else: callbackargs = (mode, 1, 'Tracing is not enabled') retvalue = 1 elif cmd == 'KeyboardInterrupt': if not threading.currentThread().ident == self.thread_id and self.breakable: self.break_sent = True self.interpreter.async_break() callbackargs = (mode, 0, 'KeyboardInterrupt send') else: callbackargs = (mode, 1, 'KeyboardInterrupt not send') retvalue = 1 elif cmd == 'system_exit': self.interpreter.async_system_exit() callbackargs = (mode, 0, 'SystemExit send') retvalue = 0 elif cmd == 'kill': parent = psutil.Process(os.getpid()) for child in parent.children(recursive=True): child.kill() parent.kill() elif cmd == 'finish': callbackargs = (mode, 0, 'Finishing') retvalue = 0 else: callbackargs = (mode, 1, 'Command unkown') retvalue = 1 elif mode == 'flow_func': func = args[0] args = args[1] if isinstance(func, str): print('str is not supported as function pointer') callbackargs = (mode, 1, 'str is not supported as function pointer') retvalue = 1 elif isinstance(func, tuple): try: func = gui_proxy.decode_func(func) result = func(*args) error_code = 0 except Exception: traceback.print_exc() result = None error_code = 1 callbackargs = (mode, error_code, result) retvalue = 1 elif mode == 'eval': try: result = [eval(arg, self.shell.wsdict) for arg in args] error_code = 0 except Exception: traceback.print_exc() result = None error_code = 1 callbackargs = (mode, error_code, result) retvalue = 1 else: callbackargs = (mode, 1, 'unkown') retvalue = 1 if callback is None: #There always should be a callback: {callbackargs}') #This is only used for the evaluate cqs.return_queue.put(callbackargs) else: gui_proxy._call(callback, *callbackargs) return retvalue def execute(self): cqs = self.cqs interpreter = self.interpreter gui_proxy = self.gui_proxy while True: try: content = cqs.stdin_queue.get(timeout=3) mode, args, callback = content break except queue.Empty: pass except KeyboardInterrupt: pass if mode in ['interprete', 'func']: error_code = None result = None try: self.breakable = True self.stop = False #the tracer seemed to be disabled after every sync break ??? if self.enable_trace: sys.settrace(self.system_tracer) else: sys.settrace(None) if self.enable_profile: self.profile = cProfile.Profile() self.profile.enable() start_moment = end_moment = time.perf_counter() redbull_timeout = config['console']['redbull'] if redbull_timeout > 0: self.gui_proxy.redbull.enable(redbull_timeout) self.set_console_mode('running') if mode == 'func': func = gui_proxy.decode_func(args[0]) func_args = args[1] if self.enable_inspect: try: filename = inspect.getfile(func) print(filename) except: print('filename not found') try: source = inspect.getsource(func) print(source) except: print('source not found') error_code, result = interpreter.use_one_func(func, func_args) self.set_console_mode('interprete') else: error_code, result = interpreter.use_one_command(*args) if self.enable_profile: self.profile.disable() self.enable_profile = False profile_stats = pstats.Stats(self.profile).sort_stats(self.profile_sortby) profile_stats.print_stats() sys.settrace(None) if self.break_sent: #A async KeyboardInterrupt was sent but still have to occur #This situation is rare, but can happen #Keep on stepping in the Python interpreter print('WARNING: KeyboardInterrupt is on its way') for i in range(100): time.sleep(0.010) except KeyboardInterrupt: error_code = 3 result = 'Thread Interrupted by KeyboardInterrupt' print(result) except SyncBreaked: error_code = 3 result = 'Thread Interrupted by SyncBreaked' print(result) except Exception as ex: error_code = 4 result = repr(ex) finally: #Finish the side thread self.breakable = False self.break_sent = False self.gui_proxy.redbull.disable() if self.timeit: end_moment = time.perf_counter() print(f'Elapased time {end_moment-start_moment} s') callbackargs = (mode, error_code, result) retvalue = 1 elif mode == 'exit': self.unregister_thread() callbackargs = (mode, 0, 'Exiting') retvalue = 0 else: callbackargs = (mode, 1, 'unkown') retvalue = 1 if callback is None: #There always should be a callback: {callbackargs}') #This is only used for the evaluate cqs.return_queue.put(callbackargs) else: gui_proxy._call(callback, *callbackargs) return retvalue class Interpreter(object): def __init__(self, workspace=None, thread_id=None): if workspace is None: workspace = dict() self.workspace = workspace self.compile = CommandCompiler() self.thread_id = thread_id def compile_source(self, source, filename="<input>", symbol="auto"): """ Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line. """ if symbol == 'auto': if source.count('\n') == 0: symbol = 'single' else: symbol = 'exec' #Compile the code, show syntax error try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return 1, None if code is None: # Case 2 # more code expected, nothing to do return 2, None return 0, code def eval_expression(self, expression): """ Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: return eval(expression, self.workspace) except (SystemExit, KeyboardInterrupt): raise except: self.showtraceback() def showsyntaxerror(self, filename=None): """ Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below. """ type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value lines = traceback.format_exception_only(type, value) self.write_error(''.join(lines)) def showtraceback(self): """ Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below. """ type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(type, value)) self.write_error(''.join(lines)) def write_error(self, text): sys.stderr.write(text) def use_one_func(self, func, args): return 0, self.exec_func(func, args) def exec_func(self, func, args): try: return func(*args) except (SystemExit, KeyboardInterrupt, SyncBreaked): raise except: self.showtraceback() def use_one_command(self, cmd): error_code, code = self.compile_source(cmd, symbol='auto') if error_code != 0: return error_code, cmd else: return error_code, self.exec_code(code) def exec_code(self, code): """ Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: return exec(code, self.workspace) except (SystemExit, KeyboardInterrupt, SyncBreaked): raise except: self.showtraceback() def async_break(self): async_break(self.thread_id) def async_system_exit(self): async_system_exit(self.thread_id) def get_code_frames(self, back): frame = sys._current_frames()[self.thread_id] yield frame for _ in range(back): if frame.f_back is None: return frame = frame.f_back yield frame def async_raise(thread_id, exctype): """ Raise the exception to the thread tid, performs cleanup if needed. """ #the async exception is not immediate; it is checked every 100 #bytecodes (=sys.getcheckinterval()). # if not inspect.isclass(exctype): # exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), ctypes.py_object(exctype)) #receiver can clear errob y ctypes.pythonapi.PyErr_Clear()? if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, None) raise SystemError("PyThreadState_SetAsyncExc failed") else: pass #print(f'{exctype} sent to thread id {thread_id}') def async_break(thread_id): async_raise(thread_id, KeyboardInterrupt) def async_system_exit(thread_id): async_raise(thread_id, SystemExit)
thocoo/gamma-desk
gdesk/panels/levels/panel.py
<gh_stars>0 import pathlib import numpy as np from qtpy import QtCore, QtGui, QtWidgets from ... import config, gui from ...graphics.view import SceneView from ...graphics.items import createCurve, Indicator from ...graphics.rulers import TickedRuler, Grid from ...graphics.point import Point from ..base import BasePanel, CheckMenu from ..imgview import fasthist respath = pathlib.Path(config['respath']) colors = { 'K': QtGui.QColor(0, 0, 0), 'RK': QtGui.QColor(255, 0, 0), 'R': QtGui.QColor(255, 0, 0), 'G': QtGui.QColor(0, 255, 0), 'B': QtGui.QColor(0, 0, 255), 'RR': QtGui.QColor(192, 0, 0), 'RG': QtGui.QColor(64, 127, 0), 'RB': QtGui.QColor(64, 0, 127)} def semilog(vec): with np.errstate(divide='ignore'): result = np.nan_to_num(np.log10(vec), neginf=0) return result class LevelPlot(QtWidgets.QWidget): blackPointChanged = QtCore.Signal(object) whitePointChanged = QtCore.Signal(object) def __init__(self, parent): super().__init__(parent=parent) self.scene = QtWidgets.QGraphicsScene() self.view = SceneView(self) self.view.freeze_y0 = True self.view.scale = [100, -100] self.view.setScene(self.scene) #self.view.fixScaleY = True self.vbox = QtWidgets.QVBoxLayout() self.vbox.setContentsMargins(0,0,0,0) self.vbox.addWidget(self.view) self.setLayout(self.vbox) self.create_x_ruler() self.create_y_ruler() # self.create_grid() self.indicators = [] self.create_indicator(0, QtGui.QColor(0,0,127), 'B:%0.5g', self.IndicatorBMoved) self.create_indicator(256, QtGui.QColor(255,127,127), 'W:%0.5g', self.IndicatorWMoved) self.curves = dict() self.plot_curve('K', np.array([0, 256]), np.array([0, 0])) #self.plot_curve('G', [-2, -1, 0 , 1, 2], [0, 0.5, 1.0, 0.5 ,0]) #self.plot_curve('B', [-2, -1, 0 , 1, 2], [1, 1.0, 1.0, 0.25 ,0]) for indicator in self.indicators: indicator.attach_curves(self.curves) self.view.translated.connect(self.update_rulers) self.view.scaled.connect(self.update_rulers) self.view.scale_ended.connect(self.update_rulers) self.view.zoom_full.connect(self.zoomFull) self.xmin = 0 self.xmax = 1e6 self.ymin = 0 self.ymax = 256 def create_indicator(self, xpos, color, text = None, slot=None): indicator = Indicator(color, text, parent=self.x_ruler) indicator.setPos(xpos, 0) indicator.setZValue(2.0) indicator.mouse_released.connect(slot) self.indicators.append(indicator) #self.scene.addItem(indicator) def create_x_ruler(self): x0, y0, x1, y1 = self.view.viewRectCoord() self.x_ruler = TickedRuler(0, x0, x1, abs(self.view.scale[0]), noDecimals=False, parent=None) self.v_grid = Grid(self.x_ruler, parent=None) self.x_ruler.setPos(0, y0 - self.view.pixelSize()[1] * 22) self.v_grid.setPos(0, y0 - self.view.pixelSize()[1] * 22) self.x_ruler.setZValue(1.0) self.v_grid.setZValue(-1) self.scene.addItem(self.x_ruler) self.scene.addItem(self.v_grid) def create_y_ruler(self): x0, y0, x1, y1 = self.view.viewRectCoord() self.y_ruler = TickedRuler(-90, y0, y1, abs(self.view.scale[1]), noDecimals=False) self.h_grid = Grid(self.y_ruler) self.y_ruler.setPos(x0 + self.view.pixelSize()[0] * 22, 0) self.h_grid.setPos(x0 + self.view.pixelSize()[0] * 22, 0) self.y_ruler.setZValue(0.9) self.h_grid.setZValue(-1) self.scene.addItem(self.y_ruler) self.scene.addItem(self.h_grid) def attach_indicators(self): for indicator in self.indicators: indicator.setParentItem(self.x_ruler) def hide_stuff(self): self.x_ruler.hide() self.y_ruler.hide() def update_x_ruler(self): x0, y0, x1, y1 = self.view.viewRectCoord() self.x_ruler.setPos(0, y0 - self.view.pixelSize()[1] * 22) self.x_ruler.update_labels(x0, x1, abs(self.view.scale[0])) self.v_grid.setPos(0, y0 - self.view.pixelSize()[1] * 22) self.v_grid.update_labels() self.x_ruler.show() self.xmin = x0 + self.view.pixelSize()[0] * 22 self.xmax = x1 def update_y_ruler(self): x0, y0, x1, y1 = self.view.viewRectCoord() self.y_ruler.setPos(x0 + self.view.pixelSize()[0] * 22, 0) self.y_ruler.update_labels(y0, y1, abs(self.view.scale[1])) self.h_grid.setPos(x0 + self.view.pixelSize()[0] * 22, 0) self.h_grid.update_labels() self.y_ruler.show() for indicator in self.indicators: indicator.updates_ylabels() self.ymin = y0 - self.view.pixelSize()[1] * 22 self.ymax = y1 def update_rulers(self, x, y): self.update_x_ruler() self.update_y_ruler() def remove_all_but(self, curve_ids): for curveid in list(self.curves.keys()): if curveid in curve_ids: continue oldcurve = self.curves[curveid] self.scene.removeItem(oldcurve) self.curves.pop(curveid) def plot_curve(self, curveid=None, x=[], y=[], color = None, fill=50): oldcolor = None if curveid in self.curves.keys(): oldcurve = self.curves[curveid] oldcolor = oldcurve.pen().color() self.scene.removeItem(oldcurve) elif curveid is None: curveid = len(self.curves) if color is None: if oldcolor is None: color = colors[curveid] else: color = oldcolor curve = createCurve(x, y, color = color, fill=fill) curve.setZValue(0) self.curves[curveid] = curve self.scene.addItem(curve) return curveid def zoomFull(self, enforce_ymin=None): self.xmin = self.xmax = None self.ymin = self.ymax = None for curve in self.curves.values(): xmin_cand = min(curve.xvector) xmax_cand = max(curve.xvector) ymin_cand = min(curve.yvector) ymax_cand = max(curve.yvector) if (self.xmin is None) or (xmin_cand < self.xmin): self.xmin = xmin_cand if (self.xmax is None) or (xmax_cand > self.xmax): self.xmax = xmax_cand if (self.ymin is None) or (ymin_cand < self.ymin): self.ymin = ymin_cand if (self.ymax is None) or (ymax_cand > self.ymax): self.ymax = ymax_cand self.ymin = enforce_ymin if not enforce_ymin is None else self.ymin if self.xmin == self.xmax: self.xmin -= 0.5 self.xmin += 0.5 if self.ymin == self.ymax: self.ymin -= 0.5 self.ymax += 0.5 self.view.setXLimits(self.xmin, self.xmax, 22, 0) self.view.setYLimits(self.ymin, self.ymax, 22, 0) #self.resetIndicators(self.xmin, self.xmax) self.update_rulers(True, True) def zoomFitYRange(self, ymin=None): self.ymin = self.ymax = None for curve in self.curves.values(): ymin_cand = min(curve.yvector) ymax_cand = max(curve.yvector) if (self.ymin is None) or (ymin_cand < self.ymin): self.ymin = ymin_cand if (self.ymax is None) or (ymax_cand > self.ymax): self.ymax = ymax_cand self.ymin = ymin if not ymin is None else self.ymin if self.ymin == self.ymax: self.ymin -= 0.5 self.ymax += 0.5 self.view.setYLimits(self.ymin, self.ymax, 22, 0) self.update_rulers(True, True) def zoomBetweenIndicators(self, skip_if_visible=False): x0 = self.indicators[0].pos().x() x1 = self.indicators[1].pos().x() if skip_if_visible: cx0, cy0, cx1, cy1 = self.view.viewRectCoord() x0 = min(x0, cx0 + 22 / self.view.scale[0]) #x0 = min(x0, cx0 + 22) x1 = max(x1, cx1) self.view.setXLimits(x0, x1, 22, 0) self.update_rulers(True, True) def resetIndicators(self, xmin=0, xmax=1): for indicator in self.indicators: x = indicator.pos().x() x = min(max(x, xmin), xmax) indicator.setPos(x, 0) def IndicatorBMoved(self, val): self.blackPointChanged.emit(val) def IndicatorWMoved(self, val): self.whitePointChanged.emit(val) def resizeEvent(self, ev): self.view.setYLimits(self.ymin, self.ymax, 22, 0) self.view.setXLimits(self.xmin, self.xmax, 22, 0) self.update_rulers(True, True) class Levels(QtWidgets.QWidget): def __init__(self, parent=None): self.panel = parent super().__init__(parent=parent) self.initUI() def initUI(self): self.setMinimumHeight(80) self.setMinimumWidth(200) self.hbox = QtWidgets.QHBoxLayout() self.hbox.addStretch() self.levelplot = LevelPlot(self) self.vbox = QtWidgets.QVBoxLayout() self.vbox.setContentsMargins(0,0,0,0) self.vbox.setSpacing(0) self.setLayout(self.vbox) self.vbox.addLayout(self.hbox) self.vbox.addWidget(self.levelplot) #@staticmethod def image_panel(self, panel_id=None): if (panel_id is None) or (panel_id==False): imagePanel = self.panel.bindedPanel('image') if imagePanel is None: imagePanel = gui.qapp.panels.selected('image') else: imagePanel = gui.qapp.panels['image'][panel_id] return imagePanel @staticmethod def xy_as_steps(xvector, yvector, stepwidth): yvector = yvector.reshape((yvector.shape[0], 1)).dot(np.ones((1, 2))).reshape(yvector.shape[0]*2) xvector = xvector.reshape((xvector.shape[0], 1)).dot(np.ones((1, 2))) xvector[:,1] += stepwidth xvector = xvector.flatten() return xvector, yvector def updateActiveHist(self): self.updateHistOfPanel(None) def updateHistOfPanel(self, panelId=None): if self.panel.cached: self.updatedCachedHistogram(panelId) else: self.updateHist(panelId) if self.panel.fitheight: self.levelplot.zoomFitYRange(ymin=0) def updatedCachedHistogram(self, panid): image_panel = self.image_panel(panid) chanstats = image_panel.imviewer.imgdata.chanstats if self.panel.histSizePolicy == 'bins': bins = int(self.panel.histSize) else: bins = None stepsize = eval(self.panel.histSize) if self.panel.roi and image_panel.imviewer.roi.isVisible(): clr_filter = set(('RK','RR', 'RG', 'RB')) else: clr_filter = set(('K', 'R', 'G', 'B')) clr_to_draw = clr_filter.intersection(set(chanstats.keys())) self.levelplot.remove_all_but(clr_to_draw) for clr in clr_to_draw: chanstat = chanstats[clr] if chanstat.arr2d is None: continue if len(chanstat._cache.keys()) == 0: chanstat.calc_histogram() if bins is None: step = round(stepsize / chanstat._cache['stepsize']) step = max(1, step) else: step = chanstat.step_for_bins(bins) hist = chanstat.histogram(step) if self.panel.log: hist = semilog(hist) starts = chanstat.starts(step) barstarts, hist = self.xy_as_steps(starts, hist, chanstat.stepsize(step)) self.levelplot.plot_curve(clr, barstarts, hist) if self.panel.gaussview: import scipy.signal std = chanstat.std() m = chanstat.mean() npixel = chanstat.n() guass = scipy.signal.gaussian(len(starts), std= std / step) offset = starts.mean() - m xvec = starts - offset yvec = guass * (npixel / guass.sum()) if self.panel.log: yvec = semilog(yvec) self.levelplot.plot_curve(f'{clr}_gv', xvec, yvec, colors[clr], fill=0) # print(xvec) # print(yvec) def updateHist(self, panelId=None): qapp = gui.qapp with qapp.waitCursor(): use_numba = config['levels']['numba'] relative = config['levels']['relative'] hist2d = fasthist.hist2d imagePanel = self.image_panel(panid) do_roi = self.panel.roi and imagePanel.imviewer.roi.isVisible() if do_roi: slices = imagePanel.imviewer.imgdata.selroi.getslices() arr = imagePanel.ndarray[slices] else: arr = imagePanel.ndarray if len(arr.shape) == 2: if self.panel.histSizePolicy == 'bins': stepcount = int(self.panel.histSize) hist, starts, stepsize = hist2d(arr, bins=stepcount-1, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepsize.setText(str(stepsize)) elif self.panel.histSizePolicy == 'step': stepsize = int(self.panel.histSize) hist, starts, stepsize = hist2d(arr, step=stepsize, pow2snap=True, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepcount.setText(str(len(hist))) if relative: hist = hist / (arr.shape[0] * arr.shape[1] * stepsize) starts, hist = self.xy_as_steps(starts, hist, stepsize) if do_roi: self.levelplot.remove_all_but(['RK']) self.levelplot.plot_curve('RK', starts, hist) else: self.levelplot.remove_all_but(['K']) self.levelplot.plot_curve('K', starts, hist) elif len(arr.shape) == 3 and do_roi: self.levelplot.remove_all_but(['RR','RG','RB']) for clr_ch, clr_str in [(0,'RR'),(1,'RG'),(2,'RB')]: if self.panel.histSizePolicy == 'bins': stepcount = int(self.panel.histSize) hist, starts, stepsize = hist2d(arr[:,:,clr_ch], bins=stepcount-1, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepsize.setText(str(stepsize)) elif self.panel.histSizePolicy == 'step': stepsize = int(self.panel.histSize) hist, starts, stepsize = hist2d(arr[:,:,clr_ch], step=stepsize, pow2snap=True, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepcount.setText(str(len(hist))) if relative: hist = hist / (arr.shape[0] * arr.shape[1] * stepsize) starts, hist = self.xy_as_steps(starts, hist, stepsize) self.levelplot.plot_curve(clr_str, starts, hist) elif len(arr.shape) == 3 and not do_roi: self.levelplot.remove_all_but(['R','G','B']) for clr_ch, clr_str in [(0,'R'),(1,'G'),(2,'B')]: if self.step_priority == 'stepcount': stepcount = eval(self.stepcount.text()) hist, starts, stepsize = hist2d(arr[:,:,clr_ch], bins=stepcount-1, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepsize.setText(str(stepsize)) elif self.step_priority == 'stepsize': stepsize = eval(self.stepsize.text()) hist, starts, stepsize = hist2d(arr[:,:,clr_ch], step=stepsize, pow2snap=True, plot=False, use_numba=use_numba) if self.panel.log: #hist = hist ** 0.5 hist = semilog(hist) self.stepcount.setText(str(len(hist))) if relative: hist = hist / (arr.shape[0] * arr.shape[1] * stepsize) starts, hist = self.xy_as_steps(starts, hist, stepsize) self.levelplot.plot_curve(clr_str, starts, hist) def updateIndicators(self, image_panel_id): qapp = gui.qapp if (image_panel_id is None) or (image_panel_id==False): imagePanel = qapp.panels.selected('image') else: imagePanel = qapp.panels['image'][image_panel_id] ind = self.levelplot.indicators[0] ind.setPos(imagePanel.offset, 0) ind.label.updateText(ind.text % imagePanel.offset) ind.updates_ylabels() ind = self.levelplot.indicators[1] ind.setPos(imagePanel.white, 0) ind.label.updateText(ind.text % imagePanel.white) ind.updates_ylabels() def indicZoom(self): self.levelplot.zoomBetweenIndicators() def bringIndicVisible(self): self.levelplot.zoomBetweenIndicators(skip_if_visible=True) def fullZoom(self): self.levelplot.zoomFull(enforce_ymin=0) def zoomFitYRange(self): self.levelplot.zoomFitYRange(ymin=0) # def focusInEvent(self, event): # self.parent().select() class LevelsToolBar(QtWidgets.QToolBar): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initUi() @property def panel(self): return self.parent() @property def levels(self): return self.parent().levels def initUi(self): self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'update.png')), 'Refresh', self.levels.updateActiveHist) self.histSizePolicyBox = QtWidgets.QComboBox() self.histSizePolicyBox.addItem('bins') self.histSizePolicyBox.addItem('step') self.histSizePolicyBox.currentTextChanged.connect(self.histSizePolicyChanged) self.addWidget(self.histSizePolicyBox) self.stepcount = QtWidgets.QLineEdit('64', self) self.stepcount.setMaximumWidth(100) self.stepcount.textChanged.connect(self.histSizeChanged) self.addWidget(self.stepcount) self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'zoom_fit.png')), 'Zoom to full histogram', self.levels.fullZoom) self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'zoom_actual_equal.png')), 'Zoom Fit Y range', self.levels.zoomFitYRange) self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'zoom_cursors.png')), 'Zoom to black white indicators', self.levels.indicZoom) self.gainSigmaMenu = QtWidgets.QMenu('Contrast') actGainSigma1 = QtWidgets.QAction('Gain to Sigma 1', self, triggered=lambda: self.panel.autoContrast(1)) actGainSigma1.setText('1σ 68.27%') actGainSigma1.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast_high.png'))) self.gainSigmaMenu.addAction(actGainSigma1) actGainSigma2 = QtWidgets.QAction('Gain to Sigma 2', self, triggered=lambda: self.panel.autoContrast(2)) actGainSigma2.setText('2σ 95.45%') actGainSigma2.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast.png'))) self.gainSigmaMenu.addAction(actGainSigma2) actGainSigma3 = QtWidgets.QAction('Gain to Sigma 3', self, triggered=lambda: self.panel.autoContrast(3)) actGainSigma3.setText('3σ 99.73%') actGainSigma3.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast_low.png'))) self.gainSigmaMenu.addAction(actGainSigma3) actGainSigma4 = QtWidgets.QAction('Gain to Sigma 4', self, triggered=lambda: self.panel.autoContrast(4)) actGainSigma4.setText('4σ 99.99%') actGainSigma4.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast_low.png'))) self.gainSigmaMenu.addAction(actGainSigma4) self.autoBtn = QtWidgets.QToolButton(self) self.autoBtn.setText(f'{self.panel.sigma}σ') self.autoBtn.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast.png'))) self.autoBtn.setMenu(self.gainSigmaMenu) self.autoBtn.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.autoBtn.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.autoBtn.clicked.connect(lambda: self.panel.autoContrast()) self.addWidget(self.autoBtn) self.useRoiBtn = QtWidgets.QToolButton(self) self.useRoiBtn.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'region_of_interest.png'))) self.useRoiBtn.setCheckable(True) self.useRoiBtn.clicked.connect(self.toggleRoi) self.addWidget(self.useRoiBtn) self.sqrtBtn = QtWidgets.QToolButton(self) self.sqrtBtn.setText('log') self.sqrtBtn.setCheckable(True) self.sqrtBtn.clicked.connect(self.toggleSqrt) self.addWidget(self.sqrtBtn) #self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'zoom_actual.png')), 'Apply default offset, gain and gamma', self.panel.gain1) self.applyUnityBtn = QtWidgets.QToolButton(self) self.applyUnityBtn.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast_decrease.png'))) self.applyUnityBtn.setToolTip('Apply default offset, gain and gamma') self.applyUnityBtn.clicked.connect(self.panel.gain1) self.addWidget(self.applyUnityBtn) self.asUnityBtn = QtWidgets.QToolButton(self) self.asUnityBtn.setIcon(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'contrast_increase.png'))) self.asUnityBtn.clicked.connect(self.panel.asUnity) self.addWidget(self.asUnityBtn) self.addAction(QtGui.QIcon(str(respath / 'icons' / 'px16' / 'dopplr.png')), 'Choose colormap', self.colorMap) fontHeight = self.fontMetrics().height() self.setIconSize(QtCore.QSize(fontHeight * 3 / 2, fontHeight * 3 / 2)) def histSizePolicyChanged(self, text): self.stepcount.setText(str(self.panel.histSizes[text])) def histSizeChanged(self, text): histSizePolicy = self.histSizePolicyBox.currentText() self.panel.histSizePolicy = histSizePolicy self.panel.histSizes[histSizePolicy] = text def toggleRoi(self): sender = self.sender() self.panel.roi = sender.isChecked() self.levels.updateActiveHist() def toggleSqrt(self): sender = self.sender() self.panel.log = sender.isChecked() self.levels.updateActiveHist() def updateButtonStates(self): self.histSizePolicyBox.setCurrentText(self.panel.histSizePolicy) self.useRoiBtn.setChecked(self.panel.roi) self.sqrtBtn.setChecked(self.panel.log) def colorMap(self): panids = self.panel.panIdsOfBounded('image') for panid in panids: gui.menu_trigger('image', panid, ['View','Colormap...']) class LevelsPanel(BasePanel): panelCategory = 'levels' panelShortName = 'basic' userVisible = True offsetGainChanged = QtCore.Signal(object, object, object) blackWhiteChanged = QtCore.Signal(object, object) classIconFile = str(respath / 'icons' / 'px16' / 'color_adjustment.png') def __init__(self, parent, panid): super().__init__(parent, panid, 'levels') self.histSizePolicy = config['levels'].get('hist_size_policy', 'bins') bins = config['levels'].get('bins', 64) step = config['levels'].get('step', 4) self.histSizes = {'bins': bins, 'step': step} self.cached = True self.fitheight = True self.gaussview = False self.log = False self.roi = False self.sigma = 3 self.levels = Levels(self) self.setCentralWidget(self.levels) self.toolbar = LevelsToolBar(self) self.addToolBar(self.toolbar) self.fileMenu = self.menuBar().addMenu("&File") self.modeMenu = CheckMenu("&Mode", self.menuBar()) self.menuBar().addMenu(self.modeMenu) self.addMenuItem(self.fileMenu, 'Close', self.close_panel, statusTip="Close this levels panel", icon = QtGui.QIcon(str(respath / 'icons' / 'px16' / 'cross.png'))) self.addMenuItem(self.modeMenu, 'Cached', self.toggle_cached, checkcall=lambda: self.cached) self.addMenuItem(self.modeMenu, 'Fit Height', self.toggle_fitheight, checkcall=lambda: self.fitheight) self.addMenuItem(self.modeMenu, 'Gaussian', self.toggle_gaussview, checkcall=lambda: self.gaussview) self.addMenuItem(self.modeMenu, 'Roi', self.toggle_roi, checkcall=lambda: self.roi) self.addMenuItem(self.modeMenu, 'Log', self.toggle_log, checkcall=lambda: self.log) self.addBaseMenu(['image']) self.levels.levelplot.blackPointChanged.connect(self.updateBlackPoint) self.levels.levelplot.whitePointChanged.connect(self.updateWhitePoint) self.levels.show() self.toolbar.updateButtonStates() self.statusBar().hide() @property def histSize(self): return self.histSizes[self.histSizePolicy] def addBindingTo(self, category, panid): targetPanel = super().addBindingTo(category, panid) if targetPanel is None: return None self.offsetGainChanged.connect(targetPanel.changeOffsetGain) self.blackWhiteChanged.connect(targetPanel.changeBlackWhite) return targetPanel def removeBindingTo(self, category, panid): targetPanel = super().removeBindingTo(category, panid) if targetPanel is None: return None self.offsetGainChanged.disconnect(targetPanel.changeOffsetGain) self.blackWhiteChanged.disconnect(targetPanel.changeBlackWhite) return targetPanel def toggle_cached(self): self.cached = not self.cached self.toolbar.updateButtonStates() self.levels.updateActiveHist() def toggle_fitheight(self): self.fitheight= not self.fitheight self.toolbar.updateButtonStates() self.levels.updateActiveHist() def toggle_gaussview(self): self.gaussview = not self.gaussview self.toolbar.updateButtonStates() self.levels.updateActiveHist() def toggle_roi(self): self.roi = not self.roi self.toolbar.updateButtonStates() self.levels.updateActiveHist() def toggle_log(self): self.log = not self.log self.toolbar.updateButtonStates() self.levels.updateActiveHist() def autoContrast(self, sigma=None): if not sigma is None: self.sigma = sigma self.toolbar.autoBtn.setText(f'{sigma}σ') for panel in self.targetPanels('image'): panel.gainToSigma(self.sigma, self.roi) self.levels.bringIndicVisible() def gain1(self): #self.offsetGainChanged.emit('default', 'default', 'default') for panel in self.targetPanels('image'): panel.changeOffsetGain('default', 'default', 'default') self.levels.indicZoom() def updateBlackPoint(self, value): #self.blackWhiteChanged.emit(value, None) for panel in self.targetPanels('image'): panel.changeBlackWhite(value, None) def updateWhitePoint(self, value): #self.blackWhiteChanged.emit(None, value) for panel in self.targetPanels('image'): panel.changeBlackWhite(None, value) def asUnity(self): for panel in self.targetPanels('image'): panel.setCurrentOffsetGainAsDefault() def imageContentChanged(self, image_panel_id, zoomFit=False): self.levels.updateHistOfPanel(image_panel_id) if zoomFit: self.levels.fullZoom() def imageGainChanged(self, image_panel_id): self.levels.updateIndicators(image_panel_id) def roiChanged(self, image_panel_id): if self.roi: self.levels.updateHistOfPanel(image_panel_id)
thocoo/gamma-desk
gdesk/core/tasks.py
import sys, io, os, builtins import json import signal import traceback import threading import multiprocessing import textwrap import types import pathlib import time import pickle import configparser import time import collections import platform import logging from multiprocessing import Process, Lock from queue import Queue try: import zmq zmq_context = zmq.Context() except: pass logger = logging.getLogger(__name__) #In case of Process call, this module will be important by the child #process by the unpickling of the CommQueues from .conf import config, configure from .. import refer_shell_instance #Configure in case of the child process before importing anthing else of ghawk2 configure(matplotlib={'backend':'svg'}) process_name = multiprocessing.current_process().name logger.debug(f'import of {__name__} by {process_name}\n') from .shellmod import Shell from .gui_proxy import GuiProxy from .interpreter import Interpreter, QueueInterpreter from .comm import NonDuplexQueue, ZmqQueues, CommQueues PROCESSES = collections.OrderedDict() here = pathlib.Path(__file__).parent class TimeOutGuiCall(object): def __init__(self, gui_proxy, timeout, callback, args=()): self.gui_proxy = gui_proxy self.callback = callback self.called = False self.timeout = timeout self.thread = threading.Thread(target=self.delay_call, args=args) self.thread.start() self.lock = threading.Lock() def delay_call(self, *args): time.sleep(self.timeout) if self.called: return try: self.lock.acquire() self.called = True self.gui_proxy._call(self.callback, *args) finally: self.lock.release() def call(self, *args): if self.called: return try: self.lock.acquire() self.called = True self.callback(*args) finally: self.lock.release() class TaskBase(object): def __init__(self, tasktype='process'): self.tasktype = tasktype self.process_id = -1 self.thread_name = 'invalid' self.thread_id = -1 self.panid = None @property def stdin_queue(self): return self.cqs.stdin_queue @property def stdout_queue(self): return self.cqs.stdout_queue @property def flow_queue(self): return self.cqs.flow_queue @property def return_queue(self): return self.cqs.return_queue def is_current_thread(self): return self.process_id == os.getpid() and self.thread_id == threading.get_ident() def getReturnedValues(self, mode, error_code, result): if error_code == 0: pass else: print(f'WARNING with error code {error_code}\n{mode} {result}') return mode, error_code, result def send_command(self, command, callback=None): return self.send_func_and_call('interprete', (command,), callback) def send_input(self, text): return self.send_func_and_call('input', (text,)) def evaluate(self, *args, multiple=False): if multiple: return self.send_func_and_call('eval', args, wait=True) else: result = self.send_func_and_call('eval', args, wait=True) return result[0] def call_func(self, func, args=(), callback=None, wait=False, queue='stdin'): if not isinstance(func, str): func = self.gui_proxy.encode_func(func) if queue == 'stdin': return self.send_func_and_call('func', (func, args), callback, wait) elif queue == 'flow': return self.send_func_and_call('flow_func', (func, args), callback, wait) def send_func_and_call(self, mode, args=(), callback=None, wait=False, timeout=0): if callback is None and not wait: callback = self.getReturnedValues if not callback is None: if timeout == 0: call_back_id = self.gui_proxy.encode_func(callback, register=True) else: callbackwrap = TimeOutGuiCall(self.gui_proxy, timeout, callback, args=('timeout', 5, None)) call_back_id = self.gui_proxy.encode_func(callbackwrap.call, register=True) else: call_back_id = None if mode in ['input', 'interprete', 'func', 'exit']: self.stdin_queue.put((mode, args, call_back_id)) if self.is_current_thread(): self.mainshell.interpreters[self.thread_id].execute() elif mode in ['flow', 'eval', 'flow_func']: self.flow_queue.put((mode, args, call_back_id)) if self.is_current_thread(): self.mainshell.interpreters[self.thread_id].control() if callback is None and wait: #This is an high risk for a deathlock #Waiting here will block the eventloop #If still prior callbacks are queued, the eventloop can not respond to it -> deathlock mode, error_code, result = self.return_queue.get(timeout=5) assert error_code == 0 return result def register(self, mainshell): #mainshell.tasks[(self.process_id, self.thread_id)] = self pass def flow(self, *args): self.send_func_and_call("flow", args) def print_trace(self): self.flow("trace") def print_locals(self): self.flow("locals") def sync_break(self): self.flow("sync_break") def async_break(self): self.flow("KeyboardInterrupt") def system_exit(self): self.flow("system_exit") def set_tracing(self, enable=True): self.flow("set_tracing", enable) def set_timeit(self, enable=True): self.flow("set_timeit", enable) def enable_profiling(self): self.flow("enable_profiling") def kill(self): import psutil parent = psutil.Process(self.process_id) for child in parent.children(recursive=True): child.kill() parent.kill() tasks = list(PROCESSES[self.process_id].values()) for task in tasks: task.console.close_panel() def flow_alive(self, callback, timeout=5): self.send_func_and_call("flow", ("heartbeat",), callback, timeout=timeout) def process_ready(self, *args): #Gui will freeze until something comes back from the return_queue anstype, error_code, (pid, tname, tid) = args self.process_id = pid self.thread_name = tname self.thread_id = tid if not self.process_id in PROCESSES: PROCESSES[self.process_id] = dict() PROCESSES[self.process_id][self.thread_id] = self #This can maybe come to soon, before the console was created if hasattr(self, 'console'): self.console.refresh_pid_tid() # Panel id is communicated on creation # self.send_func_and_call("console id", (self.console.panid,)) def unregister(self): PROCESSES[self.process_id].pop(self.thread_id) if len(PROCESSES[self.process_id]) == 0: PROCESSES.pop(self.process_id) def set_flusher(self, func): self.gui_proxy.set_func_hook(-1, func) def wait_process_ready(self, timeout=3): from qtpy import QtWidgets qapp = QtWidgets.QApplication.instance() for i in range(timeout * 10): qapp.processEvents() if self.thread_name != 'invalid': break time.sleep(0.1) class ThreadTask(TaskBase): flow_queues = dict() def __init__(self, mainshell, new_thread=True): self.new_thread = new_thread if new_thread: super().__init__('thread') else: super().__init__('main') self.mainshell = mainshell self.cqs = CommQueues(Queue) self.gui_proxy = GuiProxy(mainshell._qapp, self.cqs.gui_call_queue, #None self.cqs.gui_return_queue, #None self.process_ready) def start(self): if self.new_thread: self.mainshell.new_interactive_thread(self.cqs, self.gui_proxy, console_id=self.panid) else: self.gui_proxy.block = False self.thread = threading.currentThread() self.command_loop(self.cqs, self.gui_proxy, self.panid) def finish(self, close=False): if self.thread_name == 'MainThread': print("You can't finish the meain thread") return super().finish(close) def command_loop(self, cqs, gui_proxy=None, console_id=None): thread_id = threading.get_ident() ThreadTask.flow_queues[thread_id] = cqs.flow_queue QueueInterpreter(self.mainshell, cqs, gui_proxy, console_id) class ProcessTask(TaskBase): def __init__(self, mainshell, cqs=None): super().__init__('child') if cqs is None: self.cqs = CommQueues(multiprocessing.Queue, process=True) self.start_child = True else: self.cqs = cqs self.start_child = False self.gui_proxy = GuiProxy(mainshell._qapp, self.cqs.gui_call_queue, self.cqs.gui_return_queue, self.process_ready) def start(self): #no existing queue from an existing master process #Start a new child process if self.start_child: self.process = Process(target=ProcessTask.start_child_process, args=(self.cqs, self.panid), daemon=True) self.process.start() self.flusher = None @staticmethod def start_child_process(cqs, panid=None): try: shell = Shell() refer_shell_instance(shell) shell.start_in_this_thread(cqs, panid) finally: import psutil sys.__stdout__.write(f'End of start_child_processs\n') sys.__stdout__.flush() proc = psutil.Process() proc.kill() class ProcessThreadTask(TaskBase): def __init__(self, mainshell, master_process_task, queue_type='pipe'): super().__init__('child-thread') self.master_process_task = master_process_task if queue_type == 'pipe': self.cqs = CommQueues(NonDuplexQueue, process=True) elif queue_type == 'zmq': self.cqs = ZmqQueues() self.cqs.setup_as_server() self.gui_proxy = GuiProxy(mainshell._qapp, self.cqs.gui_call_queue, self.cqs.gui_return_queue, self.process_ready) def start(self): #Problems if master_process_task didn't not yet finished prior command #For example master_process_task is still queues flushes of a big print loop #The master_process_task.return_queue still contains the prior return result self.master_process_task.call_func(Shell.new_interactive_thread, args=(self.cqs, None, True, self.panid), queue='flow')
thocoo/gamma-desk
gdesk/ezdock/docks.py
<reponame>thocoo/gamma-desk<gh_stars>0 class DockBase(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_container(self): candidate = self #TO DO, I can not import DockContainer here because it would cause circular imports #while not isinstance(candidate, DockContainer) .... #So this is the alternative while not (candidate.__class__.__name__ == 'DockContainer' or candidate is None): candidate = candidate.parent() return candidate def get_dock_box(self): candidate = self while not (candidate.__class__.__name__ in ['DockVBox', 'DockHBox'] or candidate is None): candidate = candidate.parent() return candidate def detach(self, to_new_window=True): container = self.get_container() geo = self.geometry() return container.detach('layout', self.category, self.title, to_new_window, geo.width(), geo.height())
thocoo/gamma-desk
gdesk/panels/imgview/profile.py
import math import numpy as np from qtpy import QtCore, QtGui, QtWidgets from ...graphics.plotview import PlotView from ...graphics.rulers import TickedRuler, Axis from ...graphics.functions import arrayToQPath from ...graphics.items import createCurve from ...utils.ticks import tickValues class ProfileGraphicView(PlotView): def __init__(self, parent=None): super().__init__(parent) class ProfilerPanel(QtWidgets.QWidget): def __init__(self, parent, direction, imviewer): super().__init__(parent=parent) self.imagePanel = imviewer self.scene = QtWidgets.QGraphicsScene() self.view = ProfileGraphicView(self) self.view.setScene(self.scene) vbox = QtWidgets.QVBoxLayout(self) vbox.setContentsMargins(0,0,0,0) vbox.addWidget(self.view) self.setLayout(vbox) if direction == 'x': self.direction = 0 self.view.fixScaleX = True self.view.scale[1] = -self.view.scale[1] self.view.updateMatrix() self.setMinimumHeight(20) else: self.direction = 90 self.view.fixScaleY = True self.view.scale[0] = -self.view.scale[0] self.view.updateMatrix() self.setMinimumWidth(20) self.view.matrixUpdated.connect(self.redrawSlices) self.view.matrixUpdated.connect(self.repositionRuler) self.view.matrixUpdated.connect(self.repositionYAxis) self.view.doubleClicked.connect(self.zoomFit) self.meanProfileCurve = None self.roiProfileCurve = None self.pixProfileCurve = None self.grid = [] self.ruler = None self.yAxis = None def zoomFull(self): top = bottom = left = right = None for curve in [self.pixProfileCurve, self.roiProfileCurve, self.meanProfileCurve]: if curve is None: continue r = curve.boundingRect() top = r.top() if top is None else min(r.top(), top) bottom = r.bottom() if bottom is None else max(r.bottom(), bottom) left = r.left() if left is None else min(r.left(), left) right = r.right()if right is None else max(r.right(), right) if top is None: return height = bottom - top width = right - left if self.direction == 0: if height == 0: self.view.setYCenter(top) else: scale = -(self.height() - 20) / max(height, 1e-9) self.view.setYPosScale(bottom, scale) elif self.direction == 90: if width == 0: self.view.setXCenter(left) else: scale = -(self.width() - 20)/ max(width, 1e-9) self.view.setXPosScale(right, scale) def zoomFit(self): if self.meanProfileCurve is None: self.zoomFull() return xvec = self.meanProfileCurve.xvector yvec = self.meanProfileCurve.yvector if self.direction == 0: x0, x1 = self.view.getXLimits() x0 = max(round(x0), 0) x1 = min(round(x1), len(xvec)) y0, y1 = yvec[x0:x1].min(), yvec[x0:x1].max() if y0 != y1: self.view.setYLimits(y0, y1, 20) else: self.view.setYLimits(y0-0.5, y1+0.5, 20) elif self.direction == 90: y0, y1 = self.view.getYLimits() y0 = max(round(y0), 0) y1 = min(round(y1), len(yvec)) x0, x1 = xvec[y0:y1].min(), xvec[y0:y1].max() if x0 != x1: self.view.setXLimits(x1, x0, 20) else: self.view.setXLimits(x1+0.5, x0-0.5, 20) def refresh(self): self.removeAllItems() #self.createRuler() #self.createYAxis() #self.createGrid() if self.meanProfileCurve is not None: self.scene.addItem(self.meanProfileCurve) if self.pixProfileCurve is not None: self.scene.addItem(self.pixProfileCurve) self.view.refresh() self.redrawSlices() self.repositionRuler() self.repositionYAxis() def removeAllItems(self): for i in self.scene.items(): #only need to remove top level items if i.parentItem() == None: self.scene.removeItem(i) self.meanProfileCurve = None self.roiProfileCurve = None self.pixProfileCurve = None self.grid = [] self.ruler = None self.yAxis = None def createYAxis(self): if not self.yAxisEnabled: self.yAxis = None return 0 if self.direction == 0: scaleY = -self.view.scale[1] sceneTopLeft = self.view.mapToScene(0,0) sceneBotRight = self.view.mapToScene(self.width()-1, self.height()-1) self.stopY = sceneTopLeft.y() self.startY = sceneBotRight.y() self.thicksY = tickValues(self.startY, self.stopY, scaleY) self.yAxis = Axis(0, self.startY, self.stopY, self.thicksY) elif self.direction == 90: scaleY = -self.view.scale[0] sceneTopLeft = self.view.mapToScene(0,0) sceneBotRight = self.view.mapToScene(self.width()-1, self.height()-1) self.stopY = sceneTopLeft.x() self.startY = sceneBotRight.x() self.thicksY = tickValues(self.startY, self.stopY, scaleY) self.yAxis = Axis(90, self.startY, self.stopY, self.thicksY) #self.yAxis.setZValue(-1) self.yAxis.setZValue(0.9) self.scene.addItem(self.yAxis) def createRuler(self): #self.ruler = Ruler(self.direction, self.startX, self.stopX, self.stepX) if self.direction == 0: scaleX = self.view.scale[0] if self.imagePanel.dispOffsetX < 0: self.startX = 0 self.stopX = self.imagePanel.dispOffsetX + self.width() / scaleX else: self.startX = self.imagePanel.dispOffsetX self.stopX = math.ceil(self.startX + self.width() / scaleX) self.stopX = min(self.imagePanel.vd.width, self.stopX) self.ruler = TickedRuler(0, self.startX, self.stopX, scaleX, noDecimals=True) elif self.direction == 90: scaleX = self.view.scale[1] if self.imagePanel.dispOffsetY < 0: self.startX = 0 self.stopX = self.imagePanel.dispOffsetY + self.height() / scaleX else: self.startX = self.imagePanel.dispOffsetY self.stopX = math.ceil(self.startX + self.height() / scaleX) self.stopX = min(self.imagePanel.vd.height, self.stopX) self.ruler = TickedRuler(90, self.startX, self.stopX, scaleX, noDecimals=True) self.ruler.setZValue(1) self.scene.addItem(self.ruler) def repositionRuler(self): tr = self.view.mapToScene(self.width()-20, self.height()-20) if self.direction == 0: self.ruler.setY(tr.y()) elif self.direction == 90: self.ruler.setX(tr.x()) def repositionYAxis(self): if self.yAxis == None: return 0 tr = self.view.mapToScene(50, 10) if self.direction == 0: self.yAxis.setX(tr.x()) elif self.direction == 90: self.yAxis.setY(tr.y()) def zoomToImage(self): scale = self.imagePanel.zoomValue if self.direction == 0: x = self.imagePanel.dispOffsetX self.view.setXPosScale(x, scale) elif self.direction == 90: y = self.imagePanel.dispOffsetY self.view.setYPosScale(y, scale) def addPlot(self, x, y, color=None, z=0): curve = self.createCurve(x, y, color, z) self.curves.append(curve) def drawMeanProfile(self, x, y): if self.meanProfileCurve is not None: self.scene.removeItem(self.meanProfileCurve) self.meanProfileCurve = self.createCurve(x, y, color=QtCore.Qt.blue, z=0.5) self.scene.addItem(self.meanProfileCurve) def drawRoiProfile(self, x, y): if self.roiProfileCurve is not None: self.scene.removeItem(self.roiProfileCurve) self.roiProfileCurve = self.createCurve(x, y, color=QtCore.Qt.darkGreen, z=0.25) self.scene.addItem(self.roiProfileCurve) def drawPixelProfile(self, x, y): self.removePixelProfile() self.pixProfileCurve = self.createCurve(x, y, color=QtCore.Qt.red, z=0) self.scene.addItem(self.pixProfileCurve) def removeRoiProfile(self): if self.roiProfileCurve is not None: self.scene.removeItem(self.roiProfileCurve) self.roiProfileCurve = None def removePixelProfile(self): if self.pixProfileCurve is not None: self.scene.removeItem(self.pixProfileCurve) self.pixProfileCurve = None def removeMeanProfile(self): if self.meanProfileCurve is not None: self.scene.removeItem(self.meanProfileCurve) self.meanProfileCurve = None def createCurve(self, x, y, color=None, z=0): if color == None: color = QtCore.Qt.blue if isinstance(x, np.ndarray) and isinstance(y, np.ndarray): if self.direction == 0: curve = createCurve(x, y, color, z, None, zero_ends=False) elif self.direction == 90: curve = createCurve(y, x, color, z, None, zero_ends=False) else: #first create a Path path = QtGui.QPainterPath() if self.direction == 0: path.moveTo(x[0], y[0]) for i in range(1, len(y)): path.lineTo(x[i], y[i]) elif self.direction == 90: path.moveTo(y[0], x[0]) for i in range(1, len(y)): path.lineTo(y[i], x[i]) #transform the Path to a PathItem curve = QtWidgets.QGraphicsPathItem(path) if z != 0: curve.setZValue(z) curve.setPen(pen) return curve def clear(self): self.meanProfileCurve = None self.roiProfileCurve = None self.pixProfileCurve = None def showOnlyRuler(self): if self.direction == 0: self.setFixedHeight(20) elif self.direction == 90: self.setFixedWidth(20) self.gridEnabled = False self.yAxisEnabled = False self.plotsEnabled = False self.refresh() def showAll(self): self.gridEnabled = True self.yAxisEnabled = True self.plotsEnabled = True self.refresh() def removelast(self): if len(self.curves) > 0: lastCurve = self.curves[-1] if lastCurve in self.scene.items(): self.scene.removeItem(lastCurve) self.curves.pop() def createGrid(self): self.grid = [] if not self.gridEnabled: return 0 pens = [] pens.append(QtGui.QPen(QtGui.QColor(159,159,159), 0, QtCore.Qt.SolidLine)) pens.append(QtGui.QPen(QtGui.QColor(191,191,191), 0, QtCore.Qt.DashLine)) pens.append(QtGui.QPen(QtGui.QColor(223,223,223), 0, QtCore.Qt.DotLine)) pens.append(QtGui.QPen(QtGui.QColor(159,159,159), 0, QtCore.Qt.SolidLine)) pens.append(QtGui.QPen(QtGui.QColor(191,191,191), 0, QtCore.Qt.DashLine)) pens.append(QtGui.QPen(QtGui.QColor(223,223,223), 0, QtCore.Qt.DotLine)) paths = [] for thicklevel in range(3): paths.append(QtGui.QPainterPath()) for i in self.ruler.thicks[thicklevel][1]: if self.direction == 0: paths[-1].moveTo(i, self.startY) paths[-1].lineTo(i, self.stopY) else: paths[-1].moveTo(self.startY, i) paths[-1].lineTo(self.stopY, i) for thicklevel in range(3): paths.append(QtGui.QPainterPath()) for i in self.thicksY[thicklevel][1]: if self.direction == 0: paths[-1].moveTo(self.startX, i) paths[-1].lineTo(self.stopX, i) else: paths[-1].moveTo(i, self.startX) paths[-1].lineTo(i, self.stopX) for i in range(len(paths)): self.grid.append(QtWidgets.QGraphicsPathItem(paths[i])) self.grid[-1].setPen(pens[i]) self.grid[-1].setZValue(-2) self.scene.addItem(self.grid[-1]) def redrawSlices(self): if not self.ruler is None: self.scene.removeItem(self.ruler) self.createRuler() if not self.yAxis is None: self.scene.removeItem(self.yAxis) self.createYAxis() for items in self.grid: self.scene.removeItem(items) self.createGrid() def resizeEvent(self, ev): self.redrawSlices() self.repositionRuler() self.repositionYAxis()
thocoo/gamma-desk
test/setup/test_gdesk.py
<filename>test/setup/test_gdesk.py from gdesk import gui, config, __version__ gui.qapp.panels.ezm.set_perspective(config['layout']['image, levels & console']) panid = 1 panel = gui.qapp.panels['console'][panid] panel.stdio.stdOutputPanel.addText('This is the start-up banner, before thread is started\n') test_code_1 = '''\ import unittest from gdesk import test runner = unittest.TextTestRunner() runner.run(test.suite()) ''' gui.console.execute_code(test_code_1, panid)
thocoo/gamma-desk
gdesk/gcore/threadcom.py
import sys import threading import logging from queue import Queue from qtpy.QtCore import QObject, QMetaObject, Slot, Qt from qtpy.QtWidgets import QWidget class ReturnLock: """ Lock and return value object used to pass the return value on SignalCalls. """ def __init__(self): self.lock = threading.Lock() self.lock.acquire() def waitOnReturn(self): self.lock.acquire() return self.value def releaseReturn(self, value): self.value = value self.lock.release() def locked(self): return self.lock.locked() class HandOver(QObject): def __init__(self, parent): super().__init__(parent=parent) self.signal_call_queue = Queue() def send(self, block=True, func=None, *args, **kwargs): """ :param block: wait on the func to return :param func: the reference to the function to be called by the eventloop :param ``*args``: unnamed arguments for the function :param ``**kwargs``: key word arguments for the function """ returnlock = ReturnLock() self.signal_call_queue.put((returnlock, func, args, kwargs)) QMetaObject.invokeMethod(self, "receive", Qt.QueuedConnection) if block: returnlock.waitOnReturn() return returnlock.value else: return returnlock @Slot() def receive(self): """ Receive returnlock, func, args, kwargs from signal_call_queue """ (returnlock, func, args, kwargs) = self.signal_call_queue.get() returnvalue = None try: returnvalue = func(*args, **kwargs) except: logging.error(f'Error during gui call {func} {args} {kwargs}') raise finally: returnlock.releaseReturn(returnvalue)
thocoo/gamma-desk
gdesk/panels/dialog/proxy.py
<gh_stars>0 import pathlib from functools import wraps from ... import config if config.get('qapp', False): #Do not import anything from Qt if not needed !!! #Causes crach in Canvas ! from qtpy import QtWidgets from ...dialogs import formlayout from ...dialogs import base as dialogs from ...core.gui_proxy import gui, GuiProxyBase, StaticGuiCall class DialogGuiProxy(GuiProxyBase): category = 'values' def __init__(self): pass def attach(self, gui): gui.dialog = self gui.question = self.question gui.msgbox = self.msgbox gui.inputdlg = self.inputdlg gui.getstring = self.getstring gui.getfile = self.getfile gui.getfiles = self.getfiles gui.getfilename = self.getfilename gui.getfilenames = self.getfilenames gui.getpath = self.getpath gui.getdir = self.getdir gui.putfile = self.putfile gui.putfilename = self.putfilename gui.filterlist = self.filterlist gui.fedit = self.fedit @StaticGuiCall def msgbox(message, title = '', icon = 'none'): """ Creates a message box :param message: the message :type message: str :param title: the title :type title: str :param icon: 'none', 'help, 'info', 'warn', 'error' :type icon: str """ dialogs.messageBox(message, title, icon) @StaticGuiCall def question(question='Do you press the No Button?', title='Question'): """Yes/No question""" return dialogs.questionBox(question, title) @StaticGuiCall def inputdlg(prompt='', default='', title='Input', masked=False, timeout=None): """ Open a input dialog. The user can enter a string. :param str prompt: The prompt :param str default: The default string :param str title: The title of the dialog :param bool masked: Mask the string as stars `******` :param timeout: After time, continue the flow. Expressed in miliseconds :type timeout: None or float :returns: The user string :rtype: str Timeout can not be combined with mask. """ if isinstance(prompt, str): if masked : return dialogs.getString(prompt, default, title, 'Password') else: return dialogs.getStringTimeout(prompt, default, title, timeout=timeout) else: return dialogs.getMultiString(prompt, default, title, timeout=timeout) @StaticGuiCall def getstring(prompt='', default='', title='Input', echo='Normal', timeout=None): """\ Show a popup-window to ask the user some textual input. Makes use of QtWidgets.QInputDialog.getText; see https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText :param str prompt: The explanation that is visible just above the text input field. :param str default: The text that is already present in the editable input field. :param str title: The name of the pop-window (shown in its title bar). :param str echo: 'Normal' for normal text entry; 'Password' for password entry. See http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum """ if timeout is None: return dialogs.getString(prompt, default, title, echo=echo) else: return dialogs.getStringTimeout(prompt, default, title, echo=echo, timeout=timeout) @StaticGuiCall def getfile(filter='*.*', title='open', file=None): """ Show a file dialog to open a file. Return a string tuple of file path and choosen filter :param str filter: a filter of the form \\*.tif :param str title: the window title :param str file: default file path :return: The file path and choosen filter :rtype: tuple(str, str) """ return dialogs.getFile(filter, title, file) @staticmethod def getfilename(filter='*.*', title='open', file=None): return DialogGuiProxy.getfile(filter, title, file)[0] @StaticGuiCall def getfiles(filter='*.*', title='open', file=None): """ Multi file selection version of getfile """ return dialogs.getFiles(filter, title, file) @staticmethod def getfilenames(filter='*.*', title='open', file=None): """ Multi file selection version of getfilename """ return DialogGuiProxy.getfiles(filter, title, file)[0] @StaticGuiCall def selectfile(filter='*.*', title='Select', default_path=None): selected_files = dialogs.selectFiles(filter, title, default_path) if len(selected_files) == 0: return None return selected_files[0] @staticmethod def getpath(startpath=None, title='select a Directory'): """ Show a directory dialog to choose a dir :return: The directory :rtype: pathlib.Path """ return pathlib.Path(DialogGuiProxy.getdir(startpath, title)) @StaticGuiCall def getdir(startpath=None, title='select a Directory'): """ Show a directory dialog to choose a dir :returns: The directory :rtype: str """ return dialogs.getMap(startpath, title) @StaticGuiCall def putfile(filter='*.*', title='save', file=None, defaultfilter=""): """ Open a save file dialog and return a file name selected by the user. The file does not have to exist. :param str filter: File type filter, filters are seperated by ``;;`` e.g.: \\*.tif, Image (\\*.tif \\*.png), Text(\\*.txt);;Image (\\*.tif \\*.png) :param str title: Title of the dialog :param file: Propose of file name :type file: str or None :param str defaultfilter: Default filter to use :returns: The filename and used filter :rtype: str, str Example >>> filename, filter = gui.putfile('Text(*.txt);;Image (*.tif *.png)', "Give it a filename", r"C:\\temp\\default.tif", "Image (*.tif *.png)") """ return dialogs.putFile(filter, title, file, defaultfilter) @staticmethod def putfilename(filter='*.*', title='save', file=None, defaultfilter=""): """ Open a save file dialog and return a file name selected by the user. The file does not have to exist. :param str filter: File type filter, filters are seperated by ``;;`` e.g.: \\*.tif, Image (\\*.tif \\*.png), Text(\\*.txt);;Image (\\*.tif \\*.png) :param str title: Title of the dialog :param file: Propose of file name :type file: str or None :param str defaultfilter: Default filter to use :returns: The filename :rtype: str Example >>> filename = gui.putfile('Text(*.txt);;Image (*.tif *.png)', "Give it a filename", r"C:\\temp\\default.tif", "Image (*.tif *.png)") """ return DialogGuiProxy.putfile(filter, title, file, defaultfilter)[0] @StaticGuiCall def filterlist(items=None, selection=None, filter=None): """ Open a items filter dialog. The user have to select items from it. selection = None : select nothing = one_item : select the one item = []: use checkable items = [str1, str2] : check items on string value filter = None: check nothing = False: check everything = ``\w*01\w*``: use re to match string """ #import ghawk2.dialogs.filterlist as filterlist if items is None: items = list() if isinstance(selection, list): multiple = True else: multiple = False fl = dialogs.filterlist.FilterList(items, multiple) if not multiple: if not selection is None: fl.selectItem(selection) else: if filter is False: fl.checkAll(True) elif isinstance(filter, str): fl.checkItemsRe(filter) elif isinstance(selection, list): fl.checkItems(selection) dialog_code = fl.exec_() if dialog_code == QtWidgets.QDialog.DialogCode.Rejected: return None if multiple: return fl.checkedItems() else: return fl.selectedItem() # TO DO: formlayout.fedit doc string can not be available if the process # is not allowed to load QT (like Canvas GUI) @StaticGuiCall # @wraps(formlayout.fedit) def fedit(*args, **kwargs): """ Create form dialog and return result (if Cancel button is pressed, return None) :param tuple data: datalist, datagroup (see below) :param str title: form title :param str comment: header comment :param QIcon icon: dialog box icon :param QWidget parent: parent widget :param str ok: customized ok button label :param str cancel: customized cancel button label :param tuple apply: (label, function) customized button label and callback :param function apply: function taking two arguments (result, widgets) :param str result: result serialization ('list', 'dict', 'OrderedDict', 'JSON' or 'XML') :param str outfile: write result to the file outfile.[py|json|xml] :param str type: layout type ('form' or 'questions') :param bool scrollbar: vertical scrollbar :param str background_color: color of the background :param str widget_color: color of the widgets :return: Serialized result (data type depends on `result` parameter) datalist: list/tuple of (field_name, field_value) datagroup: list/tuple of (datalist *or* datagroup, title, comment) Tips: * one field for each member of a datalist * one tab for each member of a top-level datagroup * one page (of a multipage widget, each page can be selected with a combo box) for each member of a datagroup inside a datagroup Supported types for field_value: - int, float, str, unicode, bool - colors: in Qt-compatible text form, i.e. in hex format or name (red,...) (automatically detected from a string) - list/tuple: * the first element will be the selected index (or value) * the other elements can be couples (key, value) or only values """ return formlayout.fedit(*args, **kwargs)
thocoo/gamma-desk
gdesk/dialogs/filedialog.py
from qtpy import QtCore, QtGui, QtWidgets class FileDialog(QtWidgets.QDialog): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QtWidgets.QVBoxLayout() self.setLayout(vbox) hbox = QtWidgets.QHBoxLayout() vbox.addLayout(hbox) self.treeView = QtWidgets.QTreeView(self) hbox.addWidget(self.treeView) #self.treeView.setGeometry(0,0, 600, 800) self.dirModel = QtWidgets.QFileSystemModel() self.path = "C:\\" self.dirModel.setRootPath(self.path) self.dirModel.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Hidden) self.treeView.setModel(self.dirModel) #self.treeView.setRootIndex(self.dirModel.index(self.path)) #self.treeView.expandAll() self.treeView.clicked.connect(self.on_treeView_clicked) #self.listView = QtWidgets.QListView(self) #self.listView = QtWidgets.QTreeView(self) self.listView = QtWidgets.QTableView(self) hbox.addWidget(self.listView) self.fileModel = QtWidgets.QFileSystemModel() #self.fileModel.setFilter(QtCore.QDir.Files | QtCore.QDir.Dirs | QtCore.QDir.Hidden) self.fileModel.setFilter(QtCore.QDir.Files | QtCore.QDir.Hidden) self.listView.setModel(self.fileModel) #self.setGeometry(300, 300, 600, 800) self.setWindowTitle('Select File') def on_treeView_clicked(self, index): # // TreeView clicked # // 1. We need to extract path # // 2. Set that path into our ListView # Get the full path of the item that's user clicked on path = self.dirModel.fileInfo(index).absoluteFilePath() index = self.fileModel.setRootPath(path) self.listView.setRootIndex(index) def ok(self): self.updatePaths() self.done(QtWidgets.QDialog.DialogCode.Accepted) def cancel(self): self.done(QtWidgets.QDialog.DialogCode.Rejected)
thocoo/gamma-desk
gdesk/utils/ansi_code_processor.py
<gh_stars>0 """ Utilities for processing ANSI escape codes and special ASCII characters. """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys # Standard library imports from collections import namedtuple import re # System library imports from qtpy import QtGui #----------------------------------------------------------------------------- # Constants and datatypes #----------------------------------------------------------------------------- # An action for erase requests (ED and EL commands). EraseAction = namedtuple('EraseAction', ['action', 'area', 'erase_to']) # An action for cursor move requests (CUU, CUD, CUF, CUB, CNL, CPL, CHA, CUP, # and HVP commands). # FIXME: Not implemented in AnsiCodeProcessor. MoveAction = namedtuple('MoveAction', ['action', 'dir', 'unit', 'count']) # An action for scroll requests (SU and ST) and form feeds. ScrollAction = namedtuple('ScrollAction', ['action', 'dir', 'unit', 'count']) # An action for the carriage return character CarriageReturnAction = namedtuple('CarriageReturnAction', ['action']) # An action for the \n character NewLineAction = namedtuple('NewLineAction', ['action']) # An action for the beep character BeepAction = namedtuple('BeepAction', ['action']) # An action for backspace BackSpaceAction = namedtuple('BackSpaceAction', ['action']) # An action for backspace SetTitleAction = namedtuple('SetTitleAction', ['action', 'title']) # Regular expressions. CSI_COMMANDS = 'ABCDEFGHJKSTfmnsu' CSI_DOS = 'X' CSI_SUBPATTERN = '\[(.*?)([%s])' % (CSI_COMMANDS + CSI_DOS) OSC_SUBPATTERN = '\](.*?)[\x07\x1b]' ANSI_PATTERN = ('\x01?\x1b(%s|%s)\x02?' % \ (CSI_SUBPATTERN, OSC_SUBPATTERN)) ANSI_OR_SPECIAL_PATTERN = re.compile('(\a|\b|\r(?!\n)|\r?\n)|(?:%s)' % ANSI_PATTERN) SPECIAL_PATTERN = re.compile('([\f])') #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class AnsiCodeProcessor: """ Translates special ASCII characters and ANSI escape codes into readable attributes. It also supports a few non-standard, xterm-specific codes. """ # Whether to increase intensity or set boldness for SGR code 1. # (Different terminals handle this in different ways.) bold_text_enabled = False # We provide an empty default color map because subclasses will likely want # to use a custom color format. default_color_map = {} #--------------------------------------------------------------------------- # AnsiCodeProcessor interface #--------------------------------------------------------------------------- def __init__(self): self.actions = [] self.color_map = self.default_color_map.copy() self.reset_sgr() def reset_sgr(self): """ Reset graphics attributs to their default values. """ self.intensity = 0 self.italic = False self.bold = False self.underline = False self.foreground_color = None self.background_color = None def split_string(self, string): """ Yields substrings for which the same escape code applies. """ self.actions = [] start = 0 # strings ending with \r are assumed to be ending in \r\n since # \n is appended to output strings automatically. Accounting # for that, here. last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None string = string[:-1] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN.finditer(string): raw = string[start:match.start()] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring self.actions = [] start = match.end() groups = [x for x in match.groups() if x is not None] g0 = groups[0] if g0 == '\a': self.actions.append(BeepAction('beep')) yield None self.actions = [] elif g0 == '\r': self.actions.append(CarriageReturnAction('carriage-return')) yield None self.actions = [] elif g0 == '\b': self.actions.append(BackSpaceAction('backspace')) yield None self.actions = [] elif g0 == '\n' or g0 == '\r\n': self.actions.append(NewLineAction('newline')) yield g0 self.actions = [] else: params = [ param for param in groups[1].split(';') if param ] if g0.startswith('['): # Case 1: CSI code. try: params = list(map(int, params)) except ValueError: # Silently discard badly formed codes. pass else: self.set_csi_code(groups[2], params) elif g0.startswith(']'): # Case 2: OSC code. self.set_osc_code(params) raw = string[start:] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring if last_char is not None: self.actions.append(NewLineAction('newline')) yield last_char def set_csi_code(self, command, params=[]): """ Set attributes based on CSI (Control Sequence Introducer) code. Parameters ---------- command : str The code identifier, i.e. the final character in the sequence. params : sequence of integers, optional The parameter codes for the command. """ if command == 'm': # SGR - Select Graphic Rendition if params: self.set_sgr_code(params) else: self.set_sgr_code([0]) elif (command == 'J' or # ED - Erase Data command == 'K'): # EL - Erase in Line code = params[0] if params else 0 if 0 <= code <= 2: area = 'screen' if command == 'J' else 'line' if code == 0: erase_to = 'end' elif code == 1: erase_to = 'start' elif code == 2: erase_to = 'all' self.actions.append(EraseAction('erase', area, erase_to)) elif (command == 'S' or # SU - Scroll Up command == 'T'): # SD - Scroll Down dir = 'up' if command == 'S' else 'down' count = params[0] if params else 1 self.actions.append(ScrollAction('scroll', dir, 'line', count)) elif command == 'X': #from the Windows pty #https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-modification #Erase <n> characters from the current cursor position by overwriting them with a space character. print(f'CSI cmd: {command}, params: {params}') def set_osc_code(self, params): """ Set attributes based on OSC (Operating System Command) parameters. Parameters ---------- params : sequence of str The parameters for the command. """ try: command = int(params.pop(0)) except (IndexError, ValueError): return if command == 0: print(f'OS cmd: {command}, params: {params}') self.actions.append(SetTitleAction('set-title', params[0])) elif command == 4: # xterm-specific: set color number to color spec. try: color = int(params.pop(0)) spec = params.pop(0) self.color_map[color] = self._parse_xterm_color_spec(spec) except (IndexError, ValueError): pass def set_sgr_code(self, params): """ Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands requires multiple elements. """ # Always consume the first parameter. if not params: return code = params.pop(0) if code == 0: self.reset_sgr() elif code == 1: if self.bold_text_enabled: self.bold = True else: self.intensity = 1 elif code == 2: self.intensity = 0 elif code == 3: self.italic = True elif code == 4: self.underline = True elif code == 22: self.intensity = 0 self.bold = False elif code == 23: self.italic = False elif code == 24: self.underline = False elif code >= 30 and code <= 37: self.foreground_color = code - 30 elif code == 38 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.foreground_color = params.pop(0) elif code == 39: self.foreground_color = None elif code >= 40 and code <= 47: self.background_color = code - 40 elif code == 48 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.background_color = params.pop(0) elif code == 49: self.background_color = None # Recurse with unconsumed parameters. self.set_sgr_code(params) #--------------------------------------------------------------------------- # Protected interface #--------------------------------------------------------------------------- def _parse_xterm_color_spec(self, spec): if spec.startswith('rgb:'): return tuple([int(x, 16) for x in spec[4:].split('/')]) elif spec.startswith('rgbi:'): return tuple([int(float(x) * 255) for x in spec[5:].split('/')]) elif spec == '?': raise ValueError('Unsupported xterm color spec') return spec def _replace_special(self, match): special = match.group(1) if special == '\f': self.actions.append(ScrollAction('scroll', 'down', 'page', 1)) return '' class QtAnsiCodeProcessor(AnsiCodeProcessor): """ Translates ANSI escape codes into QTextCharFormats. """ color_plot_demo = '''for i in range(32): s = '' for j in range(8): n = j + i * 8 s += "\033[1m %3d: \033[0m \033[48;5;%dm \033[0m " % (n,n) print(s)''' xterm256_colors = { 0 : (0x00, 0x00, 0x00), 1 : (0x80, 0x00, 0x00), 2 : (0x00, 0x80, 0x00), 3 : (0x80, 0x80, 0x00), 4 : (0x00, 0x00, 0x80), 5 : (0x80, 0x00, 0x80), 6 : (0x00, 0x80, 0x80), 7 : (0xc0, 0xc0, 0xc0), 8 : (0x80, 0x80, 0x80), 9 : (0xff, 0x00, 0x00), 10 : (0x00, 0xff, 0x00), 11 : (0xff, 0xff, 0x00), 12 : (0x00, 0x00, 0xff), 13 : (0xff, 0x00, 0xff), 14 : (0x00, 0xff, 0xff), 15 : (0xff, 0xff, 0xff), 16 : (0x00, 0x00, 0x00), 17 : (0x00, 0x00, 0x5f), 18 : (0x00, 0x00, 0x87), 19 : (0x00, 0x00, 0xaf), 20 : (0x00, 0x00, 0xd7), 21 : (0x00, 0x00, 0xff), 22 : (0x00, 0x5f, 0x00), 23 : (0x00, 0x5f, 0x5f), 24 : (0x00, 0x5f, 0x87), 25 : (0x00, 0x5f, 0xaf), 26 : (0x00, 0x5f, 0xd7), 27 : (0x00, 0x5f, 0xff), 28 : (0x00, 0x87, 0x00), 29 : (0x00, 0x87, 0x5f), 30 : (0x00, 0x87, 0x87), 31 : (0x00, 0x87, 0xaf), 32 : (0x00, 0x87, 0xd7), 33 : (0x00, 0x87, 0xff), 34 : (0x00, 0xaf, 0x00), 35 : (0x00, 0xaf, 0x5f), 36 : (0x00, 0xaf, 0x87), 37 : (0x00, 0xaf, 0xaf), 38 : (0x00, 0xaf, 0xd7), 39 : (0x00, 0xaf, 0xff), 40 : (0x00, 0xd7, 0x00), 41 : (0x00, 0xd7, 0x5f), 42 : (0x00, 0xd7, 0x87), 43 : (0x00, 0xd7, 0xaf), 44 : (0x00, 0xd7, 0xd7), 45 : (0x00, 0xd7, 0xff), 46 : (0x00, 0xff, 0x00), 47 : (0x00, 0xff, 0x5f), 48 : (0x00, 0xff, 0x87), 49 : (0x00, 0xff, 0xaf), 50 : (0x00, 0xff, 0xd7), 51 : (0x00, 0xff, 0xff), 52 : (0x5f, 0x00, 0x00), 53 : (0x5f, 0x00, 0x5f), 54 : (0x5f, 0x00, 0x87), 55 : (0x5f, 0x00, 0xaf), 56 : (0x5f, 0x00, 0xd7), 57 : (0x5f, 0x00, 0xff), 58 : (0x5f, 0x5f, 0x00), 59 : (0x5f, 0x5f, 0x5f), 60 : (0x5f, 0x5f, 0x87), 61 : (0x5f, 0x5f, 0xaf), 62 : (0x5f, 0x5f, 0xd7), 63 : (0x5f, 0x5f, 0xff), 64 : (0x5f, 0x87, 0x00), 65 : (0x5f, 0x87, 0x5f), 66 : (0x5f, 0x87, 0x87), 67 : (0x5f, 0x87, 0xaf), 68 : (0x5f, 0x87, 0xd7), 69 : (0x5f, 0x87, 0xff), 70 : (0x5f, 0xaf, 0x00), 71 : (0x5f, 0xaf, 0x5f), 72 : (0x5f, 0xaf, 0x87), 73 : (0x5f, 0xaf, 0xaf), 74 : (0x5f, 0xaf, 0xd7), 75 : (0x5f, 0xaf, 0xff), 76 : (0x5f, 0xd7, 0x00), 77 : (0x5f, 0xd7, 0x5f), 78 : (0x5f, 0xd7, 0x87), 79 : (0x5f, 0xd7, 0xaf), 80 : (0x5f, 0xd7, 0xd7), 81 : (0x5f, 0xd7, 0xff), 82 : (0x5f, 0xff, 0x00), 83 : (0x5f, 0xff, 0x5f), 84 : (0x5f, 0xff, 0x87), 85 : (0x5f, 0xff, 0xaf), 86 : (0x5f, 0xff, 0xd7), 87 : (0x5f, 0xff, 0xff), 88 : (0x87, 0x00, 0x00), 89 : (0x87, 0x00, 0x5f), 90 : (0x87, 0x00, 0x87), 91 : (0x87, 0x00, 0xaf), 92 : (0x87, 0x00, 0xd7), 93 : (0x87, 0x00, 0xff), 94 : (0x87, 0x5f, 0x00), 95 : (0x87, 0x5f, 0x5f), 96 : (0x87, 0x5f, 0x87), 97 : (0x87, 0x5f, 0xaf), 98 : (0x87, 0x5f, 0xd7), 99 : (0x87, 0x5f, 0xff), 100 : (0x87, 0x87, 0x00), 101 : (0x87, 0x87, 0x5f), 102 : (0x87, 0x87, 0x87), 103 : (0x87, 0x87, 0xaf), 104 : (0x87, 0x87, 0xd7), 105 : (0x87, 0x87, 0xff), 106 : (0x87, 0xaf, 0x00), 107 : (0x87, 0xaf, 0x5f), 108 : (0x87, 0xaf, 0x87), 109 : (0x87, 0xaf, 0xaf), 110 : (0x87, 0xaf, 0xd7), 111 : (0x87, 0xaf, 0xff), 112 : (0x87, 0xd7, 0x00), 113 : (0x87, 0xd7, 0x5f), 114 : (0x87, 0xd7, 0x87), 115 : (0x87, 0xd7, 0xaf), 116 : (0x87, 0xd7, 0xd7), 117 : (0x87, 0xd7, 0xff), 118 : (0x87, 0xff, 0x00), 119 : (0x87, 0xff, 0x5f), 120 : (0x87, 0xff, 0x87), 121 : (0x87, 0xff, 0xaf), 122 : (0x87, 0xff, 0xd7), 123 : (0x87, 0xff, 0xff), 124 : (0xaf, 0x00, 0x00), 125 : (0xaf, 0x00, 0x5f), 126 : (0xaf, 0x00, 0x87), 127 : (0xaf, 0x00, 0xaf), 128 : (0xaf, 0x00, 0xd7), 129 : (0xaf, 0x00, 0xff), 130 : (0xaf, 0x5f, 0x00), 131 : (0xaf, 0x5f, 0x5f), 132 : (0xaf, 0x5f, 0x87), 133 : (0xaf, 0x5f, 0xaf), 134 : (0xaf, 0x5f, 0xd7), 135 : (0xaf, 0x5f, 0xff), 136 : (0xaf, 0x87, 0x00), 137 : (0xaf, 0x87, 0x5f), 138 : (0xaf, 0x87, 0x87), 139 : (0xaf, 0x87, 0xaf), 140 : (0xaf, 0x87, 0xd7), 141 : (0xaf, 0x87, 0xff), 142 : (0xaf, 0xaf, 0x00), 143 : (0xaf, 0xaf, 0x5f), 144 : (0xaf, 0xaf, 0x87), 145 : (0xaf, 0xaf, 0xaf), 146 : (0xaf, 0xaf, 0xd7), 147 : (0xaf, 0xaf, 0xff), 148 : (0xaf, 0xd7, 0x00), 149 : (0xaf, 0xd7, 0x5f), 150 : (0xaf, 0xd7, 0x87), 151 : (0xaf, 0xd7, 0xaf), 152 : (0xaf, 0xd7, 0xd7), 153 : (0xaf, 0xd7, 0xff), 154 : (0xaf, 0xff, 0x00), 155 : (0xaf, 0xff, 0x5f), 156 : (0xaf, 0xff, 0x87), 157 : (0xaf, 0xff, 0xaf), 158 : (0xaf, 0xff, 0xd7), 159 : (0xaf, 0xff, 0xff), 160 : (0xd7, 0x00, 0x00), 161 : (0xd7, 0x00, 0x5f), 162 : (0xd7, 0x00, 0x87), 163 : (0xd7, 0x00, 0xaf), 164 : (0xd7, 0x00, 0xd7), 165 : (0xd7, 0x00, 0xff), 166 : (0xd7, 0x5f, 0x00), 167 : (0xd7, 0x5f, 0x5f), 168 : (0xd7, 0x5f, 0x87), 169 : (0xd7, 0x5f, 0xaf), 170 : (0xd7, 0x5f, 0xd7), 171 : (0xd7, 0x5f, 0xff), 172 : (0xd7, 0x87, 0x00), 173 : (0xd7, 0x87, 0x5f), 174 : (0xd7, 0x87, 0x87), 175 : (0xd7, 0x87, 0xaf), 176 : (0xd7, 0x87, 0xd7), 177 : (0xd7, 0x87, 0xff), 178 : (0xd7, 0xaf, 0x00), 179 : (0xd7, 0xaf, 0x5f), 180 : (0xd7, 0xaf, 0x87), 181 : (0xd7, 0xaf, 0xaf), 182 : (0xd7, 0xaf, 0xd7), 183 : (0xd7, 0xaf, 0xff), 184 : (0xd7, 0xd7, 0x00), 185 : (0xd7, 0xd7, 0x5f), 186 : (0xd7, 0xd7, 0x87), 187 : (0xd7, 0xd7, 0xaf), 188 : (0xd7, 0xd7, 0xd7), 189 : (0xd7, 0xd7, 0xff), 190 : (0xd7, 0xff, 0x00), 191 : (0xd7, 0xff, 0x5f), 192 : (0xd7, 0xff, 0x87), 193 : (0xd7, 0xff, 0xaf), 194 : (0xd7, 0xff, 0xd7), 195 : (0xd7, 0xff, 0xff), 196 : (0xff, 0x00, 0x00), 197 : (0xff, 0x00, 0x5f), 198 : (0xff, 0x00, 0x87), 199 : (0xff, 0x00, 0xaf), 200 : (0xff, 0x00, 0xd7), 201 : (0xff, 0x00, 0xff), 202 : (0xff, 0x5f, 0x00), 203 : (0xff, 0x5f, 0x5f), 204 : (0xff, 0x5f, 0x87), 205 : (0xff, 0x5f, 0xaf), 206 : (0xff, 0x5f, 0xd7), 207 : (0xff, 0x5f, 0xff), 208 : (0xff, 0x87, 0x00), 209 : (0xff, 0x87, 0x5f), 210 : (0xff, 0x87, 0x87), 211 : (0xff, 0x87, 0xaf), 212 : (0xff, 0x87, 0xd7), 213 : (0xff, 0x87, 0xff), 214 : (0xff, 0xaf, 0x00), 215 : (0xff, 0xaf, 0x5f), 216 : (0xff, 0xaf, 0x87), 217 : (0xff, 0xaf, 0xaf), 218 : (0xff, 0xaf, 0xd7), 219 : (0xff, 0xaf, 0xff), 220 : (0xff, 0xd7, 0x00), 221 : (0xff, 0xd7, 0x5f), 222 : (0xff, 0xd7, 0x87), 223 : (0xff, 0xd7, 0xaf), 224 : (0xff, 0xd7, 0xd7), 225 : (0xff, 0xd7, 0xff), 226 : (0xff, 0xff, 0x00), 227 : (0xff, 0xff, 0x5f), 228 : (0xff, 0xff, 0x87), 229 : (0xff, 0xff, 0xaf), 230 : (0xff, 0xff, 0xd7), 231 : (0xff, 0xff, 0xff), 232 : (0x08, 0x08, 0x08), 233 : (0x12, 0x12, 0x12), 234 : (0x1c, 0x1c, 0x1c), 235 : (0x26, 0x26, 0x26), 236 : (0x30, 0x30, 0x30), 237 : (0x3a, 0x3a, 0x3a), 238 : (0x44, 0x44, 0x44), 239 : (0x4e, 0x4e, 0x4e), 240 : (0x58, 0x58, 0x58), 241 : (0x60, 0x60, 0x60), 242 : (0x66, 0x66, 0x66), 243 : (0x76, 0x76, 0x76), 244 : (0x80, 0x80, 0x80), 245 : (0x8a, 0x8a, 0x8a), 246 : (0x94, 0x94, 0x94), 247 : (0x9e, 0x9e, 0x9e), 248 : (0xa8, 0xa8, 0xa8), 249 : (0xb2, 0xb2, 0xb2), 250 : (0xbc, 0xbc, 0xbc), 251 : (0xc6, 0xc6, 0xc6), 252 : (0xd0, 0xd0, 0xd0), 253 : (0xda, 0xda, 0xda), 254 : (0xe4, 0xe4, 0xe4), 255 : (0xee, 0xee, 0xee)} # Set the default color map for super class. default_color_map = xterm256_colors.copy() bold_text_enabled = True def get_color(self, color, intensity=0): """ Returns a QColor for a given color code, or None if one cannot be constructed. """ if color is None: return None # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) if isinstance(constructor, str): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method # 'setAllowX11ColorNames()', but this is global and only available # on X11. It seems cleaner to aim for uniformity of behavior. return QtGui.QColor(constructor) elif isinstance(constructor, (tuple, list)): return QtGui.QColor(*constructor) return None def get_format(self): """ Returns a QTextCharFormat that encodes the current style attributes. """ format = QtGui.QTextCharFormat() # Set foreground color qcolor = self.get_color(self.foreground_color, self.intensity) if qcolor is not None: format.setForeground(qcolor) # Set background color qcolor = self.get_color(self.background_color, self.intensity) if qcolor is not None: format.setBackground(qcolor) # Set font weight/style options if self.bold: format.setFontWeight(QtGui.QFont.Bold) else: format.setFontWeight(QtGui.QFont.Normal) format.setFontItalic(self.italic) format.setFontUnderline(self.underline) return format def set_background_color(self, color): """ Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing. """ # Set a new default color map. self.default_color_map = self.darkbg_color_map.copy() if color.value() >= 127: # Colors appropriate for a terminal with a light background. For # now, only use non-bright colors... for i in range(8): self.default_color_map[i + 8] = self.default_color_map[i] # ...and replace white with black. self.default_color_map[7] = self.default_color_map[15] = 'black' # Update the current color map with the new defaults. self.color_map.update(self.default_color_map)
thocoo/gamma-desk
gdesk/panels/matplot/__init__.py
from ... import config if config['qapp']: from .plotpanel import PlotPanel from .plotproxy import PlotGuiProxy