|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +#include "arrow/python/arrow_to_python.h" |
| 19 | + |
| 20 | +#include <cstdint> |
| 21 | +#include <memory> |
| 22 | +#include <vector> |
| 23 | + |
| 24 | +#include "arrow/array.h" |
| 25 | +#include "arrow/io/interfaces.h" |
| 26 | +#include "arrow/ipc/reader.h" |
| 27 | +#include "arrow/python/common.h" |
| 28 | +#include "arrow/python/helpers.h" |
| 29 | +#include "arrow/python/numpy_convert.h" |
| 30 | +#include "arrow/table.h" |
| 31 | +#include "arrow/util/logging.h" |
| 32 | + |
| 33 | +extern "C" { |
| 34 | +extern PyObject* pyarrow_serialize_callback; |
| 35 | +extern PyObject* pyarrow_deserialize_callback; |
| 36 | +} |
| 37 | + |
| 38 | +namespace arrow { |
| 39 | +namespace py { |
| 40 | + |
| 41 | +Status CallCustomCallback(PyObject* callback, PyObject* elem, PyObject** result); |
| 42 | + |
| 43 | +Status DeserializeTuple(std::shared_ptr<Array> array, int64_t start_idx, int64_t stop_idx, |
| 44 | + PyObject* base, |
| 45 | + const std::vector<std::shared_ptr<Tensor>>& tensors, |
| 46 | + PyObject** out); |
| 47 | + |
| 48 | +Status DeserializeList(std::shared_ptr<Array> array, int64_t start_idx, int64_t stop_idx, |
| 49 | + PyObject* base, |
| 50 | + const std::vector<std::shared_ptr<Tensor>>& tensors, |
| 51 | + PyObject** out); |
| 52 | + |
| 53 | +Status DeserializeDict(std::shared_ptr<Array> array, int64_t start_idx, int64_t stop_idx, |
| 54 | + PyObject* base, |
| 55 | + const std::vector<std::shared_ptr<Tensor>>& tensors, |
| 56 | + PyObject** out) { |
| 57 | + auto data = std::dynamic_pointer_cast<StructArray>(array); |
| 58 | + ScopedRef keys, vals; |
| 59 | + ScopedRef result(PyDict_New()); |
| 60 | + RETURN_NOT_OK( |
| 61 | + DeserializeList(data->field(0), start_idx, stop_idx, base, tensors, keys.ref())); |
| 62 | + RETURN_NOT_OK( |
| 63 | + DeserializeList(data->field(1), start_idx, stop_idx, base, tensors, vals.ref())); |
| 64 | + for (int64_t i = start_idx; i < stop_idx; ++i) { |
| 65 | + // PyDict_SetItem behaves differently from PyList_SetItem and PyTuple_SetItem. |
| 66 | + // The latter two steal references whereas PyDict_SetItem does not. So we need |
| 67 | + // to make sure the reference count is decremented by letting the ScopedRef |
| 68 | + // go out of scope at the end. |
| 69 | + PyDict_SetItem(result.get(), PyList_GET_ITEM(keys.get(), i - start_idx), |
| 70 | + PyList_GET_ITEM(vals.get(), i - start_idx)); |
| 71 | + } |
| 72 | + static PyObject* py_type = PyUnicode_FromString("_pytype_"); |
| 73 | + if (PyDict_Contains(result.get(), py_type)) { |
| 74 | + RETURN_NOT_OK(CallCustomCallback(pyarrow_deserialize_callback, result.get(), out)); |
| 75 | + } else { |
| 76 | + *out = result.release(); |
| 77 | + } |
| 78 | + return Status::OK(); |
| 79 | +} |
| 80 | + |
| 81 | +Status DeserializeArray(std::shared_ptr<Array> array, int64_t offset, PyObject* base, |
| 82 | + const std::vector<std::shared_ptr<arrow::Tensor>>& tensors, |
| 83 | + PyObject** out) { |
| 84 | + DCHECK(array); |
| 85 | + int32_t index = std::static_pointer_cast<Int32Array>(array)->Value(offset); |
| 86 | + RETURN_NOT_OK(py::TensorToNdarray(*tensors[index], base, out)); |
| 87 | + // Mark the array as immutable |
| 88 | + ScopedRef flags(PyObject_GetAttrString(*out, "flags")); |
| 89 | + DCHECK(flags.get() != NULL) << "Could not mark Numpy array immutable"; |
| 90 | + Py_INCREF(Py_False); |
| 91 | + int flag_set = PyObject_SetAttrString(flags.get(), "writeable", Py_False); |
| 92 | + DCHECK(flag_set == 0) << "Could not mark Numpy array immutable"; |
| 93 | + return Status::OK(); |
| 94 | +} |
| 95 | + |
| 96 | +Status GetValue(std::shared_ptr<Array> arr, int64_t index, int32_t type, PyObject* base, |
| 97 | + const std::vector<std::shared_ptr<Tensor>>& tensors, PyObject** result) { |
| 98 | + switch (arr->type()->id()) { |
| 99 | + case Type::BOOL: |
| 100 | + *result = |
| 101 | + PyBool_FromLong(std::static_pointer_cast<BooleanArray>(arr)->Value(index)); |
| 102 | + return Status::OK(); |
| 103 | + case Type::INT64: |
| 104 | + *result = |
| 105 | + PyLong_FromSsize_t(std::static_pointer_cast<Int64Array>(arr)->Value(index)); |
| 106 | + return Status::OK(); |
| 107 | + case Type::BINARY: { |
| 108 | + int32_t nchars; |
| 109 | + const uint8_t* str = |
| 110 | + std::static_pointer_cast<BinaryArray>(arr)->GetValue(index, &nchars); |
| 111 | + *result = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(str), nchars); |
| 112 | + return CheckPyError(); |
| 113 | + } |
| 114 | + case Type::STRING: { |
| 115 | + int32_t nchars; |
| 116 | + const uint8_t* str = |
| 117 | + std::static_pointer_cast<StringArray>(arr)->GetValue(index, &nchars); |
| 118 | + *result = PyUnicode_FromStringAndSize(reinterpret_cast<const char*>(str), nchars); |
| 119 | + return CheckPyError(); |
| 120 | + } |
| 121 | + case Type::FLOAT: |
| 122 | + *result = |
| 123 | + PyFloat_FromDouble(std::static_pointer_cast<FloatArray>(arr)->Value(index)); |
| 124 | + return Status::OK(); |
| 125 | + case Type::DOUBLE: |
| 126 | + *result = |
| 127 | + PyFloat_FromDouble(std::static_pointer_cast<DoubleArray>(arr)->Value(index)); |
| 128 | + return Status::OK(); |
| 129 | + case Type::STRUCT: { |
| 130 | + auto s = std::static_pointer_cast<StructArray>(arr); |
| 131 | + auto l = std::static_pointer_cast<ListArray>(s->field(0)); |
| 132 | + if (s->type()->child(0)->name() == "list") { |
| 133 | + return DeserializeList(l->values(), l->value_offset(index), |
| 134 | + l->value_offset(index + 1), base, tensors, result); |
| 135 | + } else if (s->type()->child(0)->name() == "tuple") { |
| 136 | + return DeserializeTuple(l->values(), l->value_offset(index), |
| 137 | + l->value_offset(index + 1), base, tensors, result); |
| 138 | + } else if (s->type()->child(0)->name() == "dict") { |
| 139 | + return DeserializeDict(l->values(), l->value_offset(index), |
| 140 | + l->value_offset(index + 1), base, tensors, result); |
| 141 | + } else { |
| 142 | + DCHECK(false) << "unexpected StructArray type " << s->type()->child(0)->name(); |
| 143 | + } |
| 144 | + } |
| 145 | + // We use an Int32Builder here to distinguish the tensor indices from |
| 146 | + // the Type::INT64 above (see tensor_indices_ in SequenceBuilder). |
| 147 | + case Type::INT32: { |
| 148 | + return DeserializeArray(arr, index, base, tensors, result); |
| 149 | + } |
| 150 | + default: |
| 151 | + DCHECK(false) << "union tag " << type << " not recognized"; |
| 152 | + } |
| 153 | + return Status::OK(); |
| 154 | +} |
| 155 | + |
| 156 | +#define DESERIALIZE_SEQUENCE(CREATE_FN, SET_ITEM_FN) \ |
| 157 | + auto data = std::dynamic_pointer_cast<UnionArray>(array); \ |
| 158 | + int64_t size = array->length(); \ |
| 159 | + ScopedRef result(CREATE_FN(stop_idx - start_idx)); \ |
| 160 | + auto types = std::make_shared<Int8Array>(size, data->type_ids()); \ |
| 161 | + auto offsets = std::make_shared<Int32Array>(size, data->value_offsets()); \ |
| 162 | + for (int64_t i = start_idx; i < stop_idx; ++i) { \ |
| 163 | + if (data->IsNull(i)) { \ |
| 164 | + Py_INCREF(Py_None); \ |
| 165 | + SET_ITEM_FN(result.get(), i - start_idx, Py_None); \ |
| 166 | + } else { \ |
| 167 | + int64_t offset = offsets->Value(i); \ |
| 168 | + int8_t type = types->Value(i); \ |
| 169 | + std::shared_ptr<Array> arr = data->child(type); \ |
| 170 | + PyObject* value; \ |
| 171 | + RETURN_NOT_OK(GetValue(arr, offset, type, base, tensors, &value)); \ |
| 172 | + SET_ITEM_FN(result.get(), i - start_idx, value); \ |
| 173 | + } \ |
| 174 | + } \ |
| 175 | + *out = result.release(); \ |
| 176 | + return Status::OK(); |
| 177 | + |
| 178 | +Status DeserializeList(std::shared_ptr<Array> array, int64_t start_idx, int64_t stop_idx, |
| 179 | + PyObject* base, |
| 180 | + const std::vector<std::shared_ptr<Tensor>>& tensors, |
| 181 | + PyObject** out) { |
| 182 | + DESERIALIZE_SEQUENCE(PyList_New, PyList_SET_ITEM) |
| 183 | +} |
| 184 | + |
| 185 | +Status DeserializeTuple(std::shared_ptr<Array> array, int64_t start_idx, int64_t stop_idx, |
| 186 | + PyObject* base, |
| 187 | + const std::vector<std::shared_ptr<Tensor>>& tensors, |
| 188 | + PyObject** out) { |
| 189 | + DESERIALIZE_SEQUENCE(PyTuple_New, PyTuple_SET_ITEM) |
| 190 | +} |
| 191 | + |
| 192 | +Status ReadSerializedObject(std::shared_ptr<io::RandomAccessFile> src, |
| 193 | + SerializedPyObject* out) { |
| 194 | + std::shared_ptr<ipc::RecordBatchStreamReader> reader; |
| 195 | + int64_t offset; |
| 196 | + int64_t bytes_read; |
| 197 | + int32_t num_tensors; |
| 198 | + // Read number of tensors |
| 199 | + RETURN_NOT_OK( |
| 200 | + src->Read(sizeof(int32_t), &bytes_read, reinterpret_cast<uint8_t*>(&num_tensors))); |
| 201 | + RETURN_NOT_OK(ipc::RecordBatchStreamReader::Open(src, &reader)); |
| 202 | + RETURN_NOT_OK(reader->ReadNextRecordBatch(&out->batch)); |
| 203 | + RETURN_NOT_OK(src->Tell(&offset)); |
| 204 | + offset += 4; // Skip the end-of-stream message |
| 205 | + for (int i = 0; i < num_tensors; ++i) { |
| 206 | + std::shared_ptr<Tensor> tensor; |
| 207 | + RETURN_NOT_OK(ipc::ReadTensor(offset, src.get(), &tensor)); |
| 208 | + out->tensors.push_back(tensor); |
| 209 | + RETURN_NOT_OK(src->Tell(&offset)); |
| 210 | + } |
| 211 | + return Status::OK(); |
| 212 | +} |
| 213 | + |
| 214 | +Status DeserializeObject(const SerializedPyObject& obj, PyObject* base, PyObject** out) { |
| 215 | + PyAcquireGIL lock; |
| 216 | + return DeserializeList(obj.batch->column(0), 0, obj.batch->num_rows(), base, |
| 217 | + obj.tensors, out); |
| 218 | +} |
| 219 | + |
| 220 | +} // namespace py |
| 221 | +} // namespace arrow |
0 commit comments