|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +"""Implements iterators for deserializing data returned from an inference streaming endpoint.""" |
| 14 | +from __future__ import absolute_import |
| 15 | + |
| 16 | +from abc import ABC, abstractmethod |
| 17 | +import io |
| 18 | + |
| 19 | +from sagemaker.exceptions import ModelStreamError, InternalStreamFailure |
| 20 | + |
| 21 | + |
| 22 | +def handle_stream_errors(chunk): |
| 23 | + """Handle API Response errors within `invoke_endpoint_with_response_stream` API if any. |
| 24 | +
|
| 25 | + Args: |
| 26 | + chunk (dict): A chunk of response received as part of `botocore.eventstream.EventStream` |
| 27 | + response object. |
| 28 | +
|
| 29 | + Raises: |
| 30 | + ModelStreamError: If `ModelStreamError` error is detected in a chunk of |
| 31 | + `botocore.eventstream.EventStream` response object. |
| 32 | + InternalStreamFailure: If `InternalStreamFailure` error is detected in a chunk of |
| 33 | + `botocore.eventstream.EventStream` response object. |
| 34 | + """ |
| 35 | + if "ModelStreamError" in chunk: |
| 36 | + raise ModelStreamError( |
| 37 | + chunk["ModelStreamError"]["Message"], code=chunk["ModelStreamError"]["ErrorCode"] |
| 38 | + ) |
| 39 | + if "InternalStreamFailure" in chunk: |
| 40 | + raise InternalStreamFailure(chunk["InternalStreamFailure"]["Message"]) |
| 41 | + |
| 42 | + |
| 43 | +class BaseIterator(ABC): |
| 44 | + """Abstract base class for Inference Streaming iterators. |
| 45 | +
|
| 46 | + Provides a skeleton for customization requiring the overriding of iterator methods |
| 47 | + __iter__ and __next__. |
| 48 | +
|
| 49 | + Tenets of iterator class for Streaming Inference API Response |
| 50 | + (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ |
| 51 | + sagemaker-runtime/client/invoke_endpoint_with_response_stream.html): |
| 52 | + 1. Needs to accept an botocore.eventstream.EventStream response. |
| 53 | + 2. Needs to implement logic in __next__ to: |
| 54 | + 2.1. Concatenate and provide next chunk of response from botocore.eventstream.EventStream. |
| 55 | + While doing so parse the response_chunk["PayloadPart"]["Bytes"]. |
| 56 | + 2.2. If PayloadPart not in EventStream response, handle Errors |
| 57 | + [Recommended to use `iterators.handle_stream_errors` method]. |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self, event_stream): |
| 61 | + """Initialises a Iterator object to help parse the byte event stream input. |
| 62 | +
|
| 63 | + Args: |
| 64 | + event_stream: (botocore.eventstream.EventStream): Event Stream object to be iterated. |
| 65 | + """ |
| 66 | + self.event_stream = event_stream |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def __iter__(self): |
| 70 | + """Abstract method, returns an iterator object itself""" |
| 71 | + return self |
| 72 | + |
| 73 | + @abstractmethod |
| 74 | + def __next__(self): |
| 75 | + """Abstract method, is responsible for returning the next element in the iteration""" |
| 76 | + |
| 77 | + |
| 78 | +class ByteIterator(BaseIterator): |
| 79 | + """A helper class for parsing the byte Event Stream input to provide Byte iteration.""" |
| 80 | + |
| 81 | + def __init__(self, event_stream): |
| 82 | + """Initialises a BytesIterator Iterator object |
| 83 | +
|
| 84 | + Args: |
| 85 | + event_stream: (botocore.eventstream.EventStream): Event Stream object to be iterated. |
| 86 | + """ |
| 87 | + super().__init__(event_stream) |
| 88 | + self.byte_iterator = iter(event_stream) |
| 89 | + |
| 90 | + def __iter__(self): |
| 91 | + """Returns an iterator object itself, which allows the object to be iterated. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + iter : object |
| 95 | + An iterator object representing the iterable. |
| 96 | + """ |
| 97 | + return self |
| 98 | + |
| 99 | + def __next__(self): |
| 100 | + """Returns the next chunk of Byte directly.""" |
| 101 | + # Even with "while True" loop the function still behaves like a generator |
| 102 | + # and sends the next new byte chunk. |
| 103 | + while True: |
| 104 | + chunk = next(self.byte_iterator) |
| 105 | + if "PayloadPart" not in chunk: |
| 106 | + # handle API response errors and force terminate. |
| 107 | + handle_stream_errors(chunk) |
| 108 | + # print and move on to next response byte |
| 109 | + print("Unknown event type:" + chunk) |
| 110 | + continue |
| 111 | + return chunk["PayloadPart"]["Bytes"] |
| 112 | + |
| 113 | + |
| 114 | +class LineIterator(BaseIterator): |
| 115 | + """A helper class for parsing the byte Event Stream input to provide Line iteration.""" |
| 116 | + |
| 117 | + def __init__(self, event_stream): |
| 118 | + """Initialises a LineIterator Iterator object |
| 119 | +
|
| 120 | + Args: |
| 121 | + event_stream: (botocore.eventstream.EventStream): Event Stream object to be iterated. |
| 122 | + """ |
| 123 | + super().__init__(event_stream) |
| 124 | + self.byte_iterator = iter(self.event_stream) |
| 125 | + self.buffer = io.BytesIO() |
| 126 | + self.read_pos = 0 |
| 127 | + |
| 128 | + def __iter__(self): |
| 129 | + """Returns an iterator object itself, which allows the object to be iterated. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + iter : object |
| 133 | + An iterator object representing the iterable. |
| 134 | + """ |
| 135 | + return self |
| 136 | + |
| 137 | + def __next__(self): |
| 138 | + r"""Returns the next Line for an Line iterable. |
| 139 | +
|
| 140 | + The output of the event stream will be in the following format: |
| 141 | +
|
| 142 | + ``` |
| 143 | + b'{"outputs": [" a"]}\n' |
| 144 | + b'{"outputs": [" challenging"]}\n' |
| 145 | + b'{"outputs": [" problem"]}\n' |
| 146 | + ... |
| 147 | + ``` |
| 148 | +
|
| 149 | + While usually each PayloadPart event from the event stream will contain a byte array |
| 150 | + with a full json, this is not guaranteed and some of the json objects may be split across |
| 151 | + PayloadPart events. For example: |
| 152 | + ``` |
| 153 | + {'PayloadPart': {'Bytes': b'{"outputs": '}} |
| 154 | + {'PayloadPart': {'Bytes': b'[" problem"]}\n'}} |
| 155 | + ``` |
| 156 | +
|
| 157 | + This class accounts for this by concatenating bytes written via the 'write' function |
| 158 | + and then exposing a method which will return lines (ending with a '\n' character) within |
| 159 | + the buffer via the 'scan_lines' function. It maintains the position of the last read |
| 160 | + position to ensure that previous bytes are not exposed again. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + str: Read and return one line from the event stream. |
| 164 | + """ |
| 165 | + # Even with "while True" loop the function still behaves like a generator |
| 166 | + # and sends the next new concatenated line |
| 167 | + while True: |
| 168 | + self.buffer.seek(self.read_pos) |
| 169 | + line = self.buffer.readline() |
| 170 | + if line and line[-1] == ord("\n"): |
| 171 | + self.read_pos += len(line) |
| 172 | + return line[:-1] |
| 173 | + try: |
| 174 | + chunk = next(self.byte_iterator) |
| 175 | + except StopIteration: |
| 176 | + if self.read_pos < self.buffer.getbuffer().nbytes: |
| 177 | + continue |
| 178 | + raise |
| 179 | + if "PayloadPart" not in chunk: |
| 180 | + # handle API response errors and force terminate. |
| 181 | + handle_stream_errors(chunk) |
| 182 | + # print and move on to next response byte |
| 183 | + print("Unknown event type:" + chunk) |
| 184 | + continue |
| 185 | + self.buffer.seek(0, io.SEEK_END) |
| 186 | + self.buffer.write(chunk["PayloadPart"]["Bytes"]) |
0 commit comments