INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Enable or disable the support for websocket. | def enable_websocket(self, enable=True):
"""Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are
added to the application.
"""
if not self.websocket_enabled:
# if the server is stopped, we want to cancel any ongoing
... |
This method provides the app user a mechanism by which an already existing route can be removed from the: class: Sanic object | def remove_route(self, uri, clean_cache=True, host=None):
"""
This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it n... |
Decorate a function to be registered as a handler for exceptions | def exception(self, *exceptions):
"""Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function
"""
def response(handler):
for exception in exceptions:
if isinstance(exception, (tuple, l... |
Register an application level middleware that will be attached to all the API URLs registered under this application. | def register_middleware(self, middleware, attach_to="request"):
"""
Register an application level middleware that will be attached
to all the API URLs registered under this application.
This method is internally invoked by the :func:`middleware`
decorator provided at the app lev... |
Decorate and register middleware to be called before a request. Can either be called as * @app. middleware * or * @app. middleware ( request ) * | def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... |
Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the: class: Route necessary to serve the static files. | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... |
Register a blueprint on the application. | def blueprint(self, blueprint, **options):
"""Register a blueprint on the application.
:param blueprint: Blueprint object or (list, tuple) thereof
:param options: option dictionary with blueprint defaults
:return: Nothing
"""
if isinstance(blueprint, (list, tuple, Bluepr... |
Proxy method provided for invoking the: func: blueprint method | def register_blueprint(self, *args, **kwargs):
"""
Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictiona... |
Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object so exception handling must be done here | async def handle_request(self, request, write_callback, stream_callback):
"""Take a request from the HTTP Server and return a response object
to be sent back The HTTP Server only expects a response object, so
exception handling must be done here
:param request: HTTP Request object
... |
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination drain connections before closing. | def run(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
workers: int = 1,
protocol: Type[Protocol] = None,
backlog: int = 100,
sto... |
Asynchronous version of: func: run. | async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... |
Helper function used by run and create_server. | def _helper(
self,
host=None,
port=None,
debug=False,
ssl=None,
sock=None,
workers=1,
loop=None,
protocol=HttpProtocol,
backlog=100,
stop_event=None,
register_sys_signals=True,
run_async=False,
auto_reload=Fa... |
Returns response object with body in json format. | def json(
body,
status=200,
headers=None,
content_type="application/json",
dumps=json_dumps,
**kwargs
):
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:para... |
Returns response object with body in text format. | def text(
body, status=200, headers=None, content_type="text/plain; charset=utf-8"
):
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param headers: Custom Headers.
:param content_type: the content type (string) ... |
Return a streaming response object with file data. | async def file_stream(
location,
status=200,
chunk_size=4096,
mime_type=None,
headers=None,
filename=None,
_range=None,
):
"""Return a streaming response object with file data.
:param location: Location of file on system.
:param chunk_size: The size of each chunk in the stream (... |
Accepts an coroutine streaming_fn which can be used to write chunks to a streaming response. Returns a StreamingHTTPResponse. | def stream(
streaming_fn,
status=200,
headers=None,
content_type="text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
@app.route("/")
async def in... |
Abort execution and cause a 302 redirect ( by default ). | def redirect(
to, headers=None, status=302, content_type="text/html; charset=utf-8"
):
"""Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (i... |
Writes a chunk of data to the streaming response. | async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written.
"""
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.pr... |
Streams headers runs the streaming_fn callback that writes content to the response body then finalizes the response body. | async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
"""Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body.
"""
headers = self.get_headers(
version,
... |
The Abstract class MutableSequence leverages this insert method to perform the BlueprintGroup. append operation. | def insert(self, index: int, item: object) -> None:
"""
The Abstract class `MutableSequence` leverages this insert method to
perform the `BlueprintGroup.append` operation.
:param index: Index to use for removing a new Blueprint item
:param item: New `Blueprint` object.
:... |
A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. | def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recur... |
Fetches and executes an exception handler and returns a response object | def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type except... |
Provide a default behavior for the objects of: class: ErrorHandler. If a developer chooses to extent the: class: ErrorHandler they can provide a custom implementation for this method to behave in a way they see fit. | def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... |
Creates SSLContext instance for usage in asyncio. create_server. See ssl. SSLSocket. __init__ for more details. | def _create_ssl_context(cfg):
""" Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details.
"""
ctx = ssl.SSLContext(cfg.ssl_version)
ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
ctx.verify_mode = cfg.cert_reqs
... |
Trigger event callbacks ( functions or async ) | def trigger_events(events, loop):
"""Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop
"""
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result) |
Start asynchronous HTTP Server on an individual process. | def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
... |
Check if the connection needs to be kept alive based on the params attached to the _keep_alive attribute: attr: Signal. stopped and: func: HttpProtocol. parser. should_keep_alive | def keep_alive(self):
"""
Check if the connection needs to be kept alive based on the params
attached to the `_keep_alive` attribute, :attr:`Signal.stopped`
and :func:`HttpProtocol.parser.should_keep_alive`
:return: ``True`` if connection is to be kept alive ``False`` else
... |
Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so close the transport pipe and let the response writer handle the error. | def keep_alive_timeout_callback(self):
"""
Check if elapsed time since last response exceeds our configured
maximum keep alive timeout value and if so, close the transport
pipe and let the response writer handle the error.
:return: None
"""
time_elapsed = time() ... |
Invoke the request handler defined by the: func: sanic. app. Sanic. handle_request method | def execute_request_handler(self):
"""
Invoke the request handler defined by the
:func:`sanic.app.Sanic.handle_request` method
:return: None
"""
self._response_timeout_handler = self.loop.call_later(
self.response_timeout, self.response_timeout_callback
... |
Helper method provided to enable the logging of responses in case if the: attr: HttpProtocol. access_log is enabled. | def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... |
Writes response content synchronously to the transport. | def write_response(self, response):
"""
Writes response content synchronously to the transport.
"""
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_ali... |
In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe we log the error with proper details. | def bail_out(self, message, from_error=False):
"""
In case if the transport pipes are closed and the sanic app encounters
an error while writing data to the transport pipe, we log the error
with proper details.
:param message: Error message to display
:param from_error: ... |
This is called when KeepAlive feature is used it resets the connection in order for it to be able to handle receiving another request on the same connection. | def cleanup(self):
"""This is called when KeepAlive feature is used,
it resets the connection in order for it to be able
to handle receiving another request on the same connection."""
self.parser = None
self.request = None
self.url = None
self.headers = None
... |
Parse a request body and returns fields and files | def parse_multipart_form(body, boundary):
"""Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters)
"""
files = RequestParameters()
fields = RequestParameters(... |
Stop reading when gets None | async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload |
Attempt to return the auth header token. | def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in... |
Method to parse query_string using urllib. parse. parse_qs. This methods is used by args property. Can be used directly if you need to change default parameters.: param keep_blank_values: flag indicating whether blank values in percent - encoded queries should be treated as blank strings. A true value indicates that bl... | def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
"""
Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args... |
Method to parse query_string using urllib. parse. parse_qsl. This methods is used by query_args property. Can be used directly if you need to change default parameters.: param keep_blank_values: flag indicating whether blank values in percent - encoded queries should be treated as blank strings. A true value indicates ... | def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
"""
Method to parse `query_string` using `urllib.parse.parse_qsl`.
This methods is used by `query_args... |
Attempt to return the original client ip based on X - Forwarded - For or X - Real - IP. If HTTP headers are unavailable or untrusted returns an empty string. | def remote_addr(self):
"""Attempt to return the original client ip based on X-Forwarded-For
or X-Real-IP. If HTTP headers are unavailable or untrusted, returns
an empty string.
:return: original client ip.
"""
if not hasattr(self, "_remote_addr"):
if self.app... |
This function was borrowed from distutils. utils. While distutils is part of stdlib it feels odd to use distutils in main application code. | def strtobool(val):
"""
This function was borrowed from distutils.utils. While distutils
is part of stdlib, it feels odd to use distutils in main application code.
The function was modified to walk its talk and actually return bool
and not int.
"""
val = val.lower()
if val in ("y", "yes... |
Load a configuration from an environment variable pointing to a configuration file. | def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
config_file = os.e... |
Update the values from the given object. Objects are usually either modules or classes. | def from_object(self, obj):
"""Update the values from the given object.
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.fro... |
Looks for prefixed environment variables and applies them to the configuration if present. | def load_environment_vars(self, prefix=SANIC_PREFIX):
"""
Looks for prefixed environment variables and applies
them to the configuration if present.
"""
for k, v in os.environ.items():
if k.startswith(prefix):
_, config_key = k.split(prefix, 1)
... |
Parse a parameter string into its constituent name type and pattern | def parse_parameter_string(cls, parameter_string):
"""Parse a parameter string into its constituent name, type, and
pattern
For example::
parse_parameter_string('<param_one:[A-z]>')` ->
('param_one', str, '[A-z]')
:param parameter_string: String to parse
... |
Add a handler to the route list | def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
... |
Add a handler to the route list | def _add(self, uri, methods, handler, host=None, name=None):
"""Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When... |
Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. | def check_dynamic_route_exists(pattern, routes_to_check, parameters):
"""
Check if a URL pattern exists in a list of routes provided based on
the comparison of URL pattern and the parameters.
:param pattern: URL parameter pattern
:param routes_to_check: list of dynamic routes ei... |
Find a route in the router based on the specified view name. | def find_route_by_view_name(self, view_name, name=None):
"""Find a route in the router based on the specified view name.
:param view_name: string of view name to search by
:param kwargs: additional params, usually for static files
:return: tuple containing (uri, Route)
"""
... |
Get a request handler based on the URL of the request or raises an error | def get(self, request):
"""Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments
"""
# No virtual hosts specified; default behavior
if not self.hosts:
re... |
Get a list of supported methods for a url and optional host. | def get_supported_methods(self, url):
"""Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods
"""
route = self.routes_all.get(url)
# if methods are None then this logic will prevent a... |
Get a request handler based on the URL of the request or raises an error. Internal method for caching. | def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = unquote(h... |
Handler for request is stream or not.: param request: Request object: return: bool | def is_stream_handler(self, request):
""" Handler for request is stream or not.
:param request: Request object
:return: bool
"""
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "vi... |
Returns the executable. | def _get_args_for_reloading():
"""Returns the executable."""
rv = [sys.executable]
main_module = sys.modules["__main__"]
mod_spec = getattr(main_module, "__spec__", None)
if mod_spec:
# Parent exe was launched as a module rather than a script
rv.extend(["-m", mod_spec.name])
... |
Create a new process and a subprocess in it with the same arguments as this one. | def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = P... |
Find and kill child processes of a process ( maximum two level ). | def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... |
Find and kill child processes of a process. | def kill_process_children(pid):
"""Find and kill child processes of a process.
:param pid: PID of parent process (process ID)
:return: Nothing
"""
if sys.platform == "darwin":
kill_process_children_osx(pid)
elif sys.platform == "linux":
kill_process_children_unix(pid)
else:
... |
Watch project files restart worker process if a change happened. | def watchdog(sleep_interval):
"""Watch project files, restart worker process if a change happened.
:param sleep_interval: interval in second.
:return: Nothing
"""
mtimes = {}
worker_process = restart_with_reloader()
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly... |
Return view function for use with the routing system that dispatches request to appropriate handler method. | def as_view(cls, *class_args, **class_kwargs):
"""Return view function for use with the routing system, that
dispatches request to appropriate handler method.
"""
def view(*args, **kwargs):
self = view.view_class(*class_args, **class_kwargs)
return self.dispatch_... |
Use session object to perform get request on url | async def bounded_fetch(session, url):
"""
Use session object to perform 'get' request on url
"""
async with sem, session.get(url) as response:
return await response.json() |
Removes all the entity headers present in the headers given. According to RFC 2616 Section 10. 3. 5 Content - Location and Expires are allowed as for the strong cache validator. https:// tools. ietf. org/ html/ rfc2616#section - 10. 3. 5 | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... |
Preserve shape of the image. | def preserve_shape(func):
"""Preserve shape of the image."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
result = result.reshape(shape)
return result
return wrapped_function |
Preserve dummy channel dim. | def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(resul... |
Bleaches out pixels mitation snow. | def add_snow(img, snow_point, brightness_coeff):
"""Bleaches out pixels, mitation snow.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img:
snow_point:
brightness_coeff:
Returns:
"""
non_rgb_warning(img)
input_dtype = img.dtype
... |
Add fog to the image. | def add_fog(img, fog_coef, alpha_coef, haze_list):
"""Add fog to the image.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
fog_coef (float):
alpha_coef (float):
haze_list (list):
Returns:
"""
non_rgb_warning(img)
... |
Add sun flare. | def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):
"""Add sun flare.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
flare_center_x (float):
flare_center_y (float):
src_radius:
src_c... |
Add shadows to the image. | def add_shadow(img, vertices_list):
"""Add shadows to the image.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
vertices_list (list):
Returns:
"""
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if ... |
Barrel/ pincushion distortion. Unconventional augment. | def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
"""Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor... |
Reference: http:// pythology. blogspot. sg/ 2014/ 03/ interpolation - on - regular - distorted - grid. html | def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None):
"""
Reference:
http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
"""
height, width = img.shape[:2]
... |
Elastic deformation of images as described in [ Simard2003 ] _ ( with modifications ). Based on https:// gist. github. com/ erniejunior/ 601cdf56d2b424757de5 | def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False):
"""Elastic deformation of images as described in [Simard2003]_ (with modifications).
Based on https://gist.github.... |
Flip a bounding box vertically around the x - axis. | def bbox_vflip(bbox, rows, cols):
"""Flip a bounding box vertically around the x-axis."""
x_min, y_min, x_max, y_max = bbox
return [x_min, 1 - y_max, x_max, 1 - y_min] |
Flip a bounding box horizontally around the y - axis. | def bbox_hflip(bbox, rows, cols):
"""Flip a bounding box horizontally around the y-axis."""
x_min, y_min, x_max, y_max = bbox
return [1 - x_max, y_min, 1 - x_min, y_max] |
Flip a bounding box either vertically horizontally or both depending on the value of d. | def bbox_flip(bbox, d, rows, cols):
"""Flip a bounding box either vertically, horizontally or both depending on the value of `d`.
Raises:
ValueError: if value of `d` is not -1, 0 or 1.
"""
if d == 0:
bbox = bbox_vflip(bbox, rows, cols)
elif d == 1:
bbox = bbox_hflip(bbox, r... |
Crop a bounding box using the provided coordinates of bottom - left and top - right corners in pixels and the required height and width of the crop. | def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... |
Rotates a bounding box by 90 degrees CCW ( see np. rot90 ) | def bbox_rot90(bbox, factor, rows, cols):
"""Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image co... |
Rotates a bounding box by angle degrees | def bbox_rotate(bbox, angle, rows, cols, interpolation):
"""Rotates a bounding box by angle degrees
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
angle (int): Angle of rotation in degrees
rows (int): Image rows.
cols (int): Image cols.
interpolation (int): in... |
Transposes a bounding box along given axis. | def bbox_transpose(bbox, axis, rows, cols):
"""Transposes a bounding box along given axis.
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
axis (int): 0 - main axis, 1 - secondary axis.
rows (int): Image rows.
cols (int): Image cols.
"""
x_min, y_min, x_max, y_... |
Flip a keypoint vertically around the x - axis. | def keypoint_vflip(kp, rows, cols):
"""Flip a keypoint vertically around the x-axis."""
x, y, angle, scale = kp
c = math.cos(angle)
s = math.sin(angle)
angle = math.atan2(-s, c)
return [x, (rows - 1) - y, angle, scale] |
Flip a keypoint either vertically horizontally or both depending on the value of d. | def keypoint_flip(bbox, d, rows, cols):
"""Flip a keypoint either vertically, horizontally or both depending on the value of `d`.
Raises:
ValueError: if value of `d` is not -1, 0 or 1.
"""
if d == 0:
bbox = keypoint_vflip(bbox, rows, cols)
elif d == 1:
bbox = keypoint_hflip... |
Rotates a keypoint by 90 degrees CCW ( see np. rot90 ) | def keypoint_rot90(keypoint, factor, rows, cols, **params):
"""Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int)... |
Scales a keypoint by scale_x and scale_y. | def keypoint_scale(keypoint, scale_x, scale_y, **params):
"""Scales a keypoint by scale_x and scale_y."""
x, y, a, s = keypoint
return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)] |
Crop a keypoint using the provided coordinates of bottom - left and top - right corners in pixels and the required height and width of the crop. | def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
x, y, a, s = keypoint
x1, y1, x2, y2 = crop_coords
cropped_... |
Unified rounding in all python versions. | def py3round(number):
"""Unified rounding in all python versions."""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number)) |
Args: factor ( int ): number of times the input will be rotated by 90 degrees. | def apply(self, img, factor=0, **params):
"""
Args:
factor (int): number of times the input will be rotated by 90 degrees.
"""
return np.ascontiguousarray(np.rot90(img, factor)) |
Normalize coordinates of a bounding box. Divide x - coordinates by image width and y - coordinates by image height. | def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
"""
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
... |
Denormalize coordinates of a bounding box. Multiply x - coordinates by image width and y - coordinates by image height. This is an inverse operation for: func: ~albumentations. augmentations. bbox. normalize_bbox. | def denormalize_bbox(bbox, rows, cols):
"""Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates
by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
"""
if rows == 0:
raise ValueError('Argument ... |
Normalize a list of bounding boxes. | def normalize_bboxes(bboxes, rows, cols):
"""Normalize a list of bounding boxes."""
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes] |
Denormalize a list of bounding boxes. | def denormalize_bboxes(bboxes, rows, cols):
"""Denormalize a list of bounding boxes."""
return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes] |
Calculate the area of a bounding box in pixels. | def calculate_bbox_area(bbox, rows, cols):
"""Calculate the area of a bounding box in pixels."""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox[:4]
area = (x_max - x_min) * (y_max - y_min)
return area |
Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. | def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes,
threshold=0., min_area=0.):
"""Filter bounding boxes and return only those boxes whose visibility after transformation is above
the threshold and minimal area of bounding box in pixels ... |
Convert a bounding box from a format specified in source_format to the format used by albumentations: normalized coordinates of bottom - left and top - right corners of the bounding box in a form of [ x_min y_min x_max y_max ] e. g. [ 0. 15 0. 27 0. 67 0. 5 ]. | def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
"""Convert a bounding box from a format specified in `source_format` to the format used by albumentations:
normalized coordinates of bottom-left and top-right corners of the bounding box in a form of
`[x_min, y_min, x... |
Convert a bounding box from the format used by albumentations to a format specified in target_format. | def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
"""Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.
Args:
bbox (list): bounding box with coordinates in the format used by albumentations
target_f... |
Convert a list bounding boxes from a format specified in source_format to the format used by albumentations | def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
"""Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
"""
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox... |
Convert a list of bounding boxes from the format used by albumentations to a format specified in target_format. | def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
"""Convert a list of bounding boxes from the format used by albumentations to a format, specified
in `target_format`.
Args:
bboxes (list): List of bounding box with coordinates in the format used by alb... |
Check if bbox boundaries are in range 0 1 and minimums are lesser then maximums | def check_bbox(bbox):
"""Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"""
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
't... |
Remove bounding boxes that either lie outside of the visible area by more then min_visibility or whose area in pixels is under the threshold set by min_area. Also it crops boxes to final image size. | def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.):
"""Remove bounding boxes that either lie outside of the visible area by more then min_visibility
or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size.
Args:
bboxes (list): Lis... |
Calculate union of bounding boxes. | def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False):
"""Calculate union of bounding boxes.
Args:
height (float): Height of image or space.
width (float): Width of image or space.
bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`.
... |
Convert input argument to min - max tuple Args: param ( scalar tuple or list of 2 + elements ): Input value. If value is scalar return value would be ( offset - value offset + value ). If value is tuple return value would be value + offset ( broadcasted ). low: Second element of tuple can be passed as optional argument... | def to_tuple(param, low=None, bias=None):
"""Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offse... |
Check if keypoint coordinates are in range [ 0 1 ) | def check_keypoint(kp, rows, cols):
"""Check if keypoint coordinates are in range [0, 1)"""
for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]):
if not 0 <= value < size:
raise ValueError(
'Expected {name} for keypoint {kp} '
'to be in the range [0.... |
Check if keypoints boundaries are in range [ 0 1 ) | def check_keypoints(keypoints, rows, cols):
"""Check if keypoints boundaries are in range [0, 1)"""
for kp in keypoints:
check_keypoint(kp, rows, cols) |
Begins watching source files for changes. | def start(check_time: int = 500) -> None:
"""Begins watching source files for changes.
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been removed.
"""
io_loop = ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.