INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Reads a message from the socket and converts it to a message.
def _read_message(self): """ Reads a message from the socket and converts it to a message. """ # first 4 bytes is Big-Endian payload length payload_info = self._read_bytes_from_socket(4) read_len = unpack(">I", payload_info)[0] # now read the payload payload = self._read...
Send a message to the Chromecast.
def send_message(self, destination_id, namespace, data, inc_session_id=False, callback_function=False, no_add_request_id=False, force=False): """ Send a message to the Chromecast. """ # namespace is a string containing namespace # data is a dict that wi...
Helper method to send a message to the platform.
def send_platform_message(self, namespace, message, inc_session_id=False, callback_function_param=False): """ Helper method to send a message to the platform. """ return self.send_message(PLATFORM_DESTINATION_ID, namespace, message, inc_sess...
Helper method to send a message to current running app.
def send_app_message(self, namespace, message, inc_session_id=False, callback_function_param=False): """ Helper method to send a message to current running app. """ if namespace not in self.app_namespaces: raise UnsupportedNamespace( ("Namespace {} is...
Ensure we opened a channel to destination_id.
def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {...
Disconnect a channel with destination_id.
def disconnect_channel(self, destination_id): """ Disconnect a channel with destination_id. """ if destination_id in self._open_channels: try: self.send_message( destination_id, NS_CONNECTION, {MESSAGE_TYPE: TYPE_CLOSE, 'origin': {}}, ...
Handles a channel being disconnected.
def handle_channel_disconnected(self): """ Handles a channel being disconnected. """ for namespace in self.app_namespaces: if namespace in self._handlers: self._handlers[namespace].channel_disconnected() self.app_namespaces = [] self.destination_id = None ...
Called when a connection message is received.
def receive_message(self, message, data): """ Called when a connection message is received. """ if self._socket_client.is_stopped: return True if data[MESSAGE_TYPE] == TYPE_CLOSE: # The cast device is asking us to acknowledge closing this channel. self._socke...
Called when a heartbeat message is received.
def receive_message(self, message, data): """ Called when a heartbeat message is received. """ if self._socket_client.is_stopped: return True if data[MESSAGE_TYPE] == TYPE_PING: try: self._socket_client.send_message( PLATFORM_DESTINATI...
Send a ping message.
def ping(self): """ Send a ping message. """ self.last_ping = time.time() try: self.send_message({MESSAGE_TYPE: TYPE_PING}) except NotConnected: self._socket_client.logger.error("Chromecast is disconnected. " + "Cannot ...
Indicates if connection has expired.
def is_expired(self): """ Indicates if connection has expired. """ if time.time() - self.last_ping > HB_PING_TIME: self.ping() return (time.time() - self.last_pong) > HB_PING_TIME + HB_PONG_TIME
Called when a receiver-message has been received.
def receive_message(self, message, data): """ Called when a receiver-message has been received. """ if data[MESSAGE_TYPE] == TYPE_RECEIVER_STATUS: self._process_get_status(data) return True elif data[MESSAGE_TYPE] == TYPE_LAUNCH_ERROR: self._process_launch_e...
Sends a message to the Chromecast to update the status.
def update_status(self, callback_function_param=False): """ Sends a message to the Chromecast to update the status. """ self.logger.debug("Receiver:Updating status") self.send_message({MESSAGE_TYPE: TYPE_GET_STATUS}, callback_function=callback_function_param)
Launches an app on the Chromecast. Will only launch if it is not currently running unless force_launch=True.
def launch_app(self, app_id, force_launch=False, callback_function=False): """ Launches an app on the Chromecast. Will only launch if it is not currently running unless force_launch=True. """ if not force_launch and self.app_id is None: self.update_status(lambda res...
Stops the current running app on the Chromecast.
def stop_app(self, callback_function_param=False): """ Stops the current running app on the Chromecast. """ self.logger.info("Receiver:Stopping current app '%s'", self.app_id) return self.send_message( {MESSAGE_TYPE: 'STOP'}, inc_session_id=True, callback_function=callbac...
Allows to set volume. Should be value between 0..1. Returns the new volume.
def set_volume(self, volume): """ Allows to set volume. Should be value between 0..1. Returns the new volume. """ volume = min(max(0, volume), 1) self.logger.info("Receiver:setting volume to %.1f", volume) self.send_message({MESSAGE_TYPE: 'SET_VOLUME', ...
Parses a STATUS message and returns a CastStatus object. :type data: dict :param cast_type: Type of Chromecast. :rtype: CastStatus
def _parse_status(data, cast_type): """ Parses a STATUS message and returns a CastStatus object. :type data: dict :param cast_type: Type of Chromecast. :rtype: CastStatus """ data = data.get('status', {}) volume_data = data.get('volume', {}) try...
Processes a received STATUS message and notifies listeners.
def _process_get_status(self, data): """ Processes a received STATUS message and notifies listeners. """ status = self._parse_status(data, self.cast_type) is_new_app = self.app_id != status.app_id and self.app_to_launch self.status = status self.logger.debug("Received status: %s...
Reports the current status to all listeners.
def _report_status(self): """ Reports the current status to all listeners. """ for listener in self._status_listeners: try: listener.new_cast_status(self.status) except Exception: # pylint: disable=broad-except self.logger.exception( ...
Parses a LAUNCH_ERROR message and returns a LaunchFailure object. :type data: dict :rtype: LaunchFailure
def _parse_launch_error(data): """ Parses a LAUNCH_ERROR message and returns a LaunchFailure object. :type data: dict :rtype: LaunchFailure """ return LaunchFailure( data.get(ERROR_REASON, None), data.get(APP_ID), data.get(REQUEST_ID),...
Called when controller is destroyed.
def tear_down(self): """ Called when controller is destroyed. """ super(ReceiverController, self).tear_down() self.status = None self.launch_failure = None self.app_to_launch = None self.app_launch_event.clear() self._status_listeners[:] = []
Starts loading a URL with an optional reload time in seconds. Setting force to True may load pages which block iframe embedding, but will prevent reload from working and will cause calls to load_url() to reload the app.
def load_url(self, url, force=False, reload_seconds=0, callback_function=None): """ Starts loading a URL with an optional reload time in seconds. Setting force to True may load pages which block iframe embedding, but will prevent reload from working and ...
:param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None
def _get_status(host, services, zconf, path): """ :param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None """ if not host: for service in services.copy(): service_info = ...
:param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None
def get_device_status(host, services=None, zconf=None): """ :param host: Hostname or ip to fetch status from :type host: str :return: The device status as a named tuple. :rtype: pychromecast.dial.DeviceStatus or None """ try: status = _get_status( host, services, zconf, ...
:param host: Hostname or ip to fetch status from :type host: str :return: The multizone status as a named tuple. :rtype: pychromecast.dial.MultizoneStatus or None
def get_multizone_status(host, services=None, zconf=None): """ :param host: Hostname or ip to fetch status from :type host: str :return: The multizone status as a named tuple. :rtype: pychromecast.dial.MultizoneStatus or None """ try: status = status = _get_status( host,...
Starts a session it is not yet initialized.
def start_session_if_none(self): """ Starts a session it is not yet initialized. """ if not (self._screen_id and self._session): self.update_screen_id() self._session = YouTubeSession(screen_id=self._screen_id)
Play video(video_id) now. This ignores the current play queue order. :param video_id: YouTube video id(http://youtube.com/watch?v=video_id) :param playlist_id: youtube.com/watch?v=video_id&list=playlist_id
def play_video(self, video_id, playlist_id=None): """ Play video(video_id) now. This ignores the current play queue order. :param video_id: YouTube video id(http://youtube.com/watch?v=video_id) :param playlist_id: youtube.com/watch?v=video_id&list=playlist_id """ self.sta...
Sends a getMdxSessionStatus to get the screenId and waits for response. This function is blocking If connected we should always get a response (send message will launch app if it is not running).
def update_screen_id(self): """ Sends a getMdxSessionStatus to get the screenId and waits for response. This function is blocking If connected we should always get a response (send message will launch app if it is not running). """ self.status_update_event.clear()...
Called when a media message is received.
def receive_message(self, message, data): """ Called when a media message is received. """ if data[MESSAGE_TYPE] == TYPE_STATUS: self._process_status(data.get("data")) return True return False
Process latest status update.
def _process_status(self, status): """ Process latest status update. """ self._screen_id = status.get(ATTR_SCREEN_ID) self.status_update_event.set()
Start discovering chromecasts on the network. This method will start discovering chromecasts on a separate thread. When a chromecast is discovered, the callback will be called with the discovered chromecast's zeroconf name. This is the dictionary key to find the chromecast metadata in listener.services...
def start_discovery(add_callback=None, remove_callback=None): """ Start discovering chromecasts on the network. This method will start discovering chromecasts on a separate thread. When a chromecast is discovered, the callback will be called with the discovered chromecast's zeroconf name. This is t...
Discover chromecasts on the network.
def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT): """ Discover chromecasts on the network. """ from threading import Event browser = False try: # pylint: disable=unused-argument def callback(name): """Called when zeroconf has discovered a new chromecast.""...
Resolve service_info from service.
def get_info_from_service(service, zconf): """ Resolve service_info from service. """ service_info = None try: service_info = zconf.get_service_info('_googlecast._tcp.local.', service) if service_info: _LOGGER.debug( "...
Get hostname or IP from service_info.
def get_host_from_service_info(service_info): """ Get hostname or IP from service_info. """ host = None port = None if (service_info and service_info.port and (service_info.server or service_info.address)): if service_info.address: host = socket.inet_ntoa(service_info.add...
Remove a service from the collection.
def remove_service(self, zconf, typ, name): """ Remove a service from the collection. """ _LOGGER.debug("remove_service %s, %s", typ, name) service = self.services.pop(name, None) if not service: _LOGGER.debug("remove_service unknown %s, %s", typ, name) return ...
Add a service to the collection.
def add_service(self, zconf, typ, name): """ Add a service to the collection. """ service = None tries = 0 _LOGGER.debug("add_service %s, %s", typ, name) while service is None and tries < 4: try: service = zconf.get_service_info(typ, name) ...
Currently not doing anything with received messages.
def receive_message(self, message, data): """ Currently not doing anything with received messages. """ if data['type'] == TYPE_RESPONSE_STATUS: self.is_launched = True return True
Launch Spotify application. Will raise a LaunchError exception if there is no response from the Spotify app within timeout seconds.
def launch_app(self, timeout=10): """ Launch Spotify application. Will raise a LaunchError exception if there is no response from the Spotify app within timeout seconds. """ def callback(): """Callback function""" self.send_message({"type": TYPE_...
If set, launches app related to the controller.
def launch(self, callback_function=None): """ If set, launches app related to the controller. """ self._check_registered() self._socket_client.receiver_controller.launch_app( self.supporting_app_id, callback_function=callback_function)
Called when a controller is registered.
def registered(self, socket_client): """ Called when a controller is registered. """ self._socket_client = socket_client if self.target_platform: self._message_func = self._socket_client.send_platform_message else: self._message_func = self._socket_client.send_ap...
Send a message on this namespace to the Chromecast. Will raise a NotConnected exception if not connected.
def send_message(self, data, inc_session_id=False, callback_function=None): """ Send a message on this namespace to the Chromecast. Will raise a NotConnected exception if not connected. """ self._check_registered() if not self.target_platform and \ ...
Returns calculated current seek time of media in seconds
def adjusted_current_time(self): """ Returns calculated current seek time of media in seconds """ if self.player_state == MEDIA_PLAYER_STATE_PLAYING: # Add time since last update return (self.current_time + (datetime.utcnow() - self.last_updated).total_seconds...
Return a list of MediaImage objects for this media.
def images(self): """ Return a list of MediaImage objects for this media. """ return [ MediaImage(item.get('url'), item.get('height'), item.get('width')) for item in self.media_metadata.get('images', []) ]
New data will only contain the changed attributes.
def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'][0] media_data = status_data.get('media') or {} volume_data = status_data.get('volume', {}) self.current_time...
Called when a media message is received.
def receive_message(self, message, data): """ Called when a media message is received. """ if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS: self._process_media_status(data) return True return False
Send a command to the Chromecast on media channel.
def _send_command(self, command): """ Send a command to the Chromecast on media channel. """ if self.status is None or self.status.media_session_id is None: self.logger.warning( "%s command requested but no session is active.", command[MESSAGE_TYPE]) ...
Deprecated as of June 8, 2015. Use self.status.images. Return thumbnail url of current playing item.
def thumbnail(self): """ Deprecated as of June 8, 2015. Use self.status.images. Return thumbnail url of current playing item. """ if not self.status: return None images = self.status.images return images[0].url if images else None
Processes a STATUS message.
def _process_media_status(self, data): """ Processes a STATUS message. """ self.status.update(data) self.logger.debug("Media:Received status %s", data) # Update session active threading event if self.status.media_session_id is None: self.session_active_event.clear()...
Tells listeners of a changed status.
def _fire_status_changed(self): """ Tells listeners of a changed status. """ for listener in self._status_listeners: try: listener.new_media_status(self.status) except Exception: # pylint: disable=broad-except _LOGGER.exception("Exception thrown w...
Plays media on the Chromecast. Start default media receiver if not already started. Parameters: url: str - url of the media. content_type: str - mime type. Example: 'video/mp4'. title: str - title of the media. thumb: str - thumbnail image url. current_time: floa...
def play_media(self, url, content_type, title=None, thumb=None, current_time=0, autoplay=True, stream_type=STREAM_TYPE_BUFFERED, metadata=None, subtitles=None, subtitles_lang='en-US', subtitles_mime='text/vtt', subtitle_id=1): """ ...
Returns all possible app ids.
def get_possible_app_ids(): """ Returns all possible app ids. """ try: req = requests.get( "https://clients3.google.com/cast/chromecast/device/baseconfig") data = json.loads(req.text[4:]) return [app['app_id'] for app in data['applications']] + \ data["enabled_a...
Get specific configuration for 'app_id'.
def get_app_config(app_id): """ Get specific configuration for 'app_id'. """ try: req = requests.get( ("https://clients3.google.com/" "cast/chromecast/device/app?a={}").format(app_id)) return json.loads(req.text[4:]) if req.status_code == 200 else {} except ValueEr...
Loads the contents of the file specified by path Args: path (string): The relative or absolute path to the file to be loaded. If the path is relative, then it is combined with the base_path to generate a full path string Returns: string: The con...
def get_contents(self, path): ''' Loads the contents of the file specified by path Args: path (string): The relative or absolute path to the file to be loaded. If the path is relative, then it is combined with the base_path to generate a full path st...
Transform the path to an absolute path Args: path (string): The path to transform to an absolute path Returns: string: The absolute path to the file
def abspath(self, path): ''' Transform the path to an absolute path Args: path (string): The path to transform to an absolute path Returns: string: The absolute path to the file ''' if not path.startswith(os.path.sep) or path.startswith('~'): ...
Load the file specified by path This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk Args: path (string): The full or relative path to the file to be loaded encoding (string): The file content...
def load_file(self, path, objtype=None, encoding='utf-8'): ''' Load the file specified by path This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk Args: path (string): The full or relative...
Performs basic checks and then properly invokes - prepare_inventory - prepare_env - prepare_command It's also responsible for wrapping the command with the proper ssh agent invocation and setting early ANSIBLE_ environment variables.
def prepare(self): """ Performs basic checks and then properly invokes - prepare_inventory - prepare_env - prepare_command It's also responsible for wrapping the command with the proper ssh agent invocation and setting early ANSIBLE_ environment variables. ...
Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor.
def prepare_inventory(self): """ Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. """ if self.inventory is None: self.inventory = os.path.join(self.private_data_dir, "inventory")
Manages reading environment metadata files under ``private_data_dir`` and merging/updating with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily
def prepare_env(self): """ Manages reading environment metadata files under ``private_data_dir`` and merging/updating with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily """ try: passwords = self.loader.load_file('e...
Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command`
def prepare_command(self): """ Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command` """ try: cmdline_args = self.loader.load_file('args', string_...
Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object to start the process
def generate_ansible_command(self): """ Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object to start the p...
Create a temporary directory for process isolation to use.
def build_process_isolation_temp_dir(self): ''' Create a temporary directory for process isolation to use. ''' path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path) os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) atexit.register(...
Wrap existing command line with bwrap to restrict access to: - self.process_isolation_path (generally, /tmp) (except for own /tmp files)
def wrap_args_with_process_isolation(self, args): ''' Wrap existing command line with bwrap to restrict access to: - self.process_isolation_path (generally, /tmp) (except for own /tmp files) ''' cwd = os.path.realpath(self.cwd) pi_temp_dir = self.build_process_isolation_...
Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to ``ssh-agent``
def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False): """ Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to ``ssh-agent`` """ if ssh_key_path: ssh...
Configures the logging facility This function will setup an initial logging facility for handling display and debug outputs. The default facility will send display messages to stdout and the default debug facility will do nothing. :returns: None
def configure(): ''' Configures the logging facility This function will setup an initial logging facility for handling display and debug outputs. The default facility will send display messages to stdout and the default debug facility will do nothing. :returns: None ''' root_logger = ...
Invoked for every Ansible event to collect stdout with the event data and store it for later use
def event_callback(self, event_data): ''' Invoked for every Ansible event to collect stdout with the event data and store it for later use ''' self.last_stdout_update = time.time() job_events_path = os.path.join(self.config.artifact_dir, 'job_events') if not os.pa...
Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the invocation is complete
def run(self): ''' Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the invocation is complete ''' self.status_callback('starting') stdout_filename = os.path.join(self.config.artifact_dir, 'stdout') command_filename = os.path...
Returns an open file handle to the stdout representing the Ansible run
def stdout(self): ''' Returns an open file handle to the stdout representing the Ansible run ''' stdout_path = os.path.join(self.config.artifact_dir, 'stdout') if not os.path.exists(stdout_path): raise AnsibleRunnerException("stdout missing") return open(os.pa...
A generator that will return all ansible job events in the order that they were emitted from Ansible Example: { "event":"runner_on_ok", "uuid":"00a50d9c-161a-4b74-b978-9f60becaf209", "stdout":"ok: [localhost] => {\\r\\n \\" msg\\":\\"Test!\\"\\r\\n...
def events(self): ''' A generator that will return all ansible job events in the order that they were emitted from Ansible Example: { "event":"runner_on_ok", "uuid":"00a50d9c-161a-4b74-b978-9f60becaf209", "stdout":"ok: [localhost] => {\\...
Returns the final high level stats from the Ansible run Example: {'dark': {}, 'failures': {}, 'skipped': {}, 'ok': {u'localhost': 2}, 'processed': {u'localhost': 1}}
def stats(self): ''' Returns the final high level stats from the Ansible run Example: {'dark': {}, 'failures': {}, 'skipped': {}, 'ok': {u'localhost': 2}, 'processed': {u'localhost': 1}} ''' last_event = list(filter(lambda x: 'event' in x and x['event'] == 'playbook_...
Given a host name, this will return all task events executed on that host
def host_events(self, host): ''' Given a host name, this will return all task events executed on that host ''' all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host, self.events) ret...
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner. :param pid: the process id of the running the job. :param is_cancel: flag showing whether this termination is caused by instance's cancel_flag.
def handle_termination(cls, pid, is_cancel=True): ''' Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner. :param pid: the process id of the running the job. :param is_cancel: flag showing whether this termination is caused by ...
Get the entire fact cache only if the fact_cache_type is 'jsonfile'
def get_fact_cache(self, host): ''' Get the entire fact cache only if the fact_cache_type is 'jsonfile' ''' if self.config.fact_cache_type != 'jsonfile': raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ansible-run...
Set the entire fact cache data only if the fact_cache_type is 'jsonfile'
def set_fact_cache(self, host, data): ''' Set the entire fact cache data only if the fact_cache_type is 'jsonfile' ''' if self.config.fact_cache_type != 'jsonfile': raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ...
Initialize the Runner() instance This function will properly initialize both run() and run_async() functions in the same way and return a value instance of Runner. See parameters given to :py:func:`ansible_runner.interface.run`
def init_runner(**kwargs): ''' Initialize the Runner() instance This function will properly initialize both run() and run_async() functions in the same way and return a value instance of Runner. See parameters given to :py:func:`ansible_runner.interface.run` ''' dump_artifacts(kwargs) ...
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object. This uses the same parameters as :py:func:`ansible_runner.interface.run` :returns: A tuple containing a :py:class:`threading.Thread` object and a :py:class:`ansible_runner.runner.Runner` ...
def run_async(**kwargs): ''' Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object. This uses the same parameters as :py:func:`ansible_runner.interface.run` :returns: A tuple containing a :py:class:`threading.Thread` object and a :py:...
Inspects the object and returns if it is a playbook Args: obj (object): The object to be inspected by this function Returns: boolean: True if the object is a list and False if it is not
def isplaybook(obj): ''' Inspects the object and returns if it is a playbook Args: obj (object): The object to be inspected by this function Returns: boolean: True if the object is a list and False if it is not ''' return isinstance(obj, Iterable) and (not isinstance(obj, strin...
Check that proot is installed.
def check_isolation_executable_installed(isolation_executable): ''' Check that proot is installed. ''' cmd = [isolation_executable, '--version'] try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() ...
Write the artifact to disk at the specified path Args: obj (string): The string object to be dumped to disk in the specified path. The artifact filename will be automatically created path (string): The full path to the artifacts data directory. filename (string, optional): Th...
def dump_artifact(obj, path, filename=None): ''' Write the artifact to disk at the specified path Args: obj (string): The string object to be dumped to disk in the specified path. The artifact filename will be automatically created path (string): The full path to the artifacts...
Introspect the kwargs and dump objects to disk
def dump_artifacts(kwargs): ''' Introspect the kwargs and dump objects to disk ''' private_data_dir = kwargs.get('private_data_dir') if not private_data_dir: private_data_dir = tempfile.mkdtemp() kwargs['private_data_dir'] = private_data_dir if not os.path.exists(private_data_di...
open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process (such as ssh-agent) reads data from the pipe.
def open_fifo_write(path, data): '''open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process (such as ssh-agent) reads data from the pipe. ''' os.mkfifo(path, stat.S_IRUSR | stat.S_IWUSR) threading.Thread(target=lambda p, d: open(p, 'wb').write(...
Encode Python datetime object as PDF date string From Adobe pdfmark manual: (D:YYYYMMDDHHmmSSOHH'mm') D: is an optional prefix. YYYY is the year. All fields after the year are optional. MM is the month (01-12), DD is the day (01-31), HH is the hour (00-23), mm are the minutes (00-59), and SS are th...
def encode_pdf_date(d: datetime) -> str: """Encode Python datetime object as PDF date string From Adobe pdfmark manual: (D:YYYYMMDDHHmmSSOHH'mm') D: is an optional prefix. YYYY is the year. All fields after the year are optional. MM is the month (01-12), DD is the day (01-31), HH is the hour (0...
Decode a pdfmark date to a Python datetime object A pdfmark date is a string in a paritcular format. See the pdfmark Reference for the specification.
def decode_pdf_date(s: str) -> datetime: """Decode a pdfmark date to a Python datetime object A pdfmark date is a string in a paritcular format. See the pdfmark Reference for the specification. """ if isinstance(s, String): s = str(s) if s.startswith('D:'): s = s[2:] # Lite...
Populate the XMP metadata object with DocumentInfo Arguments: docinfo: a DocumentInfo, e.g pdf.docinfo delete_missing: if the entry is not DocumentInfo, delete the equivalent from XMP raise_failure: if True, raise any failure to convert docinfo; ...
def load_from_docinfo(self, docinfo, delete_missing=False, raise_failure=False): """Populate the XMP metadata object with DocumentInfo Arguments: docinfo: a DocumentInfo, e.g pdf.docinfo delete_missing: if the entry is not DocumentInfo, delete the equivalent from...
Update the PDF's DocumentInfo dictionary to match XMP metadata The standard mapping is described here: https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
def _update_docinfo(self): """Update the PDF's DocumentInfo dictionary to match XMP metadata The standard mapping is described here: https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/ """ self._pdf.docinfo # Touch object to ensure it exists for uri, element, do...
Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer.
def _apply_changes(self): """Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer. """ if self.mark: self[QName(XMP_NS_XMP, 'MetadataDate')] = datetime.now().isoformat() self[QName(XMP_NS_PDF, 'Pro...
Convert name to an XML QName e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer
def _qname(self, name): """Convert name to an XML QName e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer """ if isinstance(name, QName): return name if not isinstance(name, str): raise TypeError("{} must be str".format(name)) if name ==...
Given a fully qualified XML name, find a prefix e.g. {http://ns.adobe.com/pdf/1.3/}Producer -> pdf:Producer
def _prefix_from_uri(self, uriname): """Given a fully qualified XML name, find a prefix e.g. {http://ns.adobe.com/pdf/1.3/}Producer -> pdf:Producer """ uripart, tag = uriname.split('}', maxsplit=1) uri = uripart.replace('{', '') return self.REVERSE_NS[uri] + ':' + tag
Gather the sub-elements attached to a node Gather rdf:Bag and and rdf:Seq into set and list respectively. For alternate languages values, take the first language only for simplicity.
def _get_subelements(self, node): """Gather the sub-elements attached to a node Gather rdf:Bag and and rdf:Seq into set and list respectively. For alternate languages values, take the first language only for simplicity. """ items = node.find('rdf:Alt', self.NS) i...
Get elements from XMP Core routine to find elements matching name within the XMP and yield them. For XMP spec 7.9.2.2, rdf:Description with property attributes, we yield the node which will have the desired as one of its attributes. qname is returned so that the node.attrib can...
def _get_elements(self, name=''): """Get elements from XMP Core routine to find elements matching name within the XMP and yield them. For XMP spec 7.9.2.2, rdf:Description with property attributes, we yield the node which will have the desired as one of its attributes. ...
Returns the PDF/A conformance level claimed by this PDF, or False A PDF may claim to PDF/A compliant without this being true. Use an independent verifier such as veraPDF to test if a PDF is truly conformant. Returns: str: The conformance level of the PDF/A, or an empty stri...
def pdfa_status(self): """Returns the PDF/A conformance level claimed by this PDF, or False A PDF may claim to PDF/A compliant without this being true. Use an independent verifier such as veraPDF to test if a PDF is truly conformant. Returns: str: The conformance le...
PDF name of the colorspace that best describes this image
def colorspace(self): """PDF name of the colorspace that best describes this image""" if self.image_mask: return None # Undefined for image masks if self._colorspaces: if self._colorspaces[0] in self.SIMPLE_COLORSPACES: return self._colorspaces[0] ...
``PIL.Image.mode`` equivalent for this image
def mode(self): """``PIL.Image.mode`` equivalent for this image""" m = '' if self.indexed: m = 'P' elif self.bits_per_component == 1: m = '1' elif self.bits_per_component == 8: if self.colorspace == '/DeviceRGB': m = 'RGB' ...
Retrieves the color palette for this image :returns: (base_colorspace: str, palette: bytes) :rtype: tuple
def palette(self): """Retrieves the color palette for this image :returns: (base_colorspace: str, palette: bytes) :rtype: tuple """ if not self.indexed: return None _idx, base, hival, lookup = None, None, None, None try: _idx, base, hival...
Insert a PIL image into a PDF (rudimentary) :param pdf: the PDF to attach the image to :type pdf: pikepdf.Pdf :param page: the page to attach the image to :param name: the name to set the image :param image: image :type image: PIL.Image.Image
def _from_pil_image(cls, *, pdf, page, name, image): # pragma: no cover """Insert a PIL image into a PDF (rudimentary) :param pdf: the PDF to attach the image to :type pdf: pikepdf.Pdf :param page: the page to attach the image to :param name: the name to set the image :...
Attempt to extract the image directly to a usable image file If there is no way to extract the image without decompressing or transcoding then raise an exception. The type and format of image generated will vary. Args: stream: Writable stream to write data to
def _extract_direct(self, *, stream): """Attempt to extract the image directly to a usable image file If there is no way to extract the image without decompressing or transcoding then raise an exception. The type and format of image generated will vary. Args: stream...
Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the data will be decompressed and extracted to an appropriate ...
def extract_to(self, *, stream=None, fileprefix=''): """Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the da...
Extract the image as a Pillow Image, using decompression as necessary Returns: PIL.Image.Image
def as_pil_image(self): """Extract the image as a Pillow Image, using decompression as necessary Returns: PIL.Image.Image """ from PIL import Image try: bio = BytesIO() self._extract_direct(stream=bio) bio.seek(0) retu...
Construct a CCITT G3 or G4 header from the PDF metadata
def _generate_ccitt_header(self, data): """Construct a CCITT G3 or G4 header from the PDF metadata""" # https://stackoverflow.com/questions/2641770/ # https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf if not self.decode_parms: raise ValueError("/CCITTFaxDecode wi...
Display hook for IPython/Jupyter
def _repr_png_(self): """Display hook for IPython/Jupyter""" b = BytesIO() im = self.as_pil_image() im.save(b, 'PNG') return b.getvalue()
Attach methods of a Python support class to an existing class This monkeypatches all methods defined in the support class onto an existing class. Example: .. code-block:: python @augments(ClassDefinedInCpp) class SupportClass: def foo(self): pass The Pytho...
def augments(cls_cpp): """Attach methods of a Python support class to an existing class This monkeypatches all methods defined in the support class onto an existing class. Example: .. code-block:: python @augments(ClassDefinedInCpp) class SupportClass: def foo(self): ...