|
| 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 creation of new 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. Perform deserialization of response chunk based on expected response type. |
| 57 | + 2.3. If PayloadPart not in EventStream response, handle Errors. |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self, stream): |
| 61 | + """Initialises a Iterator object to help parse the byte event stream input. |
| 62 | +
|
| 63 | + Args: |
| 64 | + stream: (botocore.eventstream.EventStream): Event Stream object to be iterated. |
| 65 | + """ |
| 66 | + self.stream = stream |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def __iter__(self): |
| 70 | + """Abstract __iter__ method, returns an iterator object itself""" |
| 71 | + return self |
| 72 | + |
| 73 | + @abstractmethod |
| 74 | + def __next__(self): |
| 75 | + """Abstract __next__ method, is responsible for returning the next element in the |
| 76 | + iteration""" |
| 77 | + pass |
| 78 | + |
| 79 | + |
| 80 | +class LineIterator(BaseIterator): |
| 81 | + """ |
| 82 | + A helper class for parsing the byte stream input and provide iteration on lines with |
| 83 | + '\n' separators. |
| 84 | + """ |
| 85 | + |
| 86 | + def __init__(self, stream): |
| 87 | + """Initialises a Iterator object to help parse the byte stream input and |
| 88 | + provide iteration on lines with '\n' separators |
| 89 | +
|
| 90 | + Args: |
| 91 | + stream: (botocore.eventstream.EventStream): Event Stream object to be iterated. |
| 92 | + """ |
| 93 | + super().__init__(stream) |
| 94 | + self.byte_iterator = iter(self.stream) |
| 95 | + self.buffer = io.BytesIO() |
| 96 | + self.read_pos = 0 |
| 97 | + |
| 98 | + def __iter__(self): |
| 99 | + """Returns an iterator object itself, which allows the object to be iterated. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + iter : object |
| 103 | + An iterator object representing the iterable. |
| 104 | + """ |
| 105 | + return self |
| 106 | + |
| 107 | + def __next__(self): |
| 108 | + """ |
| 109 | + The output of the event stream will be in the following format: |
| 110 | +
|
| 111 | + ``` |
| 112 | + b'{"outputs": [" a"]}\n' |
| 113 | + b'{"outputs": [" challenging"]}\n' |
| 114 | + b'{"outputs": [" problem"]}\n' |
| 115 | + ... |
| 116 | + ``` |
| 117 | +
|
| 118 | + While usually each PayloadPart event from the event stream will contain a byte array |
| 119 | + with a full json, this is not guaranteed and some of the json objects may be split across |
| 120 | + PayloadPart events. For example: |
| 121 | + ``` |
| 122 | + {'PayloadPart': {'Bytes': b'{"outputs": '}} |
| 123 | + {'PayloadPart': {'Bytes': b'[" problem"]}\n'}} |
| 124 | + ``` |
| 125 | +
|
| 126 | + This class accounts for this by concatenating bytes written via the 'write' function |
| 127 | + and then exposing a method which will return lines (ending with a '\n' character) within |
| 128 | + the buffer via the 'scan_lines' function. It maintains the position of the last read |
| 129 | + position to ensure that previous bytes are not exposed again. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + str: Read and return one line from the event stream. |
| 133 | + """ |
| 134 | + # Even with "while True" loop the function still behaves like a generator |
| 135 | + # and sends the next new concatenated line |
| 136 | + while True: |
| 137 | + self.buffer.seek(self.read_pos) |
| 138 | + line = self.buffer.readline() |
| 139 | + if line and line[-1] == ord("\n"): |
| 140 | + self.read_pos += len(line) |
| 141 | + return line[:-1] |
| 142 | + try: |
| 143 | + chunk = next(self.byte_iterator) |
| 144 | + except StopIteration: |
| 145 | + if self.read_pos < self.buffer.getbuffer().nbytes: |
| 146 | + continue |
| 147 | + raise |
| 148 | + if "PayloadPart" not in chunk: |
| 149 | + # handle errors within API Response if any. |
| 150 | + handle_stream_errors(chunk) |
| 151 | + print("Unknown event type:" + chunk) |
| 152 | + continue |
| 153 | + self.buffer.seek(0, io.SEEK_END) |
| 154 | + self.buffer.write(chunk["PayloadPart"]["Bytes"]) |
0 commit comments