File: simple_writer.cc

package info (click to toggle)
pyosmium 4.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,584 kB
  • sloc: python: 4,400; cpp: 2,504; makefile: 20
file content (390 lines) | stat: -rw-r--r-- 12,647 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/* SPDX-License-Identifier: BSD-2-Clause
 *
 * This file is part of pyosmium. (https://osmcode.org/pyosmium/)
 *
 * Copyright (C) 2024 Sarah Hoffmann <lonvia@denofr.de> and others.
 * For a full list of authors see the git log.
 */
#include <pybind11/pybind11.h>
#include <pybind11/stl/filesystem.h>

#include <osmium/osm.hpp>
#include <osmium/io/any_output.hpp>
#include <osmium/io/writer.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/builder/osm_object_builder.hpp>

#include "cast.h"
#include "osm_base_objects.h"
#include "base_handler.h"

#include <filesystem>

namespace py = pybind11;

namespace {

class SimpleWriter : public pyosmium::BaseHandler
{
    enum { BUFFER_WRAP = 4096 };

public:
    SimpleWriter(const char* filename, size_t bufsz, osmium::io::Header const *header,
                 bool overwrite, const std::string &filetype)
    : writer(osmium::io::File(filename, filetype),
             header ? *header : osmium::io::Header(),
             overwrite ? osmium::io::overwrite::allow : osmium::io::overwrite::no),
      buffer(bufsz < 2 * BUFFER_WRAP ? 2 * BUFFER_WRAP : bufsz,
             osmium::memory::Buffer::auto_grow::yes),
      buffer_size(buffer.capacity()) // same rounding to BUFFER_WRAP
    {}

    SimpleWriter(osmium::io::File file, size_t bufsz, osmium::io::Header const *header,
                 bool overwrite)
    : writer(file, header ? *header : osmium::io::Header(),
             overwrite ? osmium::io::overwrite::allow : osmium::io::overwrite::no),
      buffer(bufsz < 2 * BUFFER_WRAP ? 2 * BUFFER_WRAP : bufsz,
             osmium::memory::Buffer::auto_grow::yes),
      buffer_size(buffer.capacity()) // same rounding to BUFFER_WRAP
    {}

    virtual ~SimpleWriter()
    { close(); }


    bool node(pyosmium::PyOSMNode &o) override
    {
        buffer.add_item(*(o.get()));
        flush_buffer();
        return false;
    }

    bool way(pyosmium::PyOSMWay &o) override
    {
        buffer.add_item(*(o.get()));
        flush_buffer();
        return false;
    }

    bool relation(pyosmium::PyOSMRelation &o) override
    {
        buffer.add_item(*(o.get()));
        flush_buffer();
        return false;
    }

    void flush() override
    {
        flush_buffer(true);
    }


    void add_node(py::object o)
    {
        if (!buffer) {
            throw std::runtime_error{"Writer already closed."};
        }

        buffer.rollback();

        auto const *inode = pyosmium::try_cast<pyosmium::COSMNode>(o);
        if (inode) {
            buffer.add_item(*inode->get());
        } else {
            osmium::builder::NodeBuilder builder(buffer);

            auto const location = py::getattr(o, "location", py::none());
            if (!location.is_none()) {
                osmium::Node& n = builder.object();
                n.set_location(get_location(location));
            }

            set_common_attributes(o, builder);
            set_taglist<pyosmium::COSMNode>(o, builder);
        }

        flush_buffer();
    }

    void add_way(py::object o)
    {
        if (!buffer) {
            throw std::runtime_error{"Writer already closed."};
        }

        buffer.rollback();

        auto const *iobj = pyosmium::try_cast<pyosmium::COSMWay>(o);
        if (iobj) {
            buffer.add_item(*iobj->get());
        } else {
            osmium::builder::WayBuilder builder(buffer);

            set_common_attributes(o, builder);
            set_nodelist(o, &builder);
            set_taglist<pyosmium::COSMWay>(o, builder);
        }

        flush_buffer();
    }

