INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Like print () but recognizes tensors and arrays and show more details about them.
def write(*args): """Like print(), but recognizes tensors and arrays and show more details about them. Example: hl.write("My Tensor", my_tensor) Prints: My Tensor float32 (10, 3, 224, 224) min: 0.0 max: 1.0 """ s = "" for a in args: # Convert tensors ...
Normalize an image to [ 0 1 ] range.
def norm(image): """Normalize an image to [0, 1] range.""" min_value = image.min() max_value = image.max() if min_value == max_value: return image - min_value return (image - min_value) / (max_value - min_value)
images: A list of images. I can be either: - A list of Numpy arrays. Each array represents an image. - A list of lists of Numpy arrays. In this case the images in the inner lists are concatentated to make one image.
def show_images(images, titles=None, cols=5, **kwargs): """ images: A list of images. I can be either: - A list of Numpy arrays. Each array represents an image. - A list of lists of Numpy arrays. In this case, the images in the inner lists are concatentated to make one image. """ ...
Inserts a text summary at the top that lists the number of steps and total training time.
def draw_summary(self, history, title=""): """Inserts a text summary at the top that lists the number of steps and total training time.""" # Generate summary string time_str = str(history.get_total_time()).split(".")[0] # remove microseconds summary = "Step: {} Time: {}".fo...
metrics: One or more metrics parameters. Each represents the history of one metric.
def draw_plot(self, metrics, labels=None, ylabel=""): """ metrics: One or more metrics parameters. Each represents the history of one metric. """ metrics = metrics if isinstance(metrics, list) else [metrics] # Loop through metrics title = "" for i, m i...
Display a series of images at different time steps.
def draw_image(self, metric, limit=5): """Display a series of images at different time steps.""" rows = 1 cols = limit self.ax.axis("off") # Take the Axes gridspec and divide it into a grid gs = matplotlib.gridspec.GridSpecFromSubplotSpec( rows, cols, subplot_...
Draw a series of histograms of the selected keys over different training steps.
def draw_hist(self, metric, title=""): """Draw a series of histograms of the selected keys over different training steps. """ # TODO: assert isinstance(list(values.values())[0], np.ndarray) rows = 1 cols = 1 limit = 10 # max steps to show # We need a 3D...
Load the data in memory. Args: dataset: string in [ train test ]
def _load(self, dataset='train'): """Load the data in memory. Args: dataset: string in ['train', 'test'] """ data, labels = None, None if dataset is 'train': files = [os.path.join(self.cifar10_dir, 'data_batch_%d' % i) for i in range(1, 6)] else: ...
Build a simple convnet ( BN before ReLU ). Args: inputs: a tensor of size [ batch_size height width channels ] mode: string in [ train test ] Returns: the last op containing the predictions Note: Best score Step: 7015 - Epoch: 18/ 20 - best batch acc: 0. 8984 - loss: 1. 5656 Worst score Step: 7523 - Epoch: 20/ 20 - bes...
def model(self, inputs, mode='train'): """Build a simple convnet (BN before ReLU). Args: inputs: a tensor of size [batch_size, height, width, channels] mode: string in ['train', 'test'] Returns: the last op containing the predictions Note: ...
Download and extract the tarball from Alex Krizhevsky s website.
def maybe_download_and_extract(self): """Download and extract the tarball from Alex Krizhevsky's website.""" if not os.path.exists(self.cifar10_dir): if not os.path.exists(self.data_dir): os.makedirs(self.data_dir) def _progress(count, block_size, total_size): ...
List all the nodes in a PyTorch graph.
def dump_pytorch_graph(graph): """List all the nodes in a PyTorch graph.""" f = "{:25} {:40} {} -> {}" print(f.format("kind", "scopeName", "inputs", "outputs")) for node in graph.nodes(): print(f.format(node.kind(), node.scopeName(), [i.unique() for i in node.inputs()], ...
Returns a unique ID for a node.
def pytorch_id(node): """Returns a unique ID for a node.""" # After ONNX simplification, the scopeName is not unique anymore # so append node outputs to guarantee uniqueness return node.scopeName() + "/outputs/" + "/".join([o.uniqueName() for o in node.outputs()])
Return the output shape of the given Pytorch node.
def get_shape(torch_node): """Return the output shape of the given Pytorch node.""" # Extract node output shape from the node string representation # This is a hack because there doesn't seem to be an official way to do it. # See my quesiton in the PyTorch forum: # https://discuss.pytorch.org/t/node...
List all the nodes in a TF graph. tfgraph: A TF Graph object. tfgraphdef: A TF GraphDef object.
def dump_tf_graph(tfgraph, tfgraphdef): """List all the nodes in a TF graph. tfgraph: A TF Graph object. tfgraphdef: A TF GraphDef object. """ print("Nodes ({})".format(len(tfgraphdef.node))) f = "{:15} {:59} {:20} {}" print(f.format("kind", "scopeName", "shape", "inputs")) for node in t...
Convert TF graph to directed graph tfgraph: A TF Graph object. output: Name of the output node ( string ). verbose: Set to True for debug print output
def import_graph(hl_graph, tf_graph, output=None, verbose=False): """Convert TF graph to directed graph tfgraph: A TF Graph object. output: Name of the output node (string). verbose: Set to True for debug print output """ # Get clean(er) list of nodes graph_def = tf_graph.as_graph_def(add_sh...
Send FetchRequests for all assigned partitions that do not already have an in - flight fetch or pending fetch data.
def send_fetches(self): """Send FetchRequests for all assigned partitions that do not already have an in-flight fetch or pending fetch data. Returns: List of Futures: each future resolves to a FetchResponse """ futures = [] for node_id, request in six.iterite...
Lookup and set offsets for any partitions which are awaiting an explicit reset.
def reset_offsets_if_needed(self, partitions): """Lookup and set offsets for any partitions which are awaiting an explicit reset. Arguments: partitions (set of TopicPartitions): the partitions to reset """ for tp in partitions: # TODO: If there are severa...
Update the fetch positions for the provided partitions.
def update_fetch_positions(self, partitions): """Update the fetch positions for the provided partitions. Arguments: partitions (list of TopicPartitions): partitions to update Raises: NoOffsetForPartitionError: if no offset is stored for a given partition...
Reset offsets for the given partition using the offset reset strategy.
def _reset_offset(self, partition): """Reset offsets for the given partition using the offset reset strategy. Arguments: partition (TopicPartition): the partition that needs reset offset Raises: NoOffsetForPartitionError: if no offset reset strategy is defined "...
Fetch offset for each partition passed in timestamps map.
def _retrieve_offsets(self, timestamps, timeout_ms=float("inf")): """Fetch offset for each partition passed in ``timestamps`` map. Blocks until offsets are obtained, a non-retriable exception is raised or ``timeout_ms`` passed. Arguments: timestamps: {TopicPartition: int} d...
Returns previously fetched records and updates consumed offsets.
def fetched_records(self, max_records=None): """Returns previously fetched records and updates consumed offsets. Arguments: max_records (int): Maximum number of records returned. Defaults to max_poll_records configuration. Raises: OffsetOutOfRangeError: ...
Iterate over fetched_records
def _message_generator(self): """Iterate over fetched_records""" while self._next_partition_records or self._completed_fetches: if not self._next_partition_records: completion = self._completed_fetches.popleft() self._next_partition_records = self._parse_fetc...
Fetch offsets for each partition in timestamps dict. This may send request to multiple nodes based on who is Leader for partition.
def _send_offset_requests(self, timestamps): """Fetch offsets for each partition in timestamps dict. This may send request to multiple nodes, based on who is Leader for partition. Arguments: timestamps (dict): {TopicPartition: int} mapping of fetching timestamps. ...
Callback for the response of the list offset call above.
def _handle_offset_response(self, future, response): """Callback for the response of the list offset call above. Arguments: future (Future): the future to update based on response response (OffsetResponse): response from the server Raises: AssertionError: if...
Create fetch requests for all assigned partitions grouped by node.
def _create_fetch_requests(self): """Create fetch requests for all assigned partitions, grouped by node. FetchRequests skipped if no leader, or node has requests in flight Returns: dict: {node_id: FetchRequest, ...} (version depends on api_version) """ # create the ...
The callback for fetch completion
def _handle_fetch_response(self, request, send_time, response): """The callback for fetch completion""" fetch_offsets = {} for topic, partitions in request.topics: for partition_data in partitions: partition, offset = partition_data[:2] fetch_offsets[T...
After each partition is parsed we update the current metric totals with the total bytes and number of records parsed. After all partitions have reported we write the metric.
def record(self, partition, num_bytes, num_records): """ After each partition is parsed, we update the current metric totals with the total bytes and number of records parsed. After all partitions have reported, we write the metric. """ self.unrecorded_partitions.remove(p...
Check if we have to commit based on number of messages and commit
def _auto_commit(self): """ Check if we have to commit based on number of messages and commit """ # Check if we are supposed to do an auto-commit if not self.auto_commit or self.auto_commit_every_n is None: return if self.count_since_commit >= self.auto_comm...
Gets the pending message count
def pending(self, partitions=None): """ Gets the pending message count Keyword Arguments: partitions (list): list of partitions to check for, default is to check all """ if partitions is None: partitions = self.offsets.keys() total = 0 re...
Pure - python Murmur2 implementation.
def murmur2(data): """Pure-python Murmur2 implementation. Based on java client, see org.apache.kafka.common.utils.Utils.murmur2 Args: data (bytes): opaque bytes Returns: MurmurHash2 of data """ # Python2 bytes is really a str, causing the bitwise operations below to fail # so conv...
Fetch the specified number of messages
def get_messages(self, count=1, block=True, timeout=10): """ Fetch the specified number of messages Keyword Arguments: count: Indicates the maximum number of messages to be fetched block: If True, the API will block till all messages are fetched. If block...
Set the high - water mark in the current context.
def mark(self, partition, offset): """ Set the high-water mark in the current context. In order to know the current partition, it is helpful to initialize the consumer to provide partition info via: .. code:: python consumer.provide_partition_info() """ ...
Commit this context s offsets:
def commit(self): """ Commit this context's offsets: - If the high-water mark has moved, commit up to and position the consumer at the high-water mark. - Otherwise, reset to the consumer to the initial offsets. """ if self.high_water_mark: sel...
Rollback this context:
def rollback(self): """ Rollback this context: - Position the consumer at the initial offsets. """ self.logger.info("Rolling back context: %s", self.initial_offsets) self.update_consumer_offsets(self.initial_offsets)
Commit explicit partition/ offset pairs.
def commit_partition_offsets(self, partition_offsets): """ Commit explicit partition/offset pairs. """ self.logger.debug("Committing partition offsets: %s", partition_offsets) commit_requests = [ OffsetCommitRequestPayload(self.consumer.topic, partition, offset, None...
Update consumer offsets to explicit positions.
def update_consumer_offsets(self, partition_offsets): """ Update consumer offsets to explicit positions. """ self.logger.debug("Updating consumer offsets to: %s", partition_offsets) for partition, offset in partition_offsets.items(): self.consumer.offsets[partition] ...
Get the current coordinator
def coordinator(self): """Get the current coordinator Returns: the current coordinator id or None if it is unknown """ if self.coordinator_id is None: return None elif self._client.is_disconnected(self.coordinator_id): self.coordinator_dead('Node Disconne...
Block until the coordinator for this group is known ( and we have an active connection -- java client uses unsent queue ).
def ensure_coordinator_ready(self): """Block until the coordinator for this group is known (and we have an active connection -- java client uses unsent queue). """ with self._client._lock, self._lock: while self.coordinator_unknown(): # Prior to 0.8.2 there w...
Check the status of the heartbeat thread ( if it is active ) and indicate the liveness of the client. This must be called periodically after joining with: meth:. ensure_active_group to ensure that the member stays in the group. If an interval of time longer than the provided rebalance timeout ( max_poll_interval_ms ) e...
def poll_heartbeat(self): """ Check the status of the heartbeat thread (if it is active) and indicate the liveness of the client. This must be called periodically after joining with :meth:`.ensure_active_group` to ensure that the member stays in the group. If an interval of time ...
Ensure that the group is active ( i. e. joined and synced )
def ensure_active_group(self): """Ensure that the group is active (i.e. joined and synced)""" with self._client._lock, self._lock: if self._heartbeat_thread is None: self._start_heartbeat_thread() while self.need_rejoin() or self._rejoin_incomplete(): ...
Join the group and return the assignment for the next generation.
def _send_join_group_request(self): """Join the group and return the assignment for the next generation. This function handles both JoinGroup and SyncGroup, delegating to :meth:`._perform_assignment` if elected leader by the coordinator. Returns: Future: resolves to the enc...
Perform leader synchronization and send back the assignment for the group via SyncGroupRequest
def _on_join_leader(self, response): """ Perform leader synchronization and send back the assignment for the group via SyncGroupRequest Arguments: response (JoinResponse): broker response to parse Returns: Future: resolves to member assignment encoded-by...
Discover the current coordinator for the group.
def _send_group_coordinator_request(self): """Discover the current coordinator for the group. Returns: Future: resolves to the node id of the coordinator """ node_id = self._client.least_loaded_node() if node_id is None: return Future().failure(Errors.NoB...
Mark the current coordinator as dead.
def coordinator_dead(self, error): """Mark the current coordinator as dead.""" if self.coordinator_id is not None: log.warning("Marking the coordinator dead (node %s) for group %s: %s.", self.coordinator_id, self.group_id, error) self.coordinator_id = None
Get the current generation state if the group is stable.
def generation(self): """Get the current generation state if the group is stable. Returns: the current generation or None if the group is unjoined/rebalancing """ with self._lock: if self.state is not MemberState.STABLE: return None return self._g...
Reset the generation and memberId because we have fallen out of the group.
def reset_generation(self): """Reset the generation and memberId because we have fallen out of the group.""" with self._lock: self._generation = Generation.NO_GENERATION self.rejoin_needed = True self.state = MemberState.UNJOINED
Leave the current group and reset local generation/ memberId.
def maybe_leave_group(self): """Leave the current group and reset local generation/memberId.""" with self._client._lock, self._lock: if (not self.coordinator_unknown() and self.state is not MemberState.UNJOINED and self._generation is not Generation.NO_GENERAT...
Send a heartbeat request
def _send_heartbeat_request(self): """Send a heartbeat request""" if self.coordinator_unknown(): e = Errors.GroupCoordinatorNotAvailableError(self.coordinator_id) return Future().failure(e) elif not self._client.ready(self.coordinator_id, metadata_priority=False): ...
Create a MetricName with the given name group description and tags plus default tags specified in the metric configuration. Tag in tags takes precedence if the same tag key is specified in the default metric configuration.
def metric_name(self, name, group, description='', tags=None): """ Create a MetricName with the given name, group, description and tags, plus default tags specified in the metric configuration. Tag in tags takes precedence if the same tag key is specified in the default metric co...
Get or create a sensor with the given unique name and zero or more parent sensors. All parent sensors will receive every value recorded with this sensor.
def sensor(self, name, config=None, inactive_sensor_expiration_time_seconds=sys.maxsize, parents=None): """ Get or create a sensor with the given unique name and zero or more parent sensors. All parent sensors will receive every value recorded with this sens...
Remove a sensor ( if it exists ) associated metrics and its children.
def remove_sensor(self, name): """ Remove a sensor (if it exists), associated metrics and its children. Arguments: name (str): The name of the sensor to be removed """ sensor = self._sensors.get(name) if sensor: child_sensors = None wi...
Add a metric to monitor an object that implements measurable. This metric won t be associated with any sensor. This is a way to expose existing values as metrics.
def add_metric(self, metric_name, measurable, config=None): """ Add a metric to monitor an object that implements measurable. This metric won't be associated with any sensor. This is a way to expose existing values as metrics. Arguments: metricName (MetricName): The ...
Remove a metric if it exists and return it. Return None otherwise. If a metric is removed metric_removal will be invoked for each reporter.
def remove_metric(self, metric_name): """ Remove a metric if it exists and return it. Return None otherwise. If a metric is removed, `metric_removal` will be invoked for each reporter. Arguments: metric_name (MetricName): The name of the metric Returns: ...
Add a MetricReporter
def add_reporter(self, reporter): """Add a MetricReporter""" with self._lock: reporter.init(list(self.metrics.values())) self._reporters.append(reporter)
Close this metrics repository.
def close(self): """Close this metrics repository.""" for reporter in self._reporters: reporter.close() self._metrics.clear()
Construct a Snappy Message containing multiple Messages
def create_snappy_message(payloads, key=None): """ Construct a Snappy Message containing multiple Messages The given payloads will be encoded, compressed, and sent as a single atomic message to Kafka. Arguments: payloads: list(bytes), a list of payload to send be sent to Kafka key:...
Create a message set using the given codec.
def create_message_set(messages, codec=CODEC_NONE, key=None, compresslevel=None): """Create a message set using the given codec. If codec is CODEC_NONE, return a list of raw Kafka messages. Otherwise, return a list containing a single codec-encoded message. """ if codec == CODEC_NONE: retur...
Encode the common request envelope
def _encode_message_header(cls, client_id, correlation_id, request_key, version=0): """ Encode the common request envelope """ return struct.pack('>hhih%ds' % len(client_id), request_key, # ApiKey ...
Encode a MessageSet. Unlike other arrays in the protocol MessageSets are not length - prefixed
def _encode_message_set(cls, messages): """ Encode a MessageSet. Unlike other arrays in the protocol, MessageSets are not length-prefixed Format ====== MessageSet => [Offset MessageSize Message] Offset => int64 MessageSize => int32 """ ...
Encode a ProduceRequest struct
def encode_produce_request(cls, payloads=(), acks=1, timeout=1000): """ Encode a ProduceRequest struct Arguments: payloads: list of ProduceRequestPayload acks: How "acky" you want the request to be 1: written to disk by the leader 0: immed...
Decode ProduceResponse to ProduceResponsePayload
def decode_produce_response(cls, response): """ Decode ProduceResponse to ProduceResponsePayload Arguments: response: ProduceResponse Return: list of ProduceResponsePayload """ return [ kafka.structs.ProduceResponsePayload(topic, partition, error...
Encodes a FetchRequest struct
def encode_fetch_request(cls, payloads=(), max_wait_time=100, min_bytes=4096): """ Encodes a FetchRequest struct Arguments: payloads: list of FetchRequestPayload max_wait_time (int, optional): ms to block waiting for min_bytes data. Defaults to 100. ...
Decode FetchResponse struct to FetchResponsePayloads
def decode_fetch_response(cls, response): """ Decode FetchResponse struct to FetchResponsePayloads Arguments: response: FetchResponse """ return [ kafka.structs.FetchResponsePayload( topic, partition, error, highwater_offset, [ ...
Decode OffsetResponse into OffsetResponsePayloads
def decode_offset_response(cls, response): """ Decode OffsetResponse into OffsetResponsePayloads Arguments: response: OffsetResponse Returns: list of OffsetResponsePayloads """ return [ kafka.structs.OffsetResponsePayload(topic, partition, error,...
Decode OffsetResponse_v2 into ListOffsetResponsePayloads
def decode_list_offset_response(cls, response): """ Decode OffsetResponse_v2 into ListOffsetResponsePayloads Arguments: response: OffsetResponse_v2 Returns: list of ListOffsetResponsePayloads """ return [ kafka.structs.ListOffsetResponsePayload(t...
Encode a MetadataRequest
def encode_metadata_request(cls, topics=(), payloads=None): """ Encode a MetadataRequest Arguments: topics: list of strings """ if payloads is not None: topics = payloads return kafka.protocol.metadata.MetadataRequest[0](topics)
Encode a ConsumerMetadataRequest
def encode_consumer_metadata_request(cls, client_id, correlation_id, payloads): """ Encode a ConsumerMetadataRequest Arguments: client_id: string correlation_id: int payloads: string (consumer group) """ message = [] message.append(cls...
Decode bytes to a kafka. structs. ConsumerMetadataResponse
def decode_consumer_metadata_response(cls, data): """ Decode bytes to a kafka.structs.ConsumerMetadataResponse Arguments: data: bytes to decode """ ((correlation_id, error, nodeId), cur) = relative_unpack('>ihi', data, 0) (host, cur) = read_short_string(data,...
Encode an OffsetCommitRequest struct
def encode_offset_commit_request(cls, group, payloads): """ Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload """ return kafka.protocol.commit.Offs...
Decode OffsetCommitResponse to an OffsetCommitResponsePayload
def decode_offset_commit_response(cls, response): """ Decode OffsetCommitResponse to an OffsetCommitResponsePayload Arguments: response: OffsetCommitResponse """ return [ kafka.structs.OffsetCommitResponsePayload(topic, partition, error) for t...
Encode an OffsetFetchRequest struct. The request is encoded using version 0 if from_kafka is false indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise indicating a request for Kafka offsets.
def encode_offset_fetch_request(cls, group, payloads, from_kafka=False): """ Encode an OffsetFetchRequest struct. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request ...
Decode OffsetFetchResponse to OffsetFetchResponsePayloads
def decode_offset_fetch_response(cls, response): """ Decode OffsetFetchResponse to OffsetFetchResponsePayloads Arguments: response: OffsetFetchResponse """ return [ kafka.structs.OffsetFetchResponsePayload( topic, partition, offset, metada...
Return a file descriptor from a file object.
def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previou...
Validate that this sensor doesn t end up referencing itself.
def _check_forest(self, sensors): """Validate that this sensor doesn't end up referencing itself.""" if self in sensors: raise ValueError('Circular dependency in sensors: %s is its own' 'parent.' % (self.name,)) sensors.add(self) for parent in sel...
Record a value at a known time. Arguments: value ( double ): The value we are recording time_ms ( int ): A POSIX timestamp in milliseconds. Default: The time when record () is evaluated ( now )
def record(self, value=1.0, time_ms=None): """ Record a value at a known time. Arguments: value (double): The value we are recording time_ms (int): A POSIX timestamp in milliseconds. Default: The time when record() is evaluated (now) Raises: ...
Check if we have violated our quota for any metric that has a configured quota
def _check_quotas(self, time_ms): """ Check if we have violated our quota for any metric that has a configured quota """ for metric in self._metrics: if metric.config and metric.config.quota: value = metric.value(time_ms) if not metric....
Register a compound statistic with this sensor which yields multiple measurable quantities ( like a histogram )
def add_compound(self, compound_stat, config=None): """ Register a compound statistic with this sensor which yields multiple measurable quantities (like a histogram) Arguments: stat (AbstractCompoundStat): The stat to register config (MetricConfig): The configura...
Register a metric with this sensor
def add(self, metric_name, stat, config=None): """ Register a metric with this sensor Arguments: metric_name (MetricName): The name of the metric stat (AbstractMeasurableStat): The statistic to keep config (MetricConfig): A special configuration for this metr...
Returns list of preferred ( protocols metadata )
def group_protocols(self): """Returns list of preferred (protocols, metadata)""" if self._subscription.subscription is None: raise Errors.IllegalStateError('Consumer has not subscribed to topics') # dpkp note: I really dislike this. # why? because we are using this strange me...
Poll for coordinator events. Only applicable if group_id is set and broker version supports GroupCoordinators. This ensures that the coordinator is known and if using automatic partition assignment ensures that the consumer has joined the group. This also handles periodic offset commits if they are enabled.
def poll(self): """ Poll for coordinator events. Only applicable if group_id is set, and broker version supports GroupCoordinators. This ensures that the coordinator is known, and if using automatic partition assignment, ensures that the consumer has joined the group. This also h...
Return seconds ( float ) remaining until: meth:. poll should be called again
def time_to_next_poll(self): """Return seconds (float) remaining until :meth:`.poll` should be called again""" if not self.config['enable_auto_commit']: return self.time_to_next_heartbeat() if time.time() > self.next_auto_commit_deadline: return 0 return min(sel...
Check whether the group should be rejoined
def need_rejoin(self): """Check whether the group should be rejoined Returns: bool: True if consumer should rejoin group, False otherwise """ if not self._subscription.partitions_auto_assigned(): return False if self._auto_assign_all_partitions(): ...
Fetch committed offsets for assigned partitions.
def refresh_committed_offsets_if_needed(self): """Fetch committed offsets for assigned partitions.""" if self._subscription.needs_fetch_committed_offsets: offsets = self.fetch_committed_offsets(self._subscription.assigned_partitions()) for partition, offset in six.iteritems(offse...
Fetch the current committed offsets for specified partitions
def fetch_committed_offsets(self, partitions): """Fetch the current committed offsets for specified partitions Arguments: partitions (list of TopicPartition): partitions to fetch Returns: dict: {TopicPartition: OffsetAndMetadata} """ if not partitions: ...
Close the coordinator leave the current group and reset local generation/ member_id.
def close(self, autocommit=True): """Close the coordinator, leave the current group, and reset local generation / member_id. Keyword Arguments: autocommit (bool): If auto-commit is configured for this consumer, this optional flag causes the consumer to attempt to com...
Commit specific offsets asynchronously.
def commit_offsets_async(self, offsets, callback=None): """Commit specific offsets asynchronously. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit callback (callable, optional): called as callback(offsets, response) response will be ...
Commit specific offsets synchronously.
def commit_offsets_sync(self, offsets): """Commit specific offsets synchronously. This method will retry until the commit completes successfully or an unrecoverable error is encountered. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit ...
Commit offsets for the specified list of topics and partitions.
def _send_offset_commit_request(self, offsets): """Commit offsets for the specified list of topics and partitions. This is a non-blocking call which returns a request future that can be polled in the case of a synchronous commit or ignored in the asynchronous case. Arguments: ...
Fetch the committed offsets for a set of partitions.
def _send_offset_fetch_request(self, partitions): """Fetch the committed offsets for a set of partitions. This is a non-blocking call. The returned future can be polled to get the actual offsets returned from the broker. Arguments: partitions (list of TopicPartition): the p...
Subscribe to a list of topics or a topic regex pattern.
def subscribe(self, topics=(), pattern=None, listener=None): """Subscribe to a list of topics, or a topic regex pattern. Partitions will be dynamically assigned via a group coordinator. Topic subscriptions are not incremental: this list will replace the current assignment (if there is o...
Ensures that the topic name is valid according to the kafka source.
def _ensure_valid_topic_name(self, topic): """ Ensures that the topic name is valid according to the kafka source. """ # See Kafka Source: # https://github.com/apache/kafka/blob/39eb31feaeebfb184d98cc5d94da9148c2319d81/clients/src/main/java/org/apache/kafka/common/internals/Topic.java i...
Change the topic subscription.
def change_subscription(self, topics): """Change the topic subscription. Arguments: topics (list of str): topics for subscription Raises: IllegalStateErrror: if assign_from_user has been used already TypeError: if a topic is None or a non-str Val...
Add topics to the current group subscription.
def group_subscribe(self, topics): """Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to t...
Reset the group s subscription to only contain topics subscribed by this consumer.
def reset_group_subscription(self): """Reset the group's subscription to only contain topics subscribed by this consumer.""" if self._user_assignment: raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE) assert self.subscription is not None, 'Subscription required' s...
Manually assign a list of TopicPartitions to this consumer.
def assign_from_user(self, partitions): """Manually assign a list of TopicPartitions to this consumer. This interface does not allow for incremental assignment and will replace the previous assignment (if there was one). Manual topic assignment through this method does not use the cons...
Update the assignment to the specified partitions
def assign_from_subscribed(self, assignments): """Update the assignment to the specified partitions This method is called by the coordinator to dynamically assign partitions based on the consumer's topic subscription. This is different from assign_from_user() which directly sets the ass...
Clear all topic subscriptions and partition assignments
def unsubscribe(self): """Clear all topic subscriptions and partition assignments""" self.subscription = None self._user_assignment.clear() self.assignment.clear() self.subscribed_pattern = None
Return current set of paused TopicPartitions.
def paused_partitions(self): """Return current set of paused TopicPartitions.""" return set(partition for partition in self.assignment if self.is_paused(partition))
Return set of TopicPartitions that should be Fetched.
def fetchable_partitions(self): """Return set of TopicPartitions that should be Fetched.""" fetchable = set() for partition, state in six.iteritems(self.assignment): if state.is_fetchable(): fetchable.add(partition) return fetchable
Returns consumed offsets as { TopicPartition: OffsetAndMetadata }
def all_consumed_offsets(self): """Returns consumed offsets as {TopicPartition: OffsetAndMetadata}""" all_consumed = {} for partition, state in six.iteritems(self.assignment): if state.has_valid_position: all_consumed[partition] = OffsetAndMetadata(state.position, '')...