partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Sanic.enable_websocket
Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application.
sanic/app.py
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 # websocket tasks, to allow the server to exit promptly @self.listener("before_server_stop") def cancel_websocket_tasks(app, loop): for task in self.websocket_tasks: task.cancel() self.websocket_enabled = enable
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 # websocket tasks, to allow the server to exit promptly @self.listener("before_server_stop") def cancel_websocket_tasks(app, loop): for task in self.websocket_tasks: task.cancel() self.websocket_enabled = enable
[ "Enable", "or", "disable", "the", "support", "for", "websocket", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L537-L551
[ "def", "enable_websocket", "(", "self", ",", "enable", "=", "True", ")", ":", "if", "not", "self", ".", "websocket_enabled", ":", "# if the server is stopped, we want to cancel any ongoing", "# websocket tasks, to allow the server to exit promptly", "@", "self", ".", "liste...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.remove_route
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 needs to clean up the LRU route cache :param host: IP address or FQDN specific to the host :return: None
sanic/app.py
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 needs to clean up the LRU route cache :param host: IP address or FQDN specific to the host :return: None """ self.router.remove(uri, clean_cache, host)
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 needs to clean up the LRU route cache :param host: IP address or FQDN specific to the host :return: None """ self.router.remove(uri, clean_cache, host)
[ "This", "method", "provides", "the", "app", "user", "a", "mechanism", "by", "which", "an", "already", "existing", "route", "can", "be", "removed", "from", "the", ":", "class", ":", "Sanic", "object" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L553-L564
[ "def", "remove_route", "(", "self", ",", "uri", ",", "clean_cache", "=", "True", ",", "host", "=", "None", ")", ":", "self", ".", "router", ".", "remove", "(", "uri", ",", "clean_cache", ",", "host", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.exception
Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function
sanic/app.py
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, list)): for e in exception: self.error_handler.add(e, handler) else: self.error_handler.add(exception, handler) return handler return response
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, list)): for e in exception: self.error_handler.add(e, handler) else: self.error_handler.add(exception, handler) return handler return response
[ "Decorate", "a", "function", "to", "be", "registered", "as", "a", "handler", "for", "exceptions" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L567-L583
[ "def", "exception", "(", "self", ",", "*", "exceptions", ")", ":", "def", "response", "(", "handler", ")", ":", "for", "exception", "in", "exceptions", ":", "if", "isinstance", "(", "exception", ",", "(", "tuple", ",", "list", ")", ")", ":", "for", "...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.register_middleware
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 level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method
sanic/app.py
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 level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method """ if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) return middleware
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 level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method """ if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) return middleware
[ "Register", "an", "application", "level", "middleware", "that", "will", "be", "attached", "to", "all", "the", "API", "URLs", "registered", "under", "this", "application", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L585-L607
[ "def", "register_middleware", "(", "self", ",", "middleware", ",", "attach_to", "=", "\"request\"", ")", ":", "if", "attach_to", "==", "\"request\"", ":", "if", "middleware", "not", "in", "self", ".", "request_middleware", ":", "self", ".", "request_middleware",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.middleware
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 type of middleware is being registered.
sanic/app.py
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 type of middleware is being registered. """ # Detect which way this was called, @middleware or @middleware('AT') if callable(middleware_or_request): return self.register_middleware(middleware_or_request) else: return partial( self.register_middleware, attach_to=middleware_or_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 type of middleware is being registered. """ # Detect which way this was called, @middleware or @middleware('AT') if callable(middleware_or_request): return self.register_middleware(middleware_or_request) else: return partial( self.register_middleware, attach_to=middleware_or_request )
[ "Decorate", "and", "register", "middleware", "to", "be", "called", "before", "a", "request", ".", "Can", "either", "be", "called", "as", "*", "@app", ".", "middleware", "*", "or", "*", "@app", ".", "middleware", "(", "request", ")", "*" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L610-L626
[ "def", "middleware", "(", "self", ",", "middleware_or_request", ")", ":", "# Detect which way this was called, @middleware or @middleware('AT')", "if", "callable", "(", "middleware_or_request", ")", ":", "return", "self", ".", "register_middleware", "(", "middleware_or_reques...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.static
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. :param uri: URL path to be used for serving static content :param file_or_directory: Path for the Static file/directory with static files :param pattern: Regex Pattern identifying the valid static files :param use_modified_since: If true, send file modified time, and return not modified if the browser's matches the server's :param use_content_range: If true, process header for range requests and sends the file part that is requested :param stream_large_files: If true, use the :func:`StreamingHTTPResponse.file_stream` handler rather than the :func:`HTTPResponse.file` handler to send the file. If this is an integer, this represents the threshold size to switch to :func:`StreamingHTTPResponse.file_stream` :param name: user defined name used for url_for :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`Sanic` to check if the request URLs need to terminate with a */* :param content_type: user defined content type for header :return: None
sanic/app.py
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, ): """ 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. :param uri: URL path to be used for serving static content :param file_or_directory: Path for the Static file/directory with static files :param pattern: Regex Pattern identifying the valid static files :param use_modified_since: If true, send file modified time, and return not modified if the browser's matches the server's :param use_content_range: If true, process header for range requests and sends the file part that is requested :param stream_large_files: If true, use the :func:`StreamingHTTPResponse.file_stream` handler rather than the :func:`HTTPResponse.file` handler to send the file. If this is an integer, this represents the threshold size to switch to :func:`StreamingHTTPResponse.file_stream` :param name: user defined name used for url_for :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`Sanic` to check if the request URLs need to terminate with a */* :param content_type: user defined content type for header :return: None """ static_register( self, uri, file_or_directory, pattern, use_modified_since, use_content_range, stream_large_files, name, host, strict_slashes, content_type, )
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, ): """ 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. :param uri: URL path to be used for serving static content :param file_or_directory: Path for the Static file/directory with static files :param pattern: Regex Pattern identifying the valid static files :param use_modified_since: If true, send file modified time, and return not modified if the browser's matches the server's :param use_content_range: If true, process header for range requests and sends the file part that is requested :param stream_large_files: If true, use the :func:`StreamingHTTPResponse.file_stream` handler rather than the :func:`HTTPResponse.file` handler to send the file. If this is an integer, this represents the threshold size to switch to :func:`StreamingHTTPResponse.file_stream` :param name: user defined name used for url_for :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`Sanic` to check if the request URLs need to terminate with a */* :param content_type: user defined content type for header :return: None """ static_register( self, uri, file_or_directory, pattern, use_modified_since, use_content_range, stream_large_files, name, host, strict_slashes, content_type, )
[ "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",...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L629-L679
[ "def", "static", "(", "self", ",", "uri", ",", "file_or_directory", ",", "pattern", "=", "r\"/?.+\"", ",", "use_modified_since", "=", "True", ",", "use_content_range", "=", "False", ",", "stream_large_files", "=", "False", ",", "name", "=", "\"static\"", ",", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.blueprint
Register a blueprint on the application. :param blueprint: Blueprint object or (list, tuple) thereof :param options: option dictionary with blueprint defaults :return: Nothing
sanic/app.py
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, BlueprintGroup)): for item in blueprint: self.blueprint(item, **options) return if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, ( 'A blueprint with the name "%s" is already registered. ' "Blueprint names must be unique." % (blueprint.name,) ) else: self.blueprints[blueprint.name] = blueprint self._blueprint_order.append(blueprint) blueprint.register(self, options)
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, BlueprintGroup)): for item in blueprint: self.blueprint(item, **options) return if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, ( 'A blueprint with the name "%s" is already registered. ' "Blueprint names must be unique." % (blueprint.name,) ) else: self.blueprints[blueprint.name] = blueprint self._blueprint_order.append(blueprint) blueprint.register(self, options)
[ "Register", "a", "blueprint", "on", "the", "application", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L681-L700
[ "def", "blueprint", "(", "self", ",", "blueprint", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "blueprint", ",", "(", "list", ",", "tuple", ",", "BlueprintGroup", ")", ")", ":", "for", "item", "in", "blueprint", ":", "self", ".", "bl...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.register_blueprint
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 dictionary with blueprint defaults :return: None
sanic/app.py
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 dictionary with blueprint defaults :return: None """ if self.debug: warnings.simplefilter("default") warnings.warn( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" " instead", DeprecationWarning, ) return self.blueprint(*args, **kwargs)
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 dictionary with blueprint defaults :return: None """ if self.debug: warnings.simplefilter("default") warnings.warn( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" " instead", DeprecationWarning, ) return self.blueprint(*args, **kwargs)
[ "Proxy", "method", "provided", "for", "invoking", "the", ":", "func", ":", "blueprint", "method" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L702-L722
[ "def", "register_blueprint", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "debug", ":", "warnings", ".", "simplefilter", "(", "\"default\"", ")", "warnings", ".", "warn", "(", "\"Use of register_blueprint will be depreca...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.handle_request
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 :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing
sanic/app.py
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 :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- # response = await self._run_request_middleware(request) # No middleware results if not response: # -------------------------------------------- # # Execute Handler # -------------------------------------------- # # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler is None: raise ServerError( ( "'None' was returned while requesting a " "handler from the router" ) ) else: if not getattr(handler, "__blueprintname__", False): request.endpoint = self._build_endpoint_name( handler.__name__ ) else: request.endpoint = self._build_endpoint_name( getattr(handler, "__blueprintname__", ""), handler.__name__, ) # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except CancelledError: # If response handler times out, the server handles the error # and cancels the handle_request job. # In this case, the transport is already closed and we cannot # issue a response. response = None cancelled = True except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- # try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if isinstance(e, SanicException): response = self.error_handler.default( request=request, exception=e ) elif self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc() ), status=500, ) else: response = HTTPResponse( "An error occurred while handling an error", status=500 ) finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # # Don't run response middleware if response is None if response is not None: try: response = await self._run_response_middleware( request, response ) except CancelledError: # Response middleware can timeout too, as above. response = None cancelled = True except BaseException: error_logger.exception( "Exception occurred in one of response " "middleware handlers" ) if cancelled: raise CancelledError() # pass the response to the correct callback if isinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)
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 :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- # response = await self._run_request_middleware(request) # No middleware results if not response: # -------------------------------------------- # # Execute Handler # -------------------------------------------- # # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler is None: raise ServerError( ( "'None' was returned while requesting a " "handler from the router" ) ) else: if not getattr(handler, "__blueprintname__", False): request.endpoint = self._build_endpoint_name( handler.__name__ ) else: request.endpoint = self._build_endpoint_name( getattr(handler, "__blueprintname__", ""), handler.__name__, ) # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except CancelledError: # If response handler times out, the server handles the error # and cancels the handle_request job. # In this case, the transport is already closed and we cannot # issue a response. response = None cancelled = True except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- # try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if isinstance(e, SanicException): response = self.error_handler.default( request=request, exception=e ) elif self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc() ), status=500, ) else: response = HTTPResponse( "An error occurred while handling an error", status=500 ) finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # # Don't run response middleware if response is None if response is not None: try: response = await self._run_response_middleware( request, response ) except CancelledError: # Response middleware can timeout too, as above. response = None cancelled = True except BaseException: error_logger.exception( "Exception occurred in one of response " "middleware handlers" ) if cancelled: raise CancelledError() # pass the response to the correct callback if isinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)
[ "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", "he...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L863-L975
[ "async", "def", "handle_request", "(", "self", ",", "request", ",", "write_callback", ",", "stream_callback", ")", ":", "# Define `response` var here to remove warnings about", "# allocation before assignment below.", "response", "=", "None", "cancelled", "=", "False", "try...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.run
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing
sanic/app.py
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, stop_event: Any = None, register_sys_signals: bool = True, access_log: Optional[bool] = None, **kwargs: Any ) -> None: """Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing """ if "loop" in kwargs: raise TypeError( "loop is not a valid argument. To use an existing loop, " "change to create_server().\nSee more: " "https://sanic.readthedocs.io/en/latest/sanic/deploying.html" "#asynchronous-support" ) # Default auto_reload to false auto_reload = False # If debug is set, default it to true (unless on windows) if debug and os.name == "posix": auto_reload = True # Allow for overriding either of the defaults auto_reload = kwargs.get("auto_reload", auto_reload) if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers, protocol=protocol, backlog=backlog, register_sys_signals=register_sys_signals, auto_reload=auto_reload, ) try: self.is_running = True if workers == 1: if auto_reload and os.name != "posix": # This condition must be removed after implementing # auto reloader for other operating systems. raise NotImplementedError if ( auto_reload and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): reloader_helpers.watchdog(2) else: serve(**server_settings) else: serve_multiple(server_settings, workers) except BaseException: error_logger.exception( "Experienced exception while trying to serve" ) raise finally: self.is_running = False logger.info("Server Stopped")
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, stop_event: Any = None, register_sys_signals: bool = True, access_log: Optional[bool] = None, **kwargs: Any ) -> None: """Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing """ if "loop" in kwargs: raise TypeError( "loop is not a valid argument. To use an existing loop, " "change to create_server().\nSee more: " "https://sanic.readthedocs.io/en/latest/sanic/deploying.html" "#asynchronous-support" ) # Default auto_reload to false auto_reload = False # If debug is set, default it to true (unless on windows) if debug and os.name == "posix": auto_reload = True # Allow for overriding either of the defaults auto_reload = kwargs.get("auto_reload", auto_reload) if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers, protocol=protocol, backlog=backlog, register_sys_signals=register_sys_signals, auto_reload=auto_reload, ) try: self.is_running = True if workers == 1: if auto_reload and os.name != "posix": # This condition must be removed after implementing # auto reloader for other operating systems. raise NotImplementedError if ( auto_reload and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): reloader_helpers.watchdog(2) else: serve(**server_settings) else: serve_multiple(server_settings, workers) except BaseException: error_logger.exception( "Experienced exception while trying to serve" ) raise finally: self.is_running = False logger.info("Server Stopped")
[ "Run", "the", "HTTP", "Server", "and", "listen", "until", "keyboard", "interrupt", "or", "term", "signal", ".", "On", "termination", "drain", "connections", "before", "closing", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L989-L1105
[ "def", "run", "(", "self", ",", "host", ":", "Optional", "[", "str", "]", "=", "None", ",", "port", ":", "Optional", "[", "int", "]", "=", "None", ",", "debug", ":", "bool", "=", "False", ",", "ssl", ":", "Union", "[", "dict", ",", "SSLContext", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic.create_server
Asynchronous version of :func:`run`. This method will take care of the operations necessary to invoke the *before_start* events via :func:`trigger_events` method invocation before starting the *sanic* app in Async mode. .. note:: This does not support multiprocessing and is not the preferred way to run a :class:`Sanic` application. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param access_log: Enables writing access logs (slows server) :type access_log: bool :param return_asyncio_server: flag that defines whether there's a need to return asyncio.Server or start it serving right away :type return_asyncio_server: bool :param asyncio_server_kwargs: key-value arguments for asyncio/uvloop create_server method :type asyncio_server_kwargs: dict :return: Nothing
sanic/app.py
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: Any = None, access_log: Optional[bool] = None, return_asyncio_server=False, asyncio_server_kwargs=None, ) -> None: """ Asynchronous version of :func:`run`. This method will take care of the operations necessary to invoke the *before_start* events via :func:`trigger_events` method invocation before starting the *sanic* app in Async mode. .. note:: This does not support multiprocessing and is not the preferred way to run a :class:`Sanic` application. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param access_log: Enables writing access logs (slows server) :type access_log: bool :param return_asyncio_server: flag that defines whether there's a need to return asyncio.Server or start it serving right away :type return_asyncio_server: bool :param asyncio_server_kwargs: key-value arguments for asyncio/uvloop create_server method :type asyncio_server_kwargs: dict :return: Nothing """ if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, loop=get_event_loop(), protocol=protocol, backlog=backlog, run_async=return_asyncio_server, ) # Trigger before_start events await self.trigger_events( server_settings.get("before_start", []), server_settings.get("loop"), ) return await serve( asyncio_server_kwargs=asyncio_server_kwargs, **server_settings )
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: Any = None, access_log: Optional[bool] = None, return_asyncio_server=False, asyncio_server_kwargs=None, ) -> None: """ Asynchronous version of :func:`run`. This method will take care of the operations necessary to invoke the *before_start* events via :func:`trigger_events` method invocation before starting the *sanic* app in Async mode. .. note:: This does not support multiprocessing and is not the preferred way to run a :class:`Sanic` application. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param access_log: Enables writing access logs (slows server) :type access_log: bool :param return_asyncio_server: flag that defines whether there's a need to return asyncio.Server or start it serving right away :type return_asyncio_server: bool :param asyncio_server_kwargs: key-value arguments for asyncio/uvloop create_server method :type asyncio_server_kwargs: dict :return: Nothing """ if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, loop=get_event_loop(), protocol=protocol, backlog=backlog, run_async=return_asyncio_server, ) # Trigger before_start events await self.trigger_events( server_settings.get("before_start", []), server_settings.get("loop"), ) return await serve( asyncio_server_kwargs=asyncio_server_kwargs, **server_settings )
[ "Asynchronous", "version", "of", ":", "func", ":", "run", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1115-L1209
[ "async", "def", "create_server", "(", "self", ",", "host", ":", "Optional", "[", "str", "]", "=", "None", ",", "port", ":", "Optional", "[", "int", "]", "=", "None", ",", "debug", ":", "bool", "=", "False", ",", "ssl", ":", "Union", "[", "dict", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Sanic._helper
Helper function used by `run` and `create_server`.
sanic/app.py
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=False, ): """Helper function used by `run` and `create_server`.""" if isinstance(ssl, dict): # try common aliaseses cert = ssl.get("cert") or ssl.get("certificate") key = ssl.get("key") or ssl.get("keyfile") if cert is None or key is None: raise ValueError("SSLContext or certificate and key required.") context = create_default_context(purpose=Purpose.CLIENT_AUTH) context.load_cert_chain(cert, keyfile=key) ssl = context if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) self.error_handler.debug = debug self.debug = debug server_settings = { "protocol": protocol, "request_class": self.request_class, "is_request_stream": self.is_request_stream, "router": self.router, "host": host, "port": port, "sock": sock, "ssl": ssl, "app": self, "signal": Signal(), "debug": debug, "request_handler": self.handle_request, "error_handler": self.error_handler, "request_timeout": self.config.REQUEST_TIMEOUT, "response_timeout": self.config.RESPONSE_TIMEOUT, "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT, "request_max_size": self.config.REQUEST_MAX_SIZE, "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE, "keep_alive": self.config.KEEP_ALIVE, "loop": loop, "register_sys_signals": register_sys_signals, "backlog": backlog, "access_log": self.config.ACCESS_LOG, "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE, "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE, "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT, "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT, "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT, } # -------------------------------------------- # # Register start/stop events # -------------------------------------------- # for event_name, settings_name, reverse in ( ("before_server_start", "before_start", False), ("after_server_start", "after_start", False), ("before_server_stop", "before_stop", True), ("after_server_stop", "after_stop", True), ): listeners = self.listeners[event_name].copy() if reverse: listeners.reverse() # Prepend sanic to the arguments when listeners are triggered listeners = [partial(listener, self) for listener in listeners] server_settings[settings_name] = listeners if self.configure_logging and debug: logger.setLevel(logging.DEBUG) if ( self.config.LOGO and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): logger.debug( self.config.LOGO if isinstance(self.config.LOGO, str) else BASE_LOGO ) if run_async: server_settings["run_async"] = True # Serve if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true": proto = "http" if ssl is not None: proto = "https" logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port)) return server_settings
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=False, ): """Helper function used by `run` and `create_server`.""" if isinstance(ssl, dict): # try common aliaseses cert = ssl.get("cert") or ssl.get("certificate") key = ssl.get("key") or ssl.get("keyfile") if cert is None or key is None: raise ValueError("SSLContext or certificate and key required.") context = create_default_context(purpose=Purpose.CLIENT_AUTH) context.load_cert_chain(cert, keyfile=key) ssl = context if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) self.error_handler.debug = debug self.debug = debug server_settings = { "protocol": protocol, "request_class": self.request_class, "is_request_stream": self.is_request_stream, "router": self.router, "host": host, "port": port, "sock": sock, "ssl": ssl, "app": self, "signal": Signal(), "debug": debug, "request_handler": self.handle_request, "error_handler": self.error_handler, "request_timeout": self.config.REQUEST_TIMEOUT, "response_timeout": self.config.RESPONSE_TIMEOUT, "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT, "request_max_size": self.config.REQUEST_MAX_SIZE, "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE, "keep_alive": self.config.KEEP_ALIVE, "loop": loop, "register_sys_signals": register_sys_signals, "backlog": backlog, "access_log": self.config.ACCESS_LOG, "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE, "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE, "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT, "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT, "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT, } # -------------------------------------------- # # Register start/stop events # -------------------------------------------- # for event_name, settings_name, reverse in ( ("before_server_start", "before_start", False), ("after_server_start", "after_start", False), ("before_server_stop", "before_stop", True), ("after_server_stop", "after_stop", True), ): listeners = self.listeners[event_name].copy() if reverse: listeners.reverse() # Prepend sanic to the arguments when listeners are triggered listeners = [partial(listener, self) for listener in listeners] server_settings[settings_name] = listeners if self.configure_logging and debug: logger.setLevel(logging.DEBUG) if ( self.config.LOGO and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): logger.debug( self.config.LOGO if isinstance(self.config.LOGO, str) else BASE_LOGO ) if run_async: server_settings["run_async"] = True # Serve if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true": proto = "http" if ssl is not None: proto = "https" logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port)) return server_settings
[ "Helper", "function", "used", "by", "run", "and", "create_server", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1243-L1351
[ "def", "_helper", "(", "self", ",", "host", "=", "None", ",", "port", "=", "None", ",", "debug", "=", "False", ",", "ssl", "=", "None", ",", "sock", "=", "None", ",", "workers", "=", "1", ",", "loop", "=", "None", ",", "protocol", "=", "HttpProto...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
json
Returns response object with body in json format. :param body: Response data to be serialized. :param status: Response code. :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder.
sanic/response.py
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. :param kwargs: Remaining arguments that are passed to the json encoder. """ return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, )
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. :param kwargs: Remaining arguments that are passed to the json encoder. """ return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, )
[ "Returns", "response", "object", "with", "body", "in", "json", "format", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L203-L224
[ "def", "json", "(", "body", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"application/json\"", ",", "dumps", "=", "json_dumps", ",", "*", "*", "kwargs", ")", ":", "return", "HTTPResponse", "(", "dumps", "(", "body",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
text
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) of the response
sanic/response.py
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) of the response """ return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
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) of the response """ return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
[ "Returns", "response", "object", "with", "body", "in", "text", "format", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L227-L240
[ "def", "text", "(", "body", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"text/plain; charset=utf-8\"", ")", ":", "return", "HTTPResponse", "(", "body", ",", "status", "=", "status", ",", "headers", "=", "headers", ",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
file_stream
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 (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range:
sanic/response.py
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 (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range: """ headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment; filename="{}"'.format(filename) ) filename = filename or path.split(location)[-1] _file = await open_async(location, mode="rb") async def _streaming_fn(response): nonlocal _file, chunk_size try: if _range: chunk_size = min((_range.size, chunk_size)) await _file.seek(_range.start) to_send = _range.size while to_send > 0: content = await _file.read(chunk_size) if len(content) < 1: break to_send -= len(content) await response.write(content) else: while True: content = await _file.read(chunk_size) if len(content) < 1: break await response.write(content) finally: await _file.close() return # Returning from this fn closes the stream mime_type = mime_type or guess_type(filename)[0] or "text/plain" if _range: headers["Content-Range"] = "bytes %s-%s/%s" % ( _range.start, _range.end, _range.total, ) status = 206 return StreamingHTTPResponse( streaming_fn=_streaming_fn, status=status, headers=headers, content_type=mime_type, )
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 (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range: """ headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment; filename="{}"'.format(filename) ) filename = filename or path.split(location)[-1] _file = await open_async(location, mode="rb") async def _streaming_fn(response): nonlocal _file, chunk_size try: if _range: chunk_size = min((_range.size, chunk_size)) await _file.seek(_range.start) to_send = _range.size while to_send > 0: content = await _file.read(chunk_size) if len(content) < 1: break to_send -= len(content) await response.write(content) else: while True: content = await _file.read(chunk_size) if len(content) < 1: break await response.write(content) finally: await _file.close() return # Returning from this fn closes the stream mime_type = mime_type or guess_type(filename)[0] or "text/plain" if _range: headers["Content-Range"] = "bytes %s-%s/%s" % ( _range.start, _range.end, _range.total, ) status = 206 return StreamingHTTPResponse( streaming_fn=_streaming_fn, status=status, headers=headers, content_type=mime_type, )
[ "Return", "a", "streaming", "response", "object", "with", "file", "data", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L323-L386
[ "async", "def", "file_stream", "(", "location", ",", "status", "=", "200", ",", "chunk_size", "=", "4096", ",", "mime_type", "=", "None", ",", "headers", "=", "None", ",", "filename", "=", "None", ",", "_range", "=", "None", ",", ")", ":", "headers", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
stream
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 index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers.
sanic/response.py
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 index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. """ return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
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 index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. """ return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
[ "Accepts", "an", "coroutine", "streaming_fn", "which", "can", "be", "used", "to", "write", "chunks", "to", "a", "streaming", "response", ".", "Returns", "a", "StreamingHTTPResponse", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L389-L415
[ "def", "stream", "(", "streaming_fn", ",", "status", "=", "200", ",", "headers", "=", "None", ",", "content_type", "=", "\"text/plain; charset=utf-8\"", ",", ")", ":", "return", "StreamingHTTPResponse", "(", "streaming_fn", ",", "headers", "=", "headers", ",", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
redirect
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 (int) of the new request, defaults to 302 :param content_type: the content type (string) of the response :returns: the redirecting Response
sanic/response.py
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 (int) of the new request, defaults to 302 :param content_type: the content type (string) of the response :returns: the redirecting Response """ headers = headers or {} # URL Quote the URL before redirecting safe_to = quote_plus(to, safe=":/%#?&=@[]!$&'()*+,;") # According to RFC 7231, a relative URI is now permitted. headers["Location"] = safe_to return HTTPResponse( status=status, headers=headers, content_type=content_type )
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 (int) of the new request, defaults to 302 :param content_type: the content type (string) of the response :returns: the redirecting Response """ headers = headers or {} # URL Quote the URL before redirecting safe_to = quote_plus(to, safe=":/%#?&=@[]!$&'()*+,;") # According to RFC 7231, a relative URI is now permitted. headers["Location"] = safe_to return HTTPResponse( status=status, headers=headers, content_type=content_type )
[ "Abort", "execution", "and", "cause", "a", "302", "redirect", "(", "by", "default", ")", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L418-L439
[ "def", "redirect", "(", "to", ",", "headers", "=", "None", ",", "status", "=", "302", ",", "content_type", "=", "\"text/html; charset=utf-8\"", ")", ":", "headers", "=", "headers", "or", "{", "}", "# URL Quote the URL before redirecting", "safe_to", "=", "quote_...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
StreamingHTTPResponse.write
Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written.
sanic/response.py
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.protocol.drain()
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.protocol.drain()
[ "Writes", "a", "chunk", "of", "data", "to", "the", "streaming", "response", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L74-L83
[ "async", "def", "write", "(", "self", ",", "data", ")", ":", "if", "type", "(", "data", ")", "!=", "bytes", ":", "data", "=", "self", ".", "_encode_body", "(", "data", ")", "self", ".", "protocol", ".", "push_data", "(", "b\"%x\\r\\n%b\\r\\n\"", "%", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
StreamingHTTPResponse.stream
Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body.
sanic/response.py
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, keep_alive=keep_alive, keep_alive_timeout=keep_alive_timeout, ) self.protocol.push_data(headers) await self.protocol.drain() await self.streaming_fn(self) self.protocol.push_data(b"0\r\n\r\n")
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, keep_alive=keep_alive, keep_alive_timeout=keep_alive_timeout, ) self.protocol.push_data(headers) await self.protocol.drain() await self.streaming_fn(self) self.protocol.push_data(b"0\r\n\r\n")
[ "Streams", "headers", "runs", "the", "streaming_fn", "callback", "that", "writes", "content", "to", "the", "response", "body", "then", "finalizes", "the", "response", "body", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L85-L99
[ "async", "def", "stream", "(", "self", ",", "version", "=", "\"1.1\"", ",", "keep_alive", "=", "False", ",", "keep_alive_timeout", "=", "None", ")", ":", "headers", "=", "self", ".", "get_headers", "(", "version", ",", "keep_alive", "=", "keep_alive", ",",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
BlueprintGroup.insert
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. :return: None
sanic/blueprint_group.py
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. :return: None """ self._blueprints.insert(index, item)
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. :return: None """ self._blueprints.insert(index, item)
[ "The", "Abstract", "class", "MutableSequence", "leverages", "this", "insert", "method", "to", "perform", "the", "BlueprintGroup", ".", "append", "operation", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L91-L100
[ "def", "insert", "(", "self", ",", "index", ":", "int", ",", "item", ":", "object", ")", "->", "None", ":", "self", ".", "_blueprints", ".", "insert", "(", "index", ",", "item", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
BlueprintGroup.middleware
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 recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware
sanic/blueprint_group.py
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 recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware """ kwargs["bp_group"] = True def register_middleware_for_blueprints(fn): for blueprint in self.blueprints: blueprint.middleware(fn, *args, **kwargs) return register_middleware_for_blueprints
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 recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware """ kwargs["bp_group"] = True def register_middleware_for_blueprints(fn): for blueprint in self.blueprints: blueprint.middleware(fn, *args, **kwargs) return register_middleware_for_blueprints
[ "A", "decorator", "that", "can", "be", "used", "to", "implement", "a", "Middleware", "plugin", "to", "all", "of", "the", "Blueprints", "that", "belongs", "to", "this", "specific", "Blueprint", "Group", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L102-L120
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"bp_group\"", "]", "=", "True", "def", "register_middleware_for_blueprints", "(", "fn", ")", ":", "for", "blueprint", "in", "self", ".", "blueprints", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
ErrorHandler.response
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 exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: Wrap the return value obtained from :func:`default` or registered handler for that type of exception.
sanic/handlers.py
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 exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: Wrap the return value obtained from :func:`default` or registered handler for that type of exception. """ handler = self.lookup(exception) response = None try: if handler: response = handler(request, exception) if response is None: response = self.default(request, exception) except Exception: self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = ( "Exception raised in exception handler " '"%s" for uri: %s' ) logger.exception(response_message, handler.__name__, url) if self.debug: return text(response_message % (handler.__name__, url), 500) else: return text("An error occurred while handling an error", 500) return response
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 exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: Wrap the return value obtained from :func:`default` or registered handler for that type of exception. """ handler = self.lookup(exception) response = None try: if handler: response = handler(request, exception) if response is None: response = self.default(request, exception) except Exception: self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = ( "Exception raised in exception handler " '"%s" for uri: %s' ) logger.exception(response_message, handler.__name__, url) if self.debug: return text(response_message % (handler.__name__, url), 500) else: return text("An error occurred while handling an error", 500) return response
[ "Fetches", "and", "executes", "an", "exception", "handler", "and", "returns", "a", "response", "object" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L111-L147
[ "def", "response", "(", "self", ",", "request", ",", "exception", ")", ":", "handler", "=", "self", ".", "lookup", "(", "exception", ")", "response", "=", "None", "try", ":", "if", "handler", ":", "response", "=", "handler", "(", "request", ",", "excep...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
ErrorHandler.default
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 request: Incoming request :param exception: Exception object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return:
sanic/handlers.py
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 request: Incoming request :param exception: Exception object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: """ self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = "Exception occurred while handling uri: %s" logger.exception(response_message, url) if issubclass(type(exception), SanicException): return text( "Error: {}".format(exception), status=getattr(exception, "status_code", 500), headers=getattr(exception, "headers", dict()), ) elif self.debug: html_output = self._render_traceback_html(exception, request) return html(html_output, status=500) else: return html(INTERNAL_SERVER_ERROR_HTML, status=500)
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 request: Incoming request :param exception: Exception object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: """ self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = "Exception occurred while handling uri: %s" logger.exception(response_message, url) if issubclass(type(exception), SanicException): return text( "Error: {}".format(exception), status=getattr(exception, "status_code", 500), headers=getattr(exception, "headers", dict()), ) elif self.debug: html_output = self._render_traceback_html(exception, request) return html(html_output, status=500) else: return html(INTERNAL_SERVER_ERROR_HTML, status=500)
[ "Provide", "a", "default", "behavior", "for", "the", "objects", "of", ":", "class", ":", "ErrorHandler", ".", "If", "a", "developer", "chooses", "to", "extent", "the", ":", "class", ":", "ErrorHandler", "they", "can", "provide", "a", "custom", "implementatio...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L154-L189
[ "def", "default", "(", "self", ",", "request", ",", "exception", ")", ":", "self", ".", "log", "(", "format_exc", "(", ")", ")", "try", ":", "url", "=", "repr", "(", "request", ".", "url", ")", "except", "AttributeError", ":", "url", "=", "\"unknown\...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
GunicornWorker._create_ssl_context
Creates SSLContext instance for usage in asyncio.create_server. See ssl.SSLSocket.__init__ for more details.
sanic/worker.py
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 if cfg.ca_certs: ctx.load_verify_locations(cfg.ca_certs) if cfg.ciphers: ctx.set_ciphers(cfg.ciphers) return ctx
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 if cfg.ca_certs: ctx.load_verify_locations(cfg.ca_certs) if cfg.ciphers: ctx.set_ciphers(cfg.ciphers) return ctx
[ "Creates", "SSLContext", "instance", "for", "usage", "in", "asyncio", ".", "create_server", ".", "See", "ssl", ".", "SSLSocket", ".", "__init__", "for", "more", "details", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/worker.py#L176-L187
[ "def", "_create_ssl_context", "(", "cfg", ")", ":", "ctx", "=", "ssl", ".", "SSLContext", "(", "cfg", ".", "ssl_version", ")", "ctx", ".", "load_cert_chain", "(", "cfg", ".", "certfile", ",", "cfg", ".", "keyfile", ")", "ctx", ".", "verify_mode", "=", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
trigger_events
Trigger event callbacks (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop
sanic/server.py
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)
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)
[ "Trigger", "event", "callbacks", "(", "functions", "or", "async", ")" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L604-L613
[ "def", "trigger_events", "(", "events", ",", "loop", ")", ":", "for", "event", "in", "events", ":", "result", "=", "event", "(", "loop", ")", "if", "isawaitable", "(", "result", ")", ":", "loop", ".", "run_until_complete", "(", "result", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
serve
Start asynchronous HTTP Server on an individual process. :param host: Address to host on :param port: Port to host on :param request_handler: Sanic request handler with middleware :param error_handler: Sanic error handler with middleware :param before_start: function to be executed before the server starts listening. Takes arguments `app` instance and `loop` :param after_start: function to be executed after the server starts listening. Takes arguments `app` instance and `loop` :param before_stop: function to be executed when a stop signal is received before it is respected. Takes arguments `app` instance and `loop` :param after_stop: function to be executed when a stop signal is received after it is respected. Takes arguments `app` instance and `loop` :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param response_timeout: time in seconds :param keep_alive_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :param request_class: Request class to use :param access_log: disable/enable access log :param websocket_max_size: enforces the maximum size for incoming messages in bytes. :param websocket_max_queue: sets the maximum length of the queue that holds incoming messages. :param websocket_read_limit: sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit. :param websocket_write_limit: sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit. :param is_request_stream: disable/enable Request.stream :param request_buffer_queue_size: streaming request buffer queue size :param router: Router object :param graceful_shutdown_timeout: How long take to Force close non-idle connection :param asyncio_server_kwargs: key-value args for asyncio/uvloop create_server method :return: Nothing
sanic/server.py
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, request_buffer_queue_size=100, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=Signal(), request_class=None, access_log=True, keep_alive=True, is_request_stream=False, router=None, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=2 ** 16, websocket_write_limit=2 ** 16, state=None, graceful_shutdown_timeout=15.0, asyncio_server_kwargs=None, ): """Start asynchronous HTTP Server on an individual process. :param host: Address to host on :param port: Port to host on :param request_handler: Sanic request handler with middleware :param error_handler: Sanic error handler with middleware :param before_start: function to be executed before the server starts listening. Takes arguments `app` instance and `loop` :param after_start: function to be executed after the server starts listening. Takes arguments `app` instance and `loop` :param before_stop: function to be executed when a stop signal is received before it is respected. Takes arguments `app` instance and `loop` :param after_stop: function to be executed when a stop signal is received after it is respected. Takes arguments `app` instance and `loop` :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param response_timeout: time in seconds :param keep_alive_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :param request_class: Request class to use :param access_log: disable/enable access log :param websocket_max_size: enforces the maximum size for incoming messages in bytes. :param websocket_max_queue: sets the maximum length of the queue that holds incoming messages. :param websocket_read_limit: sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit. :param websocket_write_limit: sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit. :param is_request_stream: disable/enable Request.stream :param request_buffer_queue_size: streaming request buffer queue size :param router: Router object :param graceful_shutdown_timeout: How long take to Force close non-idle connection :param asyncio_server_kwargs: key-value args for asyncio/uvloop create_server method :return: Nothing """ if not run_async: # create new event_loop after fork loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if debug: loop.set_debug(debug) connections = connections if connections is not None else set() server = partial( protocol, loop=loop, connections=connections, signal=signal, app=app, request_handler=request_handler, error_handler=error_handler, request_timeout=request_timeout, response_timeout=response_timeout, keep_alive_timeout=keep_alive_timeout, request_max_size=request_max_size, request_class=request_class, access_log=access_log, keep_alive=keep_alive, is_request_stream=is_request_stream, router=router, websocket_max_size=websocket_max_size, websocket_max_queue=websocket_max_queue, websocket_read_limit=websocket_read_limit, websocket_write_limit=websocket_write_limit, state=state, debug=debug, ) asyncio_server_kwargs = ( asyncio_server_kwargs if asyncio_server_kwargs else {} ) server_coroutine = loop.create_server( server, host, port, ssl=ssl, reuse_port=reuse_port, sock=sock, backlog=backlog, **asyncio_server_kwargs ) if run_async: return server_coroutine trigger_events(before_start, loop) try: http_server = loop.run_until_complete(server_coroutine) except BaseException: logger.exception("Unable to start server") return trigger_events(after_start, loop) # Ignore SIGINT when run_multiple if run_multiple: signal_func(SIGINT, SIG_IGN) # Register signals for graceful termination if register_sys_signals: _singals = (SIGTERM,) if run_multiple else (SIGINT, SIGTERM) for _signal in _singals: try: loop.add_signal_handler(_signal, loop.stop) except NotImplementedError: logger.warning( "Sanic tried to use loop.add_signal_handler " "but it is not implemented on this platform." ) pid = os.getpid() try: logger.info("Starting worker [%s]", pid) loop.run_forever() finally: logger.info("Stopping worker [%s]", pid) # Run the on_stop function if provided trigger_events(before_stop, loop) # Wait for event loop to finish and all connections to drain http_server.close() loop.run_until_complete(http_server.wait_closed()) # Complete all tasks on the loop signal.stopped = True for connection in connections: connection.close_if_idle() # Gracefully shutdown timeout. # We should provide graceful_shutdown_timeout, # instead of letting connection hangs forever. # Let's roughly calcucate time. start_shutdown = 0 while connections and (start_shutdown < graceful_shutdown_timeout): loop.run_until_complete(asyncio.sleep(0.1)) start_shutdown = start_shutdown + 0.1 # Force close non-idle connection after waiting for # graceful_shutdown_timeout coros = [] for conn in connections: if hasattr(conn, "websocket") and conn.websocket: coros.append(conn.websocket.close_connection()) else: conn.close() _shutdown = asyncio.gather(*coros, loop=loop) loop.run_until_complete(_shutdown) trigger_events(after_stop, loop) loop.close()
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, request_buffer_queue_size=100, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=Signal(), request_class=None, access_log=True, keep_alive=True, is_request_stream=False, router=None, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=2 ** 16, websocket_write_limit=2 ** 16, state=None, graceful_shutdown_timeout=15.0, asyncio_server_kwargs=None, ): """Start asynchronous HTTP Server on an individual process. :param host: Address to host on :param port: Port to host on :param request_handler: Sanic request handler with middleware :param error_handler: Sanic error handler with middleware :param before_start: function to be executed before the server starts listening. Takes arguments `app` instance and `loop` :param after_start: function to be executed after the server starts listening. Takes arguments `app` instance and `loop` :param before_stop: function to be executed when a stop signal is received before it is respected. Takes arguments `app` instance and `loop` :param after_stop: function to be executed when a stop signal is received after it is respected. Takes arguments `app` instance and `loop` :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param response_timeout: time in seconds :param keep_alive_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :param request_class: Request class to use :param access_log: disable/enable access log :param websocket_max_size: enforces the maximum size for incoming messages in bytes. :param websocket_max_queue: sets the maximum length of the queue that holds incoming messages. :param websocket_read_limit: sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit. :param websocket_write_limit: sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit. :param is_request_stream: disable/enable Request.stream :param request_buffer_queue_size: streaming request buffer queue size :param router: Router object :param graceful_shutdown_timeout: How long take to Force close non-idle connection :param asyncio_server_kwargs: key-value args for asyncio/uvloop create_server method :return: Nothing """ if not run_async: # create new event_loop after fork loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if debug: loop.set_debug(debug) connections = connections if connections is not None else set() server = partial( protocol, loop=loop, connections=connections, signal=signal, app=app, request_handler=request_handler, error_handler=error_handler, request_timeout=request_timeout, response_timeout=response_timeout, keep_alive_timeout=keep_alive_timeout, request_max_size=request_max_size, request_class=request_class, access_log=access_log, keep_alive=keep_alive, is_request_stream=is_request_stream, router=router, websocket_max_size=websocket_max_size, websocket_max_queue=websocket_max_queue, websocket_read_limit=websocket_read_limit, websocket_write_limit=websocket_write_limit, state=state, debug=debug, ) asyncio_server_kwargs = ( asyncio_server_kwargs if asyncio_server_kwargs else {} ) server_coroutine = loop.create_server( server, host, port, ssl=ssl, reuse_port=reuse_port, sock=sock, backlog=backlog, **asyncio_server_kwargs ) if run_async: return server_coroutine trigger_events(before_start, loop) try: http_server = loop.run_until_complete(server_coroutine) except BaseException: logger.exception("Unable to start server") return trigger_events(after_start, loop) # Ignore SIGINT when run_multiple if run_multiple: signal_func(SIGINT, SIG_IGN) # Register signals for graceful termination if register_sys_signals: _singals = (SIGTERM,) if run_multiple else (SIGINT, SIGTERM) for _signal in _singals: try: loop.add_signal_handler(_signal, loop.stop) except NotImplementedError: logger.warning( "Sanic tried to use loop.add_signal_handler " "but it is not implemented on this platform." ) pid = os.getpid() try: logger.info("Starting worker [%s]", pid) loop.run_forever() finally: logger.info("Stopping worker [%s]", pid) # Run the on_stop function if provided trigger_events(before_stop, loop) # Wait for event loop to finish and all connections to drain http_server.close() loop.run_until_complete(http_server.wait_closed()) # Complete all tasks on the loop signal.stopped = True for connection in connections: connection.close_if_idle() # Gracefully shutdown timeout. # We should provide graceful_shutdown_timeout, # instead of letting connection hangs forever. # Let's roughly calcucate time. start_shutdown = 0 while connections and (start_shutdown < graceful_shutdown_timeout): loop.run_until_complete(asyncio.sleep(0.1)) start_shutdown = start_shutdown + 0.1 # Force close non-idle connection after waiting for # graceful_shutdown_timeout coros = [] for conn in connections: if hasattr(conn, "websocket") and conn.websocket: coros.append(conn.websocket.close_connection()) else: conn.close() _shutdown = asyncio.gather(*coros, loop=loop) loop.run_until_complete(_shutdown) trigger_events(after_stop, loop) loop.close()
[ "Start", "asynchronous", "HTTP", "Server", "on", "an", "individual", "process", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L616-L820
[ "def", "serve", "(", "host", ",", "port", ",", "app", ",", "request_handler", ",", "error_handler", ",", "before_start", "=", "None", ",", "after_start", "=", "None", ",", "before_stop", "=", "None", ",", "after_stop", "=", "None", ",", "debug", "=", "Fa...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.keep_alive
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
sanic/server.py
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 """ return ( self._keep_alive and not self.signal.stopped and self.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 """ return ( self._keep_alive and not self.signal.stopped and self.parser.should_keep_alive() )
[ "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...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L151-L163
[ "def", "keep_alive", "(", "self", ")", ":", "return", "(", "self", ".", "_keep_alive", "and", "not", "self", ".", "signal", ".", "stopped", "and", "self", ".", "parser", ".", "should_keep_alive", "(", ")", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.keep_alive_timeout_callback
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
sanic/server.py
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() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
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() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
[ "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", ...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247
[ "def", "keep_alive_timeout_callback", "(", "self", ")", ":", "time_elapsed", "=", "time", "(", ")", "-", "self", ".", "_last_response_time", "if", "time_elapsed", "<", "self", ".", "keep_alive_timeout", ":", "time_left", "=", "self", ".", "keep_alive_timeout", "...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.execute_request_handler
Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None
sanic/server.py
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 ) self._last_request_time = time() self._request_handler_task = self.loop.create_task( self.request_handler( self.request, self.write_response, self.stream_response ) )
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 ) self._last_request_time = time() self._request_handler_task = self.loop.create_task( self.request_handler( self.request, self.write_response, self.stream_response ) )
[ "Invoke", "the", "request", "handler", "defined", "by", "the", ":", "func", ":", "sanic", ".", "app", ".", "Sanic", ".", "handle_request", "method" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L357-L372
[ "def", "execute_request_handler", "(", "self", ")", ":", "self", ".", "_response_timeout_handler", "=", "self", ".", "loop", ".", "call_later", "(", "self", ".", "response_timeout", ",", "self", ".", "response_timeout_callback", ")", "self", ".", "_last_request_ti...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.log_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 :class:`sanic.response.StreamingHTTPResponse` :return: None
sanic/server.py
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 :class:`sanic.response.StreamingHTTPResponse` :return: None """ if self.access_log: extra = {"status": getattr(response, "status", 0)} if isinstance(response, HTTPResponse): extra["byte"] = len(response.body) else: extra["byte"] = -1 extra["host"] = "UNKNOWN" if self.request is not None: if self.request.ip: extra["host"] = "{0}:{1}".format( self.request.ip, self.request.port ) extra["request"] = "{0} {1}".format( self.request.method, self.request.url ) else: extra["request"] = "nil" access_logger.info("", extra=extra)
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 :class:`sanic.response.StreamingHTTPResponse` :return: None """ if self.access_log: extra = {"status": getattr(response, "status", 0)} if isinstance(response, HTTPResponse): extra["byte"] = len(response.body) else: extra["byte"] = -1 extra["host"] = "UNKNOWN" if self.request is not None: if self.request.ip: extra["host"] = "{0}:{1}".format( self.request.ip, self.request.port ) extra["request"] = "{0} {1}".format( self.request.method, self.request.url ) else: extra["request"] = "nil" access_logger.info("", extra=extra)
[ "Helper", "method", "provided", "to", "enable", "the", "logging", "of", "responses", "in", "case", "if", "the", ":", "attr", ":", "HttpProtocol", ".", "access_log", "is", "enabled", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L377-L410
[ "def", "log_response", "(", "self", ",", "response", ")", ":", "if", "self", ".", "access_log", ":", "extra", "=", "{", "\"status\"", ":", "getattr", "(", "response", ",", "\"status\"", ",", "0", ")", "}", "if", "isinstance", "(", "response", ",", "HTT...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.write_response
Writes response content synchronously to the transport.
sanic/server.py
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_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
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_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
[ "Writes", "response", "content", "synchronously", "to", "the", "transport", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L412-L455
[ "def", "write_response", "(", "self", ",", "response", ")", ":", "if", "self", ".", "_response_timeout_handler", ":", "self", ".", "_response_timeout_handler", ".", "cancel", "(", ")", "self", ".", "_response_timeout_handler", "=", "None", "try", ":", "keep_aliv...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.bail_out
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: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None
sanic/server.py
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: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None """ if from_error or self.transport is None or self.transport.is_closing(): logger.error( "Transport closed @ %s and exception " "experienced during error handling", ( self.transport.get_extra_info("peername") if self.transport is not None else "N/A" ), ) logger.debug("Exception:", exc_info=True) else: self.write_error(ServerError(message)) logger.error(message)
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: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None """ if from_error or self.transport is None or self.transport.is_closing(): logger.error( "Transport closed @ %s and exception " "experienced during error handling", ( self.transport.get_extra_info("peername") if self.transport is not None else "N/A" ), ) logger.debug("Exception:", exc_info=True) else: self.write_error(ServerError(message)) logger.error(message)
[ "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", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L542-L570
[ "def", "bail_out", "(", "self", ",", "message", ",", "from_error", "=", "False", ")", ":", "if", "from_error", "or", "self", ".", "transport", "is", "None", "or", "self", ".", "transport", ".", "is_closing", "(", ")", ":", "logger", ".", "error", "(", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HttpProtocol.cleanup
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.
sanic/server.py
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 self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
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 self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
[ "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", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L572-L583
[ "def", "cleanup", "(", "self", ")", ":", "self", ".", "parser", "=", "None", "self", ".", "request", "=", "None", "self", ".", "url", "=", "None", "self", ".", "headers", "=", "None", "self", ".", "_request_handler_task", "=", "None", "self", ".", "_...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
parse_multipart_form
Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters)
sanic/request.py
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() form_parts = body.split(boundary) for form_part in form_parts[1:-1]: file_name = None content_type = "text/plain" content_charset = "utf-8" field_name = None line_index = 2 line_end_index = 0 while not line_end_index == -1: line_end_index = form_part.find(b"\r\n", line_index) form_line = form_part[line_index:line_end_index].decode("utf-8") line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(":") form_header_field = form_line[0:colon_index].lower() form_header_value, form_parameters = parse_header( form_line[colon_index + 2 :] ) if form_header_field == "content-disposition": field_name = form_parameters.get("name") file_name = form_parameters.get("filename") # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get("filename*"): encoding, _, value = email.utils.decode_rfc2231( form_parameters["filename*"] ) file_name = unquote(value, encoding=encoding) elif form_header_field == "content-type": content_type = form_header_value content_charset = form_parameters.get("charset", "utf-8") if field_name: post_data = form_part[line_index:-4] if file_name is None: value = post_data.decode(content_charset) if field_name in fields: fields[field_name].append(value) else: fields[field_name] = [value] else: form_file = File( type=content_type, name=file_name, body=post_data ) if field_name in files: files[field_name].append(form_file) else: files[field_name] = [form_file] else: logger.debug( "Form-data field does not have a 'name' parameter " "in the Content-Disposition header" ) return fields, 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() form_parts = body.split(boundary) for form_part in form_parts[1:-1]: file_name = None content_type = "text/plain" content_charset = "utf-8" field_name = None line_index = 2 line_end_index = 0 while not line_end_index == -1: line_end_index = form_part.find(b"\r\n", line_index) form_line = form_part[line_index:line_end_index].decode("utf-8") line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(":") form_header_field = form_line[0:colon_index].lower() form_header_value, form_parameters = parse_header( form_line[colon_index + 2 :] ) if form_header_field == "content-disposition": field_name = form_parameters.get("name") file_name = form_parameters.get("filename") # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get("filename*"): encoding, _, value = email.utils.decode_rfc2231( form_parameters["filename*"] ) file_name = unquote(value, encoding=encoding) elif form_header_field == "content-type": content_type = form_header_value content_charset = form_parameters.get("charset", "utf-8") if field_name: post_data = form_part[line_index:-4] if file_name is None: value = post_data.decode(content_charset) if field_name in fields: fields[field_name].append(value) else: fields[field_name] = [value] else: form_file = File( type=content_type, name=file_name, body=post_data ) if field_name in files: files[field_name].append(form_file) else: files[field_name] = [form_file] else: logger.debug( "Form-data field does not have a 'name' parameter " "in the Content-Disposition header" ) return fields, files
[ "Parse", "a", "request", "body", "and", "returns", "fields", "and", "files" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L445-L513
[ "def", "parse_multipart_form", "(", "body", ",", "boundary", ")", ":", "files", "=", "RequestParameters", "(", ")", "fields", "=", "RequestParameters", "(", ")", "form_parts", "=", "body", ".", "split", "(", "boundary", ")", "for", "form_part", "in", "form_p...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
StreamBuffer.read
Stop reading when gets None
sanic/request.py
async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload
async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload
[ "Stop", "reading", "when", "gets", "None" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L57-L61
[ "async", "def", "read", "(", "self", ")", ":", "payload", "=", "await", "self", ".", "_queue", ".", "get", "(", ")", "self", ".", "_queue", ".", "task_done", "(", ")", "return", "payload" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Request.token
Attempt to return the auth header token. :return: token related to request
sanic/request.py
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 auth_header: return auth_header.partition(prefix)[-1].strip() return auth_header
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 auth_header: return auth_header.partition(prefix)[-1].strip() return auth_header
[ "Attempt", "to", "return", "the", "auth", "header", "token", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L158-L171
[ "def", "token", "(", "self", ")", ":", "prefixes", "=", "(", "\"Bearer\"", ",", "\"Token\"", ")", "auth_header", "=", "self", ".", "headers", ".", "get", "(", "\"Authorization\"", ")", "if", "auth_header", "is", "not", "None", ":", "for", "prefix", "in",...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Request.get_args
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 blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: RequestParameters
sanic/request.py
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` 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 blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: RequestParameters """ if not self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = RequestParameters( parse_qs( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) ) return self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
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` 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 blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: RequestParameters """ if not self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = RequestParameters( parse_qs( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) ) return self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
[ "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", "...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L205-L252
[ "def", "get_args", "(", "self", ",", "keep_blank_values", ":", "bool", "=", "False", ",", "strict_parsing", ":", "bool", "=", "False", ",", "encoding", ":", "str", "=", "\"utf-8\"", ",", "errors", ":", "str", "=", "\"replace\"", ",", ")", "->", "RequestP...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Request.get_query_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 that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: list
sanic/request.py
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` 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 blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: list """ if not self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = parse_qsl( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) return self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
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` 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 blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: list """ if not self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = parse_qsl( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) return self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
[ "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", "parameter...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L268-L312
[ "def", "get_query_args", "(", "self", ",", "keep_blank_values", ":", "bool", "=", "False", ",", "strict_parsing", ":", "bool", "=", "False", ",", "encoding", ":", "str", "=", "\"utf-8\"", ",", "errors", ":", "str", "=", "\"replace\"", ",", ")", "->", "li...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Request.remote_addr
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.
sanic/request.py
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.config.PROXIES_COUNT == 0: self._remote_addr = "" elif self.app.config.REAL_IP_HEADER and self.headers.get( self.app.config.REAL_IP_HEADER ): self._remote_addr = self.headers[ self.app.config.REAL_IP_HEADER ] elif self.app.config.FORWARDED_FOR_HEADER: forwarded_for = self.headers.get( self.app.config.FORWARDED_FOR_HEADER, "" ).split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if self.app.config.PROXIES_COUNT == -1: self._remote_addr = remote_addrs[0] elif len(remote_addrs) >= self.app.config.PROXIES_COUNT: self._remote_addr = remote_addrs[ -self.app.config.PROXIES_COUNT ] else: self._remote_addr = "" else: self._remote_addr = "" return self._remote_addr
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.config.PROXIES_COUNT == 0: self._remote_addr = "" elif self.app.config.REAL_IP_HEADER and self.headers.get( self.app.config.REAL_IP_HEADER ): self._remote_addr = self.headers[ self.app.config.REAL_IP_HEADER ] elif self.app.config.FORWARDED_FOR_HEADER: forwarded_for = self.headers.get( self.app.config.FORWARDED_FOR_HEADER, "" ).split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if self.app.config.PROXIES_COUNT == -1: self._remote_addr = remote_addrs[0] elif len(remote_addrs) >= self.app.config.PROXIES_COUNT: self._remote_addr = remote_addrs[ -self.app.config.PROXIES_COUNT ] else: self._remote_addr = "" else: self._remote_addr = "" return self._remote_addr
[ "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", ...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L357-L392
[ "def", "remote_addr", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_remote_addr\"", ")", ":", "if", "self", ".", "app", ".", "config", ".", "PROXIES_COUNT", "==", "0", ":", "self", ".", "_remote_addr", "=", "\"\"", "elif", "self"...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
strtobool
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.
sanic/config.py
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", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
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", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
[ "This", "function", "was", "borrowed", "from", "distutils", ".", "utils", ".", "While", "distutils", "is", "part", "of", "stdlib", "it", "feels", "odd", "to", "use", "distutils", "in", "main", "application", "code", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L136-L150
[ "def", "strtobool", "(", "val", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "\"y\"", ",", "\"yes\"", ",", "\"t\"", ",", "\"true\"", ",", "\"on\"", ",", "\"1\"", ")", ":", "return", "True", "elif", "val", "in", "("...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Config.from_envvar
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.
sanic/config.py
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.environ.get(variable_name) if not config_file: raise RuntimeError( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name ) return self.from_pyfile(config_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.environ.get(variable_name) if not config_file: raise RuntimeError( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name ) return self.from_pyfile(config_file)
[ "Load", "a", "configuration", "from", "an", "environment", "variable", "pointing", "to", "a", "configuration", "file", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L57-L70
[ "def", "from_envvar", "(", "self", ",", "variable_name", ")", ":", "config_file", "=", "os", ".", "environ", ".", "get", "(", "variable_name", ")", "if", "not", "config_file", ":", "raise", "RuntimeError", "(", "\"The environment variable %r is not set and \"", "\...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Config.from_object
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.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration
sanic/config.py
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.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
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.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
[ "Update", "the", "values", "from", "the", "given", "object", ".", "Objects", "are", "usually", "either", "modules", "or", "classes", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L95-L114
[ "def", "from_object", "(", "self", ",", "obj", ")", ":", "for", "key", "in", "dir", "(", "obj", ")", ":", "if", "key", ".", "isupper", "(", ")", ":", "self", "[", "key", "]", "=", "getattr", "(", "obj", ",", "key", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Config.load_environment_vars
Looks for prefixed environment variables and applies them to the configuration if present.
sanic/config.py
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) try: self[config_key] = int(v) except ValueError: try: self[config_key] = float(v) except ValueError: try: self[config_key] = strtobool(v) except ValueError: self[config_key] = v
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) try: self[config_key] = int(v) except ValueError: try: self[config_key] = float(v) except ValueError: try: self[config_key] = strtobool(v) except ValueError: self[config_key] = v
[ "Looks", "for", "prefixed", "environment", "variables", "and", "applies", "them", "to", "the", "configuration", "if", "present", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L116-L133
[ "def", "load_environment_vars", "(", "self", ",", "prefix", "=", "SANIC_PREFIX", ")", ":", "for", "k", ",", "v", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "k", ".", "startswith", "(", "prefix", ")", ":", "_", ",", "config_key", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.parse_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 :return: tuple containing (parameter_name, parameter_type, parameter_pattern)
sanic/router.py
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 :return: tuple containing (parameter_name, parameter_type, parameter_pattern) """ # We could receive NAME or NAME:PATTERN name = parameter_string pattern = "string" if ":" in parameter_string: name, pattern = parameter_string.split(":", 1) if not name: raise ValueError( "Invalid parameter syntax: {}".format(parameter_string) ) default = (str, pattern) # Pull from pre-configured types _type, pattern = REGEX_TYPES.get(pattern, default) return name, _type, 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 :return: tuple containing (parameter_name, parameter_type, parameter_pattern) """ # We could receive NAME or NAME:PATTERN name = parameter_string pattern = "string" if ":" in parameter_string: name, pattern = parameter_string.split(":", 1) if not name: raise ValueError( "Invalid parameter syntax: {}".format(parameter_string) ) default = (str, pattern) # Pull from pre-configured types _type, pattern = REGEX_TYPES.get(pattern, default) return name, _type, pattern
[ "Parse", "a", "parameter", "string", "into", "its", "constituent", "name", "type", "and", "pattern" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L92-L119
[ "def", "parse_parameter_string", "(", "cls", ",", "parameter_string", ")", ":", "# We could receive NAME or NAME:PATTERN", "name", "=", "parameter_string", "pattern", "=", "\"string\"", "if", "\":\"", "in", "parameter_string", ":", "name", ",", "pattern", "=", "parame...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.add
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 executed, it should provide a response object. :param strict_slashes: strict to trailing slash :param version: current version of the route or blueprint. See docs for further details. :return: Nothing
sanic/router.py
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 provided, any method is allowed :param handler: request handler function. When executed, it should provide a response object. :param strict_slashes: strict to trailing slash :param version: current version of the route or blueprint. See docs for further details. :return: Nothing """ if version is not None: version = re.escape(str(version).strip("/").lstrip("v")) uri = "/".join(["/v{}".format(version), uri.lstrip("/")]) # add regular version self._add(uri, methods, handler, host, name) if strict_slashes: return if not isinstance(host, str) and host is not None: # we have gotten back to the top of the recursion tree where the # host was originally a list. By now, we've processed the strict # slashes logic on the leaf nodes (the individual host strings in # the list of host) return # Add versions with and without trailing / slashed_methods = self.routes_all.get(uri + "/", frozenset({})) unslashed_methods = self.routes_all.get(uri[:-1], frozenset({})) if isinstance(methods, Iterable): _slash_is_missing = all( method in slashed_methods for method in methods ) _without_slash_is_missing = all( method in unslashed_methods for method in methods ) else: _slash_is_missing = methods in slashed_methods _without_slash_is_missing = methods in unslashed_methods slash_is_missing = not uri[-1] == "/" and not _slash_is_missing without_slash_is_missing = ( uri[-1] == "/" and not _without_slash_is_missing and not uri == "/" ) # add version with trailing slash if slash_is_missing: self._add(uri + "/", methods, handler, host, name) # add version without trailing slash elif without_slash_is_missing: self._add(uri[:-1], methods, handler, host, name)
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 provided, any method is allowed :param handler: request handler function. When executed, it should provide a response object. :param strict_slashes: strict to trailing slash :param version: current version of the route or blueprint. See docs for further details. :return: Nothing """ if version is not None: version = re.escape(str(version).strip("/").lstrip("v")) uri = "/".join(["/v{}".format(version), uri.lstrip("/")]) # add regular version self._add(uri, methods, handler, host, name) if strict_slashes: return if not isinstance(host, str) and host is not None: # we have gotten back to the top of the recursion tree where the # host was originally a list. By now, we've processed the strict # slashes logic on the leaf nodes (the individual host strings in # the list of host) return # Add versions with and without trailing / slashed_methods = self.routes_all.get(uri + "/", frozenset({})) unslashed_methods = self.routes_all.get(uri[:-1], frozenset({})) if isinstance(methods, Iterable): _slash_is_missing = all( method in slashed_methods for method in methods ) _without_slash_is_missing = all( method in unslashed_methods for method in methods ) else: _slash_is_missing = methods in slashed_methods _without_slash_is_missing = methods in unslashed_methods slash_is_missing = not uri[-1] == "/" and not _slash_is_missing without_slash_is_missing = ( uri[-1] == "/" and not _without_slash_is_missing and not uri == "/" ) # add version with trailing slash if slash_is_missing: self._add(uri + "/", methods, handler, host, name) # add version without trailing slash elif without_slash_is_missing: self._add(uri[:-1], methods, handler, host, name)
[ "Add", "a", "handler", "to", "the", "route", "list" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L121-L182
[ "def", "add", "(", "self", ",", "uri", ",", "methods", ",", "handler", ",", "host", "=", "None", ",", "strict_slashes", "=", "False", ",", "version", "=", "None", ",", "name", "=", "None", ",", ")", ":", "if", "version", "is", "not", "None", ":", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router._add
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 executed, it should provide a response object. :param name: user defined route name for url_for :return: Nothing
sanic/router.py
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 executed, it should provide a response object. :param name: user defined route name for url_for :return: Nothing """ if host is not None: if isinstance(host, str): uri = host + uri self.hosts.add(host) else: if not isinstance(host, Iterable): raise ValueError( "Expected either string or Iterable of " "host strings, not {!r}".format(host) ) for host_ in host: self.add(uri, methods, handler, host_, name) return # Dict for faster lookups of if method allowed if methods: methods = frozenset(methods) parameters = [] parameter_names = set() properties = {"unhashable": None} def add_parameter(match): name = match.group(1) name, _type, pattern = self.parse_parameter_string(name) if name in parameter_names: raise ParameterNameConflicts( "Multiple parameter named <{name}> " "in route uri {uri}".format(name=name, uri=uri) ) parameter_names.add(name) parameter = Parameter(name=name, cast=_type) parameters.append(parameter) # Mark the whole route as unhashable if it has the hash key in it if re.search(r"(^|[^^]){1}/", pattern): properties["unhashable"] = True # Mark the route as unhashable if it matches the hash key elif re.search(r"/", pattern): properties["unhashable"] = True return "({})".format(pattern) pattern_string = re.sub(self.parameter_pattern, add_parameter, uri) pattern = re.compile(r"^{}$".format(pattern_string)) def merge_route(route, methods, handler): # merge to the existing route when possible. if not route.methods or not methods: # method-unspecified routes are not mergeable. raise RouteExists("Route already registered: {}".format(uri)) elif route.methods.intersection(methods): # already existing method is not overloadable. duplicated = methods.intersection(route.methods) raise RouteExists( "Route already registered: {} [{}]".format( uri, ",".join(list(duplicated)) ) ) if isinstance(route.handler, CompositionView): view = route.handler else: view = CompositionView() view.add(route.methods, route.handler) view.add(methods, handler) route = route._replace( handler=view, methods=methods.union(route.methods) ) return route if parameters: # TODO: This is too complex, we need to reduce the complexity if properties["unhashable"]: routes_to_check = self.routes_always_check ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) else: routes_to_check = self.routes_dynamic[url_hash(uri)] ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) if ndx != -1: # Pop the ndx of the route, no dups of the same route routes_to_check.pop(ndx) else: route = self.routes_all.get(uri) # prefix the handler name with the blueprint name # if available # special prefix for static files is_static = False if name and name.startswith("_static_"): is_static = True name = name.split("_static_", 1)[-1] if hasattr(handler, "__blueprintname__"): handler_name = "{}.{}".format( handler.__blueprintname__, name or handler.__name__ ) else: handler_name = name or getattr(handler, "__name__", None) if route: route = merge_route(route, methods, handler) else: route = Route( handler=handler, methods=methods, pattern=pattern, parameters=parameters, name=handler_name, uri=uri, ) self.routes_all[uri] = route if is_static: pair = self.routes_static_files.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_static_files[handler_name] = (uri, route) else: pair = self.routes_names.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_names[handler_name] = (uri, route) if properties["unhashable"]: self.routes_always_check.append(route) elif parameters: self.routes_dynamic[url_hash(uri)].append(route) else: self.routes_static[uri] = route
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 executed, it should provide a response object. :param name: user defined route name for url_for :return: Nothing """ if host is not None: if isinstance(host, str): uri = host + uri self.hosts.add(host) else: if not isinstance(host, Iterable): raise ValueError( "Expected either string or Iterable of " "host strings, not {!r}".format(host) ) for host_ in host: self.add(uri, methods, handler, host_, name) return # Dict for faster lookups of if method allowed if methods: methods = frozenset(methods) parameters = [] parameter_names = set() properties = {"unhashable": None} def add_parameter(match): name = match.group(1) name, _type, pattern = self.parse_parameter_string(name) if name in parameter_names: raise ParameterNameConflicts( "Multiple parameter named <{name}> " "in route uri {uri}".format(name=name, uri=uri) ) parameter_names.add(name) parameter = Parameter(name=name, cast=_type) parameters.append(parameter) # Mark the whole route as unhashable if it has the hash key in it if re.search(r"(^|[^^]){1}/", pattern): properties["unhashable"] = True # Mark the route as unhashable if it matches the hash key elif re.search(r"/", pattern): properties["unhashable"] = True return "({})".format(pattern) pattern_string = re.sub(self.parameter_pattern, add_parameter, uri) pattern = re.compile(r"^{}$".format(pattern_string)) def merge_route(route, methods, handler): # merge to the existing route when possible. if not route.methods or not methods: # method-unspecified routes are not mergeable. raise RouteExists("Route already registered: {}".format(uri)) elif route.methods.intersection(methods): # already existing method is not overloadable. duplicated = methods.intersection(route.methods) raise RouteExists( "Route already registered: {} [{}]".format( uri, ",".join(list(duplicated)) ) ) if isinstance(route.handler, CompositionView): view = route.handler else: view = CompositionView() view.add(route.methods, route.handler) view.add(methods, handler) route = route._replace( handler=view, methods=methods.union(route.methods) ) return route if parameters: # TODO: This is too complex, we need to reduce the complexity if properties["unhashable"]: routes_to_check = self.routes_always_check ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) else: routes_to_check = self.routes_dynamic[url_hash(uri)] ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) if ndx != -1: # Pop the ndx of the route, no dups of the same route routes_to_check.pop(ndx) else: route = self.routes_all.get(uri) # prefix the handler name with the blueprint name # if available # special prefix for static files is_static = False if name and name.startswith("_static_"): is_static = True name = name.split("_static_", 1)[-1] if hasattr(handler, "__blueprintname__"): handler_name = "{}.{}".format( handler.__blueprintname__, name or handler.__name__ ) else: handler_name = name or getattr(handler, "__name__", None) if route: route = merge_route(route, methods, handler) else: route = Route( handler=handler, methods=methods, pattern=pattern, parameters=parameters, name=handler_name, uri=uri, ) self.routes_all[uri] = route if is_static: pair = self.routes_static_files.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_static_files[handler_name] = (uri, route) else: pair = self.routes_names.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_names[handler_name] = (uri, route) if properties["unhashable"]: self.routes_always_check.append(route) elif parameters: self.routes_dynamic[url_hash(uri)].append(route) else: self.routes_static[uri] = route
[ "Add", "a", "handler", "to", "the", "route", "list" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L184-L330
[ "def", "_add", "(", "self", ",", "uri", ",", "methods", ",", "handler", ",", "host", "=", "None", ",", "name", "=", "None", ")", ":", "if", "host", "is", "not", "None", ":", "if", "isinstance", "(", "host", ",", "str", ")", ":", "uri", "=", "ho...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.check_dynamic_route_exists
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 either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route
sanic/router.py
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 either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route """ for ndx, route in enumerate(routes_to_check): if route.pattern == pattern and route.parameters == parameters: return ndx, route else: return -1, None
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 either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route """ for ndx, route in enumerate(routes_to_check): if route.pattern == pattern and route.parameters == parameters: return ndx, route else: return -1, None
[ "Check", "if", "a", "URL", "pattern", "exists", "in", "a", "list", "of", "routes", "provided", "based", "on", "the", "comparison", "of", "URL", "pattern", "and", "the", "parameters", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L333-L349
[ "def", "check_dynamic_route_exists", "(", "pattern", ",", "routes_to_check", ",", "parameters", ")", ":", "for", "ndx", ",", "route", "in", "enumerate", "(", "routes_to_check", ")", ":", "if", "route", ".", "pattern", "==", "pattern", "and", "route", ".", "p...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.find_route_by_view_name
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)
sanic/router.py
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) """ if not view_name: return (None, None) if view_name == "static" or view_name.endswith(".static"): return self.routes_static_files.get(name, (None, None)) return self.routes_names.get(view_name, (None, None))
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) """ if not view_name: return (None, None) if view_name == "static" or view_name.endswith(".static"): return self.routes_static_files.get(name, (None, None)) return self.routes_names.get(view_name, (None, None))
[ "Find", "a", "route", "in", "the", "router", "based", "on", "the", "specified", "view", "name", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L383-L396
[ "def", "find_route_by_view_name", "(", "self", ",", "view_name", ",", "name", "=", "None", ")", ":", "if", "not", "view_name", ":", "return", "(", "None", ",", "None", ")", "if", "view_name", "==", "\"static\"", "or", "view_name", ".", "endswith", "(", "...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.get
Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments
sanic/router.py
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: return self._get(request.path, request.method, "") # virtual hosts specified; try to match route to the host header try: return self._get( request.path, request.method, request.headers.get("Host", "") ) # try default hosts except NotFound: return self._get(request.path, request.method, "")
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: return self._get(request.path, request.method, "") # virtual hosts specified; try to match route to the host header try: return self._get( request.path, request.method, request.headers.get("Host", "") ) # try default hosts except NotFound: return self._get(request.path, request.method, "")
[ "Get", "a", "request", "handler", "based", "on", "the", "URL", "of", "the", "request", "or", "raises", "an", "error" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L398-L415
[ "def", "get", "(", "self", ",", "request", ")", ":", "# No virtual hosts specified; default behavior", "if", "not", "self", ".", "hosts", ":", "return", "self", ".", "_get", "(", "request", ".", "path", ",", "request", ".", "method", ",", "\"\"", ")", "# v...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.get_supported_methods
Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods
sanic/router.py
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 an error return getattr(route, "methods", None) or frozenset()
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 an error return getattr(route, "methods", None) or frozenset()
[ "Get", "a", "list", "of", "supported", "methods", "for", "a", "url", "and", "optional", "host", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L417-L425
[ "def", "get_supported_methods", "(", "self", ",", "url", ")", ":", "route", "=", "self", ".", "routes_all", ".", "get", "(", "url", ")", "# if methods are None then this logic will prevent an error", "return", "getattr", "(", "route", ",", "\"methods\"", ",", "Non...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router._get
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
sanic/router.py
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(host + url) # Check against known static routes route = self.routes_static.get(url) method_not_supported = MethodNotSupported( "Method {} not allowed for URL {}".format(method, url), method=method, allowed_methods=self.get_supported_methods(url), ) if route: if route.methods and method not in route.methods: raise method_not_supported match = route.pattern.match(url) else: route_found = False # Move on to testing all regex routes for route in self.routes_dynamic[url_hash(url)]: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Lastly, check against all regex routes that cannot be hashed for route in self.routes_always_check: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Route was found but the methods didn't match if route_found: raise method_not_supported raise NotFound("Requested URL {} not found".format(url)) kwargs = { p.name: p.cast(value) for value, p in zip(match.groups(1), route.parameters) } route_handler = route.handler if hasattr(route_handler, "handlers"): route_handler = route_handler.handlers[method] return route_handler, [], kwargs, route.uri
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(host + url) # Check against known static routes route = self.routes_static.get(url) method_not_supported = MethodNotSupported( "Method {} not allowed for URL {}".format(method, url), method=method, allowed_methods=self.get_supported_methods(url), ) if route: if route.methods and method not in route.methods: raise method_not_supported match = route.pattern.match(url) else: route_found = False # Move on to testing all regex routes for route in self.routes_dynamic[url_hash(url)]: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Lastly, check against all regex routes that cannot be hashed for route in self.routes_always_check: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Route was found but the methods didn't match if route_found: raise method_not_supported raise NotFound("Requested URL {} not found".format(url)) kwargs = { p.name: p.cast(value) for value, p in zip(match.groups(1), route.parameters) } route_handler = route.handler if hasattr(route_handler, "handlers"): route_handler = route_handler.handlers[method] return route_handler, [], kwargs, route.uri
[ "Get", "a", "request", "handler", "based", "on", "the", "URL", "of", "the", "request", "or", "raises", "an", "error", ".", "Internal", "method", "for", "caching", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L428-L478
[ "def", "_get", "(", "self", ",", "url", ",", "method", ",", "host", ")", ":", "url", "=", "unquote", "(", "host", "+", "url", ")", "# Check against known static routes", "route", "=", "self", ".", "routes_static", ".", "get", "(", "url", ")", "method_not...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
Router.is_stream_handler
Handler for request is stream or not. :param request: Request object :return: bool
sanic/router.py
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, "view_class") and hasattr( handler.view_class, request.method.lower() ): handler = getattr(handler.view_class, request.method.lower()) return hasattr(handler, "is_stream")
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, "view_class") and hasattr( handler.view_class, request.method.lower() ): handler = getattr(handler.view_class, request.method.lower()) return hasattr(handler, "is_stream")
[ "Handler", "for", "request", "is", "stream", "or", "not", ".", ":", "param", "request", ":", "Request", "object", ":", "return", ":", "bool" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L480-L493
[ "def", "is_stream_handler", "(", "self", ",", "request", ")", ":", "try", ":", "handler", "=", "self", ".", "get", "(", "request", ")", "[", "0", "]", "except", "(", "NotFound", ",", "MethodNotSupported", ")", ":", "return", "False", "if", "hasattr", "...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
_get_args_for_reloading
Returns the executable.
sanic/reloader_helpers.py
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]) if len(sys.argv) > 1: rv.extend(sys.argv[1:]) else: rv.extend(sys.argv) return rv
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]) if len(sys.argv) > 1: rv.extend(sys.argv[1:]) else: rv.extend(sys.argv) return rv
[ "Returns", "the", "executable", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L36-L48
[ "def", "_get_args_for_reloading", "(", ")", ":", "rv", "=", "[", "sys", ".", "executable", "]", "main_module", "=", "sys", ".", "modules", "[", "\"__main__\"", "]", "mod_spec", "=", "getattr", "(", "main_module", ",", "\"__spec__\"", ",", "None", ")", "if"...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
restart_with_reloader
Create a new process and a subprocess in it with the same arguments as this one.
sanic/reloader_helpers.py
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 = Process( target=subprocess.call, args=(cmd,), kwargs={"cwd": cwd, "shell": True, "env": new_environ}, ) worker_process.start() return worker_process
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 = Process( target=subprocess.call, args=(cmd,), kwargs={"cwd": cwd, "shell": True, "env": new_environ}, ) worker_process.start() return worker_process
[ "Create", "a", "new", "process", "and", "a", "subprocess", "in", "it", "with", "the", "same", "arguments", "as", "this", "one", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L51-L66
[ "def", "restart_with_reloader", "(", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "args", "=", "_get_args_for_reloading", "(", ")", "new_environ", "=", "os", ".", "environ", ".", "copy", "(", ")", "new_environ", "[", "\"SANIC_SERVER_RUNNING\"", "]", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
kill_process_children_unix
Find and kill child processes of a process (maximum two level). :param pid: PID of parent process (process ID) :return: Nothing
sanic/reloader_helpers.py
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): return with open(root_process_path) as children_list_file: children_list_pid = children_list_file.read().split() for child_pid in children_list_pid: children_proc_path = "/proc/%s/task/%s/children" % ( child_pid, child_pid, ) if not os.path.isfile(children_proc_path): continue with open(children_proc_path) as children_list_file_2: children_list_pid_2 = children_list_file_2.read().split() for _pid in children_list_pid_2: try: os.kill(int(_pid), signal.SIGTERM) except ProcessLookupError: continue try: os.kill(int(child_pid), signal.SIGTERM) except ProcessLookupError: continue
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): return with open(root_process_path) as children_list_file: children_list_pid = children_list_file.read().split() for child_pid in children_list_pid: children_proc_path = "/proc/%s/task/%s/children" % ( child_pid, child_pid, ) if not os.path.isfile(children_proc_path): continue with open(children_proc_path) as children_list_file_2: children_list_pid_2 = children_list_file_2.read().split() for _pid in children_list_pid_2: try: os.kill(int(_pid), signal.SIGTERM) except ProcessLookupError: continue try: os.kill(int(child_pid), signal.SIGTERM) except ProcessLookupError: continue
[ "Find", "and", "kill", "child", "processes", "of", "a", "process", "(", "maximum", "two", "level", ")", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L69-L98
[ "def", "kill_process_children_unix", "(", "pid", ")", ":", "root_process_path", "=", "\"/proc/{pid}/task/{pid}/children\"", ".", "format", "(", "pid", "=", "pid", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "root_process_path", ")", ":", "return", ...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
kill_process_children
Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing
sanic/reloader_helpers.py
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: pass
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: pass
[ "Find", "and", "kill", "child", "processes", "of", "a", "process", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L110-L121
[ "def", "kill_process_children", "(", "pid", ")", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "kill_process_children_osx", "(", "pid", ")", "elif", "sys", ".", "platform", "==", "\"linux\"", ":", "kill_process_children_unix", "(", "pid", ")", "e...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
watchdog
Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing
sanic/reloader_helpers.py
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(worker_process) ) signal.signal( signal.SIGINT, lambda *args: kill_program_completly(worker_process) ) while True: for filename in _iter_module_files(): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: kill_process_children(worker_process.pid) worker_process.terminate() worker_process = restart_with_reloader() mtimes[filename] = mtime break sleep(sleep_interval)
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(worker_process) ) signal.signal( signal.SIGINT, lambda *args: kill_program_completly(worker_process) ) while True: for filename in _iter_module_files(): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: kill_process_children(worker_process.pid) worker_process.terminate() worker_process = restart_with_reloader() mtimes[filename] = mtime break sleep(sleep_interval)
[ "Watch", "project", "files", "restart", "worker", "process", "if", "a", "change", "happened", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L135-L167
[ "def", "watchdog", "(", "sleep_interval", ")", ":", "mtimes", "=", "{", "}", "worker_process", "=", "restart_with_reloader", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "lambda", "*", "args", ":", "kill_program_completly", "(", "wo...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
HTTPMethodView.as_view
Return view function for use with the routing system, that dispatches request to appropriate handler method.
sanic/views.py
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_request(*args, **kwargs) if cls.decorators: view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) view.view_class = cls view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__name__ = cls.__name__ return view
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_request(*args, **kwargs) if cls.decorators: view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) view.view_class = cls view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__name__ = cls.__name__ return view
[ "Return", "view", "function", "for", "use", "with", "the", "routing", "system", "that", "dispatches", "request", "to", "appropriate", "handler", "method", "." ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/views.py#L47-L65
[ "def", "as_view", "(", "cls", ",", "*", "class_args", ",", "*", "*", "class_kwargs", ")", ":", "def", "view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "view", ".", "view_class", "(", "*", "class_args", ",", "*", "*", "cla...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
bounded_fetch
Use session object to perform 'get' request on url
examples/limit_concurrency.py
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()
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()
[ "Use", "session", "object", "to", "perform", "get", "request", "on", "url" ]
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/examples/limit_concurrency.py#L18-L23
[ "async", "def", "bounded_fetch", "(", "session", ",", "url", ")", ":", "async", "with", "sem", ",", "session", ".", "get", "(", "url", ")", "as", "response", ":", "return", "await", "response", ".", "json", "(", ")" ]
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
remove_entity_headers
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 returns the headers without the entity headers
sanic/helpers.py
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#section-10.3.5 returns the headers without the entity headers """ allowed = set([h.lower() for h in allowed]) headers = { header: value for header, value in headers.items() if not is_entity_header(header) or header.lower() in allowed } return headers
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#section-10.3.5 returns the headers without the entity headers """ allowed = set([h.lower() for h in allowed]) headers = { header: value for header, value in headers.items() if not is_entity_header(header) or header.lower() in allowed } return headers
[ "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", "str...
huge-success/sanic
python
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/helpers.py#L117-L133
[ "def", "remove_entity_headers", "(", "headers", ",", "allowed", "=", "(", "\"content-location\"", ",", "\"expires\"", ")", ")", ":", "allowed", "=", "set", "(", "[", "h", ".", "lower", "(", ")", "for", "h", "in", "allowed", "]", ")", "headers", "=", "{...
6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd
train
preserve_shape
Preserve shape of the image.
albumentations/augmentations/functional.py
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
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", "shape", "of", "the", "image", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L35-L44
[ "def", "preserve_shape", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_function", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "shape", "=", "img", ".", "shape", "result", "=", "func", "(", "img", ",", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
preserve_channel_dim
Preserve dummy channel dim.
albumentations/augmentations/functional.py
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(result, axis=-1) return result return wrapped_function
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(result, axis=-1) return result return wrapped_function
[ "Preserve", "dummy", "channel", "dim", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L47-L57
[ "def", "preserve_channel_dim", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_function", "(", "img", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "shape", "=", "img", ".", "shape", "result", "=", "func", "(", "img", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
add_snow
Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns:
albumentations/augmentations/functional.py
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 needs_float = False snow_point *= 127.5 # = 255 / 2 snow_point += 85 # = 255 / 3 if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) image_HLS = np.array(image_HLS, dtype=np.float32) image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255) image_HLS = np.array(image_HLS, dtype=np.uint8) image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB) if needs_float: image_RGB = to_float(image_RGB, max_value=255) return image_RGB
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 needs_float = False snow_point *= 127.5 # = 255 / 2 snow_point += 85 # = 255 / 3 if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) image_HLS = np.array(image_HLS, dtype=np.float32) image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255) image_HLS = np.array(image_HLS, dtype=np.uint8) image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB) if needs_float: image_RGB = to_float(image_RGB, max_value=255) return image_RGB
[ "Bleaches", "out", "pixels", "mitation", "snow", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L438-L479
[ "def", "add_snow", "(", "img", ",", "snow_point", ",", "brightness_coeff", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "snow_point", "*=", "127.5", "# = 255 / 2", "snow_point", "+=", "85",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
add_fog
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:
albumentations/augmentations/functional.py
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) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype)) height, width = img.shape[:2] hw = max(int(width // 3 * fog_coef), 10) for haze_points in haze_list: x, y = haze_points overlay = img.copy() output = img.copy() alpha = alpha_coef * fog_coef rad = hw // 2 point = (x + hw // 2, y + hw // 2) cv2.circle(overlay, point, int(rad), (255, 255, 255), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) img = output.copy() image_rgb = cv2.blur(img, (hw // 10, hw // 10)) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype)) height, width = img.shape[:2] hw = max(int(width // 3 * fog_coef), 10) for haze_points in haze_list: x, y = haze_points overlay = img.copy() output = img.copy() alpha = alpha_coef * fog_coef rad = hw // 2 point = (x + hw // 2, y + hw // 2) cv2.circle(overlay, point, int(rad), (255, 255, 255), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) img = output.copy() image_rgb = cv2.blur(img, (hw // 10, hw // 10)) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "Add", "fog", "to", "the", "image", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L533-L578
[ "def", "add_fog", "(", "img", ",", "fog_coef", ",", "alpha_coef", ",", "haze_list", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "input_dtype", "==", "np", ".", "float32", ":", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
add_sun_flare
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_color (int, int, int): circles (list): Returns:
albumentations/augmentations/functional.py
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_color (int, int, int): circles (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype)) overlay = img.copy() output = img.copy() for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles: cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) point = (int(flare_center_x), int(flare_center_y)) overlay = output.copy() num_times = src_radius // 10 alpha = np.linspace(0.0, 1, num=num_times) rad = np.linspace(1, src_radius, num=num_times) for i in range(num_times): cv2.circle(overlay, point, int(rad[i]), src_color, -1) alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1] cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output) image_rgb = output if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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_color (int, int, int): circles (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype)) overlay = img.copy() output = img.copy() for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles: cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) point = (int(flare_center_x), int(flare_center_y)) overlay = output.copy() num_times = src_radius // 10 alpha = np.linspace(0.0, 1, num=num_times) rad = np.linspace(1, src_radius, num=num_times) for i in range(num_times): cv2.circle(overlay, point, int(rad[i]), src_color, -1) alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1] cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output) image_rgb = output if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "Add", "sun", "flare", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L582-L633
[ "def", "add_sun_flare", "(", "img", ",", "flare_center_x", ",", "flare_center_y", ",", "src_radius", ",", "src_color", ",", "circles", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
add_shadow
Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns:
albumentations/augmentations/functional.py
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 input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) mask = np.zeros_like(img) # adding all shadow polygons on empty mask, single 255 denotes only red channel for vertices in vertices_list: cv2.fillPoly(mask, vertices, 255) # if red channel is hot, image's "Lightness" channel's brightness is lowered red_max_value_ind = mask[:, :, 0] == 255 image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5 image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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 input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) mask = np.zeros_like(img) # adding all shadow polygons on empty mask, single 255 denotes only red channel for vertices in vertices_list: cv2.fillPoly(mask, vertices, 255) # if red channel is hot, image's "Lightness" channel's brightness is lowered red_max_value_ind = mask[:, :, 0] == 255 image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5 image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
[ "Add", "shadows", "to", "the", "image", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L637-L675
[ "def", "add_shadow", "(", "img", ",", "vertices_list", ")", ":", "non_rgb_warning", "(", "img", ")", "input_dtype", "=", "img", ".", "dtype", "needs_float", "=", "False", "if", "input_dtype", "==", "np", ".", "float32", ":", "img", "=", "from_float", "(", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
optical_distortion
Barrel / pincushion distortion. Unconventional augment. Reference: | https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv | https://stackoverflow.com/questions/2477774/correcting-fisheye-distortion-programmatically | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/
albumentations/augmentations/functional.py
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-distortion | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv | https://stackoverflow.com/questions/2477774/correcting-fisheye-distortion-programmatically | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/ """ height, width = img.shape[:2] fx = width fy = width cx = width * 0.5 + dx cy = height * 0.5 + dy camera_matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) distortion = np.array([k, k, 0, 0, 0], dtype=np.float32) map1, map2 = cv2.initUndistortRectifyMap(camera_matrix, distortion, None, None, (width, height), cv2.CV_32FC1) img = cv2.remap(img, map1, map2, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
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-distortion | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv | https://stackoverflow.com/questions/2477774/correcting-fisheye-distortion-programmatically | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/ """ height, width = img.shape[:2] fx = width fy = width cx = width * 0.5 + dx cy = height * 0.5 + dy camera_matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) distortion = np.array([k, k, 0, 0, 0], dtype=np.float32) map1, map2 = cv2.initUndistortRectifyMap(camera_matrix, distortion, None, None, (width, height), cv2.CV_32FC1) img = cv2.remap(img, map1, map2, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
[ "Barrel", "/", "pincushion", "distortion", ".", "Unconventional", "augment", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L679-L704
[ "def", "optical_distortion", "(", "img", ",", "k", "=", "0", ",", "dx", "=", "0", ",", "dy", "=", "0", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ",", "border_mode", "=", "cv2", ".", "BORDER_REFLECT_101", ",", "value", "=", "None", ")", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
grid_distortion
Reference: http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
albumentations/augmentations/functional.py
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] x_step = width // num_steps xx = np.zeros(width, np.float32) prev = 0 for idx, x in enumerate(range(0, width, x_step)): start = x end = x + x_step if end > width: end = width cur = width else: cur = prev + x_step * xsteps[idx] xx[start:end] = np.linspace(prev, cur, end - start) prev = cur y_step = height // num_steps yy = np.zeros(height, np.float32) prev = 0 for idx, y in enumerate(range(0, height, y_step)): start = y end = y + y_step if end > height: end = height cur = height else: cur = prev + y_step * ysteps[idx] yy[start:end] = np.linspace(prev, cur, end - start) prev = cur map_x, map_y = np.meshgrid(xx, yy) map_x = map_x.astype(np.float32) map_y = map_y.astype(np.float32) img = cv2.remap(img, map_x, map_y, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
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] x_step = width // num_steps xx = np.zeros(width, np.float32) prev = 0 for idx, x in enumerate(range(0, width, x_step)): start = x end = x + x_step if end > width: end = width cur = width else: cur = prev + x_step * xsteps[idx] xx[start:end] = np.linspace(prev, cur, end - start) prev = cur y_step = height // num_steps yy = np.zeros(height, np.float32) prev = 0 for idx, y in enumerate(range(0, height, y_step)): start = y end = y + y_step if end > height: end = height cur = height else: cur = prev + y_step * ysteps[idx] yy[start:end] = np.linspace(prev, cur, end - start) prev = cur map_x, map_y = np.meshgrid(xx, yy) map_x = map_x.astype(np.float32) map_y = map_y.astype(np.float32) img = cv2.remap(img, map_x, map_y, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
[ "Reference", ":", "http", ":", "//", "pythology", ".", "blogspot", ".", "sg", "/", "2014", "/", "03", "/", "interpolation", "-", "on", "-", "regular", "-", "distorted", "-", "grid", ".", "html" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L708-L750
[ "def", "grid_distortion", "(", "img", ",", "num_steps", "=", "10", ",", "xsteps", "=", "[", "]", ",", "ysteps", "=", "[", "]", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ",", "border_mode", "=", "cv2", ".", "BORDER_REFLECT_101", ",", "value",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
elastic_transform
Elastic deformation of images as described in [Simard2003]_ (with modifications). Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5 .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003.
albumentations/augmentations/functional.py
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.com/erniejunior/601cdf56d2b424757de5 .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. """ if random_state is None: random_state = np.random.RandomState(1234) height, width = image.shape[:2] # Random affine center_square = np.float32((height, width)) // 2 square_size = min((height, width)) // 3 alpha = float(alpha) sigma = float(sigma) alpha_affine = float(alpha_affine) pts1 = np.float32([center_square + square_size, [center_square[0] + square_size, center_square[1] - square_size], center_square - square_size]) pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32) matrix = cv2.getAffineTransform(pts1, pts2) image = cv2.warpAffine(image, matrix, (width, height), flags=interpolation, borderMode=border_mode, borderValue=value) if approximate: # Approximate computation smooth displacement map with a large enough kernel. # On large images (512+) this is approximately 2X times faster dx = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dx, (17, 17), sigma, dst=dx) dx *= alpha dy = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dy, (17, 17), sigma, dst=dy) dy *= alpha else: dx = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) dy = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) x, y = np.meshgrid(np.arange(width), np.arange(height)) mapx = np.float32(x + dx) mapy = np.float32(y + dy) return cv2.remap(image, mapx, mapy, interpolation, borderMode=border_mode)
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.com/erniejunior/601cdf56d2b424757de5 .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. """ if random_state is None: random_state = np.random.RandomState(1234) height, width = image.shape[:2] # Random affine center_square = np.float32((height, width)) // 2 square_size = min((height, width)) // 3 alpha = float(alpha) sigma = float(sigma) alpha_affine = float(alpha_affine) pts1 = np.float32([center_square + square_size, [center_square[0] + square_size, center_square[1] - square_size], center_square - square_size]) pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32) matrix = cv2.getAffineTransform(pts1, pts2) image = cv2.warpAffine(image, matrix, (width, height), flags=interpolation, borderMode=border_mode, borderValue=value) if approximate: # Approximate computation smooth displacement map with a large enough kernel. # On large images (512+) this is approximately 2X times faster dx = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dx, (17, 17), sigma, dst=dx) dx *= alpha dy = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dy, (17, 17), sigma, dst=dy) dy *= alpha else: dx = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) dy = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) x, y = np.meshgrid(np.arange(width), np.arange(height)) mapx = np.float32(x + dx) mapy = np.float32(y + dy) return cv2.remap(image, mapx, mapy, interpolation, borderMode=border_mode)
[ "Elastic", "deformation", "of", "images", "as", "described", "in", "[", "Simard2003", "]", "_", "(", "with", "modifications", ")", ".", "Based", "on", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "erniejunior", "/", "601cdf56d2b424757de5" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L754-L803
[ "def", "elastic_transform", "(", "image", ",", "alpha", ",", "sigma", ",", "alpha_affine", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ",", "border_mode", "=", "cv2", ".", "BORDER_REFLECT_101", ",", "value", "=", "None", ",", "random_state", "=", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_vflip
Flip a bounding box vertically around the x-axis.
albumentations/augmentations/functional.py
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]
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", "vertically", "around", "the", "x", "-", "axis", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L918-L921
[ "def", "bbox_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "return", "[", "x_min", ",", "1", "-", "y_max", ",", "x_max", ",", "1", "-", "y_min", "]" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_hflip
Flip a bounding box horizontally around the y-axis.
albumentations/augmentations/functional.py
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]
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", "horizontally", "around", "the", "y", "-", "axis", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L924-L927
[ "def", "bbox_hflip", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "return", "[", "1", "-", "x_max", ",", "y_min", ",", "1", "-", "x_min", ",", "y_max", "]" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_flip
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.
albumentations/augmentations/functional.py
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, rows, cols) elif d == -1: bbox = bbox_hflip(bbox, rows, cols) bbox = bbox_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
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, rows, cols) elif d == -1: bbox = bbox_hflip(bbox, rows, cols) bbox = bbox_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
[ "Flip", "a", "bounding", "box", "either", "vertically", "horizontally", "or", "both", "depending", "on", "the", "value", "of", "d", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L930-L946
[ "def", "bbox_flip", "(", "bbox", ",", "d", ",", "rows", ",", "cols", ")", ":", "if", "d", "==", "0", ":", "bbox", "=", "bbox_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "1", ":", "bbox", "=", "bbox_hflip", "(", "bbox"...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
crop_bbox_by_coords
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.
albumentations/augmentations/functional.py
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_max = bbox x1, y1, x2, y2 = crop_coords cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1] return normalize_bbox(cropped_bbox, crop_height, crop_width)
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_max = bbox x1, y1, x2, y2 = crop_coords cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1] return normalize_bbox(cropped_bbox, crop_height, crop_width)
[ "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", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L949-L957
[ "def", "crop_bbox_by_coords", "(", "bbox", ",", "crop_coords", ",", "crop_height", ",", "crop_width", ",", "rows", ",", "cols", ")", ":", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "x_min", ",", "y_min", ",", "x_max", ",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_rot90
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 cols.
albumentations/augmentations/functional.py
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 cols. """ if factor < 0 or factor > 3: raise ValueError('Parameter n must be in range [0;3]') x_min, y_min, x_max, y_max = bbox if factor == 1: bbox = [y_min, 1 - x_max, y_max, 1 - x_min] if factor == 2: bbox = [1 - x_max, 1 - y_max, 1 - x_min, 1 - y_min] if factor == 3: bbox = [1 - y_max, x_min, 1 - y_min, x_max] return bbox
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 cols. """ if factor < 0 or factor > 3: raise ValueError('Parameter n must be in range [0;3]') x_min, y_min, x_max, y_max = bbox if factor == 1: bbox = [y_min, 1 - x_max, y_max, 1 - x_min] if factor == 2: bbox = [1 - x_max, 1 - y_max, 1 - x_min, 1 - y_min] if factor == 3: bbox = [1 - y_max, x_min, 1 - y_min, x_max] return bbox
[ "Rotates", "a", "bounding", "box", "by", "90", "degrees", "CCW", "(", "see", "np", ".", "rot90", ")" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L977-L995
[ "def", "bbox_rot90", "(", "bbox", ",", "factor", ",", "rows", ",", "cols", ")", ":", "if", "factor", "<", "0", "or", "factor", ">", "3", ":", "raise", "ValueError", "(", "'Parameter n must be in range [0;3]'", ")", "x_min", ",", "y_min", ",", "x_max", ",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_rotate
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): interpolation method. return a tuple (x_min, y_min, x_max, y_max)
albumentations/augmentations/functional.py
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): interpolation method. return a tuple (x_min, y_min, x_max, y_max) """ scale = cols / float(rows) x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]]) y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]]) x = x - 0.5 y = y - 0.5 angle = np.deg2rad(angle) x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y) x_t = x_t + 0.5 y_t = y_t + 0.5 return [min(x_t), min(y_t), max(x_t), max(y_t)]
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): interpolation method. return a tuple (x_min, y_min, x_max, y_max) """ scale = cols / float(rows) x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]]) y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]]) x = x - 0.5 y = y - 0.5 angle = np.deg2rad(angle) x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y) x_t = x_t + 0.5 y_t = y_t + 0.5 return [min(x_t), min(y_t), max(x_t), max(y_t)]
[ "Rotates", "a", "bounding", "box", "by", "angle", "degrees" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L998-L1020
[ "def", "bbox_rotate", "(", "bbox", ",", "angle", ",", "rows", ",", "cols", ",", "interpolation", ")", ":", "scale", "=", "cols", "/", "float", "(", "rows", ")", "x", "=", "np", ".", "array", "(", "[", "bbox", "[", "0", "]", ",", "bbox", "[", "2...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
bbox_transpose
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.
albumentations/augmentations/functional.py
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_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
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_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
[ "Transposes", "a", "bounding", "box", "along", "given", "axis", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1023-L1039
[ "def", "bbox_transpose", "(", "bbox", ",", "axis", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "if", "axis", "!=", "0", "and", "axis", "!=", "1", ":", "raise", "ValueError", "(", "'Axis must be ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
keypoint_vflip
Flip a keypoint vertically around the x-axis.
albumentations/augmentations/functional.py
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]
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", "vertically", "around", "the", "x", "-", "axis", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1042-L1048
[ "def", "keypoint_vflip", "(", "kp", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "angle", ",", "scale", "=", "kp", "c", "=", "math", ".", "cos", "(", "angle", ")", "s", "=", "math", ".", "sin", "(", "angle", ")", "angle", "=", "mat...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
keypoint_flip
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.
albumentations/augmentations/functional.py
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(bbox, rows, cols) elif d == -1: bbox = keypoint_hflip(bbox, rows, cols) bbox = keypoint_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
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(bbox, rows, cols) elif d == -1: bbox = keypoint_hflip(bbox, rows, cols) bbox = keypoint_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
[ "Flip", "a", "keypoint", "either", "vertically", "horizontally", "or", "both", "depending", "on", "the", "value", "of", "d", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1060-L1076
[ "def", "keypoint_flip", "(", "bbox", ",", "d", ",", "rows", ",", "cols", ")", ":", "if", "d", "==", "0", ":", "bbox", "=", "keypoint_vflip", "(", "bbox", ",", "rows", ",", "cols", ")", "elif", "d", "==", "1", ":", "bbox", "=", "keypoint_hflip", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
keypoint_rot90
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): Image cols.
albumentations/augmentations/functional.py
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): Image cols. """ if factor < 0 or factor > 3: raise ValueError('Parameter n must be in range [0;3]') x, y, angle, scale = keypoint if factor == 1: keypoint = [y, (cols - 1) - x, angle - math.pi / 2, scale] if factor == 2: keypoint = [(cols - 1) - x, (rows - 1) - y, angle - math.pi, scale] if factor == 3: keypoint = [(rows - 1) - y, x, angle + math.pi / 2, scale] return keypoint
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): Image cols. """ if factor < 0 or factor > 3: raise ValueError('Parameter n must be in range [0;3]') x, y, angle, scale = keypoint if factor == 1: keypoint = [y, (cols - 1) - x, angle - math.pi / 2, scale] if factor == 2: keypoint = [(cols - 1) - x, (rows - 1) - y, angle - math.pi, scale] if factor == 3: keypoint = [(rows - 1) - y, x, angle + math.pi / 2, scale] return keypoint
[ "Rotates", "a", "keypoint", "by", "90", "degrees", "CCW", "(", "see", "np", ".", "rot90", ")" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1079-L1097
[ "def", "keypoint_rot90", "(", "keypoint", ",", "factor", ",", "rows", ",", "cols", ",", "*", "*", "params", ")", ":", "if", "factor", "<", "0", "or", "factor", ">", "3", ":", "raise", "ValueError", "(", "'Parameter n must be in range [0;3]'", ")", "x", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
keypoint_scale
Scales a keypoint by scale_x and scale_y.
albumentations/augmentations/functional.py
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)]
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)]
[ "Scales", "a", "keypoint", "by", "scale_x", "and", "scale_y", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1107-L1110
[ "def", "keypoint_scale", "(", "keypoint", ",", "scale_x", ",", "scale_y", ",", "*", "*", "params", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "return", "[", "x", "*", "scale_x", ",", "y", "*", "scale_y", ",", "a", ",", "s", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
crop_keypoint_by_coords
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.
albumentations/augmentations/functional.py
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_keypoint = [x - x1, y - y1, a, s] return cropped_keypoint
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_keypoint = [x - x1, y - y1, a, s] return cropped_keypoint
[ "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", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1113-L1120
[ "def", "crop_keypoint_by_coords", "(", "keypoint", ",", "crop_coords", ",", "crop_height", ",", "crop_width", ",", "rows", ",", "cols", ")", ":", "x", ",", "y", ",", "a", ",", "s", "=", "keypoint", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "crop_co...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
py3round
Unified rounding in all python versions.
albumentations/augmentations/functional.py
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))
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))
[ "Unified", "rounding", "in", "all", "python", "versions", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1133-L1138
[ "def", "py3round", "(", "number", ")", ":", "if", "abs", "(", "round", "(", "number", ")", "-", "number", ")", "==", "0.5", ":", "return", "int", "(", "2.0", "*", "round", "(", "number", "/", "2.0", ")", ")", "return", "int", "(", "round", "(", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
RandomRotate90.apply
Args: factor (int): number of times the input will be rotated by 90 degrees.
albumentations/augmentations/transforms.py
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))
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))
[ "Args", ":", "factor", "(", "int", ")", ":", "number", "of", "times", "the", "input", "will", "be", "rotated", "by", "90", "degrees", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/transforms.py#L319-L324
[ "def", "apply", "(", "self", ",", "img", ",", "factor", "=", "0", ",", "*", "*", "params", ")", ":", "return", "np", ".", "ascontiguousarray", "(", "np", ".", "rot90", "(", "img", ",", "factor", ")", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
normalize_bbox
Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height.
albumentations/augmentations/bbox_utils.py
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') x_min, y_min, x_max, y_max = bbox[:4] normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows] return normalized_bbox + list(bbox[4:])
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') x_min, y_min, x_max, y_max = bbox[:4] normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows] return normalized_bbox + list(bbox[4:])
[ "Normalize", "coordinates", "of", "a", "bounding", "box", ".", "Divide", "x", "-", "coordinates", "by", "image", "width", "and", "y", "-", "coordinates", "by", "image", "height", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L10-L20
[ "def", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "if", "rows", "==", "0", ":", "raise", "ValueError", "(", "'Argument rows cannot be zero'", ")", "if", "cols", "==", "0", ":", "raise", "ValueError", "(", "'Argument cols cannot be zero'...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
denormalize_bbox
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`.
albumentations/augmentations/bbox_utils.py
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 rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') x_min, y_min, x_max, y_max = bbox[:4] denormalized_bbox = [x_min * cols, y_min * rows, x_max * cols, y_max * rows] return denormalized_bbox + list(bbox[4:])
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 rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') x_min, y_min, x_max, y_max = bbox[:4] denormalized_bbox = [x_min * cols, y_min * rows, x_max * cols, y_max * rows] return denormalized_bbox + list(bbox[4:])
[ "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", ":",...
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L23-L34
[ "def", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "if", "rows", "==", "0", ":", "raise", "ValueError", "(", "'Argument rows cannot be zero'", ")", "if", "cols", "==", "0", ":", "raise", "ValueError", "(", "'Argument cols cannot be zer...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
normalize_bboxes
Normalize a list of bounding boxes.
albumentations/augmentations/bbox_utils.py
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "Normalize", "a", "list", "of", "bounding", "boxes", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L37-L39
[ "def", "normalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "normalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
denormalize_bboxes
Denormalize a list of bounding boxes.
albumentations/augmentations/bbox_utils.py
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
[ "Denormalize", "a", "list", "of", "bounding", "boxes", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L42-L44
[ "def", "denormalize_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ")", ":", "return", "[", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "for", "bbox", "in", "bboxes", "]" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
calculate_bbox_area
Calculate the area of a bounding box in pixels.
albumentations/augmentations/bbox_utils.py
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
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
[ "Calculate", "the", "area", "of", "a", "bounding", "box", "in", "pixels", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L47-L52
[ "def", "calculate_bbox_area", "(", "bbox", ",", "rows", ",", "cols", ")", ":", "bbox", "=", "denormalize_bbox", "(", "bbox", ",", "rows", ",", "cols", ")", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "[", ":", "4", "]", "area", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
filter_bboxes_by_visibility
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. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold.
albumentations/augmentations/bbox_utils.py
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 is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold. """ img_height, img_width = original_shape[:2] transformed_img_height, transformed_img_width = transformed_shape[:2] visible_bboxes = [] for bbox, transformed_bbox in zip(bboxes, transformed_bboxes): if not all(0.0 <= value <= 1.0 for value in transformed_bbox[:4]): continue bbox_area = calculate_bbox_area(bbox, img_height, img_width) transformed_bbox_area = calculate_bbox_area(transformed_bbox, transformed_img_height, transformed_img_width) if transformed_bbox_area < min_area: continue visibility = transformed_bbox_area / bbox_area if visibility >= threshold: visible_bboxes.append(transformed_bbox) return visible_bboxes
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 is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tuple): transformed image transformed_bboxes (list): transformed bounding boxes threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0]. min_area (float): Minimal area threshold. """ img_height, img_width = original_shape[:2] transformed_img_height, transformed_img_width = transformed_shape[:2] visible_bboxes = [] for bbox, transformed_bbox in zip(bboxes, transformed_bboxes): if not all(0.0 <= value <= 1.0 for value in transformed_bbox[:4]): continue bbox_area = calculate_bbox_area(bbox, img_height, img_width) transformed_bbox_area = calculate_bbox_area(transformed_bbox, transformed_img_height, transformed_img_width) if transformed_bbox_area < min_area: continue visibility = transformed_bbox_area / bbox_area if visibility >= threshold: visible_bboxes.append(transformed_bbox) return visible_bboxes
[ "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", ...
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L55-L82
[ "def", "filter_bboxes_by_visibility", "(", "original_shape", ",", "bboxes", ",", "transformed_shape", ",", "transformed_bboxes", ",", "threshold", "=", "0.", ",", "min_area", "=", "0.", ")", ":", "img_height", ",", "img_width", "=", "original_shape", "[", ":", "...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
convert_bbox_to_albumentations
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]`. Args: bbox (list): bounding box source_format (str): format of the bounding box. Should be 'coco' or 'pascal_voc'. check_validity (bool): check if all boxes are valid boxes rows (int): image height cols (int): image width Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`.
albumentations/augmentations/bbox_utils.py
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_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`. Args: bbox (list): bounding box source_format (str): format of the bounding box. Should be 'coco' or 'pascal_voc'. check_validity (bool): check if all boxes are valid boxes rows (int): image height cols (int): image width Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if source_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown source_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(source_format) ) if source_format == 'coco': x_min, y_min, width, height = bbox[:4] x_max = x_min + width y_max = y_min + height else: x_min, y_min, x_max, y_max = bbox[:4] bbox = [x_min, y_min, x_max, y_max] + list(bbox[4:]) bbox = normalize_bbox(bbox, rows, cols) if check_validity: check_bbox(bbox) return bbox
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_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`. Args: bbox (list): bounding box source_format (str): format of the bounding box. Should be 'coco' or 'pascal_voc'. check_validity (bool): check if all boxes are valid boxes rows (int): image height cols (int): image width Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if source_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown source_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(source_format) ) if source_format == 'coco': x_min, y_min, width, height = bbox[:4] x_max = x_min + width y_max = y_min + height else: x_min, y_min, x_max, y_max = bbox[:4] bbox = [x_min, y_min, x_max, y_max] + list(bbox[4:]) bbox = normalize_bbox(bbox, rows, cols) if check_validity: check_bbox(bbox) return bbox
[ "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", "...
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L85-L119
[ "def", "convert_bbox_to_albumentations", "(", "bbox", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "if", "source_format", "not", "in", "{", "'coco'", ",", "'pascal_voc'", "}", ":", "raise", "ValueError", "(", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
convert_bbox_from_albumentations
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_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`.
albumentations/augmentations/bbox_utils.py
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_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if target_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(target_format) ) if check_validity: check_bbox(bbox) bbox = denormalize_bbox(bbox, rows, cols) if target_format == 'coco': x_min, y_min, x_max, y_max = bbox[:4] width = x_max - x_min height = y_max - y_min bbox = [x_min, y_min, width, height] + list(bbox[4:]) return bbox
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_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes Note: The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200]. The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212]. Raises: ValueError: if `target_format` is not equal to `coco` or `pascal_voc`. """ if target_format not in {'coco', 'pascal_voc'}: raise ValueError( "Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(target_format) ) if check_validity: check_bbox(bbox) bbox = denormalize_bbox(bbox, rows, cols) if target_format == 'coco': x_min, y_min, x_max, y_max = bbox[:4] width = x_max - x_min height = y_max - y_min bbox = [x_min, y_min, width, height] + list(bbox[4:]) return bbox
[ "Convert", "a", "bounding", "box", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L122-L152
[ "def", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "if", "target_format", "not", "in", "{", "'coco'", ",", "'pascal_voc'", "}", ":", "raise", "ValueError", "(",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
convert_bboxes_to_albumentations
Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
albumentations/augmentations/bbox_utils.py
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 in bboxes]
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 in bboxes]
[ "Convert", "a", "list", "bounding", "boxes", "from", "a", "format", "specified", "in", "source_format", "to", "the", "format", "used", "by", "albumentations" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L155-L158
[ "def", "convert_bboxes_to_albumentations", "(", "bboxes", ",", "source_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_to_albumentations", "(", "bbox", ",", "source_format", ",", "rows", ",", "cols", ...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
convert_bboxes_from_albumentations
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 albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes
albumentations/augmentations/bbox_utils.py
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 albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes """ return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
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 albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int): image height cols (int): image width check_validity (bool): check if all boxes are valid boxes """ return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
[ "Convert", "a", "list", "of", "bounding", "boxes", "from", "the", "format", "used", "by", "albumentations", "to", "a", "format", "specified", "in", "target_format", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L161-L172
[ "def", "convert_bboxes_from_albumentations", "(", "bboxes", ",", "target_format", ",", "rows", ",", "cols", ",", "check_validity", "=", "False", ")", ":", "return", "[", "convert_bbox_from_albumentations", "(", "bbox", ",", "target_format", ",", "rows", ",", "cols...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
check_bbox
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
albumentations/augmentations/bbox_utils.py
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} ' 'to be in the range [0.0, 1.0], got {value}.'.format( bbox=bbox, name=name, value=value, ) ) x_min, y_min, x_max, y_max = bbox[:4] if x_max <= x_min: raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format( bbox=bbox, )) if y_max <= y_min: raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format( bbox=bbox, ))
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} ' 'to be in the range [0.0, 1.0], got {value}.'.format( bbox=bbox, name=name, value=value, ) ) x_min, y_min, x_max, y_max = bbox[:4] if x_max <= x_min: raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format( bbox=bbox, )) if y_max <= y_min: raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format( bbox=bbox, ))
[ "Check", "if", "bbox", "boundaries", "are", "in", "range", "0", "1", "and", "minimums", "are", "lesser", "then", "maximums" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L175-L195
[ "def", "check_bbox", "(", "bbox", ")", ":", "for", "name", ",", "value", "in", "zip", "(", "[", "'x_min'", ",", "'y_min'", ",", "'x_max'", ",", "'y_max'", "]", ",", "bbox", "[", ":", "4", "]", ")", ":", "if", "not", "0", "<=", "value", "<=", "1...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
filter_bboxes
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): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0.
albumentations/augmentations/bbox_utils.py
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): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0. """ resulting_boxes = [] for bbox in bboxes: transformed_box_area = calculate_bbox_area(bbox, rows, cols) bbox[:4] = np.clip(bbox[:4], 0, 1.) clipped_box_area = calculate_bbox_area(bbox, rows, cols) if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility: continue else: bbox[:4] = np.clip(bbox[:4], 0, 1.) if calculate_bbox_area(bbox, rows, cols) <= min_area: continue resulting_boxes.append(bbox) return resulting_boxes
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): List of bounding box with coordinates in the format used by albumentations rows (int): Image rows. cols (int): Image cols. min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than this value will be removed. Default: 0.0. min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0. """ resulting_boxes = [] for bbox in bboxes: transformed_box_area = calculate_bbox_area(bbox, rows, cols) bbox[:4] = np.clip(bbox[:4], 0, 1.) clipped_box_area = calculate_bbox_area(bbox, rows, cols) if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility: continue else: bbox[:4] = np.clip(bbox[:4], 0, 1.) if calculate_bbox_area(bbox, rows, cols) <= min_area: continue resulting_boxes.append(bbox) return resulting_boxes
[ "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", ...
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L204-L228
[ "def", "filter_bboxes", "(", "bboxes", ",", "rows", ",", "cols", ",", "min_area", "=", "0.", ",", "min_visibility", "=", "0.", ")", ":", "resulting_boxes", "=", "[", "]", "for", "bbox", "in", "bboxes", ":", "transformed_box_area", "=", "calculate_bbox_area",...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
union_of_bboxes
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]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume.
albumentations/augmentations/bbox_utils.py
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]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume. """ x1, y1 = width, height x2, y2 = 0, 0 for b in bboxes: w, h = b[2] - b[0], b[3] - b[1] lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h lim_x2, lim_y2 = b[2] - erosion_rate * w, b[3] - erosion_rate * h x1, y1 = np.min([x1, lim_x1]), np.min([y1, lim_y1]) x2, y2 = np.max([x2, lim_x2]), np.max([y2, lim_y2]) return x1, y1, x2, y2
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]`. erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping. Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume. """ x1, y1 = width, height x2, y2 = 0, 0 for b in bboxes: w, h = b[2] - b[0], b[3] - b[1] lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h lim_x2, lim_y2 = b[2] - erosion_rate * w, b[3] - erosion_rate * h x1, y1 = np.min([x1, lim_x1]), np.min([y1, lim_y1]) x2, y2 = np.max([x2, lim_x2]), np.max([y2, lim_y2]) return x1, y1, x2, y2
[ "Calculate", "union", "of", "bounding", "boxes", "." ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L231-L249
[ "def", "union_of_bboxes", "(", "height", ",", "width", ",", "bboxes", ",", "erosion_rate", "=", "0.0", ",", "to_int", "=", "False", ")", ":", "x1", ",", "y1", "=", "width", ",", "height", "x2", ",", "y2", "=", "0", ",", "0", "for", "b", "in", "bb...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
to_tuple
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 bias: An offset factor added to each element
albumentations/core/transforms_interface.py
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 + offset (broadcasted). low: Second element of tuple can be passed as optional argument bias: An offset factor added to each element """ if low is not None and bias is not None: raise ValueError('Arguments low and bias are mutually exclusive') if param is None: return param if isinstance(param, (int, float)): if low is None: param = - param, + param else: param = (low, param) if low < param else (param, low) elif isinstance(param, (list, tuple)): param = tuple(param) else: raise ValueError('Argument param must be either scalar (int,float) or tuple') if bias is not None: return tuple([bias + x for x in param]) return tuple(param)
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 + offset (broadcasted). low: Second element of tuple can be passed as optional argument bias: An offset factor added to each element """ if low is not None and bias is not None: raise ValueError('Arguments low and bias are mutually exclusive') if param is None: return param if isinstance(param, (int, float)): if low is None: param = - param, + param else: param = (low, param) if low < param else (param, low) elif isinstance(param, (list, tuple)): param = tuple(param) else: raise ValueError('Argument param must be either scalar (int,float) or tuple') if bias is not None: return tuple([bias + x for x in param]) return tuple(param)
[ "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", ...
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/core/transforms_interface.py#L8-L36
[ "def", "to_tuple", "(", "param", ",", "low", "=", "None", ",", "bias", "=", "None", ")", ":", "if", "low", "is", "not", "None", "and", "bias", "is", "not", "None", ":", "raise", "ValueError", "(", "'Arguments low and bias are mutually exclusive'", ")", "if...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
check_keypoint
Check if keypoint coordinates are in range [0, 1)
albumentations/augmentations/keypoints_utils.py
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.0, {size}], got {value}.'.format( kp=kp, name=name, value=value, size=size ) )
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.0, {size}], got {value}.'.format( kp=kp, name=name, value=value, size=size ) )
[ "Check", "if", "keypoint", "coordinates", "are", "in", "range", "[", "0", "1", ")" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L5-L17
[ "def", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")", ":", "for", "name", ",", "value", ",", "size", "in", "zip", "(", "[", "'x'", ",", "'y'", "]", ",", "kp", "[", ":", "2", "]", ",", "[", "cols", ",", "rows", "]", ")", ":", "i...
b31393cd6126516d37a84e44c879bd92c68ffc93
train
check_keypoints
Check if keypoints boundaries are in range [0, 1)
albumentations/augmentations/keypoints_utils.py
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
def check_keypoints(keypoints, rows, cols): """Check if keypoints boundaries are in range [0, 1)""" for kp in keypoints: check_keypoint(kp, rows, cols)
[ "Check", "if", "keypoints", "boundaries", "are", "in", "range", "[", "0", "1", ")" ]
albu/albumentations
python
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/keypoints_utils.py#L20-L23
[ "def", "check_keypoints", "(", "keypoints", ",", "rows", ",", "cols", ")", ":", "for", "kp", "in", "keypoints", ":", "check_keypoint", "(", "kp", ",", "rows", ",", "cols", ")" ]
b31393cd6126516d37a84e44c879bd92c68ffc93
train
start
Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed.
tornado/autoreload.py
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 if len(_io_loops) > 1: gen_log.warning("tornado.autoreload started more than once in the same process") modify_times = {} # type: Dict[str, float] callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time) scheduler.start()
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 if len(_io_loops) > 1: gen_log.warning("tornado.autoreload started more than once in the same process") modify_times = {} # type: Dict[str, float] callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time) scheduler.start()
[ "Begins", "watching", "source", "files", "for", "changes", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L118-L133
[ "def", "start", "(", "check_time", ":", "int", "=", "500", ")", "->", "None", ":", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "if", "io_loop", "in", "_io_loops", ":", "return", "_io_loops", "[", "io_loop", "]", "=", "True", "i...
b8b481770bcdb333a69afde5cce7eaa449128326