    void add_relation(py::object o)
    {
        if (!buffer) {
            throw std::runtime_error{"Writer already closed."};
        }

        buffer.rollback();

        auto const *iobj = pyosmium::try_cast<pyosmium::COSMRelation>(o);
        if (iobj) {
            buffer.add_item(*iobj->get());
        } else {
            osmium::builder::RelationBuilder builder(buffer);

            set_common_attributes(o, builder);
            set_memberlist(o, &builder);
            set_taglist<pyosmium::COSMRelation>(o, builder);
        }

        flush_buffer();
    }

    void close()
    {
        if (buffer) {
            writer(std::move(buffer));
            writer.close();
            buffer = osmium::memory::Buffer();
        }
    }

private:
    void set_object_attributes(py::object const &o, osmium::OSMObject& t)
    {
        {
            auto const id = py::getattr(o, "id", py::none());
            if (!id.is_none())
                t.set_id(id.cast<osmium::object_id_type>());
        }
        {
            auto const attr = py::getattr(o, "visible", py::none());
            if (!attr.is_none())
                t.set_visible(attr.cast<bool>());
        }
        {
            auto const attr = py::getattr(o, "version", py::none());
            if (!attr.is_none())
                t.set_version(attr.cast<osmium::object_version_type>());
        }
        {
            auto const attr = py::getattr(o, "changeset", py::none());
            if (!attr.is_none())
                t.set_changeset(attr.cast<osmium::changeset_id_type>());
        }
        {
            auto const attr = py::getattr(o, "uid", py::none());
            if (!attr.is_none())
                t.set_uid_from_signed(attr.cast<osmium::signed_user_id_type>());
        }
        {
            auto const attr = py::getattr(o, "timestamp", py::none());
            if (!attr.is_none())
                t.set_timestamp(attr.cast<osmium::Timestamp>());
        }
    }

    template <typename T>
    void set_common_attributes(py::object const &o, T& builder)
    {
        set_object_attributes(o, builder.object());

        auto const attr = py::getattr(o, "user", py::none());
        if (!attr.is_none())
            builder.set_user(attr.cast<std::string>());
    }

    template <typename Base, typename T>
    void set_taglist(py::object const &container, T& obuilder)
    {
        auto const o = py::getattr(container, "tags", py::none());

        if (o.is_none()) {
            return;
        }

        // original taglist
        auto const &iobj = pyosmium::try_cast<Base>(o);
        if (iobj) {
            auto const &otl = iobj->get()->tags();
            if (otl.size() > 0)
                obuilder.add_item(otl);
            return;
        }

        if (py::len(o) == 0)
            return;

        // dict
        if (py::isinstance<py::dict>(o)) {
            osmium::builder::TagListBuilder builder(buffer, &obuilder);
            auto const dict = o.cast<py::dict>();
            for (auto const &k : dict) {
                builder.add_tag(k.first.cast<std::string>(),
                                k.second.cast<std::string>());
            }
            return;
        }

        // else must be an iterable
        osmium::builder::TagListBuilder builder(buffer, &obuilder);
        for (auto const item : o) {
            auto const tag = item.cast<py::tuple>();
            builder.add_tag(tag[0].cast<std::string>(),
                            tag[1].cast<std::string>());
        }
    }

    void set_nodelist(py::object const &container, osmium::builder::WayBuilder *builder)
    {
        auto const o = py::getattr(container, "nodes", py::none());

        if (o.is_none()) {
            return;
        }

        // original nodelist
        auto const *onl = pyosmium::try_cast_list<osmium::WayNodeList>(o);
        if (onl) {
            if (onl->size() > 0)
                builder->add_item(*onl);
            return;
        }

        // accept an iterable of IDs otherwise
        if (py::len(o) == 0)
            return;

        osmium::builder::WayNodeListBuilder wnl_builder(buffer, builder);

        for (auto const ref : o) {
            auto const attr = py::getattr(ref, "ref", py::none());
            if (!attr.is_none())
                wnl_builder.add_node_ref(attr.cast<osmium::object_id_type>());
            else
                wnl_builder.add_node_ref(ref.cast<osmium::object_id_type>());
        }
    }

