repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
BrianHicks/emit
|
emit/router/core.py
|
Router.regenerate_routes
|
python
|
def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not destination
and any(origin.search(name) for origin in origins)
]
ignores = self.ignore_regexes.get(destination, [])
for origin in resolved:
destinations = self.routes.setdefault(origin, set())
if any(ignore.search(origin) for ignore in ignores):
self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
try:
destinations.remove(destination)
self.logger.debug('removed "%s" -> "%s"', origin, destination)
except KeyError:
pass
continue
if destination not in destinations:
self.logger.info('added route "%s" -> "%s"', origin, destination)
destinations.add(destination)
|
regenerate the routes after a new route is added
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L290-L317
| null |
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
self.message_class = message_class or Message
# manage imported packages, lazily importing before the first message
# is routed.
self.resolved_node_modules = []
self.node_modules = node_modules or []
self.node_package = node_package
self.logger = logging.getLogger(__name__ + '.Router')
self.logger.debug('Initialized Router')
self.routing_enabled = True
def __call__(self, **kwargs):
'''\
Route a message to all nodes marked as entry points.
.. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
if item is not NoResult
]
self.logger.debug(
'%s returned generator yielding %d items', func, len(results)
)
[self.route(name, item) for item in results]
return tuple(results)
# the case of a direct return is simpler. wrap, route, and
# return the value.
else:
if result is NoResult:
return result
result = self.wrap_result(name, result)
self.logger.debug(
'%s returned single value %s', func, result
)
self.route(name, result)
return result
return wrapped
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
:py:class:`emit.message.Message`. Nodes can be called directly by
providing a dictionary argument or a set of keyword arguments. Other
uses will raise a ``TypeError``.
:param fields: fields that this function returns
:type fields: ordered iterable of :py:class:`str`
:param subscribe_to: functions in the graph to subscribe to. These
indicators can be regular expressions.
:type subscribe_to: :py:class:`str` or iterable of :py:class:`str`
:param ignore: functions in the graph to ignore (also uses regular
expressions.) Useful for ignoring specific functions in
a broad regex.
:type ignore: :py:class:`str` or iterable of :py:class:`str`
:param entry_point: Set to ``True`` to mark this as an entry point -
that is, this function will be called when the
router is called directly.
:type entry_point: :py:class:`bool`
In addition to all of the above, you can define a ``wrap_node``
function on a subclass of Router, which will need to receive node and
an options dictionary. Any extra options passed to node will be passed
down to the options dictionary. See
:py:class:`emit.router.CeleryRouter.wrap_node` as an example.
:returns: decorated and wrapped function, or decorator if called directly
'''
def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
wrapped = self.wrap_node(wrapped, wrapper_options)
# register the task in the graph
name = self.get_name(func)
self.register(
name, wrapped, fields, subscribe_to, entry_point, ignore
)
return wrapped
return outer
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]
except ImportError:
self.resolved_node_modules = []
raise
return self.resolved_node_modules
def get_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No positional arguments and a number of keyword arguments
'''
if len(args) == 1 and isinstance(args[0], dict):
# then it's a message
self.logger.debug('called with arg dictionary')
result = args[0]
elif len(args) == 0 and kwargs != {}:
# then it's a set of kwargs
self.logger.debug('called with kwargs')
result = kwargs
else:
# it's neither, and we don't handle that
self.logger.error(
'get_message_from_call could not handle "%r", "%r"',
args, kwargs
)
raise TypeError('Pass either keyword arguments or a dictionary argument')
return self.message_class(result)
def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscribe_to`` and ``entry_point`` are the same as in
:py:meth:`Router.node`.
'''
self.fields[name] = fields
self.functions[name] = func
self.register_route(subscribe_to, name)
if ignore:
self.register_ignore(ignore, name)
if entry_point:
self.add_entry_point(name)
self.logger.info('registered %s', name)
def add_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point']
def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type destination: :py:class:`str`
Routing dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
self.names.add(destination)
self.logger.debug('added "%s" to names', destination)
origins = origins or [] # remove None
if not isinstance(origins, list):
origins = [origins]
self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.regexes[destination]
def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination: :py:class:`str`
Ignore dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
if not isinstance(origins, list):
origins = [origins]
self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.ignore_regexes[destination]
def disable_routing(self):
'disable routing (usually for testing purposes)'
self.routing_enabled = False
def enable_routing(self):
'enable routing (after calling ``disable_routing``)'
self.routing_enabled = True
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
# side-effect: we have to know all the routes before we can route. But
# we can't resolve them while the object is initializing, so we have to
# do it just in time to route.
self.resolve_node_modules()
if not self.routing_enabled:
return
subs = self.routes.get(origin, set())
for destination in subs:
self.logger.debug('routing "%s" -> "%s"', origin, destination)
self.dispatch(origin, destination, message)
def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('calling %r directly', func)
return func(_origin=origin, **message)
def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
'''
if not isinstance(result, tuple):
result = tuple([result])
try:
return dict(zip(self.fields[name], result))
except KeyError:
msg = '"%s" has no associated fields'
self.logger.exception(msg, name)
raise ValueError(msg % name)
def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name__
)
|
BrianHicks/emit
|
emit/router/core.py
|
Router.route
|
python
|
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
# side-effect: we have to know all the routes before we can route. But
# we can't resolve them while the object is initializing, so we have to
# do it just in time to route.
self.resolve_node_modules()
if not self.routing_enabled:
return
subs = self.routes.get(origin, set())
for destination in subs:
self.logger.debug('routing "%s" -> "%s"', origin, destination)
self.dispatch(origin, destination, message)
|
\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L327-L348
|
[
"def resolve_node_modules(self):\n 'import the modules specified in init'\n if not self.resolved_node_modules:\n try:\n self.resolved_node_modules = [\n importlib.import_module(mod, self.node_package)\n for mod in self.node_modules\n ]\n except ImportError:\n self.resolved_node_modules = []\n raise\n\n return self.resolved_node_modules\n",
"def dispatch(self, origin, destination, message):\n '''\\\n dispatch a message to a named function\n\n :param destination: destination to dispatch to\n :type destination: :py:class:`str`\n :param message: message to dispatch\n :type message: :py:class:`emit.message.Message` or subclass\n '''\n func = self.functions[destination]\n self.logger.debug('calling %r directly', func)\n return func(_origin=origin, **message)\n"
] |
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
self.message_class = message_class or Message
# manage imported packages, lazily importing before the first message
# is routed.
self.resolved_node_modules = []
self.node_modules = node_modules or []
self.node_package = node_package
self.logger = logging.getLogger(__name__ + '.Router')
self.logger.debug('Initialized Router')
self.routing_enabled = True
def __call__(self, **kwargs):
'''\
Route a message to all nodes marked as entry points.
.. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
if item is not NoResult
]
self.logger.debug(
'%s returned generator yielding %d items', func, len(results)
)
[self.route(name, item) for item in results]
return tuple(results)
# the case of a direct return is simpler. wrap, route, and
# return the value.
else:
if result is NoResult:
return result
result = self.wrap_result(name, result)
self.logger.debug(
'%s returned single value %s', func, result
)
self.route(name, result)
return result
return wrapped
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
:py:class:`emit.message.Message`. Nodes can be called directly by
providing a dictionary argument or a set of keyword arguments. Other
uses will raise a ``TypeError``.
:param fields: fields that this function returns
:type fields: ordered iterable of :py:class:`str`
:param subscribe_to: functions in the graph to subscribe to. These
indicators can be regular expressions.
:type subscribe_to: :py:class:`str` or iterable of :py:class:`str`
:param ignore: functions in the graph to ignore (also uses regular
expressions.) Useful for ignoring specific functions in
a broad regex.
:type ignore: :py:class:`str` or iterable of :py:class:`str`
:param entry_point: Set to ``True`` to mark this as an entry point -
that is, this function will be called when the
router is called directly.
:type entry_point: :py:class:`bool`
In addition to all of the above, you can define a ``wrap_node``
function on a subclass of Router, which will need to receive node and
an options dictionary. Any extra options passed to node will be passed
down to the options dictionary. See
:py:class:`emit.router.CeleryRouter.wrap_node` as an example.
:returns: decorated and wrapped function, or decorator if called directly
'''
def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
wrapped = self.wrap_node(wrapped, wrapper_options)
# register the task in the graph
name = self.get_name(func)
self.register(
name, wrapped, fields, subscribe_to, entry_point, ignore
)
return wrapped
return outer
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]
except ImportError:
self.resolved_node_modules = []
raise
return self.resolved_node_modules
def get_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No positional arguments and a number of keyword arguments
'''
if len(args) == 1 and isinstance(args[0], dict):
# then it's a message
self.logger.debug('called with arg dictionary')
result = args[0]
elif len(args) == 0 and kwargs != {}:
# then it's a set of kwargs
self.logger.debug('called with kwargs')
result = kwargs
else:
# it's neither, and we don't handle that
self.logger.error(
'get_message_from_call could not handle "%r", "%r"',
args, kwargs
)
raise TypeError('Pass either keyword arguments or a dictionary argument')
return self.message_class(result)
def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscribe_to`` and ``entry_point`` are the same as in
:py:meth:`Router.node`.
'''
self.fields[name] = fields
self.functions[name] = func
self.register_route(subscribe_to, name)
if ignore:
self.register_ignore(ignore, name)
if entry_point:
self.add_entry_point(name)
self.logger.info('registered %s', name)
def add_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point']
def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type destination: :py:class:`str`
Routing dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
self.names.add(destination)
self.logger.debug('added "%s" to names', destination)
origins = origins or [] # remove None
if not isinstance(origins, list):
origins = [origins]
self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.regexes[destination]
def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination: :py:class:`str`
Ignore dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
if not isinstance(origins, list):
origins = [origins]
self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.ignore_regexes[destination]
def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not destination
and any(origin.search(name) for origin in origins)
]
ignores = self.ignore_regexes.get(destination, [])
for origin in resolved:
destinations = self.routes.setdefault(origin, set())
if any(ignore.search(origin) for ignore in ignores):
self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
try:
destinations.remove(destination)
self.logger.debug('removed "%s" -> "%s"', origin, destination)
except KeyError:
pass
continue
if destination not in destinations:
self.logger.info('added route "%s" -> "%s"', origin, destination)
destinations.add(destination)
def disable_routing(self):
'disable routing (usually for testing purposes)'
self.routing_enabled = False
def enable_routing(self):
'enable routing (after calling ``disable_routing``)'
self.routing_enabled = True
def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('calling %r directly', func)
return func(_origin=origin, **message)
def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
'''
if not isinstance(result, tuple):
result = tuple([result])
try:
return dict(zip(self.fields[name], result))
except KeyError:
msg = '"%s" has no associated fields'
self.logger.exception(msg, name)
raise ValueError(msg % name)
def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name__
)
|
BrianHicks/emit
|
emit/router/core.py
|
Router.dispatch
|
python
|
def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('calling %r directly', func)
return func(_origin=origin, **message)
|
\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L350-L361
| null |
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
self.message_class = message_class or Message
# manage imported packages, lazily importing before the first message
# is routed.
self.resolved_node_modules = []
self.node_modules = node_modules or []
self.node_package = node_package
self.logger = logging.getLogger(__name__ + '.Router')
self.logger.debug('Initialized Router')
self.routing_enabled = True
def __call__(self, **kwargs):
'''\
Route a message to all nodes marked as entry points.
.. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
if item is not NoResult
]
self.logger.debug(
'%s returned generator yielding %d items', func, len(results)
)
[self.route(name, item) for item in results]
return tuple(results)
# the case of a direct return is simpler. wrap, route, and
# return the value.
else:
if result is NoResult:
return result
result = self.wrap_result(name, result)
self.logger.debug(
'%s returned single value %s', func, result
)
self.route(name, result)
return result
return wrapped
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
:py:class:`emit.message.Message`. Nodes can be called directly by
providing a dictionary argument or a set of keyword arguments. Other
uses will raise a ``TypeError``.
:param fields: fields that this function returns
:type fields: ordered iterable of :py:class:`str`
:param subscribe_to: functions in the graph to subscribe to. These
indicators can be regular expressions.
:type subscribe_to: :py:class:`str` or iterable of :py:class:`str`
:param ignore: functions in the graph to ignore (also uses regular
expressions.) Useful for ignoring specific functions in
a broad regex.
:type ignore: :py:class:`str` or iterable of :py:class:`str`
:param entry_point: Set to ``True`` to mark this as an entry point -
that is, this function will be called when the
router is called directly.
:type entry_point: :py:class:`bool`
In addition to all of the above, you can define a ``wrap_node``
function on a subclass of Router, which will need to receive node and
an options dictionary. Any extra options passed to node will be passed
down to the options dictionary. See
:py:class:`emit.router.CeleryRouter.wrap_node` as an example.
:returns: decorated and wrapped function, or decorator if called directly
'''
def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
wrapped = self.wrap_node(wrapped, wrapper_options)
# register the task in the graph
name = self.get_name(func)
self.register(
name, wrapped, fields, subscribe_to, entry_point, ignore
)
return wrapped
return outer
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]
except ImportError:
self.resolved_node_modules = []
raise
return self.resolved_node_modules
def get_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No positional arguments and a number of keyword arguments
'''
if len(args) == 1 and isinstance(args[0], dict):
# then it's a message
self.logger.debug('called with arg dictionary')
result = args[0]
elif len(args) == 0 and kwargs != {}:
# then it's a set of kwargs
self.logger.debug('called with kwargs')
result = kwargs
else:
# it's neither, and we don't handle that
self.logger.error(
'get_message_from_call could not handle "%r", "%r"',
args, kwargs
)
raise TypeError('Pass either keyword arguments or a dictionary argument')
return self.message_class(result)
def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscribe_to`` and ``entry_point`` are the same as in
:py:meth:`Router.node`.
'''
self.fields[name] = fields
self.functions[name] = func
self.register_route(subscribe_to, name)
if ignore:
self.register_ignore(ignore, name)
if entry_point:
self.add_entry_point(name)
self.logger.info('registered %s', name)
def add_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point']
def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type destination: :py:class:`str`
Routing dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
self.names.add(destination)
self.logger.debug('added "%s" to names', destination)
origins = origins or [] # remove None
if not isinstance(origins, list):
origins = [origins]
self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.regexes[destination]
def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination: :py:class:`str`
Ignore dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
if not isinstance(origins, list):
origins = [origins]
self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.ignore_regexes[destination]
def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not destination
and any(origin.search(name) for origin in origins)
]
ignores = self.ignore_regexes.get(destination, [])
for origin in resolved:
destinations = self.routes.setdefault(origin, set())
if any(ignore.search(origin) for ignore in ignores):
self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
try:
destinations.remove(destination)
self.logger.debug('removed "%s" -> "%s"', origin, destination)
except KeyError:
pass
continue
if destination not in destinations:
self.logger.info('added route "%s" -> "%s"', origin, destination)
destinations.add(destination)
def disable_routing(self):
'disable routing (usually for testing purposes)'
self.routing_enabled = False
def enable_routing(self):
'enable routing (after calling ``disable_routing``)'
self.routing_enabled = True
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
# side-effect: we have to know all the routes before we can route. But
# we can't resolve them while the object is initializing, so we have to
# do it just in time to route.
self.resolve_node_modules()
if not self.routing_enabled:
return
subs = self.routes.get(origin, set())
for destination in subs:
self.logger.debug('routing "%s" -> "%s"', origin, destination)
self.dispatch(origin, destination, message)
def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
'''
if not isinstance(result, tuple):
result = tuple([result])
try:
return dict(zip(self.fields[name], result))
except KeyError:
msg = '"%s" has no associated fields'
self.logger.exception(msg, name)
raise ValueError(msg % name)
def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name__
)
|
BrianHicks/emit
|
emit/router/core.py
|
Router.wrap_result
|
python
|
def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
'''
if not isinstance(result, tuple):
result = tuple([result])
try:
return dict(zip(self.fields[name], result))
except KeyError:
msg = '"%s" has no associated fields'
self.logger.exception(msg, name)
raise ValueError(msg % name)
|
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L363-L384
| null |
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
self.message_class = message_class or Message
# manage imported packages, lazily importing before the first message
# is routed.
self.resolved_node_modules = []
self.node_modules = node_modules or []
self.node_package = node_package
self.logger = logging.getLogger(__name__ + '.Router')
self.logger.debug('Initialized Router')
self.routing_enabled = True
def __call__(self, **kwargs):
'''\
Route a message to all nodes marked as entry points.
.. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
if item is not NoResult
]
self.logger.debug(
'%s returned generator yielding %d items', func, len(results)
)
[self.route(name, item) for item in results]
return tuple(results)
# the case of a direct return is simpler. wrap, route, and
# return the value.
else:
if result is NoResult:
return result
result = self.wrap_result(name, result)
self.logger.debug(
'%s returned single value %s', func, result
)
self.route(name, result)
return result
return wrapped
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
:py:class:`emit.message.Message`. Nodes can be called directly by
providing a dictionary argument or a set of keyword arguments. Other
uses will raise a ``TypeError``.
:param fields: fields that this function returns
:type fields: ordered iterable of :py:class:`str`
:param subscribe_to: functions in the graph to subscribe to. These
indicators can be regular expressions.
:type subscribe_to: :py:class:`str` or iterable of :py:class:`str`
:param ignore: functions in the graph to ignore (also uses regular
expressions.) Useful for ignoring specific functions in
a broad regex.
:type ignore: :py:class:`str` or iterable of :py:class:`str`
:param entry_point: Set to ``True`` to mark this as an entry point -
that is, this function will be called when the
router is called directly.
:type entry_point: :py:class:`bool`
In addition to all of the above, you can define a ``wrap_node``
function on a subclass of Router, which will need to receive node and
an options dictionary. Any extra options passed to node will be passed
down to the options dictionary. See
:py:class:`emit.router.CeleryRouter.wrap_node` as an example.
:returns: decorated and wrapped function, or decorator if called directly
'''
def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
wrapped = self.wrap_node(wrapped, wrapper_options)
# register the task in the graph
name = self.get_name(func)
self.register(
name, wrapped, fields, subscribe_to, entry_point, ignore
)
return wrapped
return outer
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]
except ImportError:
self.resolved_node_modules = []
raise
return self.resolved_node_modules
def get_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No positional arguments and a number of keyword arguments
'''
if len(args) == 1 and isinstance(args[0], dict):
# then it's a message
self.logger.debug('called with arg dictionary')
result = args[0]
elif len(args) == 0 and kwargs != {}:
# then it's a set of kwargs
self.logger.debug('called with kwargs')
result = kwargs
else:
# it's neither, and we don't handle that
self.logger.error(
'get_message_from_call could not handle "%r", "%r"',
args, kwargs
)
raise TypeError('Pass either keyword arguments or a dictionary argument')
return self.message_class(result)
def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscribe_to`` and ``entry_point`` are the same as in
:py:meth:`Router.node`.
'''
self.fields[name] = fields
self.functions[name] = func
self.register_route(subscribe_to, name)
if ignore:
self.register_ignore(ignore, name)
if entry_point:
self.add_entry_point(name)
self.logger.info('registered %s', name)
def add_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point']
def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type destination: :py:class:`str`
Routing dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
self.names.add(destination)
self.logger.debug('added "%s" to names', destination)
origins = origins or [] # remove None
if not isinstance(origins, list):
origins = [origins]
self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.regexes[destination]
def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination: :py:class:`str`
Ignore dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
if not isinstance(origins, list):
origins = [origins]
self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.ignore_regexes[destination]
def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not destination
and any(origin.search(name) for origin in origins)
]
ignores = self.ignore_regexes.get(destination, [])
for origin in resolved:
destinations = self.routes.setdefault(origin, set())
if any(ignore.search(origin) for ignore in ignores):
self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
try:
destinations.remove(destination)
self.logger.debug('removed "%s" -> "%s"', origin, destination)
except KeyError:
pass
continue
if destination not in destinations:
self.logger.info('added route "%s" -> "%s"', origin, destination)
destinations.add(destination)
def disable_routing(self):
'disable routing (usually for testing purposes)'
self.routing_enabled = False
def enable_routing(self):
'enable routing (after calling ``disable_routing``)'
self.routing_enabled = True
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
# side-effect: we have to know all the routes before we can route. But
# we can't resolve them while the object is initializing, so we have to
# do it just in time to route.
self.resolve_node_modules()
if not self.routing_enabled:
return
subs = self.routes.get(origin, set())
for destination in subs:
self.logger.debug('routing "%s" -> "%s"', origin, destination)
self.dispatch(origin, destination, message)
def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('calling %r directly', func)
return func(_origin=origin, **message)
def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name__
)
|
BrianHicks/emit
|
emit/router/core.py
|
Router.get_name
|
python
|
def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name__
)
|
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L386-L399
| null |
class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages passed to nodes
:type message_class: :py:class:`emit.message.Message` or subclass
:param node_modules: a list of modules that contain nodes
:type node_modules: a list of :py:class:`str`, or ``None``.
:param node_package: if any node_modules are relative, the path to base
off of.
:type node_package: :py:class:`str`, or ``None``.
:exceptions: None
:returns: None
'''
self.routes = {}
self.names = set()
self.regexes = {}
self.ignore_regexes = {}
self.fields = {}
self.functions = {}
self.message_class = message_class or Message
# manage imported packages, lazily importing before the first message
# is routed.
self.resolved_node_modules = []
self.node_modules = node_modules or []
self.node_package = node_package
self.logger = logging.getLogger(__name__ + '.Router')
self.logger.debug('Initialized Router')
self.routing_enabled = True
def __call__(self, **kwargs):
'''\
Route a message to all nodes marked as entry points.
.. note::
This function does not optionally accept a single argument
(dictionary) as other points in this API do - it must be expanded to
keyword arguments in this case.
'''
self.logger.info('Calling entry point with %r', kwargs)
self.route('__entry_point', kwargs)
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', name, message)
result = func(message)
# functions can return multiple values ("emit" multiple times)
# by yielding instead of returning. Handle this case by making
# a list of the results and processing them all after the
# generator successfully exits. If we were to process them as
# they came out of the generator, we might get a partially
# processed input sent down the graph. This may be possible in
# the future via a flag.
if isinstance(result, GeneratorType):
results = [
self.wrap_result(name, item)
for item in result
if item is not NoResult
]
self.logger.debug(
'%s returned generator yielding %d items', func, len(results)
)
[self.route(name, item) for item in results]
return tuple(results)
# the case of a direct return is simpler. wrap, route, and
# return the value.
else:
if result is NoResult:
return result
result = self.wrap_result(name, result)
self.logger.debug(
'%s returned single value %s', func, result
)
self.route(name, result)
return result
return wrapped
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
:py:class:`emit.message.Message`. Nodes can be called directly by
providing a dictionary argument or a set of keyword arguments. Other
uses will raise a ``TypeError``.
:param fields: fields that this function returns
:type fields: ordered iterable of :py:class:`str`
:param subscribe_to: functions in the graph to subscribe to. These
indicators can be regular expressions.
:type subscribe_to: :py:class:`str` or iterable of :py:class:`str`
:param ignore: functions in the graph to ignore (also uses regular
expressions.) Useful for ignoring specific functions in
a broad regex.
:type ignore: :py:class:`str` or iterable of :py:class:`str`
:param entry_point: Set to ``True`` to mark this as an entry point -
that is, this function will be called when the
router is called directly.
:type entry_point: :py:class:`bool`
In addition to all of the above, you can define a ``wrap_node``
function on a subclass of Router, which will need to receive node and
an options dictionary. Any extra options passed to node will be passed
down to the options dictionary. See
:py:class:`emit.router.CeleryRouter.wrap_node` as an example.
:returns: decorated and wrapped function, or decorator if called directly
'''
def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
wrapped = self.wrap_node(wrapped, wrapper_options)
# register the task in the graph
name = self.get_name(func)
self.register(
name, wrapped, fields, subscribe_to, entry_point, ignore
)
return wrapped
return outer
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]
except ImportError:
self.resolved_node_modules = []
raise
return self.resolved_node_modules
def get_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No positional arguments and a number of keyword arguments
'''
if len(args) == 1 and isinstance(args[0], dict):
# then it's a message
self.logger.debug('called with arg dictionary')
result = args[0]
elif len(args) == 0 and kwargs != {}:
# then it's a set of kwargs
self.logger.debug('called with kwargs')
result = kwargs
else:
# it's neither, and we don't handle that
self.logger.error(
'get_message_from_call could not handle "%r", "%r"',
args, kwargs
)
raise TypeError('Pass either keyword arguments or a dictionary argument')
return self.message_class(result)
def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscribe_to`` and ``entry_point`` are the same as in
:py:meth:`Router.node`.
'''
self.fields[name] = fields
self.functions[name] = func
self.register_route(subscribe_to, name)
if ignore:
self.register_ignore(ignore, name)
if entry_point:
self.add_entry_point(name)
self.logger.info('registered %s', name)
def add_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point']
def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type destination: :py:class:`str`
Routing dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
self.names.add(destination)
self.logger.debug('added "%s" to names', destination)
origins = origins or [] # remove None
if not isinstance(origins, list):
origins = [origins]
self.regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.regexes[destination]
def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination: :py:class:`str`
Ignore dictionary takes the following form::
{'node_a': set(['node_b', 'node_c']),
'node_b': set(['node_d'])}
'''
if not isinstance(origins, list):
origins = [origins]
self.ignore_regexes.setdefault(destination, [re.compile(origin) for origin in origins])
self.regenerate_routes()
return self.ignore_regexes[destination]
def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not destination
and any(origin.search(name) for origin in origins)
]
ignores = self.ignore_regexes.get(destination, [])
for origin in resolved:
destinations = self.routes.setdefault(origin, set())
if any(ignore.search(origin) for ignore in ignores):
self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
try:
destinations.remove(destination)
self.logger.debug('removed "%s" -> "%s"', origin, destination)
except KeyError:
pass
continue
if destination not in destinations:
self.logger.info('added route "%s" -> "%s"', origin, destination)
destinations.add(destination)
def disable_routing(self):
'disable routing (usually for testing purposes)'
self.routing_enabled = False
def enable_routing(self):
'enable routing (after calling ``disable_routing``)'
self.routing_enabled = True
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
# side-effect: we have to know all the routes before we can route. But
# we can't resolve them while the object is initializing, so we have to
# do it just in time to route.
self.resolve_node_modules()
if not self.routing_enabled:
return
subs = self.routes.get(origin, set())
for destination in subs:
self.logger.debug('routing "%s" -> "%s"', origin, destination)
self.dispatch(origin, destination, message)
def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('calling %r directly', func)
return func(_origin=origin, **message)
def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
:returns: :py:class:`dict`
'''
if not isinstance(result, tuple):
result = tuple([result])
try:
return dict(zip(self.fields[name], result))
except KeyError:
msg = '"%s" has no associated fields'
self.logger.exception(msg, name)
raise ValueError(msg % name)
|
BrianHicks/emit
|
emit/router/celery.py
|
CeleryRouter.wrap_node
|
python
|
def wrap_node(self, node, options):
'''\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
'''
if 'celery_task' in options:
return options['celery_task'](node)
return self.celery_task(node)
|
\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/celery.py#L33-L42
| null |
class CeleryRouter(Router):
'Router specifically for Celery routing'
def __init__(self, celery_task, *args, **kwargs):
'''\
Specifically route when celery is needed
:param celery_task: celery task to apply to all nodes (can be
overridden in :py:meth:`Router.node`.)
:type celery_task: A celery task decorator, in any form
'''
super(CeleryRouter, self).__init__(*args, **kwargs)
self.celery_task = celery_task
self.logger.debug('Initialized Celery Router')
def dispatch(self, origin, destination, message):
'''\
enqueue a message with Celery
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass
'''
func = self.functions[destination]
self.logger.debug('delaying %r', func)
return func.delay(_origin=origin, **message)
|
BrianHicks/emit
|
emit/router/rq.py
|
RQRouter.wrap_node
|
python
|
def wrap_node(self, node, options):
'''
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
'''
job_kwargs = {
'queue': options.get('queue', 'default'),
'connection': options.get('connection', self.redis_connection),
'timeout': options.get('timeout', None),
'result_ttl': options.get('result_ttl', 500),
}
return job(**job_kwargs)(node)
|
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/rq.py#L28-L40
| null |
class RQRouter(Router):
'Router specifically for RQ routing'
def __init__(self, redis_connection, *args, **kwargs):
'''\
Specific routing when using RQ
:param redis_connection: a redis connection to send to all the tasks
(can be overridden in :py:meth:`Router.node`.)
:type redis_connection: :py:class:`redis.Redis`
'''
super(RQRouter, self).__init__(*args, **kwargs)
self.redis_connection = redis_connection
self.logger.debug('Initialized RQ Router')
def dispatch(self, origin, destination, message):
'dispatch through RQ'
func = self.functions[destination]
self.logger.debug('enqueueing %r', func)
return func.delay(_origin=origin, **message)
|
BrianHicks/emit
|
emit/multilang.py
|
ShellNode.deserialize
|
python
|
def deserialize(self, msg):
'deserialize output to a Python object'
self.logger.debug('deserializing %s', msg)
return json.loads(msg)
|
deserialize output to a Python object
|
train
|
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/multilang.py#L65-L68
| null |
class ShellNode(object):
'''\
callable object to wrap communication to a node in another language
to use this, subclass ``ShellNode``, providing "command". Decorate it
however you feel like.
Messages will be passed in on lines in msgpack format. This class expects
similar output: msgpack messages separated by a newline.
'''
def __init__(self):
self.logger = logging.getLogger('%s.%s' % (
self.__class__.__module__,
self.__class__.__name__
))
self.logger.debug('initialized %s', self.__class__.__name__)
@property
def __name__(self):
'fix for being able to use functools.wraps on a class'
return self.__class__.__name__
def __call__(self, msg):
'call the command specified, processing output'
process = Popen(
self.get_command(),
stdout=PIPE, stderr=PIPE, stdin=PIPE,
cwd=self.get_cwd()
)
msg_json = msg.as_json()
try:
stdout, stderr = process.communicate(bytes(msg_json, 'UTF-8'))
except TypeError: # python 2.7.2
stdout, stderr = process.communicate(msg_json)
if stderr:
self.logger.error('Error calling "%s": %s', self.command, stderr)
raise RuntimeError(stderr)
messages = stdout.decode('UTF-8').strip().split('\n')
self.logger.debug('subprocess returned %d messages', len(messages))
for message in messages:
yield self.deserialize(message)
def get_command(self):
'get the command as a list'
return shlex.split(self.command)
def get_cwd(self):
'get directory to change to before running the command'
try:
return self.cwd
except AttributeError:
self.logger.debug('no cwd specified, returning None')
return None
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/commands.py
|
commandstr
|
python
|
def commandstr(command):
if command == CMD_MESSAGE_ERROR:
msg = "CMD_MESSAGE_ERROR"
elif command == CMD_MESSAGE_LIST:
msg = "CMD_MESSAGE_LIST"
elif command == CMD_MESSAGE_PASSWORD:
msg = "CMD_MESSAGE_PASSWORD"
elif command == CMD_MESSAGE_MP3:
msg = "CMD_MESSAGE_MP3"
elif command == CMD_MESSAGE_DELETE:
msg = "CMD_MESSAGE_DELETE"
elif command == CMD_MESSAGE_VERSION:
msg = "CMD_MESSAGE_VERSION"
elif command == CMD_MESSAGE_CDR_AVAILABLE:
msg = "CMD_MESSAGE_CDR_AVAILABLE"
elif command == CMD_MESSAGE_CDR:
msg = "CMD_MESSAGE_CDR"
else:
msg = "CMD_MESSAGE_UNKNOWN"
return msg
|
Convert command into string.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/commands.py#L13-L33
| null |
# coding: utf-8
"""Commands used to communicate between client and server."""
CMD_MESSAGE_ERROR = 0
CMD_MESSAGE_LIST = 1
CMD_MESSAGE_PASSWORD = 2
CMD_MESSAGE_MP3 = 3
CMD_MESSAGE_DELETE = 4
CMD_MESSAGE_VERSION = 5
CMD_MESSAGE_CDR = 6
CMD_MESSAGE_CDR_AVAILABLE = 7
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
_build_request
|
python
|
def _build_request(request):
msg = bytes([request['cmd']])
if 'dest' in request:
msg += bytes([request['dest']])
else:
msg += b'\0'
if 'sha' in request:
msg += request['sha']
else:
for dummy in range(64):
msg += b'0'
logging.debug("Request (%d): %s", len(msg), msg)
return msg
|
Build message to transfer over the socket from a request.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L28-L41
| null |
"""asterisk_mbox_client: Client API for Asterisk Mailboxes."""
import sys
import socket
import select
import json
import configparser
import logging
import zlib
import queue
import threading
from distutils.version import StrictVersion
from asterisk_mbox.utils import (PollableQueue, recv_blocking,
encode_password, encode_to_sha)
import asterisk_mbox.commands as cmd
__min_server_version__ = '0.5.0'
class ServerError(Exception):
"""Server reported an error during synchronous tranfer."""
pass
def _get_bytes(data):
"""Ensure data is type 'bytes'."""
if isinstance(data, str):
return data.encode('utf-8')
return data
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
def _callback(command, message):
logging.debug("Async: %d: %s", command, message)
def main():
"""Show example using the API."""
__async__ = True
logging.basicConfig(format="%(levelname)-10s %(message)s",
level=logging.DEBUG)
if len(sys.argv) != 2:
logging.error("Must specify configuration file")
sys.exit()
config = configparser.ConfigParser()
config.read(sys.argv[1])
password = config.get('default', 'password')
if __async__:
client = Client(config.get('default', 'host'),
config.getint('default', 'port'), password, _callback)
else:
client = Client(config.get('default', 'host'),
config.getint('default', 'port'),
password)
status = client.messages()
msg = status[0]
print(msg)
print(client.mp3(msg['sha'].encode('utf-8')))
while True:
continue
if __name__ == '__main__':
main()
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
main
|
python
|
def main():
__async__ = True
logging.basicConfig(format="%(levelname)-10s %(message)s",
level=logging.DEBUG)
if len(sys.argv) != 2:
logging.error("Must specify configuration file")
sys.exit()
config = configparser.ConfigParser()
config.read(sys.argv[1])
password = config.get('default', 'password')
if __async__:
client = Client(config.get('default', 'host'),
config.getint('default', 'port'), password, _callback)
else:
client = Client(config.get('default', 'host'),
config.getint('default', 'port'),
password)
status = client.messages()
msg = status[0]
print(msg)
print(client.mp3(msg['sha'].encode('utf-8')))
while True:
continue
|
Show example using the API.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L242-L267
| null |
"""asterisk_mbox_client: Client API for Asterisk Mailboxes."""
import sys
import socket
import select
import json
import configparser
import logging
import zlib
import queue
import threading
from distutils.version import StrictVersion
from asterisk_mbox.utils import (PollableQueue, recv_blocking,
encode_password, encode_to_sha)
import asterisk_mbox.commands as cmd
__min_server_version__ = '0.5.0'
class ServerError(Exception):
"""Server reported an error during synchronous tranfer."""
pass
def _build_request(request):
"""Build message to transfer over the socket from a request."""
msg = bytes([request['cmd']])
if 'dest' in request:
msg += bytes([request['dest']])
else:
msg += b'\0'
if 'sha' in request:
msg += request['sha']
else:
for dummy in range(64):
msg += b'0'
logging.debug("Request (%d): %s", len(msg), msg)
return msg
def _get_bytes(data):
"""Ensure data is type 'bytes'."""
if isinstance(data, str):
return data.encode('utf-8')
return data
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
def _callback(command, message):
logging.debug("Async: %d: %s", command, message)
if __name__ == '__main__':
main()
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client.start
|
python
|
def start(self):
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
|
Start thread.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L73-L85
|
[
"def get(self, block=True, timeout=None):\n \"\"\"get.\"\"\"\n try:\n item = super().get(block, timeout)\n self._getsocket.recv(1)\n return item\n except queue.Empty:\n raise queue.Empty\n"
] |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client.stop
|
python
|
def stop(self):
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
|
Stop thread.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L87-L95
| null |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client._connect
|
python
|
def _connect(self):
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
|
Connect to server.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L97-L102
| null |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client._recv_msg
|
python
|
def _recv_msg(self):
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
|
Read a message from the server.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L104-L111
| null |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client._loop
|
python
|
def _loop(self):
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
|
Handle data.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L146-L196
| null |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client.mp3
|
python
|
def mp3(self, sha, **kwargs):
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
|
Get raw MP3 of a message.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L216-L219
|
[
"def _get_bytes(data):\n \"\"\"Ensure data is type 'bytes'.\"\"\"\n if isinstance(data, str):\n return data.encode('utf-8')\n return data\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerError(\"Client not running\")\n if not self._callback or kwargs.get('sync'):\n item['sync'] = True\n self.request_queue.put(item)\n command, msg = self.result_queue.get()\n if command == cmd.CMD_MESSAGE_ERROR:\n raise ServerError(msg)\n\n return msg\n else:\n self.request_queue.put(item)\n"
] |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client.delete
|
python
|
def delete(self, sha, **kwargs):
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
|
Delete a message.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L221-L224
|
[
"def _get_bytes(data):\n \"\"\"Ensure data is type 'bytes'.\"\"\"\n if isinstance(data, str):\n return data.encode('utf-8')\n return data\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerError(\"Client not running\")\n if not self._callback or kwargs.get('sync'):\n item['sync'] = True\n self.request_queue.put(item)\n command, msg = self.result_queue.get()\n if command == cmd.CMD_MESSAGE_ERROR:\n raise ServerError(msg)\n\n return msg\n else:\n self.request_queue.put(item)\n"
] |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages"""
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/__init__.py
|
Client.get_cdr
|
python
|
def get_cdr(self, start=0, count=-1, **kwargs):
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs)
|
Request range of CDR messages
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L231-L235
|
[
"def encode_to_sha(msg):\n \"\"\"coerce numeric list inst sha-looking bytearray\"\"\"\n if isinstance(msg, str):\n msg = msg.encode('utf-8')\n return (codecs.encode(msg, \"hex_codec\") + (b'00' * 32))[:64]\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerError(\"Client not running\")\n if not self._callback or kwargs.get('sync'):\n item['sync'] = True\n self.request_queue.put(item)\n command, msg = self.result_queue.get()\n if command == cmd.CMD_MESSAGE_ERROR:\n raise ServerError(msg)\n\n return msg\n else:\n self.request_queue.put(item)\n"
] |
class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._soc = None
self._thread = None
self._status = {}
# Stop thread
self.signal = PollableQueue()
# Send data to the server
self.request_queue = PollableQueue()
# Receive data from the server
self.result_queue = PollableQueue()
if 'autostart' not in kwargs or kwargs['autostart']:
self.start()
def start(self):
"""Start thread."""
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(target=self._loop)
self._thread.setDaemon(True)
self._thread.start()
def stop(self):
"""Stop thread."""
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None
def _connect(self):
"""Connect to server."""
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password}))
def _recv_msg(self):
"""Read a message from the server."""
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg
def _handle_msg(self, command, msg, request):
if command == cmd.CMD_MESSAGE_ERROR:
logging.warning("Received error: %s", msg.decode('utf-8'))
elif command == cmd.CMD_MESSAGE_VERSION:
min_ver = StrictVersion(__min_server_version__)
server_ver = StrictVersion(msg.decode('utf-8'))
if server_ver < min_ver:
raise ServerError("Server version is too low: {} < {}".format(
msg.decode('utf-8'), __min_server_version__))
elif command == cmd.CMD_MESSAGE_LIST:
self._status = json.loads(msg.decode('utf-8'))
msg = self._status
elif command == cmd.CMD_MESSAGE_CDR:
self._status = json.loads(zlib.decompress(msg).decode('utf-8'))
msg = self._status
if self._callback and 'sync' not in request:
self._callback(command, msg)
elif request and (command == request.get('cmd') or
command == cmd.CMD_MESSAGE_ERROR):
logging.debug("Got command: %s", cmd.commandstr(command))
self.result_queue.put([command, msg])
request.clear()
else:
logging.debug("Got unhandled command: %s",
cmd.commandstr(command))
def _clear_request(self, request):
if not self._callback or 'sync' in request:
self.result_queue.put(
[cmd.CMD_MESSAGE_ERROR, "Not connected to server"])
request.clear()
def _loop(self):
"""Handle data."""
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_LIST}))
self._soc.send(_build_request(
{'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE}))
connected = True
except ConnectionRefusedError:
timeout = 5.0
if connected:
sockets.append(self._soc)
readable, _writable, _errored = select.select(
sockets, [], [], timeout)
if self.signal in readable:
break
if self._soc in readable:
# We have incoming data
try:
command, msg = self._recv_msg()
self._handle_msg(command, msg, request)
except (RuntimeError, ConnectionResetError):
logging.warning("Lost connection")
connected = False
self._clear_request(request)
if self.request_queue in readable:
request = self.request_queue.get()
self.request_queue.task_done()
if not connected:
self._clear_request(request)
else:
if (request['cmd'] == cmd.CMD_MESSAGE_LIST and
self._status and
(not self._callback or 'sync' in request)):
self.result_queue.put(
[cmd.CMD_MESSAGE_LIST, self._status])
request = {}
else:
self._soc.send(_build_request(request))
def _queue_msg(self, item, **kwargs):
if not self._thread:
raise ServerError("Client not running")
if not self._callback or kwargs.get('sync'):
item['sync'] = True
self.request_queue.put(item)
command, msg = self.result_queue.get()
if command == cmd.CMD_MESSAGE_ERROR:
raise ServerError(msg)
return msg
else:
self.request_queue.put(item)
def messages(self, **kwargs):
"""Get list of messages with metadata."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_LIST}, **kwargs)
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs)
def delete(self, sha, **kwargs):
"""Delete a message."""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs)
def cdr_count(self, **kwargs):
"""Request count of CDR entries"""
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR_AVAILABLE},
**kwargs)
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
recv_blocking
|
python
|
def recv_blocking(conn, msglen):
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket connection broken")
msg += tmpmsg
logging.debug("Msglen: %d of %d", len(msg), msglen)
logging.debug("Message: %s", msg)
return msg
|
Recieve data until msglen bytes have been received.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L52-L65
| null |
"""Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def put(self, item, block=True, timeout=None):
"""put."""
super().put(item, block, timeout)
self._putsocket.send(b'x')
def get(self, block=True, timeout=None):
"""get."""
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
def encode_password(password):
"""Hash password and append current asterisk_mbox version."""
return(hashlib.sha256(password.encode('utf-8')).hexdigest()[:-8] +
(__version__ + " ")[:8])
def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp != ver_act:
msg.append("asterisk_mbox version mismatch. Client: '" +
ver_act + "', Server: '" + ver_exp + "'")
return False, ". ".join(msg)
def encode_to_sha(msg):
"""coerce numeric list inst sha-looking bytearray"""
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64]
def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec")
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
compare_password
|
python
|
def compare_password(expected, actual):
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp != ver_act:
msg.append("asterisk_mbox version mismatch. Client: '" +
ver_act + "', Server: '" + ver_exp + "'")
return False, ". ".join(msg)
|
Compare two 64byte encoded passwords.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L74-L87
| null |
"""Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def put(self, item, block=True, timeout=None):
"""put."""
super().put(item, block, timeout)
self._putsocket.send(b'x')
def get(self, block=True, timeout=None):
"""get."""
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
def recv_blocking(conn, msglen):
"""Recieve data until msglen bytes have been received."""
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket connection broken")
msg += tmpmsg
logging.debug("Msglen: %d of %d", len(msg), msglen)
logging.debug("Message: %s", msg)
return msg
def encode_password(password):
"""Hash password and append current asterisk_mbox version."""
return(hashlib.sha256(password.encode('utf-8')).hexdigest()[:-8] +
(__version__ + " ")[:8])
def encode_to_sha(msg):
"""coerce numeric list inst sha-looking bytearray"""
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64]
def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec")
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
encode_to_sha
|
python
|
def encode_to_sha(msg):
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64]
|
coerce numeric list inst sha-looking bytearray
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L90-L94
| null |
"""Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def put(self, item, block=True, timeout=None):
"""put."""
super().put(item, block, timeout)
self._putsocket.send(b'x')
def get(self, block=True, timeout=None):
"""get."""
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
def recv_blocking(conn, msglen):
"""Recieve data until msglen bytes have been received."""
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket connection broken")
msg += tmpmsg
logging.debug("Msglen: %d of %d", len(msg), msglen)
logging.debug("Message: %s", msg)
return msg
def encode_password(password):
"""Hash password and append current asterisk_mbox version."""
return(hashlib.sha256(password.encode('utf-8')).hexdigest()[:-8] +
(__version__ + " ")[:8])
def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp != ver_act:
msg.append("asterisk_mbox version mismatch. Client: '" +
ver_act + "', Server: '" + ver_exp + "'")
return False, ". ".join(msg)
def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec")
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
decode_from_sha
|
python
|
def decode_from_sha(sha):
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec")
|
convert coerced sha back into numeric list
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L97-L101
| null |
"""Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def put(self, item, block=True, timeout=None):
"""put."""
super().put(item, block, timeout)
self._putsocket.send(b'x')
def get(self, block=True, timeout=None):
"""get."""
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
def recv_blocking(conn, msglen):
"""Recieve data until msglen bytes have been received."""
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket connection broken")
msg += tmpmsg
logging.debug("Msglen: %d of %d", len(msg), msglen)
logging.debug("Message: %s", msg)
return msg
def encode_password(password):
"""Hash password and append current asterisk_mbox version."""
return(hashlib.sha256(password.encode('utf-8')).hexdigest()[:-8] +
(__version__ + " ")[:8])
def compare_password(expected, actual):
"""Compare two 64byte encoded passwords."""
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp != ver_act:
msg.append("asterisk_mbox version mismatch. Client: '" +
ver_act + "', Server: '" + ver_exp + "'")
return False, ". ".join(msg)
def encode_to_sha(msg):
"""coerce numeric list inst sha-looking bytearray"""
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64]
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
PollableQueue.put
|
python
|
def put(self, item, block=True, timeout=None):
super().put(item, block, timeout)
self._putsocket.send(b'x')
|
put.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L37-L40
| null |
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def get(self, block=True, timeout=None):
"""get."""
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
|
PhracturedBlue/asterisk_mbox
|
asterisk_mbox/utils.py
|
PollableQueue.get
|
python
|
def get(self, block=True, timeout=None):
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty
|
get.
|
train
|
https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L42-L49
| null |
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
# Compatibility on non-POSIX systems
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 0))
server.listen(1)
self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._putsocket.connect(server.getsockname())
self._getsocket, _ = server.accept()
server.close()
def fileno(self):
"""fileno."""
return self._getsocket.fileno()
def put(self, item, block=True, timeout=None):
"""put."""
super().put(item, block, timeout)
self._putsocket.send(b'x')
|
mjirik/sed3
|
sed3/sed3.py
|
show_slices
|
python
|
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
|
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L607-L700
|
[
"def _import_data(data, axis, slice_step, first_slice_offset=0):\n \"\"\"\n import ndarray or SimpleITK data\n \"\"\"\n try:\n import SimpleITK as sitk\n if type(data) is sitk.SimpleITK.Image:\n data = sitk.GetArrayFromImage(data)\n except:\n pass\n\n data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)\n return data\n",
"def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):\n \"\"\"\n\n :param data:\n :param slice_number:\n :param axis:\n :param flipV: vertical flip\n :param flipH: horizontal flip\n :return:\n \"\"\"\n if axis == 0:\n data2d = data[slice_number, :, :]\n elif axis == 1:\n data2d = data[:, slice_number, :]\n elif axis == 2:\n data2d = data[:, :, slice_number]\n else:\n logger.error(\"axis number error\")\n print(\"axis number error\")\n return None\n\n if flipV:\n if data2d is not None:\n data2d = data2d[-1:0:-1,:]\n if flipH:\n if data2d is not None:\n data2d = data2d[:, -1:0:-1]\n return data2d\n",
"def __put_slice_in_slim(slim, dataim, sh, i):\n \"\"\"\n put one small slice as a tile in a big image\n \"\"\"\n a, b = np.unravel_index(int(i), sh)\n\n st0 = int(dataim.shape[0] * a)\n st1 = int(dataim.shape[1] * b)\n sp0 = int(st0 + dataim.shape[0])\n sp1 = int(st1 + dataim.shape[1])\n\n slim[\n st0:sp0,\n st1:sp1\n ] = dataim\n\n return slim\n",
"def show_slice(data2d, contour2d=None, seeds2d=None):\n \"\"\"\n\n :param data2d:\n :param contour2d:\n :param seeds2d:\n :return:\n \"\"\"\n\n import copy as cp\n # Show results\n\n colormap = cp.copy(plt.cm.get_cmap('brg'))\n colormap._init()\n colormap._lut[:1:, 3] = 0\n\n plt.imshow(data2d, cmap='gray', interpolation='none')\n if contour2d is not None:\n plt.contour(contour2d, levels=[0.5, 1.5, 2.5])\n if seeds2d is not None:\n # Show results\n colormap = copy.copy(plt.cm.get_cmap('Paired'))\n # colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))\n colormap._init()\n\n colormap._lut[0, 3] = 0\n\n tmp0 = copy.copy(colormap._lut[:,0])\n tmp1 = copy.copy(colormap._lut[:,1])\n tmp2 = copy.copy(colormap._lut[:,2])\n\n colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)\n colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)\n colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)\n # seed 4\n colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)\n colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)\n # seed 2\n colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)\n colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)\n\n\n # seed 2\n colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)\n colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)\n\n # my colors\n\n # colormap._lut[1,:] = [.0,.1,.0,1]\n # colormap._lut[2,:] = [.1,.1,.0,1]\n # colormap._lut[3,:] = [.1,.1,.1,1]\n # colormap._lut[4,:] = [.3,.3,.3,1]\n\n plt.imshow(seeds2d, cmap=colormap, interpolation='none')\n"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
__get_slice
|
python
|
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
|
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L708-L735
| null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
__put_slice_in_slim
|
python
|
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
|
put one small slice as a tile in a big image
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L738-L754
| null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
show_slice
|
python
|
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
|
:param data2d:
:param contour2d:
:param seeds2d:
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L768-L821
|
[
"def sigmoid(x, x0, k):\n y = 1 / (1 + np.exp(-k*(x-x0)))\n return y\n"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
_import_data
|
python
|
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
|
import ndarray or SimpleITK data
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L845-L857
|
[
"def __select_slices(data, axis, slice_step, first_slice_offset=0):\n if data is None:\n return None\n\n inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)\n # import ipdb\n # ipdb.set_trace()\n # logger.warning(\"select slices\")\n\n if axis == 0:\n # data = data[first_slice_offset::slice_step, :, :]\n data = data[inds, :, :]\n if axis == 1:\n # data = data[:, first_slice_offset::slice_step, :]\n data = data[:, inds, :]\n if axis == 2:\n # data = data[:, :, first_slice_offset::slice_step]\n data = data[:, :, inds]\n return data\n"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
generate_data
|
python
|
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
|
Generating data
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1020-L1027
| null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
index_to_coords
|
python
|
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
|
convert index to coordinates given the shape
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1115-L1124
| null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
slices
|
python
|
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
|
create tiled image with multiple slices
:param img:
:param shape:
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1130-L1154
|
[
"def index_to_coords(index, shape):\n '''convert index to coordinates given the shape'''\n coords = []\n for i in xrange(1, len(shape)):\n divisor = int(np.product(shape[i:]))\n value = index // divisor\n coords.append(value)\n index -= value * divisor\n coords.append(index)\n return tuple(coords)\n"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
sed2
|
python
|
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1159-L1177
|
[
"def slices(img, shape=[3, 4]):\n \"\"\"\n create tiled image with multiple slices\n :param img:\n :param shape:\n :return:\n \"\"\"\n sh = np.asarray(shape)\n i_max = np.prod(sh)\n allimg = np.zeros(img.shape[-2:] * sh)\n\n for i in range(0, i_max):\n # i = 0\n islice = round((img.shape[0] / float(i_max)) * i)\n # print(islice)\n imgi = img[islice, :, :]\n coords = index_to_coords(i, sh)\n aic = np.asarray(img.shape[-2:]) * coords\n\n allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi\n\n # plt.imshow(imgi)\n # print(imgi.shape)\n # print(img.shape)\n return allimg\n"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
# import pdb
# pdb.set_trace();
try:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
try:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
except:
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
except:
logger.exception('PyQt4 not detected')
print('PyQt4 not detected')
# compatibility between python 2 and 3
if sys.version_info[0] >= 3:
xrange = range
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
"""
Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape of output tiled image. slice_step is
estimated if it is not set explicitly
:param first_slice_offset: set offset of first slice
:param first_slice_offset_to_see_seed_with_label: find offset to see slice with seed with defined label
:param slice_number: int, Number of showed slices. Overwrites shape and slice_step.
"""
if slice_number is not None:
slice_step = data3d.shape[axis] / slice_number
# odhad slice_step, neni li zadan
# slice_step estimation
# TODO make precise estimation (use np.linspace to indexing?)
if slice_step is None:
if shape is None:
slice_step = 1
else:
slice_step = ((data3d.shape[axis] - first_slice_offset ) / float(np.prod(shape)))
if first_slice_offset_to_see_seed_with_label is not None:
if seeds is not None:
inds = np.nonzero(seeds==first_slice_offset_to_see_seed_with_label)
# print(inds)
# take first one with defined seed
# ind = inds[axis][0]
# take most used index
ind = np.median(inds[axis])
first_slice_offset = ind % slice_step
data3d = _import_data(data3d, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
contour = _import_data(contour, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
seeds = _import_data(seeds, axis=axis, slice_step=slice_step, first_slice_offset=first_slice_offset)
number_of_slices = data3d.shape[axis]
# square image
# nn = int(math.ceil(number_of_slices ** 0.5))
# sh = [nn, nn]
# 4:3 image
meta_shape = shape
if meta_shape is None:
na = int(math.ceil(number_of_slices * 16.0 / 9.0) ** 0.5)
nb = int(math.ceil(float(number_of_slices) / na))
meta_shape = [nb, na]
dsh = __get_slice(data3d, 0, axis).shape
slimsh = [int(dsh[0] * meta_shape[0]), int(dsh[1] * meta_shape[1])]
slim = np.zeros(slimsh, dtype=data3d.dtype)
slco = None
slse = None
if seeds is not None:
slse = np.zeros(slimsh, dtype=seeds.dtype)
if contour is not None:
slco = np.zeros(slimsh, dtype=contour.dtype)
# slse =
# f, axarr = plt.subplots(sh[0], sh[1])
for i in range(0, number_of_slices):
cont = None
seeds2d = None
im2d = __get_slice(data3d, i, axis, flipH=flipH, flipV=flipV)
if contour is not None:
cont = __get_slice(contour, i, axis, flipH=flipH, flipV=flipV)
slco = __put_slice_in_slim(slco, cont, meta_shape, i)
if seeds is not None:
seeds2d = __get_slice(seeds, i, axis, flipH=flipH, flipV=flipV)
slse = __put_slice_in_slim(slse, seeds2d, meta_shape, i)
# plt.axis('off')
# plt.subplot(sh[0], sh[1], i+1)
# plt.subplots_adjust(wspace=0, hspace=0)
slim = __put_slice_in_slim(slim, im2d, meta_shape, i)
# show_slice(im2d, cont, seeds2d)
show_slice(slim, slco, slse)
if show:
plt.show()
# a, b = np.unravel_index(i, sh)
# pass
def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
data2d = data[:, slice_number, :]
elif axis == 2:
data2d = data[:, :, slice_number]
else:
logger.error("axis number error")
print("axis number error")
return None
if flipV:
if data2d is not None:
data2d = data2d[-1:0:-1,:]
if flipH:
if data2d is not None:
data2d = data2d[:, -1:0:-1]
return data2d
def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim
# def show():
# plt.show()
# \
#
# def close():
# plt.close()
def sigmoid(x, x0, k):
y = 1 / (1 + np.exp(-k*(x-x0)))
return y
def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(data2d, cmap='gray', interpolation='none')
if contour2d is not None:
plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
if seeds2d is not None:
# Show results
colormap = copy.copy(plt.cm.get_cmap('Paired'))
# colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
colormap._init()
colormap._lut[0, 3] = 0
tmp0 = copy.copy(colormap._lut[:,0])
tmp1 = copy.copy(colormap._lut[:,1])
tmp2 = copy.copy(colormap._lut[:,2])
colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
# seed 4
colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)
# seed 2
colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)
# my colors
# colormap._lut[1,:] = [.0,.1,.0,1]
# colormap._lut[2,:] = [.1,.1,.0,1]
# colormap._lut[3,:] = [.1,.1,.1,1]
# colormap._lut[4,:] = [.3,.3,.3,1]
plt.imshow(seeds2d, cmap=colormap, interpolation='none')
def __select_slices(data, axis, slice_step, first_slice_offset=0):
if data is None:
return None
inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)
# import ipdb
# ipdb.set_trace()
# logger.warning("select slices")
if axis == 0:
# data = data[first_slice_offset::slice_step, :, :]
data = data[inds, :, :]
if axis == 1:
# data = data[:, first_slice_offset::slice_step, :]
data = data[:, inds, :]
if axis == 2:
# data = data[:, :, first_slice_offset::slice_step]
data = data[:, :, inds]
return data
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return data
# self.rect.figure.canvas.draw()
# return data
try:
from PyQt4 import QtGui, QtCore
class sed3qt(QtGui.QDialog):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
QtGui.QDialog.__init__(self, parent)
# super(Window, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
return self.sed.show_fcn()
def get_values(self):
return self.sed
class sed3qtWidget(QtGui.QWidget):
def __init__(self, *pars, **params):
# def __init__(self,parent=None):
parent = None
# QtGui.QWidget.__init__(self, parent)
super(sed3qtWidget, self).__init__(parent)
# self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
# self.toolbar = NavigationToolbar(self.canvas, self)
# set the layout
layout = QtGui.QVBoxLayout()
# layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
# def set_params(self, *pars, **params):
# import sed3.sed3
params["figure"] = self.figure
self.sed = sed3(*pars, **params)
self.sed.sed3_on_close = self.callback_close
# ed.show()
self.output = None
def callback_close(self, sed):
self.output = sed
sed.prepare_output_data()
self.seeds = sed.seeds
self.close()
def show(self):
super(sed3qtWidget, self).show()
return self.sed.show_fcn()
def get_values(self):
return self.sed
except:
pass
# --------------------------tests-----------------------------
class Tests(unittest.TestCase):
def test_t(self):
pass
def setUp(self):
""" Nastavení společných proměnných pro testy """
datashape = [120, 85, 30]
self.datashape = datashape
self.rnddata = np.random.rand(datashape[0], datashape[1], datashape[2])
self.segmcube = np.zeros(datashape)
self.segmcube[30:70, 40:60, 5:15] = 1
self.ed = sed3(self.rnddata)
# ed.show()
# selected_seeds = ed.seeds
def test_same_size_input_and_output(self):
"""Funkce testuje stejnost vstupních a výstupních dat"""
# outputdata = vesselSegmentation(self.rnddata,self.segmcube)
self.assertEqual(self.ed.seeds.shape, self.rnddata.shape)
def test_set_seeds(self):
''' Testuje uložení do seedů '''
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
self.assertEqual(self.ed.seeds[10, 13, 3], val)
def test_prepare_overlay(self):
''' Testuje vytvoření rgba obrázku z labelů'''
overlay = self.ed.prepare_overlay(self.segmcube[:, :, 6])
onePixel = overlay[30, 40]
self.assertTrue(all(onePixel == [1, 0, 0, 1]))
def test_get_seed_sub(self):
""" Testuje, jestli funkce pro vracení dat funguje správně,
je to zkoušeno na konkrétních hodnotách
"""
val = 7
self.ed.set_seeds([10, 12, 13], [13, 13, 15], 3, value=val)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(val)
found = [False, False, False]
for i in range(len(seedsx)):
if (seedsx[i] == 10) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[0] = True
if (seedsx[i] == 12) & (seedsy[i] == 13) & (seedsz[i] == 3):
found[1] = True
if (seedsx[i] == 13) & (seedsy[i] == 15) & (seedsz[i] == 3):
found[2] = True
logger.debug(found)
self.assertTrue(all(found))
def test_get_seed_val(self):
""" Testuje, jestli jsou správně vraceny hodnoty pro označené pixely
je to zkoušeno na konkrétních hodnotách
"""
label = 7
self.ed.set_seeds([11], [14], 4, value=label)
seedsx, seedsy, seedsz = self.ed.get_seed_sub(label)
val = self.ed.get_seed_val(label)
expected_val = self.ed.img[11, 14, 4]
logger.debug(val)
logger.debug(expected_val)
self.assertIn(expected_val, val)
def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy
# --------------------------main------------------------------
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
# při vývoji si necháme vypisovat všechny hlášky
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
# output configureation
# logging.basicConfig(format='%(asctime)s %(message)s')
logging.basicConfig(format='%(message)s')
formatter = logging.Formatter(
"%(levelname)-5s [%(module)s:%(funcName)s:%(lineno)d] %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
logger.addHandler(ch)
# input parser
parser = argparse.ArgumentParser(
description='Segment vessels from liver. Try call sed3 -f lena')
parser.add_argument(
'-f', '--filename',
# default = '../jatra/main/step.mat',
default='lena',
help='*.mat file with variables "data", "segmentation" and "threshod"')
parser.add_argument(
'-d', '--debug', action='store_true',
help='run in debug mode')
parser.add_argument(
'-e3', '--example3d', action='store_true',
help='run with 3D example data')
parser.add_argument(
'-t', '--tests', action='store_true',
help='run unittest')
parser.add_argument(
'-o', '--outputfile', type=str,
default='output.mat', help='output file name')
args = parser.parse_args()
voxelsize = None
if args.debug:
logger.setLevel(logging.DEBUG)
if args.tests:
# hack for use argparse and unittest in one module
sys.argv[1:] = []
unittest.main()
if args.example3d:
data = generate_data([16, 20, 24])
voxelsize = [0.1, 1.2, 2.5]
elif args.filename == 'lena':
from scipy import misc
data = misc.lena()
else:
# load all
mat = scipy.io.loadmat(args.filename)
logger.debug(mat.keys())
# load specific variable
dataraw = scipy.io.loadmat(args.filename, variable_names=['data'])
data = dataraw['data']
# logger.debug(matthreshold['threshold'][0][0])
# zastavení chodu programu pro potřeby debugu,
# ovládá se klávesou's','c',...
# zakomentovat
# pdb.set_trace();
# zde by byl prostor pro ruční (interaktivní) zvolení prahu z
# klávesnice
# tě ebo jinak
pyed = sed3(data, voxelsize=voxelsize)
output = pyed.show()
scipy.io.savemat(args.outputfile, {'data': output})
pyed.get_seed_val(1)
def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
return tuple(coords)
sh = np.asarray([3, 4])
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / float(i_max)) * i)
# print(islice)
imgi = img[islice, :, :]
coords = index_to_coords(i, sh)
aic = np.asarray(img.shape[-2:]) * coords
allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi
# plt.imshow(imgi)
# print(imgi.shape)
# print(img.shape)
return allimg
# sz = img.shape
# np.zeros()
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
if contour is not None:
plt.contour(slices(contour, shape))
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.set_window
|
python
|
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
|
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L249-L263
| null |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.rotate_to_zaxis
|
python
|
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
|
rotate image to selected axis
:param new_zaxis:
:return:
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L297-L328
|
[
"def _rotate_start(self, data, zaxis):\n if data is not None:\n if zaxis == 0:\n tr =(1, 2, 0)\n data = np.transpose(data, tr)\n vs = self.actual_voxelsize\n if self.actual_voxelsize is not None:\n self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]\n elif zaxis == 1:\n tr = (2, 0, 1)\n data = np.transpose(data, tr)\n vs = self.actual_voxelsize\n if self.actual_voxelsize is not None:\n self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]\n elif zaxis == 2:\n # data = np.transpose(data, (0, 1, 2))\n pass\n else:\n print(\"problem with zaxis in _rotate_start()\")\n logger.warning(\"problem with zaxis in _rotate_start()\")\n\n return data\n",
"def _rotate_end(self, data, zaxis):\n if data is not None:\n if self.rotated_back is False:\n if zaxis == 0:\n tr = (2, 0, 1)\n data = np.transpose(data, tr)\n vs = self.actual_voxelsize\n if self.actual_voxelsize is not None:\n self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]\n elif zaxis == 1:\n tr = (1, 2, 0)\n data = np.transpose(data, tr)\n vs = self.actual_voxelsize\n if self.actual_voxelsize is not None:\n self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]\n elif zaxis == 2:\n pass\n else:\n print(\"problem with zaxis in _rotate_start()\")\n logger.warning(\"problem with zaxis in _rotate_start()\")\n\n else:\n print(\"There is a danger in calling show() twice\")\n logger.warning(\"There is a danger in calling show() twice\")\n\n return data\n",
"def update_slice(self):\n # TODO tohle je tu kvuli contour, neumim ji odstranit jinak\n self.ax.cla()\n\n self.draw_slice()\n"
] |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.__flip
|
python
|
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
|
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L386-L398
| null |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.on_scroll
|
python
|
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
|
mouse wheel is used for setting slider value
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L517-L523
|
[
"def next_slice(self):\n self.actual_slice = self.actual_slice + 1\n if self.actual_slice >= self.imgshape[2]:\n self.actual_slice = 0\n",
"def prev_slice(self):\n self.actual_slice = self.actual_slice - 1\n if self.actual_slice < 0:\n self.actual_slice = self.imgshape[2] - 1\n"
] |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.on_press
|
python
|
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
|
on but-ton press we will see if the mouse is over us and store data
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L529-L537
| null |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.on_motion
|
python
|
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
|
on motion we will move the rect if the mouse is over us
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L540-L551
| null |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.on_release
|
python
|
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
|
on release we reset the press data
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L553-L573
|
[
"def update_slice(self):\n # TODO tohle je tu kvuli contour, neumim ji odstranit jinak\n self.ax.cla()\n\n self.draw_slice()\n",
"def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],\n cursorsizemm=[1, 1, 1]):\n assert len(px) == len(\n py), 'px and py describes a point, their size must be same'\n\n for i, item in enumerate(px):\n self.seeds[int(item), int(py[i]), int(pz)] = value\n"
] |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
mjirik/sed3
|
sed3/sed3.py
|
sed3.get_seed_sub
|
python
|
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
|
Return list of all seeds with specific label
|
train
|
https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L595-L600
| null |
class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call show() function
sed3_on_close: callback function on close
ed = sed3(img)
ed.show()
selected_seeds = ed.seeds
"""
# if data.shape != segmentation.shape:
# raise Exception('Input size error','Shape if input data and segmentation
# must be same')
def __init__(
self, img, voxelsize=[1, 1, 1], initslice=0, colorbar=True,
cmap=matplotlib.cm.Greys_r, seeds=None, contour=None, zaxis=0,
mouse_button_map={1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
windowW=None, windowC=None, show=False, sed3_on_close=None, figure=None,
show_axis=False, flipV=False, flipH=False
):
"""
:param img:
:param voxelsize: size of voxel
:param initslice:
:param colorbar:
:param cmap:
:param seeds: define seeds
:param contour: contour
:param zaxis:
:param mouse_button_map:
:param windowW: window width
:param windowC: window center
:param show:
:param sed3_on_close:
:param figure:
:param show_axis:
:param flipH: horizontal flip
:param flipV: vertical flip
:return:
"""
self.sed3_on_close = sed3_on_close
self.show_fcn = plt.show
if figure is None:
self.fig = plt.figure()
else:
self.fig = figure
img = _import_data(img, axis=0, slice_step=1)
if len(img.shape) == 2:
imgtmp = img
img = np.zeros([1, imgtmp.shape[0], imgtmp.shape[1]])
# self.imgshape.append(1)
img[-1, :, :] = imgtmp
zaxis = 0
# pdb.set_trace();
self.voxelsize = voxelsize
self.actual_voxelsize = copy.copy(voxelsize)
# Rotate data in depndecy on zaxispyplot
img = self._rotate_start(img, zaxis)
seeds = self._rotate_start(seeds, zaxis)
contour = self._rotate_start(contour, zaxis)
self.rotated_back = False
self.zaxis = zaxis
# self.ax = self.fig.add_subplot(111)
self.imgshape = list(img.shape)
self.img = img
self.actual_slice = initslice
self.colorbar = colorbar
self.cmap = cmap
self.show_axis = show_axis
self.flipH = flipH
self.flipV = flipV
if seeds is None:
self.seeds = np.zeros(self.imgshape, np.int8)
else:
self.seeds = seeds
self.set_window(windowC, windowW)
""" Mapping mouse button to class number. Default is normal order"""
self.button_map = mouse_button_map
self.contour = contour
self.press = None
self.press2 = None
# language
self.texts = {'btn_delete': 'Delete', 'btn_close': 'Close',
'btn_view0': "v0", 'btn_view1': "v1", 'btn_view2': "v2"}
# iself.fig.subplots_adjust(left=0.25, bottom=0.25)
if self.show_axis:
self.ax = self.fig.add_axes([0.20, 0.25, 0.70, 0.70])
else:
self.ax = self.fig.add_axes([0.1, 0.20, 0.8, 0.75])
self.ax_colorbar = self.fig.add_axes([0.9, 0.30, 0.02, 0.6])
self.draw_slice()
if self.colorbar:
# self.colorbar_obj = self.fig.colorbar(self.imsh)
self.colorbar_obj = plt.colorbar(self.imsh, cax=self.ax_colorbar)
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
# user interface look
axcolor = 'lightgoldenrodyellow'
self.ax_actual_slice = self.fig.add_axes(
[0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.imgshape[2] - 1,
valinit=initslice)
immax = np.max(self.img)
immin = np.min(self.img)
# axcolor_front = 'darkslategray'
ax_window_c = self.fig.add_axes(
[0.5, 0.05, 0.2, 0.02], axisbg=axcolor)
self.window_c_slider = Slider(ax_window_c, 'Center',
immin,
immax,
valinit=float(self.windowC))
ax_window_w = self.fig.add_axes(
[0.5, 0.10, 0.2, 0.02], axisbg=axcolor)
self.window_w_slider = Slider(ax_window_w, 'Width',
0,
(immax - immin) * 2,
valinit=float(self.windowW))
# conenction to wheel events
self.fig.canvas.mpl_connect('scroll_event', self.on_scroll)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.window_c_slider.on_changed(self._on_window_c_change)
self.window_w_slider.on_changed(self._on_window_w_change)
# draw
self.fig.canvas.mpl_connect('button_press_event', self.on_press)
self.fig.canvas.mpl_connect('button_release_event', self.on_release)
self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
# delete seeds
self.ax_delete_seeds = self.fig.add_axes([0.05, 0.05, 0.1, 0.075])
self.btn_delete = Button(
self.ax_delete_seeds, self.texts['btn_delete'])
self.btn_delete.on_clicked(self.callback_delete)
# close button
self.ax_delete_seeds = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.btn_delete = Button(self.ax_delete_seeds, self.texts['btn_close'])
self.btn_delete.on_clicked(self.callback_close)
# im shape
# self.ax_shape = self.fig.add_axes([0.85, 0.05, 0.1, 0.075])
self.fig.text(0.20, 0.10, 'shape')
sh = self.img.shape
self.fig.text(0.20, 0.05, "%ix%ix%i" % (sh[0], sh[1], sh[2]))
self.draw_slice()
# view0
self.ax_v0= self.fig.add_axes([0.05, 0.80, 0.08, 0.075])
self.btn_v0 = Button(
self.ax_v0, self.texts['btn_view0'])
self.btn_v0.on_clicked(self._callback_v0)
# view1
self.ax_v1= self.fig.add_axes([0.05, 0.70, 0.08, 0.075])
self.btn_v1 = Button(
self.ax_v1, self.texts['btn_view1'])
self.btn_v1.on_clicked(self._callback_v1)
# view2
self.ax_v2= self.fig.add_axes([0.05, 0.60, 0.08, 0.075])
self.btn_v2 = Button(
self.ax_v2, self.texts['btn_view2'])
self.btn_v2.on_clicked(self._callback_v2)
if show:
self.show()
def _callback_v0(self, event):
self.rotate_to_zaxis(0)
def _callback_v1(self, event):
self.rotate_to_zaxis(1)
def _callback_v2(self, event):
self.rotate_to_zaxis(2)
def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np.max(self.img) + np.min(self.img)) / 2.0
self.imgmax = windowC + (windowW / 2)
self.imgmin = windowC - (windowW / 2)
self.windowC = windowC
self.windowW = windowW
# self.imgmax = np.max(self.img)
# self.imgmin = np.min(self.img)
# self.windowC = windowC
# self.windowW = windowW
# else:
# self.imgmax = windowC + (windowW / 2)
# self.imgmin = windowC - (windowW / 2)
# self.windowC = windowC
# self.windowW = windowW
def _on_window_w_change(self, windowW):
self.set_window(self.windowC, windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def _on_window_c_change(self, windowC):
self.set_window(windowC, self.windowW)
if self.colorbar:
try:
self.colorbar_obj.on_mappable_changed(self.imsh)
except:
traceback.print_exc()
logger.warning("with old matplotlib version does not work colorbar redraw")
self.update_slice()
def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zaxis)
# Rotate data in depndecy on zaxispyplot
self.img = self._rotate_start(img, new_zaxis)
self.seeds = self._rotate_start(seeds, new_zaxis)
self.contour = self._rotate_start(contour, new_zaxis)
self.zaxis = new_zaxis
# import ipdb
# ipdb.set_trace()
# self.actual_slice_slider.valmax = self.img.shape[2] - 1
self.actual_slice = 0
self.rotated_back = False
# update slicer
self.fig.delaxes(self.ax_actual_slice)
self.ax_actual_slice.cla()
del(self.actual_slice_slider)
self.fig.add_axes(self.ax_actual_slice)
self.actual_slice_slider = Slider(self.ax_actual_slice, 'Slice', 0,
self.img.shape[2] - 1,
valinit=0)
self.actual_slice_slider.on_changed(self.sliceslider_update)
self.update_slice()
def _rotate_start(self, data, zaxis):
if data is not None:
if zaxis == 0:
tr =(1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
# data = np.transpose(data, (0, 1, 2))
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
return data
def _rotate_end(self, data, zaxis):
if data is not None:
if self.rotated_back is False:
if zaxis == 0:
tr = (2, 0, 1)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 1:
tr = (1, 2, 0)
data = np.transpose(data, tr)
vs = self.actual_voxelsize
if self.actual_voxelsize is not None:
self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs[tr[2]]]
elif zaxis == 2:
pass
else:
print("problem with zaxis in _rotate_start()")
logger.warning("problem with zaxis in _rotate_start()")
else:
print("There is a danger in calling show() twice")
logger.warning("There is a danger in calling show() twice")
return data
def update_slice(self):
# TODO tohle je tu kvuli contour, neumim ji odstranit jinak
self.ax.cla()
self.draw_slice()
def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
return sliceimg
def draw_slice(self):
sliceimg = self.img[:, :, int(self.actual_slice)]
sliceimg = self.__flip(sliceimg)
self.imsh = self.ax.imshow(sliceimg, self.cmap, vmin=self.imgmin,
vmax=self.imgmax, interpolation='nearest')
# plt.hold(True)
# pdb.set_trace();
sliceseeds = self.seeds[:, :, int(self.actual_slice)]
sliceseeds = self.__flip(sliceseeds)
self.ax.imshow(self.prepare_overlay(
sliceseeds
), interpolation='nearest', vmin=self.imgmin, vmax=self.imgmax)
# vykreslení okraje
# X,Y = np.meshgrid(self.imgshape[0], self.imgshape[1])
if self.contour is not None:
try:
# exception catch problem with none object in image
# ctr =
slicecontour = self.contour[:, :, int(self.actual_slice)]
slicecontour = self.__flip(slicecontour)
self.ax.contour(
slicecontour, 1,
levels=[0.5, 1.5, 2.5],
linewidths=2)
except:
pass
# self.ax.set_axis_off()
# self.ax.set_axis_below(False)
self._ticklabels()
# print(ctr)
# import pdb; pdb.set_trace()
self.fig.canvas.draw()
# self.ax.cla()
# del(ctr)
# pdb.set_trace();
# plt.hold(False)
def _ticklabels(self):
if self.show_axis and self.actual_voxelsize is not None:
# pass
xmax = self.img.shape[0]
ymax = self.img.shape[1]
xmaxmm = xmax * self.actual_voxelsize[0]
ymaxmm = ymax * self.actual_voxelsize[1]
xmm = 10.0**np.floor(np.log10(xmaxmm))
ymm = 10.0**np.floor(np.log10(ymaxmm))
x = xmm * 1.0 / self.actual_voxelsize[0]
y = ymm * 1.0 / self.actual_voxelsize[1]
self.ax.set_xticks([0, x])
self.ax.set_xticklabels([0, xmm])
self.ax.set_yticks([0, y])
self.ax.set_yticklabels([0, ymm])
# self.ax.set_yticklabels([13,12])
else:
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
def next_slice(self):
self.actual_slice = self.actual_slice + 1
if self.actual_slice >= self.imgshape[2]:
self.actual_slice = 0
def prev_slice(self):
self.actual_slice = self.actual_slice - 1
if self.actual_slice < 0:
self.actual_slice = self.imgshape[2] - 1
def sliceslider_update(self, val):
# zaokrouhlení
# self.actual_slice_slider.set_val(round(self.actual_slice_slider.val))
self.actual_slice = round(val)
self.update_slice()
def prepare_overlay(self, seeds):
sh = list(seeds.shape)
if len(sh) == 2:
sh.append(4)
else:
sh[2] = 4
# assert sh[2] == 1, 'wrong overlay shape'
# sh[2] = 4
overlay = np.zeros(sh)
overlay[:, :, 0] = (seeds == 1)
overlay[:, :, 1] = (seeds == 2)
overlay[:, :, 2] = (seeds == 3)
overlay[:, :, 3] = (seeds > 0)
return overlay
def show(self):
""" Function run viewer window.
"""
self.show_fcn()
# plt.show()\
return self.prepare_output_data()
def prepare_output_data(self):
if self.rotated_back is False:
# Rotate data in depndecy on zaxis
self.img = self._rotate_end(self.img, self.zaxis)
self.seeds = self._rotate_end(self.seeds, self.zaxis)
self.contour = self._rotate_end(self.contour, self.zaxis)
self.rotated_back = True
return self.seeds
def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice)
# tim, ze dojde ke zmene slideru je show_slce volan z nej
# self.show_slice()
# print(self.actual_slice)
# malování -------------------
def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button
# self.press1 = True
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.append(event.ydata)
def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_slice()
def callback_delete(self, event):
self.seeds[:, :, int(self.actual_slice)] = 0
self.update_slice()
def callback_close(self, event):
matplotlib.pyplot.clf()
matplotlib.pyplot.close()
if self.sed3_on_close is not None:
self.sed3_on_close(self)
def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],
cursorsizemm=[1, 1, 1]):
assert len(px) == len(
py), 'px and py describes a point, their size must be same'
for i, item in enumerate(px):
self.seeds[int(item), int(py[i]), int(pz)] = value
# @todo
def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz
def get_seed_val(self, label):
""" Return data values for specific seed label"""
return self.img[self.seeds == label]
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
create_hlk_sw16_connection
|
python
|
async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None):
client = SW16Client(host, port=port,
disconnect_callback=disconnect_callback,
reconnect_callback=reconnect_callback,
loop=loop, logger=logger,
timeout=timeout, reconnect_interval=reconnect_interval)
await client.setup()
return client
|
Create HLK-SW16 Client class.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L292-L305
|
[
"async def setup(self):\n \"\"\"Set up the connection with automatic retry.\"\"\"\n while True:\n fut = self.loop.create_connection(\n lambda: SW16Protocol(\n self,\n disconnect_callback=self.handle_disconnect_callback,\n loop=self.loop, logger=self.logger),\n host=self.host,\n port=self.port)\n try:\n self.transport, self.protocol = \\\n await asyncio.wait_for(fut, timeout=self.timeout)\n except asyncio.TimeoutError:\n self.logger.warning(\"Could not connect due to timeout error.\")\n except OSError as exc:\n self.logger.warning(\"Could not connect due to error: %s\",\n str(exc))\n else:\n self.is_connected = True\n if self.reconnect_callback:\n self.reconnect_callback()\n break\n await asyncio.sleep(self.reconnect_interval)\n"
] |
"""HLK-SW16 Protocol Support."""
import asyncio
from collections import deque
import logging
import codecs
import binascii
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol._reset_timeout
|
python
|
def _reset_timeout(self):
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
|
Reset timeout for date keep alive.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol.reset_cmd_timeout
|
python
|
def reset_cmd_timeout(self):
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
|
Reset timeout for command execution.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L37-L42
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol._handle_lines
|
python
|
def _handle_lines(self):
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
|
Assemble incoming data into per-line packets.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L49-L59
|
[
"def _valid_packet(raw_packet):\n \"\"\"Validate incoming packet.\"\"\"\n if raw_packet[0:1] != b'\\xcc':\n return False\n if len(raw_packet) != 19:\n return False\n checksum = 0\n for i in range(1, 17):\n checksum += raw_packet[i]\n if checksum != raw_packet[18]:\n return False\n return True\n"
] |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol._valid_packet
|
python
|
def _valid_packet(raw_packet):
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
|
Validate incoming packet.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L62-L73
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol._handle_raw_packet
|
python
|
def _handle_raw_packet(self, raw_packet):
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
|
Parse incoming packet.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L75-L125
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol.send_packet
|
python
|
def send_packet(self):
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
|
Write next packet in send queue.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L127-L135
|
[
"def reset_cmd_timeout(self):\n \"\"\"Reset timeout for command execution.\"\"\"\n if self._cmd_timeout:\n self._cmd_timeout.cancel()\n self._cmd_timeout = self.loop.call_later(self.client.timeout,\n self.transport.close)\n"
] |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol.format_packet
|
python
|
def format_packet(command):
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
|
Format packet to be sent.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L138-L143
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Protocol.connection_lost
|
python
|
def connection_lost(self, exc):
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop)
|
Log when connection is closed, if needed call callback.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L145-L152
| null |
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.loop = loop
self.logger = logger
self._buffer = b''
self.disconnect_callback = disconnect_callback
self._timeout = None
self._cmd_timeout = None
def connection_made(self, transport):
"""Initialize protocol transport."""
self.transport = transport
self._reset_timeout()
def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close)
def data_received(self, data):
"""Add incoming data to buffer."""
self._buffer += data
self._handle_lines()
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
self.logger.warning('dropping invalid data: %s',
binascii.hexlify(line))
@staticmethod
def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
return True
def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
week = raw_packet[8]
self.logger.debug(
'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
'Minute: %s, Sec: %s, Week %s',
year, month, day, hour, minute, sec, week)
elif raw_packet[1:2] == b'\x0c':
states = {}
changes = []
for switch in range(0, 16):
if raw_packet[2+switch:3+switch] == b'\x01':
states[format(switch, 'x')] = True
if (self.client.states.get(format(switch, 'x'), None)
is not True):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = True
elif raw_packet[2+switch:3+switch] == b'\x02':
states[format(switch, 'x')] = False
if (self.client.states.get(format(switch, 'x'), None)
is not False):
changes.append(format(switch, 'x'))
self.client.states[format(switch, 'x')] = False
for switch in changes:
for status_cb in self.client.status_callbacks.get(switch, []):
status_cb(states[switch])
self.logger.debug(states)
if self.client.in_transaction:
self.client.in_transaction = False
self.client.active_packet = False
self.client.active_transaction.set_result(states)
while self.client.status_waiters:
waiter = self.client.status_waiters.popleft()
waiter.set_result(states)
if self.client.waiters:
self.send_packet()
else:
self._cmd_timeout.cancel()
elif self._cmd_timeout:
self._cmd_timeout.cancel()
else:
self.logger.warning('received unknown packet: %s',
binascii.hexlify(raw_packet))
def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
self.transport.write(packet)
@staticmethod
def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.setup
|
python
|
async def setup(self):
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
|
Set up the connection with automatic retry.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L188-L211
| null |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.stop
|
python
|
def stop(self):
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
|
Shut down transport.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L213-L218
| null |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.handle_disconnect_callback
|
python
|
async def handle_disconnect_callback(self):
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
|
Reconnect automatically unless stopping.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L220-L233
|
[
"async def setup(self):\n \"\"\"Set up the connection with automatic retry.\"\"\"\n while True:\n fut = self.loop.create_connection(\n lambda: SW16Protocol(\n self,\n disconnect_callback=self.handle_disconnect_callback,\n loop=self.loop, logger=self.logger),\n host=self.host,\n port=self.port)\n try:\n self.transport, self.protocol = \\\n await asyncio.wait_for(fut, timeout=self.timeout)\n except asyncio.TimeoutError:\n self.logger.warning(\"Could not connect due to timeout error.\")\n except OSError as exc:\n self.logger.warning(\"Could not connect due to error: %s\",\n str(exc))\n else:\n self.is_connected = True\n if self.reconnect_callback:\n self.reconnect_callback()\n break\n await asyncio.sleep(self.reconnect_interval)\n"
] |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.register_status_callback
|
python
|
def register_status_callback(self, callback, switch):
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
|
Register a callback which will fire when state changes.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L235-L239
| null |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client._send
|
python
|
def _send(self, packet):
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
|
Add packet to send queue.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L241-L247
| null |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.turn_on
|
python
|
async def turn_on(self, switch=None):
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
|
Turn on relay.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L249-L257
|
[
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.turn_off
|
python
|
async def turn_off(self, switch=None):
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
|
Turn off relay.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L259-L267
|
[
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
jameshilliard/hlk-sw16
|
hlk_sw16/protocol.py
|
SW16Client.status
|
python
|
async def status(self, switch=None):
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
packet = self.protocol.format_packet(b"\x1e")
states = await self._send(packet)
state = states[switch]
else:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
state = await fut
else:
packet = self.protocol.format_packet(b"\x1e")
state = await self._send(packet)
return state
|
Get current relay status.
|
train
|
https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L269-L289
|
[
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] |
class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
self.loop = loop
else:
self.loop = asyncio.get_event_loop()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger(__name__)
self.host = host
self.port = port
self.transport = None
self.protocol = None
self.is_connected = False
self.reconnect = True
self.timeout = timeout
self.reconnect_interval = reconnect_interval
self.disconnect_callback = disconnect_callback
self.reconnect_callback = reconnect_callback
self.waiters = deque()
self.status_waiters = deque()
self.in_transaction = False
self.active_transaction = None
self.active_packet = None
self.status_callbacks = {}
self.states = {}
async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval)
def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close()
async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_timeout()
if self.in_transaction:
self.protocol.transport.write(self.active_packet)
else:
packet = self.protocol.format_packet(b"\x1e")
self.protocol.transport.write(packet)
def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback)
def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut
async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(packet)
return states
async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(packet)
return states
|
bibanon/BASC-py4chan
|
basc_py4chan/util.py
|
clean_comment_body
|
python
|
def clean_comment_body(body):
body = _parser.unescape(body)
body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body)
body = body.replace('<br>', '\n')
body = re.sub(r'<.+?>', '', body)
return body
|
Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/util.py#L16-L26
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utility functions."""
import re
# HTML parser was renamed in python 3.x
try:
from html.parser import HTMLParser
except ImportError:
from HTMLParser import HTMLParser
_parser = HTMLParser()
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
get_boards
|
python
|
def get_boards(board_name_list, *args, **kwargs):
if isinstance(board_name_list, basestring):
board_name_list = board_name_list.split()
return [Board(name, *args, **kwargs) for name in board_name_list]
|
Given a list of boards, return :class:`basc_py4chan.Board` objects.
Args:
board_name_list (list): List of board names to get, eg: ['b', 'tg']
Returns:
dict of :class:`basc_py4chan.Board`: Requested boards.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L43-L54
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from . import __version__
from .thread import Thread
from .url import Url
# cached metadata for boards
_metadata = {}
# compatibility layer for Python2's `basestring` variable
# http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/
try:
unicode = unicode
except NameError:
# 'unicode' is undefined, must be Python 3
str = str
unicode = str
bytes = bytes
basestring = str, bytes
else:
# 'unicode' exists, must be Python 2
str = str
unicode = unicode
bytes = str
basestring = basestring
def _fetch_boards_metadata(url_generator):
if not _metadata:
resp = requests.get(url_generator.board_list())
resp.raise_for_status()
data = {entry['board']: entry for entry in resp.json()['boards']}
_metadata.update(data)
def _get_board_metadata(url_generator, board, key):
_fetch_boards_metadata(url_generator)
return _metadata[board][key]
def get_all_boards(*args, **kwargs):
"""Returns every board on 4chan.
Returns:
dict of :class:`basc_py4chan.Board`: All boards.
"""
# Use https based on how the Board class instances are to be instantiated
https = kwargs.get('https', args[1] if len(args) > 1 else False)
# Dummy URL generator, only used to generate the board list which doesn't
# require a valid board name
url_generator = Url(None, https)
_fetch_boards_metadata(url_generator)
return get_boards(_metadata.keys(), *args, **kwargs)
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
board = Board
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
get_all_boards
|
python
|
def get_all_boards(*args, **kwargs):
# Use https based on how the Board class instances are to be instantiated
https = kwargs.get('https', args[1] if len(args) > 1 else False)
# Dummy URL generator, only used to generate the board list which doesn't
# require a valid board name
url_generator = Url(None, https)
_fetch_boards_metadata(url_generator)
return get_boards(_metadata.keys(), *args, **kwargs)
|
Returns every board on 4chan.
Returns:
dict of :class:`basc_py4chan.Board`: All boards.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L57-L70
|
[
"def get_boards(board_name_list, *args, **kwargs):\n \"\"\"Given a list of boards, return :class:`basc_py4chan.Board` objects.\n\n Args:\n board_name_list (list): List of board names to get, eg: ['b', 'tg']\n\n Returns:\n dict of :class:`basc_py4chan.Board`: Requested boards.\n \"\"\"\n if isinstance(board_name_list, basestring):\n board_name_list = board_name_list.split()\n return [Board(name, *args, **kwargs) for name in board_name_list]\n",
"def _fetch_boards_metadata(url_generator):\n if not _metadata:\n resp = requests.get(url_generator.board_list())\n resp.raise_for_status()\n data = {entry['board']: entry for entry in resp.json()['boards']}\n _metadata.update(data)\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from . import __version__
from .thread import Thread
from .url import Url
# cached metadata for boards
_metadata = {}
# compatibility layer for Python2's `basestring` variable
# http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/
try:
unicode = unicode
except NameError:
# 'unicode' is undefined, must be Python 3
str = str
unicode = str
bytes = bytes
basestring = str, bytes
else:
# 'unicode' exists, must be Python 2
str = str
unicode = unicode
bytes = str
basestring = basestring
def _fetch_boards_metadata(url_generator):
if not _metadata:
resp = requests.get(url_generator.board_list())
resp.raise_for_status()
data = {entry['board']: entry for entry in resp.json()['boards']}
_metadata.update(data)
def _get_board_metadata(url_generator, board, key):
_fetch_boards_metadata(url_generator)
return _metadata[board][key]
def get_boards(board_name_list, *args, **kwargs):
"""Given a list of boards, return :class:`basc_py4chan.Board` objects.
Args:
board_name_list (list): List of board names to get, eg: ['b', 'tg']
Returns:
dict of :class:`basc_py4chan.Board`: Requested boards.
"""
if isinstance(board_name_list, basestring):
board_name_list = board_name_list.split()
return [Board(name, *args, **kwargs) for name in board_name_list]
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
board = Board
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.get_thread
|
python
|
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
|
Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L110-L143
|
[
"def _from_request(cls, board, res, id):\n if res.status_code == 404:\n return None\n\n res.raise_for_status()\n\n return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])\n",
"def thread_api_url(self, thread_id):\n return self.URL['api']['thread'].format(\n board=self._board_name,\n thread_id=thread_id\n )\n"
] |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.thread_exists
|
python
|
def thread_exists(self, thread_id):
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
|
Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L145-L158
| null |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.get_threads
|
python
|
def get_threads(self, page=1):
url = self._url.page_url(page)
return self._request_threads(url)
|
Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L192-L208
|
[
"def _request_threads(self, url):\n json = self._get_json(url)\n\n if url == self._url.catalog():\n thread_list = self._catalog_to_threads(json)\n else:\n thread_list = json['threads']\n\n threads = []\n for thread_json in thread_list:\n id = thread_json['posts'][0]['no']\n if id in self._thread_cache:\n thread = self._thread_cache[id]\n thread.want_update = True\n else:\n thread = Thread._from_json(thread_json, self)\n self._thread_cache[thread.id] = thread\n\n threads.append(thread)\n\n return threads\n",
"def page_url(self, page):\n return self.URL['api']['board'].format(\n board=self._board_name,\n page=page\n )\n"
] |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.get_all_thread_ids
|
python
|
def get_all_thread_ids(self):
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
|
Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L210-L217
|
[
"def _get_json(self, url):\n res = self._requests_session.get(url)\n res.raise_for_status()\n return res.json()\n",
"def thread_list(self):\n return self.URL['listing']['thread_list'].format(\n board=self._board_name\n )\n"
] |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.get_all_threads
|
python
|
def get_all_threads(self, expand=False):
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
|
Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L219-L243
|
[
"def _request_threads(self, url):\n json = self._get_json(url)\n\n if url == self._url.catalog():\n thread_list = self._catalog_to_threads(json)\n else:\n thread_list = json['threads']\n\n threads = []\n for thread_json in thread_list:\n id = thread_json['posts'][0]['no']\n if id in self._thread_cache:\n thread = self._thread_cache[id]\n thread.want_update = True\n else:\n thread = Thread._from_json(thread_json, self)\n self._thread_cache[thread.id] = thread\n\n threads.append(thread)\n\n return threads\n",
"def get_all_thread_ids(self):\n \"\"\"Return the ID of every thread on this board.\n\n Returns:\n list of ints: List of IDs of every thread on this board.\n \"\"\"\n json = self._get_json(self._url.thread_list())\n return [thread['no'] for page in json for thread in page['threads']]\n"
] |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
basc_py4chan/board.py
|
Board.refresh_cache
|
python
|
def refresh_cache(self, if_want_update=False):
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update()
|
Update all threads currently stored in our cache.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L245-L251
| null |
class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is worksafe.
page_count (int): How many pages this board has.
threads_per_page (int): How many threads there are on each page.
"""
def __init__(self, board_name, https=False, session=None):
"""Creates a :mod:`basc_py4chan.Board` object.
Args:
board_name (string): Name of the board, such as "tg" or "etc".
https (bool): Whether to use a secure connection to 4chan.
session: Existing requests.session object to use instead of our current one.
"""
self._board_name = board_name
self._https = https
self._protocol = 'https://' if https else 'http://'
self._url = Url(board_name=board_name, https=self._https)
self._requests_session = session or requests.session()
self._requests_session.headers['User-Agent'] = 'py-4chan/%s' % __version__
self._thread_cache = {}
def _get_metadata(self, key):
return _get_board_metadata(self._url, self._board_name, key)
def _get_json(self, url):
res = self._requests_session.get(url)
res.raise_for_status()
return res.json()
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thread`: Thread object
"""
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._requests_session.get(
self._url.thread_api_url(
thread_id = thread_id
)
)
# check if thread exists
if raise_404:
res.raise_for_status()
elif not res.ok:
return None
thread = Thread._from_request(self, res, thread_id)
self._thread_cache[thread_id] = thread
return thread
def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok
def _catalog_to_threads(self, json):
threads_json = [thread for page in json for thread in page['threads']]
thread_list = [{'posts': [thread] + thread.get('last_replies', [])}
for thread in threads_json]
for thread in thread_list:
thread['posts'][0].pop('last_replies', None)
return thread_list
def _request_threads(self, url):
json = self._get_json(url)
if url == self._url.catalog():
thread_list = self._catalog_to_threads(json)
else:
thread_list = json['threads']
threads = []
for thread_json in thread_list:
id = thread_json['posts'][0]['no']
if id in self._thread_cache:
thread = self._thread_cache[id]
thread.want_update = True
else:
thread = Thread._from_json(thread_json, self)
self._thread_cache[thread.id] = thread
threads.append(thread)
return threads
def get_threads(self, page=1):
"""Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
Args:
page (int): Page to request threads for. Defaults to the first page.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing the threads on the given page.
"""
url = self._url.page_url(page)
return self._request_threads(url)
def get_all_thread_ids(self):
"""Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board.
"""
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']]
def get_all_threads(self, expand=False):
"""Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usage.
If expanded, all data of all threads is returned with no omitted posts.
Args:
expand (bool): Whether to download every single post of every thread.
If enabled, this option can be very slow and bandwidth-intensive.
Returns:
list of :mod:`basc_py4chan.Thread`: List of Thread objects representing every thread on this board.
"""
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads)
def clear_cache(self):
"""Remove everything currently stored in our cache."""
self._thread_cache.clear()
@property
def name(self):
return self._board_name
@property
def title(self):
return self._get_metadata('title')
@property
def is_worksafe(self):
if self._get_metadata('ws_board'):
return True
return False
@property
def page_count(self):
return self._get_metadata('pages')
@property
def threads_per_page(self):
return self._get_metadata('per_page')
@property
def https(self):
return self._https
def __repr__(self):
return '<Board /%s/>' % self.name
|
bibanon/BASC-py4chan
|
examples/example6-download-thread.py
|
download_file
|
python
|
def download_file(local_filename, url, clobber=False):
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', local_filename, url)
return False
# write out in 1MB chunks
chunk_size_in_bytes = 1024*1024 # 1MB
with open(local_filename, 'wb') as local_file:
for chunk in i.iter_content(chunk_size=chunk_size_in_bytes):
local_file.write(chunk)
return True
|
Download the given file. Clobber overwrites file if exists.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/examples/example6-download-thread.py#L14-L33
|
[
"def mkdirs(path):\n \"\"\"Make directory, if it doesn't exist.\"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n"
] |
# example6-download-thread.py - download json and all full-size images from a thread
from __future__ import print_function
import basc_py4chan
import sys
import os
import requests
import json
def mkdirs(path):
"""Make directory, if it doesn't exist."""
if not os.path.exists(path):
os.makedirs(path)
def download_json(local_filename, url, clobber=False):
"""Download the given JSON file, and pretty-print before we output it."""
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Quick and dirty 4chan Archiver")
print("%s - Save the JSON and all images for an 4chan post." % (sys.argv[0]))
print("\tUsage: %s <board> <thread_id>" % (sys.argv[0]))
sys.exit(1)
board_name = sys.argv[1]
thread_id = sys.argv[2]
# grab the first thread on the board by checking first page
board = basc_py4chan.Board(board_name)
thread = board.get_thread(thread_id)
# create folders according to chan.arc standard
path = os.path.join(os.getcwd(), "4chan", board_name, thread_id)
images_path = os.path.join(path, "images")
mkdirs(images_path)
# archive the thread JSON
url_builder = basc_py4chan.Url(board_name)
json_url = url_builder.thread_api_url(thread_id)
print(url_builder.thread_api_url(thread_id))
download_json(os.path.join(path, "%s.json" % thread_id), json_url)
# record the url of every file on the first thread, even extra files in posts
for img in thread.file_objects():
print("Downloading %s..." % img.file_url)
download_file(os.path.join(images_path, "%s" % img.filename), img.file_url)
if __name__ == '__main__':
main()
|
bibanon/BASC-py4chan
|
examples/example6-download-thread.py
|
download_json
|
python
|
def download_json(local_filename, url, clobber=False):
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))
|
Download the given JSON file, and pretty-print before we output it.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/examples/example6-download-thread.py#L35-L38
| null |
# example6-download-thread.py - download json and all full-size images from a thread
from __future__ import print_function
import basc_py4chan
import sys
import os
import requests
import json
def mkdirs(path):
"""Make directory, if it doesn't exist."""
if not os.path.exists(path):
os.makedirs(path)
def download_file(local_filename, url, clobber=False):
"""Download the given file. Clobber overwrites file if exists."""
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', local_filename, url)
return False
# write out in 1MB chunks
chunk_size_in_bytes = 1024*1024 # 1MB
with open(local_filename, 'wb') as local_file:
for chunk in i.iter_content(chunk_size=chunk_size_in_bytes):
local_file.write(chunk)
return True
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Quick and dirty 4chan Archiver")
print("%s - Save the JSON and all images for an 4chan post." % (sys.argv[0]))
print("\tUsage: %s <board> <thread_id>" % (sys.argv[0]))
sys.exit(1)
board_name = sys.argv[1]
thread_id = sys.argv[2]
# grab the first thread on the board by checking first page
board = basc_py4chan.Board(board_name)
thread = board.get_thread(thread_id)
# create folders according to chan.arc standard
path = os.path.join(os.getcwd(), "4chan", board_name, thread_id)
images_path = os.path.join(path, "images")
mkdirs(images_path)
# archive the thread JSON
url_builder = basc_py4chan.Url(board_name)
json_url = url_builder.thread_api_url(thread_id)
print(url_builder.thread_api_url(thread_id))
download_json(os.path.join(path, "%s.json" % thread_id), json_url)
# record the url of every file on the first thread, even extra files in posts
for img in thread.file_objects():
print("Downloading %s..." % img.file_url)
download_file(os.path.join(images_path, "%s" % img.filename), img.file_url)
if __name__ == '__main__':
main()
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.files
|
python
|
def files(self):
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
|
Returns the URLs of all files attached to posts in the thread.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L105-L111
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
def file_objects(self):
"""Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
def update(self, force=False):
"""Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
"""
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.thumbs
|
python
|
def thumbs(self):
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
|
Returns the URLs of all thumbnails in the thread.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L113-L119
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
def file_objects(self):
"""Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
def update(self, force=False):
"""Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
"""
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.filenames
|
python
|
def filenames(self):
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
|
Returns the filenames of all files attached to posts in the thread.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L121-L127
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
def file_objects(self):
"""Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
def update(self, force=False):
"""Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
"""
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.thumbnames
|
python
|
def thumbnames(self):
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
|
Returns the filenames of all thumbnails in the thread.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L129-L135
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
def file_objects(self):
"""Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
def update(self, force=False):
"""Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
"""
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.file_objects
|
python
|
def file_objects(self):
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
|
Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L137-L143
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
def update(self, force=False):
"""Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
"""
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
bibanon/BASC-py4chan
|
basc_py4chan/thread.py
|
Thread.update
|
python
|
def update(self, force=False):
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection errors, just return 0 and try again later
try:
res = self._board._requests_session.get(self._api_url, headers=headers)
except:
# try again later
return 0
# 304 Not Modified, no new posts.
if res.status_code == 304:
return 0
# 404 Not Found, thread died.
elif res.status_code == 404:
self.is_404 = True
# remove post from cache, because it's gone.
self._board._thread_cache.pop(self.id, None)
return 0
elif res.status_code == 200:
# If we somehow 404'ed, we should put ourself back in the cache.
if self.is_404:
self.is_404 = False
self._board._thread_cache[self.id] = self
# Remove
self.want_update = False
self.omitted_images = 0
self.omitted_posts = 0
self._last_modified = res.headers['Last-Modified']
posts = res.json()['posts']
original_post_count = len(self.replies)
self.topic = Post(self, posts[0])
if self.last_reply_id and not force:
self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id)
else:
self.replies[:] = [Post(self, p) for p in posts[1:]]
new_post_count = len(self.replies)
post_count_delta = new_post_count - original_post_count
if not post_count_delta:
return 0
self.last_reply_id = self.replies[-1].post_number
return post_count_delta
else:
res.raise_for_status()
|
Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched.
|
train
|
https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L145-L214
| null |
class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit.
imagelimit (bool): Whether the thread has hit the image limit.
custom_spoiler (int): Number of custom spoilers in the thread (if the board supports it)
topic (:class:`basc_py4chan.Post`): Topic post of the thread, the OP.
posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP.
all_posts (list of :class:`basc_py4chan.Post`): List of all posts in the thread, including the OP and any omitted posts.
url (string): URL of the thread, not including semantic slug.
semantic_url (string): URL of the thread, with the semantic slug.
semantic_slug (string): The 'pretty URL slug' assigned to this thread by 4chan.
"""
def __init__(self, board, id):
self._board = board
self._url = Url(board_name=board.name, https=board.https) # 4chan URL generator
self.id = self.number = self.num = self.no = id
self.topic = None
self.replies = []
self.is_404 = False
self.last_reply_id = 0
self.omitted_posts = 0
self.omitted_images = 0
self.want_update = False
self._last_modified = None
def __len__(self):
return self.num_replies
@property
def _api_url(self):
return self._url.thread_api_url(self.id)
@property
def closed(self):
return self.topic._data.get('closed') == 1
@property
def sticky(self):
return self.topic._data.get('sticky') == 1
@property
def archived(self):
return self.topic._data.get('archived') == 1
@property
def imagelimit(self):
return self.topic._data.get('imagelimit') == 1
@property
def bumplimit(self):
return self.topic._data.get('bumplimit') == 1
@property
def custom_spoiler(self):
return self.topic._data.get('custom_spoiler', 0)
@classmethod
def _from_request(cls, board, res, id):
if res.status_code == 404:
return None
res.raise_for_status()
return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])
@classmethod
def _from_json(cls, json, board, id=None, last_modified=None):
t = cls(board, id)
t._last_modified = last_modified
posts = json['posts']
head, rest = posts[0], posts[1:]
t.topic = t.op = Post(t, head)
t.replies.extend(Post(t, p) for p in rest)
t.id = head.get('no', id)
t.num_replies = head['replies']
t.num_images = head['images']
t.omitted_images = head.get('omitted_images', 0)
t.omitted_posts = head.get('omitted_posts', 0)
if id is not None:
if not t.replies:
t.last_reply_id = t.topic.post_number
else:
t.last_reply_id = t.replies[-1].post_number
else:
t.want_update = True
return t
def files(self):
"""Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname
def file_objects(self):
"""Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread."""
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file
def expand(self):
"""If there are omitted posts, update to include all posts."""
if self.omitted_posts > 0:
self.update()
@property
def posts(self):
return [self.topic] + self.replies
@property
def all_posts(self):
self.expand()
return self.posts
@property
def https(self):
return self._board._https
@property
def url(self):
return self._url.thread_url(self.id)
@property
def semantic_url(self):
return '%s/%s' % (self.url, self.semantic_slug)
@property
def semantic_slug(self):
return self.topic.semantic_slug
def __repr__(self):
extra = ''
if self.omitted_images or self.omitted_posts:
extra = ', %i omitted images, %i omitted posts' % (
self.omitted_images, self.omitted_posts
)
return '<Thread /%s/%i, %i replies%s>' % (
self._board.name, self.id, len(self.replies), extra
)
|
hfaran/progressive
|
progressive/examples.py
|
simple
|
python
|
def simple():
MAX_VALUE = 100
# Create our test progress bar
bar = Bar(max_value=MAX_VALUE, fallback=True)
bar.cursor.clear_lines(2)
# Before beginning to draw our bars, we save the position
# of our cursor so we can restore back to this position before writing
# the next time.
bar.cursor.save()
for i in range(MAX_VALUE + 1):
sleep(0.1 * random.random())
# We restore the cursor to saved position before writing
bar.cursor.restore()
# Now we draw the bar
bar.draw(value=i)
|
Simple example using just the Bar class
This example is intended to show usage of the Bar class at the lowest
level.
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/examples.py#L16-L37
|
[
"def draw(self, value, newline=True, flush=True):\n \"\"\"Draw the progress bar\n\n :type value: int\n :param value: Progress value relative to ``self.max_value``\n :type newline: bool\n :param newline: If this is set, a newline will be written after drawing\n \"\"\"\n # This is essentially winch-handling without having\n # to do winch-handling; cleanly redrawing on winch is difficult\n # and out of the intended scope of this class; we *can*\n # however, adjust the next draw to be proper by re-measuring\n # the terminal since the code is mostly written dynamically\n # and many attributes and dynamically calculated properties.\n self._measure_terminal()\n\n # To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0\n amount_complete = 1.0 if self.max_value == 0 else value / self.max_value\n fill_amount = int(floor(amount_complete * self.max_width))\n empty_amount = self.max_width - fill_amount\n\n # e.g., '10/20' if 'fraction' or '50%' if 'percentage'\n amount_complete_str = (\n u\"{}/{}\".format(value, self.max_value)\n if self._num_rep == \"fraction\" else\n u\"{}%\".format(int(floor(amount_complete * 100)))\n )\n\n # Write title if supposed to be above\n if self._title_pos == \"above\":\n title_str = u\"{}{}\\n\".format(\n \" \" * self._indent,\n self.title,\n )\n self._write(title_str, ignore_overflow=True)\n\n # Construct just the progress bar\n bar_str = u''.join([\n u(self.filled(self._filled_char * fill_amount)),\n u(self.empty(self._empty_char * empty_amount)),\n ])\n # Wrap with start and end character\n bar_str = u\"{}{}{}\".format(self.start_char, bar_str, self.end_char)\n # Add on title if supposed to be on left or right\n if self._title_pos == \"left\":\n bar_str = u\"{} {}\".format(self.title, bar_str)\n elif self._title_pos == \"right\":\n bar_str = u\"{} {}\".format(bar_str, self.title)\n # Add indent\n bar_str = u''.join([\" \" * self._indent, bar_str])\n # Add complete percentage or fraction\n bar_str = u\"{} {}\".format(bar_str, amount_complete_str)\n # Set back to normal after printing\n bar_str = u\"{}{}\".format(bar_str, self.term.normal)\n # Finally, write the completed bar_str\n self._write(bar_str, s_length=self.full_line_width)\n\n # Write title if supposed to be below\n if self._title_pos == \"below\":\n title_str = u\"\\n{}{}\".format(\n \" \" * self._indent,\n self.title,\n )\n self._write(title_str, ignore_overflow=True)\n\n # Newline to wrap up\n if newline:\n self.cursor.newline()\n if flush:\n self.cursor.flush()\n"
] |
# -*- coding: utf-8 -*-
"""Examples
Usage:
`python -c "from progressive.examples import *; tree()"` as an example
"""
import random
from time import sleep
from blessings import Terminal
from progressive.bar import Bar
from progressive.tree import ProgressTree, Value, BarDescriptor
def tree():
"""Example showing tree progress view"""
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(max_value=10))
test_d = {
"Warp Jump": {
"1) Prepare fuel": {
"Load Tanks": {
"Tank 1": BarDescriptor(value=leaf_values[0], **bd_defaults),
"Tank 2": BarDescriptor(value=leaf_values[1], **bd_defaults),
},
"Refine tylium ore": BarDescriptor(
value=leaf_values[2], **bd_defaults
),
},
"2) Calculate jump co-ordinates": {
"Resolve common name to co-ordinates": {
"Querying resolution from baseship": BarDescriptor(
value=leaf_values[3], **bd_defaults
),
},
},
"3) Perform jump": {
"Check FTL drive readiness": BarDescriptor(
value=leaf_values[4], **bd_defaults
),
"Juuuuuump!": BarDescriptor(value=leaf_values[5],
**bd_defaults)
}
}
}
# We'll use this function to bump up the leaf values
def incr_value(obj):
for val in leaf_values:
if val.value < 10:
val.value += 1
break
# And this to check if we're to stop drawing
def are_we_done(obj):
return all(val.value == 10 for val in leaf_values)
###################
# The actual code #
###################
# Create blessings.Terminal instance
t = Terminal()
# Initialize a ProgressTree instance
n = ProgressTree(term=t)
# We'll use the make_room method to make sure the terminal
# is filled out with all the room we need
n.make_room(test_d)
while not are_we_done(test_d):
sleep(0.2 * random.random())
# After the cursor position is first saved (in the first draw call)
# this will restore the cursor back to the top so we can draw again
n.cursor.restore()
# We use our incr_value method to bump the fake numbers
incr_value(test_d)
# Actually draw out the bars
n.draw(test_d, BarDescriptor(bd_defaults))
|
hfaran/progressive
|
progressive/examples.py
|
tree
|
python
|
def tree():
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(max_value=10))
test_d = {
"Warp Jump": {
"1) Prepare fuel": {
"Load Tanks": {
"Tank 1": BarDescriptor(value=leaf_values[0], **bd_defaults),
"Tank 2": BarDescriptor(value=leaf_values[1], **bd_defaults),
},
"Refine tylium ore": BarDescriptor(
value=leaf_values[2], **bd_defaults
),
},
"2) Calculate jump co-ordinates": {
"Resolve common name to co-ordinates": {
"Querying resolution from baseship": BarDescriptor(
value=leaf_values[3], **bd_defaults
),
},
},
"3) Perform jump": {
"Check FTL drive readiness": BarDescriptor(
value=leaf_values[4], **bd_defaults
),
"Juuuuuump!": BarDescriptor(value=leaf_values[5],
**bd_defaults)
}
}
}
# We'll use this function to bump up the leaf values
def incr_value(obj):
for val in leaf_values:
if val.value < 10:
val.value += 1
break
# And this to check if we're to stop drawing
def are_we_done(obj):
return all(val.value == 10 for val in leaf_values)
###################
# The actual code #
###################
# Create blessings.Terminal instance
t = Terminal()
# Initialize a ProgressTree instance
n = ProgressTree(term=t)
# We'll use the make_room method to make sure the terminal
# is filled out with all the room we need
n.make_room(test_d)
while not are_we_done(test_d):
sleep(0.2 * random.random())
# After the cursor position is first saved (in the first draw call)
# this will restore the cursor back to the top so we can draw again
n.cursor.restore()
# We use our incr_value method to bump the fake numbers
incr_value(test_d)
# Actually draw out the bars
n.draw(test_d, BarDescriptor(bd_defaults))
|
Example showing tree progress view
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/examples.py#L40-L111
|
[
"def restore(self):\n \"\"\"Restores cursor to the previously saved location\n\n Cursor position will only be restored IF it was previously saved\n by this instance (and not by any external force)\n \"\"\"\n if self._saved:\n self.write(self.term.restore)\n",
"def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):\n \"\"\"Draw ``tree`` to the terminal\n\n :type tree: dict\n :param tree: ``tree`` should be a tree representing a hierarchy; each\n key should be a string describing that hierarchy level and value\n should also be ``dict`` except for leaves which should be\n ``BarDescriptors``. See ``BarDescriptor`` for a tree example.\n :type bar_desc: BarDescriptor|NoneType\n :param bar_desc: For describing non-leaf bars in that will be\n drawn from ``tree``; certain attributes such as ``value``\n and ``kwargs[\"max_value\"]`` will of course be overridden\n if provided.\n :type flush: bool\n :param flush: If this is set, output written will be flushed\n :type save_cursor: bool\n :param save_cursor: If this is set, cursor location will be saved before\n drawing; this will OVERWRITE a previous save, so be sure to set\n this accordingly (to your needs).\n \"\"\"\n if save_cursor:\n self.cursor.save()\n\n tree = deepcopy(tree)\n # TODO: Automatically collapse hierarchy so something\n # will always be displayable (well, unless the top-level)\n # contains too many to display\n lines_required = self.lines_required(tree)\n ensure(lines_required <= self.cursor.term.height,\n LengthOverflowError,\n \"Terminal is not long ({} rows) enough to fit all bars \"\n \"({} rows).\".format(self.cursor.term.height, lines_required))\n bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc\n self._calculate_values(tree, bar_desc)\n self._draw(tree)\n if flush:\n self.cursor.flush()\n",
"def make_room(self, tree):\n \"\"\"Clear lines in terminal below current cursor position as required\n\n This is important to do before drawing to ensure sufficient\n room at the bottom of your terminal.\n\n :type tree: dict\n :param tree: tree as described in ``BarDescriptor``\n \"\"\"\n lines_req = self.lines_required(tree)\n self.cursor.clear_lines(lines_req)\n",
"def incr_value(obj):\n for val in leaf_values:\n if val.value < 10:\n val.value += 1\n break\n",
"def are_we_done(obj):\n return all(val.value == 10 for val in leaf_values)\n"
] |
# -*- coding: utf-8 -*-
"""Examples
Usage:
`python -c "from progressive.examples import *; tree()"` as an example
"""
import random
from time import sleep
from blessings import Terminal
from progressive.bar import Bar
from progressive.tree import ProgressTree, Value, BarDescriptor
def simple():
"""Simple example using just the Bar class
This example is intended to show usage of the Bar class at the lowest
level.
"""
MAX_VALUE = 100
# Create our test progress bar
bar = Bar(max_value=MAX_VALUE, fallback=True)
bar.cursor.clear_lines(2)
# Before beginning to draw our bars, we save the position
# of our cursor so we can restore back to this position before writing
# the next time.
bar.cursor.save()
for i in range(MAX_VALUE + 1):
sleep(0.1 * random.random())
# We restore the cursor to saved position before writing
bar.cursor.restore()
# Now we draw the bar
bar.draw(value=i)
|
hfaran/progressive
|
progressive/tree.py
|
ProgressTree.draw
|
python
|
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ensure(lines_required <= self.cursor.term.height,
LengthOverflowError,
"Terminal is not long ({} rows) enough to fit all bars "
"({} rows).".format(self.cursor.term.height, lines_required))
bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc
self._calculate_values(tree, bar_desc)
self._draw(tree)
if flush:
self.cursor.flush()
|
Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``BarDescriptor`` for a tree example.
:type bar_desc: BarDescriptor|NoneType
:param bar_desc: For describing non-leaf bars in that will be
drawn from ``tree``; certain attributes such as ``value``
and ``kwargs["max_value"]`` will of course be overridden
if provided.
:type flush: bool
:param flush: If this is set, output written will be flushed
:type save_cursor: bool
:param save_cursor: If this is set, cursor location will be saved before
drawing; this will OVERWRITE a previous save, so be sure to set
this accordingly (to your needs).
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L73-L109
|
[
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n",
"def save(self):\n \"\"\"Saves current cursor position, so that it can be restored later\"\"\"\n self.write(self.term.save)\n self._saved = True\n",
"def flush(self):\n \"\"\"Flush buffer of terminal output stream\"\"\"\n self._stream.flush()\n",
"def lines_required(self, tree, count=0):\n \"\"\"Calculate number of lines required to draw ``tree``\"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n return sum(self.lines_required(v, count=count)\n for v in tree.values()) + 2\n elif isinstance(tree, BarDescriptor):\n if tree.get(\"kwargs\", {}).get(\"title_pos\") in [\"left\", \"right\"]:\n return 1\n else:\n return 2\n",
"def _calculate_values(self, tree, bar_d):\n \"\"\"Calculate values for drawing bars of non-leafs in ``tree``\n\n Recurses through ``tree``, replaces ``dict``s with\n ``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use\n the ``BarDescriptor``s to draw the tree\n \"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n # Calculate value and max_value\n max_val = 0\n value = 0\n for k in tree:\n # Get descriptor by recursing\n bar_desc = self._calculate_values(tree[k], bar_d)\n # Reassign to tuple of (new descriptor, tree below)\n tree[k] = (bar_desc, tree[k])\n value += bar_desc[\"value\"].value\n max_val += bar_desc.get(\"kwargs\", {}).get(\"max_value\", 100)\n # Merge in values from ``bar_d`` before returning descriptor\n kwargs = merge_dicts(\n [bar_d.get(\"kwargs\", {}),\n dict(max_value=max_val)],\n deepcopy=True\n )\n ret_d = merge_dicts(\n [bar_d,\n dict(value=Value(floor(value)), kwargs=kwargs)],\n deepcopy=True\n )\n return BarDescriptor(ret_d)\n elif isinstance(tree, BarDescriptor):\n return tree\n else:\n raise TypeError(\"Unexpected type {}\".format(type(tree)))\n",
"def _draw(self, tree, indent=0):\n \"\"\"Recurse through ``tree`` and draw all nodes\"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n for k, v in sorted(tree.items()):\n bar_desc, subdict = v[0], v[1]\n\n args = [self.cursor.term] + bar_desc.get(\"args\", [])\n kwargs = dict(title_pos=\"above\", indent=indent, title=k)\n kwargs.update(bar_desc.get(\"kwargs\", {}))\n\n b = Bar(*args, **kwargs)\n b.draw(value=bar_desc[\"value\"].value, flush=False)\n\n self._draw(subdict, indent=indent + self.indent)\n"
] |
class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between each level in hierarchy
"""
def __init__(self, term=None, indent=4):
self.cursor = Cursor(term)
self.indent = indent
##################
# Public Methods #
##################
def make_room(self, tree):
"""Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor``
"""
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req)
def lines_required(self, tree, count=0):
"""Calculate number of lines required to draw ``tree``"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ["left", "right"]:
return 1
else:
return 2
###################
# Private Methods #
###################
def _calculate_values(self, tree, bar_d):
"""Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree
"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(tree[k], bar_d)
# Reassign to tuple of (new descriptor, tree below)
tree[k] = (bar_desc, tree[k])
value += bar_desc["value"].value
max_val += bar_desc.get("kwargs", {}).get("max_value", 100)
# Merge in values from ``bar_d`` before returning descriptor
kwargs = merge_dicts(
[bar_d.get("kwargs", {}),
dict(max_value=max_val)],
deepcopy=True
)
ret_d = merge_dicts(
[bar_d,
dict(value=Value(floor(value)), kwargs=kwargs)],
deepcopy=True
)
return BarDescriptor(ret_d)
elif isinstance(tree, BarDescriptor):
return tree
else:
raise TypeError("Unexpected type {}".format(type(tree)))
def _draw(self, tree, indent=0):
"""Recurse through ``tree`` and draw all nodes"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", indent=indent, title=k)
kwargs.update(bar_desc.get("kwargs", {}))
b = Bar(*args, **kwargs)
b.draw(value=bar_desc["value"].value, flush=False)
self._draw(subdict, indent=indent + self.indent)
|
hfaran/progressive
|
progressive/tree.py
|
ProgressTree.make_room
|
python
|
def make_room(self, tree):
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req)
|
Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor``
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L111-L121
|
[
"def clear_lines(self, num_lines=0):\n for i in range(num_lines):\n self.write(self.term.clear_eol)\n self.write(self.term.move_down)\n for i in range(num_lines):\n self.write(self.term.move_up)\n",
"def lines_required(self, tree, count=0):\n \"\"\"Calculate number of lines required to draw ``tree``\"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n return sum(self.lines_required(v, count=count)\n for v in tree.values()) + 2\n elif isinstance(tree, BarDescriptor):\n if tree.get(\"kwargs\", {}).get(\"title_pos\") in [\"left\", \"right\"]:\n return 1\n else:\n return 2\n"
] |
class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between each level in hierarchy
"""
def __init__(self, term=None, indent=4):
self.cursor = Cursor(term)
self.indent = indent
##################
# Public Methods #
##################
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``BarDescriptor`` for a tree example.
:type bar_desc: BarDescriptor|NoneType
:param bar_desc: For describing non-leaf bars in that will be
drawn from ``tree``; certain attributes such as ``value``
and ``kwargs["max_value"]`` will of course be overridden
if provided.
:type flush: bool
:param flush: If this is set, output written will be flushed
:type save_cursor: bool
:param save_cursor: If this is set, cursor location will be saved before
drawing; this will OVERWRITE a previous save, so be sure to set
this accordingly (to your needs).
"""
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ensure(lines_required <= self.cursor.term.height,
LengthOverflowError,
"Terminal is not long ({} rows) enough to fit all bars "
"({} rows).".format(self.cursor.term.height, lines_required))
bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc
self._calculate_values(tree, bar_desc)
self._draw(tree)
if flush:
self.cursor.flush()
def lines_required(self, tree, count=0):
"""Calculate number of lines required to draw ``tree``"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ["left", "right"]:
return 1
else:
return 2
###################
# Private Methods #
###################
def _calculate_values(self, tree, bar_d):
"""Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree
"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(tree[k], bar_d)
# Reassign to tuple of (new descriptor, tree below)
tree[k] = (bar_desc, tree[k])
value += bar_desc["value"].value
max_val += bar_desc.get("kwargs", {}).get("max_value", 100)
# Merge in values from ``bar_d`` before returning descriptor
kwargs = merge_dicts(
[bar_d.get("kwargs", {}),
dict(max_value=max_val)],
deepcopy=True
)
ret_d = merge_dicts(
[bar_d,
dict(value=Value(floor(value)), kwargs=kwargs)],
deepcopy=True
)
return BarDescriptor(ret_d)
elif isinstance(tree, BarDescriptor):
return tree
else:
raise TypeError("Unexpected type {}".format(type(tree)))
def _draw(self, tree, indent=0):
"""Recurse through ``tree`` and draw all nodes"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", indent=indent, title=k)
kwargs.update(bar_desc.get("kwargs", {}))
b = Bar(*args, **kwargs)
b.draw(value=bar_desc["value"].value, flush=False)
self._draw(subdict, indent=indent + self.indent)
|
hfaran/progressive
|
progressive/tree.py
|
ProgressTree.lines_required
|
python
|
def lines_required(self, tree, count=0):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ["left", "right"]:
return 1
else:
return 2
|
Calculate number of lines required to draw ``tree``
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L123-L135
| null |
class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between each level in hierarchy
"""
def __init__(self, term=None, indent=4):
self.cursor = Cursor(term)
self.indent = indent
##################
# Public Methods #
##################
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``BarDescriptor`` for a tree example.
:type bar_desc: BarDescriptor|NoneType
:param bar_desc: For describing non-leaf bars in that will be
drawn from ``tree``; certain attributes such as ``value``
and ``kwargs["max_value"]`` will of course be overridden
if provided.
:type flush: bool
:param flush: If this is set, output written will be flushed
:type save_cursor: bool
:param save_cursor: If this is set, cursor location will be saved before
drawing; this will OVERWRITE a previous save, so be sure to set
this accordingly (to your needs).
"""
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ensure(lines_required <= self.cursor.term.height,
LengthOverflowError,
"Terminal is not long ({} rows) enough to fit all bars "
"({} rows).".format(self.cursor.term.height, lines_required))
bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc
self._calculate_values(tree, bar_desc)
self._draw(tree)
if flush:
self.cursor.flush()
def make_room(self, tree):
"""Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor``
"""
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req)
###################
# Private Methods #
###################
def _calculate_values(self, tree, bar_d):
"""Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree
"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(tree[k], bar_d)
# Reassign to tuple of (new descriptor, tree below)
tree[k] = (bar_desc, tree[k])
value += bar_desc["value"].value
max_val += bar_desc.get("kwargs", {}).get("max_value", 100)
# Merge in values from ``bar_d`` before returning descriptor
kwargs = merge_dicts(
[bar_d.get("kwargs", {}),
dict(max_value=max_val)],
deepcopy=True
)
ret_d = merge_dicts(
[bar_d,
dict(value=Value(floor(value)), kwargs=kwargs)],
deepcopy=True
)
return BarDescriptor(ret_d)
elif isinstance(tree, BarDescriptor):
return tree
else:
raise TypeError("Unexpected type {}".format(type(tree)))
def _draw(self, tree, indent=0):
"""Recurse through ``tree`` and draw all nodes"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", indent=indent, title=k)
kwargs.update(bar_desc.get("kwargs", {}))
b = Bar(*args, **kwargs)
b.draw(value=bar_desc["value"].value, flush=False)
self._draw(subdict, indent=indent + self.indent)
|
hfaran/progressive
|
progressive/tree.py
|
ProgressTree._calculate_values
|
python
|
def _calculate_values(self, tree, bar_d):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(tree[k], bar_d)
# Reassign to tuple of (new descriptor, tree below)
tree[k] = (bar_desc, tree[k])
value += bar_desc["value"].value
max_val += bar_desc.get("kwargs", {}).get("max_value", 100)
# Merge in values from ``bar_d`` before returning descriptor
kwargs = merge_dicts(
[bar_d.get("kwargs", {}),
dict(max_value=max_val)],
deepcopy=True
)
ret_d = merge_dicts(
[bar_d,
dict(value=Value(floor(value)), kwargs=kwargs)],
deepcopy=True
)
return BarDescriptor(ret_d)
elif isinstance(tree, BarDescriptor):
return tree
else:
raise TypeError("Unexpected type {}".format(type(tree)))
|
Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L141-L177
|
[
"def floor(x):\n \"\"\"Returns the floor of ``x``\n :returns: floor of ``x``\n :rtype: int\n \"\"\"\n return int(math.floor(x))\n",
"def merge_dicts(dicts, deepcopy=False):\n \"\"\"Merges dicts\n\n In case of key conflicts, the value kept will be from the latter\n dictionary in the list of dictionaries\n\n :param dicts: [dict, ...]\n :param deepcopy: deepcopy items within dicts\n \"\"\"\n assert isinstance(dicts, list) and all(isinstance(d, dict) for d in dicts)\n return dict(chain(*[copy.deepcopy(d).items() if deepcopy else d.items()\n for d in dicts]))\n",
"def _calculate_values(self, tree, bar_d):\n \"\"\"Calculate values for drawing bars of non-leafs in ``tree``\n\n Recurses through ``tree``, replaces ``dict``s with\n ``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use\n the ``BarDescriptor``s to draw the tree\n \"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n # Calculate value and max_value\n max_val = 0\n value = 0\n for k in tree:\n # Get descriptor by recursing\n bar_desc = self._calculate_values(tree[k], bar_d)\n # Reassign to tuple of (new descriptor, tree below)\n tree[k] = (bar_desc, tree[k])\n value += bar_desc[\"value\"].value\n max_val += bar_desc.get(\"kwargs\", {}).get(\"max_value\", 100)\n # Merge in values from ``bar_d`` before returning descriptor\n kwargs = merge_dicts(\n [bar_d.get(\"kwargs\", {}),\n dict(max_value=max_val)],\n deepcopy=True\n )\n ret_d = merge_dicts(\n [bar_d,\n dict(value=Value(floor(value)), kwargs=kwargs)],\n deepcopy=True\n )\n return BarDescriptor(ret_d)\n elif isinstance(tree, BarDescriptor):\n return tree\n else:\n raise TypeError(\"Unexpected type {}\".format(type(tree)))\n"
] |
class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between each level in hierarchy
"""
def __init__(self, term=None, indent=4):
self.cursor = Cursor(term)
self.indent = indent
##################
# Public Methods #
##################
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``BarDescriptor`` for a tree example.
:type bar_desc: BarDescriptor|NoneType
:param bar_desc: For describing non-leaf bars in that will be
drawn from ``tree``; certain attributes such as ``value``
and ``kwargs["max_value"]`` will of course be overridden
if provided.
:type flush: bool
:param flush: If this is set, output written will be flushed
:type save_cursor: bool
:param save_cursor: If this is set, cursor location will be saved before
drawing; this will OVERWRITE a previous save, so be sure to set
this accordingly (to your needs).
"""
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ensure(lines_required <= self.cursor.term.height,
LengthOverflowError,
"Terminal is not long ({} rows) enough to fit all bars "
"({} rows).".format(self.cursor.term.height, lines_required))
bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc
self._calculate_values(tree, bar_desc)
self._draw(tree)
if flush:
self.cursor.flush()
def make_room(self, tree):
"""Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor``
"""
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req)
def lines_required(self, tree, count=0):
"""Calculate number of lines required to draw ``tree``"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ["left", "right"]:
return 1
else:
return 2
###################
# Private Methods #
###################
def _draw(self, tree, indent=0):
"""Recurse through ``tree`` and draw all nodes"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", indent=indent, title=k)
kwargs.update(bar_desc.get("kwargs", {}))
b = Bar(*args, **kwargs)
b.draw(value=bar_desc["value"].value, flush=False)
self._draw(subdict, indent=indent + self.indent)
|
hfaran/progressive
|
progressive/tree.py
|
ProgressTree._draw
|
python
|
def _draw(self, tree, indent=0):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwargs = dict(title_pos="above", indent=indent, title=k)
kwargs.update(bar_desc.get("kwargs", {}))
b = Bar(*args, **kwargs)
b.draw(value=bar_desc["value"].value, flush=False)
self._draw(subdict, indent=indent + self.indent)
|
Recurse through ``tree`` and draw all nodes
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L179-L195
|
[
"def draw(self, value, newline=True, flush=True):\n \"\"\"Draw the progress bar\n\n :type value: int\n :param value: Progress value relative to ``self.max_value``\n :type newline: bool\n :param newline: If this is set, a newline will be written after drawing\n \"\"\"\n # This is essentially winch-handling without having\n # to do winch-handling; cleanly redrawing on winch is difficult\n # and out of the intended scope of this class; we *can*\n # however, adjust the next draw to be proper by re-measuring\n # the terminal since the code is mostly written dynamically\n # and many attributes and dynamically calculated properties.\n self._measure_terminal()\n\n # To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0\n amount_complete = 1.0 if self.max_value == 0 else value / self.max_value\n fill_amount = int(floor(amount_complete * self.max_width))\n empty_amount = self.max_width - fill_amount\n\n # e.g., '10/20' if 'fraction' or '50%' if 'percentage'\n amount_complete_str = (\n u\"{}/{}\".format(value, self.max_value)\n if self._num_rep == \"fraction\" else\n u\"{}%\".format(int(floor(amount_complete * 100)))\n )\n\n # Write title if supposed to be above\n if self._title_pos == \"above\":\n title_str = u\"{}{}\\n\".format(\n \" \" * self._indent,\n self.title,\n )\n self._write(title_str, ignore_overflow=True)\n\n # Construct just the progress bar\n bar_str = u''.join([\n u(self.filled(self._filled_char * fill_amount)),\n u(self.empty(self._empty_char * empty_amount)),\n ])\n # Wrap with start and end character\n bar_str = u\"{}{}{}\".format(self.start_char, bar_str, self.end_char)\n # Add on title if supposed to be on left or right\n if self._title_pos == \"left\":\n bar_str = u\"{} {}\".format(self.title, bar_str)\n elif self._title_pos == \"right\":\n bar_str = u\"{} {}\".format(bar_str, self.title)\n # Add indent\n bar_str = u''.join([\" \" * self._indent, bar_str])\n # Add complete percentage or fraction\n bar_str = u\"{} {}\".format(bar_str, amount_complete_str)\n # Set back to normal after printing\n bar_str = u\"{}{}\".format(bar_str, self.term.normal)\n # Finally, write the completed bar_str\n self._write(bar_str, s_length=self.full_line_width)\n\n # Write title if supposed to be below\n if self._title_pos == \"below\":\n title_str = u\"\\n{}{}\".format(\n \" \" * self._indent,\n self.title,\n )\n self._write(title_str, ignore_overflow=True)\n\n # Newline to wrap up\n if newline:\n self.cursor.newline()\n if flush:\n self.cursor.flush()\n",
"def _draw(self, tree, indent=0):\n \"\"\"Recurse through ``tree`` and draw all nodes\"\"\"\n if all([\n isinstance(tree, dict),\n type(tree) != BarDescriptor\n ]):\n for k, v in sorted(tree.items()):\n bar_desc, subdict = v[0], v[1]\n\n args = [self.cursor.term] + bar_desc.get(\"args\", [])\n kwargs = dict(title_pos=\"above\", indent=indent, title=k)\n kwargs.update(bar_desc.get(\"kwargs\", {}))\n\n b = Bar(*args, **kwargs)\n b.draw(value=bar_desc[\"value\"].value, flush=False)\n\n self._draw(subdict, indent=indent + self.indent)\n"
] |
class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between each level in hierarchy
"""
def __init__(self, term=None, indent=4):
self.cursor = Cursor(term)
self.indent = indent
##################
# Public Methods #
##################
def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
"""Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``BarDescriptor`` for a tree example.
:type bar_desc: BarDescriptor|NoneType
:param bar_desc: For describing non-leaf bars in that will be
drawn from ``tree``; certain attributes such as ``value``
and ``kwargs["max_value"]`` will of course be overridden
if provided.
:type flush: bool
:param flush: If this is set, output written will be flushed
:type save_cursor: bool
:param save_cursor: If this is set, cursor location will be saved before
drawing; this will OVERWRITE a previous save, so be sure to set
this accordingly (to your needs).
"""
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to display
lines_required = self.lines_required(tree)
ensure(lines_required <= self.cursor.term.height,
LengthOverflowError,
"Terminal is not long ({} rows) enough to fit all bars "
"({} rows).".format(self.cursor.term.height, lines_required))
bar_desc = BarDescriptor(type=Bar) if not bar_desc else bar_desc
self._calculate_values(tree, bar_desc)
self._draw(tree)
if flush:
self.cursor.flush()
def make_room(self, tree):
"""Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor``
"""
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req)
def lines_required(self, tree, count=0):
"""Calculate number of lines required to draw ``tree``"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tree.get("kwargs", {}).get("title_pos") in ["left", "right"]:
return 1
else:
return 2
###################
# Private Methods #
###################
def _calculate_values(self, tree, bar_d):
"""Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree
"""
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
bar_desc = self._calculate_values(tree[k], bar_d)
# Reassign to tuple of (new descriptor, tree below)
tree[k] = (bar_desc, tree[k])
value += bar_desc["value"].value
max_val += bar_desc.get("kwargs", {}).get("max_value", 100)
# Merge in values from ``bar_d`` before returning descriptor
kwargs = merge_dicts(
[bar_d.get("kwargs", {}),
dict(max_value=max_val)],
deepcopy=True
)
ret_d = merge_dicts(
[bar_d,
dict(value=Value(floor(value)), kwargs=kwargs)],
deepcopy=True
)
return BarDescriptor(ret_d)
elif isinstance(tree, BarDescriptor):
return tree
else:
raise TypeError("Unexpected type {}".format(type(tree)))
|
hfaran/progressive
|
progressive/util.py
|
merge_dicts
|
python
|
def merge_dicts(dicts, deepcopy=False):
assert isinstance(dicts, list) and all(isinstance(d, dict) for d in dicts)
return dict(chain(*[copy.deepcopy(d).items() if deepcopy else d.items()
for d in dicts]))
|
Merges dicts
In case of key conflicts, the value kept will be from the latter
dictionary in the list of dictionaries
:param dicts: [dict, ...]
:param deepcopy: deepcopy items within dicts
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/util.py#L34-L45
| null |
import math
import copy
from itertools import chain
def floor(x):
"""Returns the floor of ``x``
:returns: floor of ``x``
:rtype: int
"""
return int(math.floor(x))
def ensure(expr, exc, *args, **kwargs):
"""
:raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``
"""
if not expr:
raise exc(*args, **kwargs)
def u(s):
"""Cast ``s`` as unicode string
This is a convenience function to make up for the fact
that Python3 does not have a unicode() cast (for obvious reasons)
:rtype: unicode
:returns: Equivalent of unicode(s) (at least I hope so)
"""
return u'{}'.format(s)
|
hfaran/progressive
|
progressive/bar.py
|
Bar.max_width
|
python
|
def max_width(self):
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
|
Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L144-L166
|
[
"def floor(x):\n \"\"\"Returns the floor of ``x``\n :returns: floor of ``x``\n :rtype: int\n \"\"\"\n return int(math.floor(x))\n",
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
@property
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
"""
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
@staticmethod
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
"""
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
"""Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
"""
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/bar.py
|
Bar.full_line_width
|
python
|
def full_line_width(self):
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
|
Find actual length of bar_str
e.g., Progress [ | ] 10/10
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L169-L184
| null |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
@property
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
"""
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
@staticmethod
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
"""
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
"""Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
"""
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/bar.py
|
Bar._supports_colors
|
python
|
def _supports_colors(term, raise_err, colors):
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
|
Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L243-L270
|
[
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
@property
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
@staticmethod
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
"""
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
"""Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
"""
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/bar.py
|
Bar._get_format_callable
|
python
|
def _get_format_callable(term, color, back_color):
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
|
Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L273-L301
|
[
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
@property
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
"""
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
@staticmethod
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
"""Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
"""
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/bar.py
|
Bar._write
|
python
|
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
|
Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L309-L333
|
[
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
@property
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
"""
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
@staticmethod
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
"""
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/bar.py
|
Bar.draw
|
python
|
def draw(self, value, newline=True, flush=True):
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L339-L408
|
[
"def u(s):\n \"\"\"Cast ``s`` as unicode string\n\n This is a convenience function to make up for the fact\n that Python3 does not have a unicode() cast (for obvious reasons)\n\n :rtype: unicode\n :returns: Equivalent of unicode(s) (at least I hope so)\n \"\"\"\n return u'{}'.format(s)\n",
"def floor(x):\n \"\"\"Returns the floor of ``x``\n :returns: floor of ``x``\n :rtype: int\n \"\"\"\n return int(math.floor(x))\n",
"def _measure_terminal(self):\n self.lines, self.columns = (\n self.term.height or 24,\n self.term.width or 80\n )\n",
"def _write(self, s, s_length=None, flush=False, ignore_overflow=False,\n err_msg=None):\n \"\"\"Write ``s``\n\n :type s: str|unicode\n :param s: String to write\n :param s_length: Custom length of ``s``\n :param flush: Set this to flush the terminal stream after writing\n :param ignore_overflow: Set this to ignore if s will exceed\n the terminal's width\n :param err_msg: The error message given to WidthOverflowError\n if it is triggered\n \"\"\"\n if not ignore_overflow:\n s_length = len(s) if s_length is None else s_length\n if err_msg is None:\n err_msg = (\n \"Terminal has {} columns; attempted to write \"\n \"a string {} of length {}.\".format(\n self.columns, repr(s), s_length)\n )\n ensure(s_length <= self.columns, WidthOverflowError, err_msg)\n self.cursor.write(s)\n if flush:\n self.cursor.flush()\n"
] |
class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github.com/erikrose/nose-progressive/blob/master/noseprogressive/bar.py>`_
Terminal with 256 colors is recommended. See
`this <http://pastelinux.wordpress.com/2010/12/01/upgrading-linux-terminal-to-256-colors/>`_ for Ubuntu
installation as an example.
:type term: blessings.Terminal|NoneType
:param term: blessings.Terminal instance for the terminal of display
:type max_value: int
:param max_value: The capacity of the bar, i.e., ``value/max_value``
:type width: str
:param width: Must be of format {num: int}{unit: c|%}. Unit "c"
can be used to specify number of maximum columns; unit "%".
to specify percentage of the total terminal width to use.
e.g., "20c", "25%", etc.
:type title_pos: str
:param title_pos: Position of title relative to the progress bar;
can be any one of ["left", "right", "above", "below"]
:type title: str
:param title: Title of the progress bar
:type num_rep: str
:param num_rep: Numeric representation of completion;
can be one of ["fraction", "percentage"]
:type indent: int
:param indent: Spaces to indent the bar from the left-hand side
:type filled_color: str|int
:param filled_color: color of the ``filled_char``; can be a string
of the color's name or number representing the color; see the
``blessings`` documentation for details
:type empty_color: str|int
:param empty_color: color of the ``empty_char``
:type back_color: str|NoneType
:param back_color: Background color of the progress bar; must be
a string of the color name, unused if numbers used for
``filled_color`` and ``empty_color``. If set to None,
will not be used.
:type filled_char: unicode
:param filled_char: Character representing completeness on the
progress bar
:type empty_char: unicode
:param empty_char: The complement to ``filled_char``
:type start_char: unicode
:param start_char: Character at the start of the progress bar
:type end_char: unicode
:param end_char: Character at the end of the progress bar
:type fallback: bool
:param fallback: If this is set, if the terminal does not support
provided colors, this will fall back to plain formatting
that works on terminals with no color support, using the
provided ``fallback_empty_char` and ``fallback_filled_char``
:type force_color: bool|NoneType
:param force_color: ``True`` forces color to be used even if it
may not be supported by the terminal; ``False`` forces use of
the fallback formatting; ``None`` does not force anything
and allows automatic detection as usual.
"""
def __init__(
self, term=None, max_value=100, width="25%", title_pos="left",
title="Progress", num_rep="fraction", indent=0, filled_color=2,
empty_color=7, back_color=None, filled_char=u' ',
empty_char=u' ', start_char=u'', end_char=u'', fallback=True,
fallback_empty_char=u'◯', fallback_filled_char=u'◉',
force_color=None
):
self.cursor = Cursor(term)
self.term = self.cursor.term
self._measure_terminal()
self._width_str = width
self._max_value = max_value
ensure(title_pos in ["left", "right", "above", "below"], ValueError,
"Invalid choice for title position.")
self._title_pos = title_pos
self._title = title
ensure(num_rep in ["fraction", "percentage"], ValueError,
"num_rep must be either 'fraction' or 'percentage'.")
self._num_rep = num_rep
ensure(indent < self.columns, ValueError,
"Indent must be smaller than terminal width.")
self._indent = indent
self._start_char = start_char
self._end_char = end_char
# Setup callables and characters depending on if terminal has
# has color support
if force_color is not None:
supports_colors = force_color
else:
supports_colors = self._supports_colors(
term=self.term,
raise_err=not fallback,
colors=(filled_color, empty_color)
)
if supports_colors:
self._filled_char = filled_char
self._empty_char = empty_char
self._filled = self._get_format_callable(
term=self.term,
color=filled_color,
back_color=back_color
)
self._empty = self._get_format_callable(
term=self.term,
color=empty_color,
back_color=back_color
)
else:
self._empty_char = fallback_empty_char
self._filled_char = fallback_filled_char
self._filled = self._empty = lambda s: s
ensure(self.full_line_width <= self.columns, WidthOverflowError,
"Attempting to initialize Bar with full_line_width {}; "
"terminal has width of only {}.".format(
self.full_line_width,
self.columns))
######################
# Public Attributes #
######################
@property
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} columns, cannot draw "
"bar of size {}.".format(self.columns, value))
retval = value
else: # unit == "%"
ensure(0 < value <= 100, ValueError,
"value=={} does not satisfy 0 < value <= 100".format(value))
dec = value / 100
retval = dec * self.columns
return floor(retval)
@property
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
1, # Space between end_char and amount_complete_str
len(str(self.max_value)) * 2 + 1 # 100/100
])
return bar_str_len
@property
def filled(self):
"""Callable for drawing filled portion of progress bar
:rtype: callable
"""
return self._filled
@property
def empty(self):
"""Callable for drawing empty portion of progress bar
:rtype: callable
"""
return self._empty
@property
def max_value(self):
"""The capacity of the bar, i.e., ``value/max_value``"""
return self._max_value
@max_value.setter
def max_value(self, val):
self._max_value = val
@property
def title(self):
"""Title of the progress bar"""
return self._title
@title.setter
def title(self, t):
self._title = t
@property
def start_char(self):
"""Character at the start of the progress bar"""
return self._start_char
@start_char.setter
def start_char(self, c):
self._start_char = c
@property
def end_char(self):
"""Character at the end of the progress bar"""
return self._end_char
@end_char.setter
def end_char(self, c):
self._end_char = c
###################
# Private Methods #
###################
@staticmethod
def _supports_colors(term, raise_err, colors):
"""Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support rather than raising ColorUnsupportedError
:type colors: [str, ...]
"""
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
elif isinstance(color, int):
ensure(term.number_of_colors >= color,
ColorUnsupportedError,
"{} is unsupported by your terminal.".format(color))
except ColorUnsupportedError as e:
if raise_err:
raise e
else:
return False
else:
return True
@staticmethod
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:returns: callable(s: str) -> str
"""
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
return getattr(term, "_".join(
[color, "on", back_color]
))
elif back_color is None:
return getattr(term, color)
elif isinstance(color, int):
return term.on_color(color)
else:
raise TypeError("Invalid type {} for color".format(
type(color)
))
def _measure_terminal(self):
self.lines, self.columns = (
self.term.height or 24,
self.term.width or 80
)
def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
"""Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_msg: The error message given to WidthOverflowError
if it is triggered
"""
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to write "
"a string {} of length {}.".format(
self.columns, repr(s), s_length)
)
ensure(s_length <= self.columns, WidthOverflowError, err_msg)
self.cursor.write(s)
if flush:
self.cursor.flush()
##################
# Public Methods #
##################
def draw(self, value, newline=True, flush=True):
"""Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing
"""
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
# the terminal since the code is mostly written dynamically
# and many attributes and dynamically calculated properties.
self._measure_terminal()
# To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0
amount_complete = 1.0 if self.max_value == 0 else value / self.max_value
fill_amount = int(floor(amount_complete * self.max_width))
empty_amount = self.max_width - fill_amount
# e.g., '10/20' if 'fraction' or '50%' if 'percentage'
amount_complete_str = (
u"{}/{}".format(value, self.max_value)
if self._num_rep == "fraction" else
u"{}%".format(int(floor(amount_complete * 100)))
)
# Write title if supposed to be above
if self._title_pos == "above":
title_str = u"{}{}\n".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Construct just the progress bar
bar_str = u''.join([
u(self.filled(self._filled_char * fill_amount)),
u(self.empty(self._empty_char * empty_amount)),
])
# Wrap with start and end character
bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char)
# Add on title if supposed to be on left or right
if self._title_pos == "left":
bar_str = u"{} {}".format(self.title, bar_str)
elif self._title_pos == "right":
bar_str = u"{} {}".format(bar_str, self.title)
# Add indent
bar_str = u''.join([" " * self._indent, bar_str])
# Add complete percentage or fraction
bar_str = u"{} {}".format(bar_str, amount_complete_str)
# Set back to normal after printing
bar_str = u"{}{}".format(bar_str, self.term.normal)
# Finally, write the completed bar_str
self._write(bar_str, s_length=self.full_line_width)
# Write title if supposed to be below
if self._title_pos == "below":
title_str = u"\n{}{}".format(
" " * self._indent,
self.title,
)
self._write(title_str, ignore_overflow=True)
# Newline to wrap up
if newline:
self.cursor.newline()
if flush:
self.cursor.flush()
|
hfaran/progressive
|
progressive/cursor.py
|
Cursor.write
|
python
|
def write(self, s):
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s)
|
Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L18-L26
| null |
class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = self.term.stream
self._saved = False
def save(self):
"""Saves current cursor position, so that it can be restored later"""
self.write(self.term.save)
self._saved = True
def restore(self):
"""Restores cursor to the previously saved location
Cursor position will only be restored IF it was previously saved
by this instance (and not by any external force)
"""
if self._saved:
self.write(self.term.restore)
def flush(self):
"""Flush buffer of terminal output stream"""
self._stream.flush()
def newline(self):
"""Effects a newline by moving the cursor down and clearing"""
self.write(self.term.move_down)
self.write(self.term.clear_bol)
def clear_lines(self, num_lines=0):
for i in range(num_lines):
self.write(self.term.clear_eol)
self.write(self.term.move_down)
for i in range(num_lines):
self.write(self.term.move_up)
|
hfaran/progressive
|
progressive/cursor.py
|
Cursor.save
|
python
|
def save(self):
self.write(self.term.save)
self._saved = True
|
Saves current cursor position, so that it can be restored later
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L28-L31
|
[
"def write(self, s):\n \"\"\"Writes ``s`` to the terminal output stream\n\n Writes can be disabled by setting the environment variable\n `PROGRESSIVE_NOWRITE` to `'True'`\n \"\"\"\n should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != \"True\"\n if should_write_s:\n self._stream.write(s)\n"
] |
class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = self.term.stream
self._saved = False
def write(self, s):
"""Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
"""
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s)
def restore(self):
"""Restores cursor to the previously saved location
Cursor position will only be restored IF it was previously saved
by this instance (and not by any external force)
"""
if self._saved:
self.write(self.term.restore)
def flush(self):
"""Flush buffer of terminal output stream"""
self._stream.flush()
def newline(self):
"""Effects a newline by moving the cursor down and clearing"""
self.write(self.term.move_down)
self.write(self.term.clear_bol)
def clear_lines(self, num_lines=0):
for i in range(num_lines):
self.write(self.term.clear_eol)
self.write(self.term.move_down)
for i in range(num_lines):
self.write(self.term.move_up)
|
hfaran/progressive
|
progressive/cursor.py
|
Cursor.newline
|
python
|
def newline(self):
self.write(self.term.move_down)
self.write(self.term.clear_bol)
|
Effects a newline by moving the cursor down and clearing
|
train
|
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L46-L49
|
[
"def write(self, s):\n \"\"\"Writes ``s`` to the terminal output stream\n\n Writes can be disabled by setting the environment variable\n `PROGRESSIVE_NOWRITE` to `'True'`\n \"\"\"\n should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != \"True\"\n if should_write_s:\n self._stream.write(s)\n"
] |
class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = self.term.stream
self._saved = False
def write(self, s):
"""Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
"""
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s)
def save(self):
"""Saves current cursor position, so that it can be restored later"""
self.write(self.term.save)
self._saved = True
def restore(self):
"""Restores cursor to the previously saved location
Cursor position will only be restored IF it was previously saved
by this instance (and not by any external force)
"""
if self._saved:
self.write(self.term.restore)
def flush(self):
"""Flush buffer of terminal output stream"""
self._stream.flush()
def clear_lines(self, num_lines=0):
for i in range(num_lines):
self.write(self.term.clear_eol)
self.write(self.term.move_down)
for i in range(num_lines):
self.write(self.term.move_up)
|
kalbhor/MusicNow
|
musicnow/command_line.py
|
add_config
|
python
|
def add_config():
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile)
|
Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L66-L79
| null |
#!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
import requests
import youtube_dl
import spotipy
import six
from os import system, rename, listdir, curdir, name
from os.path import basename, realpath
from collections import OrderedDict
from bs4 import BeautifulSoup
try:
from . import repair
from . import log
except:
import repair
import log
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
input = raw_input
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
YOUTUBECLASS = 'spf-prefetch'
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
BING_KEY = CONFIG['keys']['bing_key']
if GENIUS_KEY == '<insert genius key here>':
log.log_error('Warning, you are missing the Genius key. Add it using --config')
if BING_KEY == '<insert bing key here>':
log.log_error('Warning, you are missing the Bing key. Add it using --config')
def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
songs = []
for items in results['items']:
songs.append(items['name'])
return songs
def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
# In all Youtube Search Results
for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
song_url = 'https://www.youtube.com' + (i.get('href'))
song_title = (i.get('title'))
# Adds title and song url to dictionary
youtube_list.update({song_title: song_url})
if not auto:
print('(%s) %s' % (str(num + 1), song_title)) # Prints list
num = num + 1
elif auto:
print(song_title)
return list(youtube_list.values())[0], list(youtube_list.keys())[0]
# Checks if YouTube search return no results
if youtube_list == {}:
log.log_error('No match found!')
exit()
# Gets the demanded song title and url
song_url, song_title = prompt(youtube_list)
return song_url, song_title # Returns Name of Song and URL of Music Video
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid Input')
exit()
system('clear')
print('Download Song: ')
print(song_title)
print('Y/n?')
confirm = input('>')
if confirm == '' or confirm.lower() == 'y':
pass
elif confirm.lower() == 'n':
exit()
else:
log.log_error('Invalid Input')
exit()
return song_url, song_title
def download_song(song_url, song_title):
'''
Downloads song from youtube-dl
'''
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True)
def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
help='Set your API keys')
parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
help='Download multiple songs from a text file list')
parser.add_argument('-a', '--auto', action='store_true',
help='Automatically chooses top result')
parser.add_argument('--album', action='store_true',
help='Downloads all songs from an album')
args = parser.parse_args()
arg_multiple = args.multiple_file or None
arg_auto = args.auto or None
arg_album = args.album or None
arg_config = args.config
if arg_config:
add_config()
elif arg_multiple and arg_album:
log.log_error("Can't do both!")
elif arg_album:
album_name = input('Enter album name : ')
try:
tracks = get_tracks_from_album(album_name)
for songs in tracks:
print(songs)
confirm = input(
'\nAre these the songs you want to download? (Y/n)\n> ')
except IndexError:
log.log_error("Couldn't find album")
exit()
if confirm == '' or confirm.lower() == ('y'):
for track_name in tracks:
track_name = track_name + ' song'
song_url, file_name = get_url(track_name, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
elif confirm.lower() == 'n':
log.log_error("Sorry, if appropriate results weren't found")
exit()
else:
log.log_error('Invalid Input')
exit()
elif arg_multiple:
with open(arg_multiple, "r") as f:
file_names = []
for line in f:
file_names.append(line.rstrip('\n'))
for files in file_names:
files = files + ' song'
song_url, file_name = get_url(files, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
else:
query = input('Enter Song Name : ')
song_url, file_name = get_url(query, arg_auto) # Gets YT url
download_song(song_url, file_name) # Saves as .mp3 file
system('clear')
repair.fix_music(file_name + '.mp3')
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/command_line.py
|
get_tracks_from_album
|
python
|
def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
songs = []
for items in results['items']:
songs.append(items['name'])
return songs
|
Gets tracks from an album using Spotify's API
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L82-L96
| null |
#!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
import requests
import youtube_dl
import spotipy
import six
from os import system, rename, listdir, curdir, name
from os.path import basename, realpath
from collections import OrderedDict
from bs4 import BeautifulSoup
try:
from . import repair
from . import log
except:
import repair
import log
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
input = raw_input
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
YOUTUBECLASS = 'spf-prefetch'
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
BING_KEY = CONFIG['keys']['bing_key']
if GENIUS_KEY == '<insert genius key here>':
log.log_error('Warning, you are missing the Genius key. Add it using --config')
if BING_KEY == '<insert bing key here>':
log.log_error('Warning, you are missing the Bing key. Add it using --config')
def add_config():
"""
Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script
"""
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile)
def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
# In all Youtube Search Results
for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
song_url = 'https://www.youtube.com' + (i.get('href'))
song_title = (i.get('title'))
# Adds title and song url to dictionary
youtube_list.update({song_title: song_url})
if not auto:
print('(%s) %s' % (str(num + 1), song_title)) # Prints list
num = num + 1
elif auto:
print(song_title)
return list(youtube_list.values())[0], list(youtube_list.keys())[0]
# Checks if YouTube search return no results
if youtube_list == {}:
log.log_error('No match found!')
exit()
# Gets the demanded song title and url
song_url, song_title = prompt(youtube_list)
return song_url, song_title # Returns Name of Song and URL of Music Video
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid Input')
exit()
system('clear')
print('Download Song: ')
print(song_title)
print('Y/n?')
confirm = input('>')
if confirm == '' or confirm.lower() == 'y':
pass
elif confirm.lower() == 'n':
exit()
else:
log.log_error('Invalid Input')
exit()
return song_url, song_title
def download_song(song_url, song_title):
'''
Downloads song from youtube-dl
'''
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True)
def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
help='Set your API keys')
parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
help='Download multiple songs from a text file list')
parser.add_argument('-a', '--auto', action='store_true',
help='Automatically chooses top result')
parser.add_argument('--album', action='store_true',
help='Downloads all songs from an album')
args = parser.parse_args()
arg_multiple = args.multiple_file or None
arg_auto = args.auto or None
arg_album = args.album or None
arg_config = args.config
if arg_config:
add_config()
elif arg_multiple and arg_album:
log.log_error("Can't do both!")
elif arg_album:
album_name = input('Enter album name : ')
try:
tracks = get_tracks_from_album(album_name)
for songs in tracks:
print(songs)
confirm = input(
'\nAre these the songs you want to download? (Y/n)\n> ')
except IndexError:
log.log_error("Couldn't find album")
exit()
if confirm == '' or confirm.lower() == ('y'):
for track_name in tracks:
track_name = track_name + ' song'
song_url, file_name = get_url(track_name, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
elif confirm.lower() == 'n':
log.log_error("Sorry, if appropriate results weren't found")
exit()
else:
log.log_error('Invalid Input')
exit()
elif arg_multiple:
with open(arg_multiple, "r") as f:
file_names = []
for line in f:
file_names.append(line.rstrip('\n'))
for files in file_names:
files = files + ' song'
song_url, file_name = get_url(files, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
else:
query = input('Enter Song Name : ')
song_url, file_name = get_url(query, arg_auto) # Gets YT url
download_song(song_url, file_name) # Saves as .mp3 file
system('clear')
repair.fix_music(file_name + '.mp3')
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/command_line.py
|
get_url
|
python
|
def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
# In all Youtube Search Results
for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
song_url = 'https://www.youtube.com' + (i.get('href'))
song_title = (i.get('title'))
# Adds title and song url to dictionary
youtube_list.update({song_title: song_url})
if not auto:
print('(%s) %s' % (str(num + 1), song_title)) # Prints list
num = num + 1
elif auto:
print(song_title)
return list(youtube_list.values())[0], list(youtube_list.keys())[0]
# Checks if YouTube search return no results
if youtube_list == {}:
log.log_error('No match found!')
exit()
# Gets the demanded song title and url
song_url, song_title = prompt(youtube_list)
return song_url, song_title
|
Provides user with a list of songs to choose from
returns the url of chosen song.
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L99-L135
|
[
"def prompt(youtube_list):\n '''\n Prompts for song number from list of songs\n '''\n\n option = int(input('\\nEnter song number > '))\n try:\n song_url = list(youtube_list.values())[option - 1]\n song_title = list(youtube_list.keys())[option - 1]\n except IndexError:\n log.log_error('Invalid Input')\n exit()\n\n system('clear')\n print('Download Song: ')\n print(song_title)\n print('Y/n?')\n confirm = input('>')\n if confirm == '' or confirm.lower() == 'y':\n pass\n elif confirm.lower() == 'n':\n exit()\n else:\n log.log_error('Invalid Input')\n exit()\n\n return song_url, song_title\n"
] |
#!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
import requests
import youtube_dl
import spotipy
import six
from os import system, rename, listdir, curdir, name
from os.path import basename, realpath
from collections import OrderedDict
from bs4 import BeautifulSoup
try:
from . import repair
from . import log
except:
import repair
import log
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
input = raw_input
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
YOUTUBECLASS = 'spf-prefetch'
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
BING_KEY = CONFIG['keys']['bing_key']
if GENIUS_KEY == '<insert genius key here>':
log.log_error('Warning, you are missing the Genius key. Add it using --config')
if BING_KEY == '<insert bing key here>':
log.log_error('Warning, you are missing the Bing key. Add it using --config')
def add_config():
"""
Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script
"""
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile)
def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
songs = []
for items in results['items']:
songs.append(items['name'])
return songs
# Returns Name of Song and URL of Music Video
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid Input')
exit()
system('clear')
print('Download Song: ')
print(song_title)
print('Y/n?')
confirm = input('>')
if confirm == '' or confirm.lower() == 'y':
pass
elif confirm.lower() == 'n':
exit()
else:
log.log_error('Invalid Input')
exit()
return song_url, song_title
def download_song(song_url, song_title):
'''
Downloads song from youtube-dl
'''
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True)
def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
help='Set your API keys')
parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
help='Download multiple songs from a text file list')
parser.add_argument('-a', '--auto', action='store_true',
help='Automatically chooses top result')
parser.add_argument('--album', action='store_true',
help='Downloads all songs from an album')
args = parser.parse_args()
arg_multiple = args.multiple_file or None
arg_auto = args.auto or None
arg_album = args.album or None
arg_config = args.config
if arg_config:
add_config()
elif arg_multiple and arg_album:
log.log_error("Can't do both!")
elif arg_album:
album_name = input('Enter album name : ')
try:
tracks = get_tracks_from_album(album_name)
for songs in tracks:
print(songs)
confirm = input(
'\nAre these the songs you want to download? (Y/n)\n> ')
except IndexError:
log.log_error("Couldn't find album")
exit()
if confirm == '' or confirm.lower() == ('y'):
for track_name in tracks:
track_name = track_name + ' song'
song_url, file_name = get_url(track_name, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
elif confirm.lower() == 'n':
log.log_error("Sorry, if appropriate results weren't found")
exit()
else:
log.log_error('Invalid Input')
exit()
elif arg_multiple:
with open(arg_multiple, "r") as f:
file_names = []
for line in f:
file_names.append(line.rstrip('\n'))
for files in file_names:
files = files + ' song'
song_url, file_name = get_url(files, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
else:
query = input('Enter Song Name : ')
song_url, file_name = get_url(query, arg_auto) # Gets YT url
download_song(song_url, file_name) # Saves as .mp3 file
system('clear')
repair.fix_music(file_name + '.mp3')
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/command_line.py
|
prompt
|
python
|
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid Input')
exit()
system('clear')
print('Download Song: ')
print(song_title)
print('Y/n?')
confirm = input('>')
if confirm == '' or confirm.lower() == 'y':
pass
elif confirm.lower() == 'n':
exit()
else:
log.log_error('Invalid Input')
exit()
return song_url, song_title
|
Prompts for song number from list of songs
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L138-L164
|
[
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n"
] |
#!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
import requests
import youtube_dl
import spotipy
import six
from os import system, rename, listdir, curdir, name
from os.path import basename, realpath
from collections import OrderedDict
from bs4 import BeautifulSoup
try:
from . import repair
from . import log
except:
import repair
import log
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
input = raw_input
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
YOUTUBECLASS = 'spf-prefetch'
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
BING_KEY = CONFIG['keys']['bing_key']
if GENIUS_KEY == '<insert genius key here>':
log.log_error('Warning, you are missing the Genius key. Add it using --config')
if BING_KEY == '<insert bing key here>':
log.log_error('Warning, you are missing the Bing key. Add it using --config')
def add_config():
"""
Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script
"""
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile)
def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
songs = []
for items in results['items']:
songs.append(items['name'])
return songs
def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
# In all Youtube Search Results
for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
song_url = 'https://www.youtube.com' + (i.get('href'))
song_title = (i.get('title'))
# Adds title and song url to dictionary
youtube_list.update({song_title: song_url})
if not auto:
print('(%s) %s' % (str(num + 1), song_title)) # Prints list
num = num + 1
elif auto:
print(song_title)
return list(youtube_list.values())[0], list(youtube_list.keys())[0]
# Checks if YouTube search return no results
if youtube_list == {}:
log.log_error('No match found!')
exit()
# Gets the demanded song title and url
song_url, song_title = prompt(youtube_list)
return song_url, song_title # Returns Name of Song and URL of Music Video
def download_song(song_url, song_title):
'''
Downloads song from youtube-dl
'''
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True)
def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
help='Set your API keys')
parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
help='Download multiple songs from a text file list')
parser.add_argument('-a', '--auto', action='store_true',
help='Automatically chooses top result')
parser.add_argument('--album', action='store_true',
help='Downloads all songs from an album')
args = parser.parse_args()
arg_multiple = args.multiple_file or None
arg_auto = args.auto or None
arg_album = args.album or None
arg_config = args.config
if arg_config:
add_config()
elif arg_multiple and arg_album:
log.log_error("Can't do both!")
elif arg_album:
album_name = input('Enter album name : ')
try:
tracks = get_tracks_from_album(album_name)
for songs in tracks:
print(songs)
confirm = input(
'\nAre these the songs you want to download? (Y/n)\n> ')
except IndexError:
log.log_error("Couldn't find album")
exit()
if confirm == '' or confirm.lower() == ('y'):
for track_name in tracks:
track_name = track_name + ' song'
song_url, file_name = get_url(track_name, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
elif confirm.lower() == 'n':
log.log_error("Sorry, if appropriate results weren't found")
exit()
else:
log.log_error('Invalid Input')
exit()
elif arg_multiple:
with open(arg_multiple, "r") as f:
file_names = []
for line in f:
file_names.append(line.rstrip('\n'))
for files in file_names:
files = files + ' song'
song_url, file_name = get_url(files, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
else:
query = input('Enter Song Name : ')
song_url, file_name = get_url(query, arg_auto) # Gets YT url
download_song(song_url, file_name) # Saves as .mp3 file
system('clear')
repair.fix_music(file_name + '.mp3')
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/command_line.py
|
main
|
python
|
def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
help='Set your API keys')
parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
help='Download multiple songs from a text file list')
parser.add_argument('-a', '--auto', action='store_true',
help='Automatically chooses top result')
parser.add_argument('--album', action='store_true',
help='Downloads all songs from an album')
args = parser.parse_args()
arg_multiple = args.multiple_file or None
arg_auto = args.auto or None
arg_album = args.album or None
arg_config = args.config
if arg_config:
add_config()
elif arg_multiple and arg_album:
log.log_error("Can't do both!")
elif arg_album:
album_name = input('Enter album name : ')
try:
tracks = get_tracks_from_album(album_name)
for songs in tracks:
print(songs)
confirm = input(
'\nAre these the songs you want to download? (Y/n)\n> ')
except IndexError:
log.log_error("Couldn't find album")
exit()
if confirm == '' or confirm.lower() == ('y'):
for track_name in tracks:
track_name = track_name + ' song'
song_url, file_name = get_url(track_name, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
elif confirm.lower() == 'n':
log.log_error("Sorry, if appropriate results weren't found")
exit()
else:
log.log_error('Invalid Input')
exit()
elif arg_multiple:
with open(arg_multiple, "r") as f:
file_names = []
for line in f:
file_names.append(line.rstrip('\n'))
for files in file_names:
files = files + ' song'
song_url, file_name = get_url(files, arg_auto)
download_song(song_url, file_name)
system('clear')
repair.fix_music(file_name + '.mp3')
else:
query = input('Enter Song Name : ')
song_url, file_name = get_url(query, arg_auto) # Gets YT url
download_song(song_url, file_name) # Saves as .mp3 file
system('clear')
repair.fix_music(file_name + '.mp3')
|
Starts here, handles arguments
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L189-L267
|
[
"def setup():\n \"\"\"\n Gathers all configs\n \"\"\"\n\n global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR \n\n LOG_FILENAME = 'musicrepair_log.txt'\n LOG_LINE_SEPERATOR = '........................\\n'\n\n CONFIG = configparser.ConfigParser()\n config_path = realpath(__file__).replace(basename(__file__),'')\n config_path = config_path + 'config.ini'\n CONFIG.read(config_path)\n\n GENIUS_KEY = CONFIG['keys']['genius_key']\n BING_KEY = CONFIG['keys']['bing_key']\n\n if GENIUS_KEY == '<insert genius key here>':\n log.log_error('Warning, you are missing the Genius key. Add it using --config')\n\n if BING_KEY == '<insert bing key here>':\n log.log_error('Warning, you are missing the Bing key. Add it using --config')\n",
"def add_config():\n \"\"\"\n Prompts user for API keys, adds them in an .ini file stored in the same\n location as that of the script\n \"\"\"\n\n genius_key = input('Enter Genius key : ')\n bing_key = input('Enter Bing key : ')\n\n CONFIG['keys']['bing_key'] = bing_key\n CONFIG['keys']['genius_key'] = genius_key\n\n with open(config_path, 'w') as configfile:\n CONFIG.write(configfile)\n"
] |
#!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
import requests
import youtube_dl
import spotipy
import six
from os import system, rename, listdir, curdir, name
from os.path import basename, realpath
from collections import OrderedDict
from bs4 import BeautifulSoup
try:
from . import repair
from . import log
except:
import repair
import log
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
input = raw_input
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
YOUTUBECLASS = 'spf-prefetch'
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
BING_KEY = CONFIG['keys']['bing_key']
if GENIUS_KEY == '<insert genius key here>':
log.log_error('Warning, you are missing the Genius key. Add it using --config')
if BING_KEY == '<insert bing key here>':
log.log_error('Warning, you are missing the Bing key. Add it using --config')
def add_config():
"""
Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script
"""
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile)
def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
songs = []
for items in results['items']:
songs.append(items['name'])
return songs
def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_input})
soup = BeautifulSoup(html.text, 'html.parser')
# In all Youtube Search Results
for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
song_url = 'https://www.youtube.com' + (i.get('href'))
song_title = (i.get('title'))
# Adds title and song url to dictionary
youtube_list.update({song_title: song_url})
if not auto:
print('(%s) %s' % (str(num + 1), song_title)) # Prints list
num = num + 1
elif auto:
print(song_title)
return list(youtube_list.values())[0], list(youtube_list.keys())[0]
# Checks if YouTube search return no results
if youtube_list == {}:
log.log_error('No match found!')
exit()
# Gets the demanded song title and url
song_url, song_title = prompt(youtube_list)
return song_url, song_title # Returns Name of Song and URL of Music Video
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid Input')
exit()
system('clear')
print('Download Song: ')
print(song_title)
print('Y/n?')
confirm = input('>')
if confirm == '' or confirm.lower() == 'y':
pass
elif confirm.lower() == 'n':
exit()
else:
log.log_error('Invalid Input')
exit()
return song_url, song_title
def download_song(song_url, song_title):
'''
Downloads song from youtube-dl
'''
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(song_url, download=True)
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
setup
|
python
|
def setup():
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
|
Gathers all configs
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L42-L57
| null |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
kalbhor/MusicNow
|
musicnow/repair.py
|
matching_details
|
python
|
def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio()
if max(match_name,match_title) >= 0.55:
return True, max(match_name,match_title)
else:
return False, (match_name + match_title) / 2
|
Provides a score out of 10 that determines the
relevance of the search result
|
train
|
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L60-L73
| null |
#!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, environ
from os.path import realpath, basename
import difflib
import six
import configparser
from bs4 import BeautifulSoup
from mutagen.id3 import ID3, APIC, USLT, _util
from mutagen.mp3 import EasyMP3
from mutagen import File
import requests
import spotipy
if six.PY2:
from urllib2 import urlopen
from urllib2 import quote
Py3 = False
elif six.PY3:
from urllib.parse import quote
from urllib.request import urlopen
Py3 = True
def setup():
"""
Gathers all configs
"""
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_path = config_path + 'config.ini'
CONFIG.read(config_path)
GENIUS_KEY = CONFIG['keys']['genius_key']
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
except:
lyrics = ""
return lyrics
def get_lyrics_genius(song_title):
'''
Scrapes the lyrics from Genius.com
'''
base_url = "http://api.genius.com"
headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)}
search_url = base_url + "/search"
data = {'q': song_title}
response = requests.get(search_url, data=data, headers=headers)
json = response.json()
song_api_path = json["response"]["hits"][0]["result"]["api_path"]
song_url = base_url + song_api_path
response = requests.get(song_url, headers=headers)
json = response.json()
path = json["response"]["song"]["path"]
page_url = "http://genius.com" + path
page = requests.get(page_url)
soup = BeautifulSoup(page.text, "html.parser")
div = soup.find('div',{'class': 'song_body-lyrics'})
lyrics = div.find('p').getText()
return lyrics
def get_details_spotify(song_name):
'''
Tries finding metadata through Spotify
'''
song_name = improvename.songname(song_name)
spotify = spotipy.Spotify()
results = spotify.search(song_name, limit=1) # Find top result
log.log_indented('* Finding metadata from Spotify.')
try:
album = (results['tracks']['items'][0]['album']
['name']) # Parse json dictionary
artist = (results['tracks']['items'][0]['album']['artists'][0]['name'])
song_title = (results['tracks']['items'][0]['name'])
try:
log_indented("* Finding lyrics from Genius.com")
lyrics = get_lyrics_genius(song_title)
except:
log_error("* Could not find lyrics from Genius.com, trying something else")
lyrics = get_lyrics_letssingit(song_title)
match_bool, score = matching_details(song_name, song_title, artist)
if match_bool:
return artist, album, song_title, lyrics, match_bool, score
else:
return None
except IndexError:
log.log_error(
'* Could not find metadata from spotify, trying something else.', indented=True)
return None
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
link = soup.find('a', {'class': 'high_profile'})
try:
link = link.get('href')
link = urlopen(link).read()
soup = BeautifulSoup(link, "html.parser")
album_div = soup.find('div', {'id': 'albums'})
title_div = soup.find('div', {'id': 'content_artist'}).find('h1')
try:
lyrics = soup.find('div', {'id': 'lyrics'}).text
lyrics = lyrics[3:]
except AttributeError:
lyrics = ""
log.log_error("* Couldn't find lyrics", indented=True)
try:
song_title = title_div.contents[0]
song_title = song_title[1:-8]
except AttributeError:
log.log_error("* Couldn't reset song title", indented=True)
song_title = song_name
try:
artist = title_div.contents[1].getText()
except AttributeError:
log.log_error("* Couldn't find artist name", indented=True)
artist = "Unknown"
try:
album = album_div.find('a').contents[0]
album = album[:-7]
except AttributeError:
log.log_error("* Couldn't find the album name", indented=True)
album = artist
except AttributeError:
log.log_error("* Couldn't find song details", indented=True)
album = song_name
song_title = song_name
artist = "Unknown"
lyrics = ""
match_bool, score = matching_details(song_name, song_title, artist)
return artist, album, song_title, lyrics, match_bool, score
def add_albumart(albumart, song_title):
'''
Adds the album art to the song
'''
try:
img = urlopen(albumart) # Gets album art from url
except Exception:
log.log_error("* Could not add album art", indented=True)
return None
audio = EasyMP3(song_title, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3, # UTF-8
mime='image/png',
type=3, # 3 is for album art
desc='Cover',
data=img.read() # Reads and adds album art
)
)
audio.save()
log.log("> Added album art")
def add_details(file_name, title, artist, album, lyrics=""):
'''
Adds the details to song
'''
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
tags["USLT::'eng'"] = uslt_output
tags.save(file_name)
log.log("> Adding properties")
log.log_indented("[*] Title: %s" % title)
log.log_indented("[*] Artist: %s" % artist)
log.log_indented("[*] Album: %s " % album)
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
log.log('> Adding metadata')
try:
artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
file_name) # Try finding details through spotify
except Exception:
artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
file_name) # Use bad scraping method as last resort
try:
log.log_indented('* Trying to extract album art from Google.com')
albumart = albumsearch.img_search_google(artist+' '+album)
except Exception:
log.log_indented('* Trying to extract album art from Bing.com')
albumart = albumsearch.img_search_bing(artist+' '+album)
if match_bool:
add_albumart(albumart, file_name)
add_details(file_name, song_name, artist, album, lyrics)
try:
rename(file_name, artist+' - '+song_name+'.mp3')
except Exception:
log.log_error("Couldn't rename file")
pass
else:
log.log_error(
"* Couldn't find appropriate details of your song", indented=True)
log.log("Match score: %s/10.0" % round(score * 10, 1))
log.log(LOG_LINE_SEPERATOR)
log.log_success()
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.