    void set_memberlist(py::object const &container, osmium::builder::RelationBuilder *builder)
    {
        auto const o = py::getattr(container, "members", py::none());

        if (o.is_none()) {
            return;
        }

        // original memberlist
        auto const &iobj = pyosmium::try_cast<pyosmium::COSMRelation>(o);
        if (iobj) {
            auto const &oml = iobj->get()->members();
            if (oml.size() > 0)
                builder->add_item(oml);
            return;
        }

        // accept an iterable of (type, id, role) otherwise
        if (py::len(o) == 0)
            return;

        osmium::builder::RelationMemberListBuilder rml_builder(buffer, builder);

        for (auto const m: o) {
            if (py::isinstance<py::tuple>(m)) {
                auto const member = m.cast<py::tuple>();
                auto const type = member[0].cast<std::string>();
                auto const id = member[1].cast<osmium::object_id_type>();
                auto const role = member[2].cast<std::string>();
                rml_builder.add_member(osmium::char_to_item_type(type[0]), id, role.c_str());
            } else {
                auto const type = m.attr("type").cast<std::string>();
                auto const id = m.attr("ref").cast<osmium::object_id_type>();
                auto const role = m.attr("role").cast<std::string>();
                rml_builder.add_member(osmium::char_to_item_type(type[0]), id, role.c_str());
            }
        }
    }

    osmium::Location get_location(py::object const &o) const
    {
        if (py::isinstance<osmium::Location>(o)) {
            return o.cast<osmium::Location>();
        }

        // default is a tuple with two doubles
        auto l = o.cast<py::tuple>();
        return osmium::Location{l[0].cast<double>(), l[1].cast<double>()};
    }

    void flush_buffer(bool force = false)
    {
        buffer.commit();

        if (force || buffer.committed() > buffer_size - BUFFER_WRAP) {
            osmium::memory::Buffer new_buffer(buffer_size, osmium::memory::Buffer::auto_grow::yes);
            using std::swap;
            swap(buffer, new_buffer);
            writer(std::move(new_buffer));
        }
    }

    osmium::io::Writer writer;
    osmium::memory::Buffer buffer;
    size_t buffer_size;
};

} // namespace

namespace pyosmium {

void init_simple_writer(pybind11::module &m)
{
    py::class_<SimpleWriter, BaseHandler>(m, "SimpleWriter")
        .def(py::init<const char*, unsigned long, osmium::io::Header const *, bool, const std::string&>(),
             py::arg("filename"), py::arg("bufsz") = 4096*1024,
             py::arg("header") = nullptr,
             py::arg("overwrite") = false,
             py::arg("filetype") = "")
        .def(py::init<>([] (std::filesystem::path const &file, unsigned long bufsz,
                            osmium::io::Header const *header, bool overwrite) {
                 return new SimpleWriter(file.string().c_str(), bufsz, header, overwrite, "");
             }),
             py::arg("filename"), py::arg("bufsz") = 4096*1024,
             py::arg("header") = nullptr,
             py::arg("overwrite") = false)
        .def(py::init<osmium::io::File, unsigned long, osmium::io::Header const *, bool>(),
             py::arg("filename"), py::arg("bufsz") = 4096*1024,
             py::arg("header") = nullptr,
             py::arg("overwrite") = false)
        .def("add_node", &SimpleWriter::add_node, py::arg("node"))
        .def("add_way", &SimpleWriter::add_way, py::arg("way"))
        .def("add_relation", &SimpleWriter::add_relation, py::arg("relation"))
        .def("add", [](SimpleWriter &self, py::object const &o) {
                           if (py::isinstance<pyosmium::COSMNode>(o) || py::hasattr(o, "location")) {
                               self.add_node(o);
                           } else if (py::isinstance<pyosmium::COSMWay>(o) || py::hasattr(o, "nodes")) {
                               self.add_way(o);
                           } else if (py::isinstance<pyosmium::COSMRelation>(o) || py::hasattr(o, "members")) {
                               self.add_relation(o);
                           } else {
                               throw py::type_error("Need node, way or relation object.");
                           }
                    })
        .def("close", &SimpleWriter::close)
        .def("__enter__", [](py::object const &self) { return self; })
        .def("__exit__", [](SimpleWriter &self, py::args args) { self.close(); })
    ;
}

} // namespace