Skip to main content

Library for reading OSM XML/GZ/BZ2/PBF files

Project description

osmiter

A simple library for parsing OSM data. Supports simple OSM XML files as well as OSM GZ, OSM BZ2 and OSM PBF.

Please be aware that osmiter uses Google's protobuf library, written in pure Python, which isn't particularly fast.

Example Usage

import osmiter

shop_count = 0

for feature in osmiter.iter_from_osm("some_osm_file.osm"):
    if feature["type"] == "node" and "shop" in feature["tag"]:
        shop_count += 1

print(f"this osm file containes {shop_count} shop nodes")

What is osmiter generating?

For each feature (node/way/relation) it yields a dict containing element attributes (like id, lat or timestamp) and 2 additional items: key "type" holding "node"/"way"/"relation" and key "tag" holding a dict with feature tags (this dict may be empty).

Additionally nodes will contain keys "lat" and "lon" with node coordinates, ways will contain key "nd" with a list of all node_ids references by this way, and relations contain a key "member" with a list of dicts of each member's attributes.

Almost all attributes are returned as strings with the exception for:

  • id, ref, version, changeset, uid and changeset_count → int
  • lat, lon → float
  • open and visible → bool
  • timestampaware datetime.datetime item.

Data validation

osmiter preforms almost no data validation, so it is possible to recieve ways with no nodes, relations with no members, empty tag values, invalid coordinates, references to non-existing items, or duplicate ids※.

However, several data assumptions are made:

  1. Each feature has an id attribute.
    (※) For OSM PBF files, if an object is missing an id -1 will be assigned, per the osmformat.proto definition. This can result in multiple objects with an id equal to -1.
  2. Each node has to have both lat and lon defined.
  3. Every attribute defined in the table on attribute type conversion has to be convertible to its type.
    So, id == 0x1453, changeset_count == AAAAAA, ref == 12.433 or lat == 1.23E+10 will cause an exception;
    timestamp value has to be either ISO8601-compliant or epoch time represented by an integer.
  4. Boolean atributes are only considered truthy if they're set to true (case-insensitive). Values 1, on, yes, TRUE will all evaluate to False.

Minimum requirements for each element

Bare-minimum node:

{
    "id": int,
    "type": "node",
    "lat": float,
    "lon": float,
    "tag": Dict[str, str], # May be empty
}

Bare-minimum way:

{
    "id": int,
    "type": "way",
    "tag": Dict[str, str], # May be empty
    "nd": List[int],
}

Bare-minimum relation:

{
    "id": int,
    "type": "relation",
    "tag": Dict[str, str], # May be empty
    "member": List[ dict ]
}

Example elements

See the corresponding OSM XML examples.

{
    "type": "node",
    "tag": {}
    "id": 298887269,
    "lat": 54.0901746,
    "lon": 12.2482632,
    "user": "SvenHRO",
    "uid": 46882,
    "visible": True,
    "version": 1,
    "changeset": 676636,
    "timestamp": datetime.datetime(2008, 9, 21, 21, 37, 45, tzinfo=datetime.timezone.utc)
}
{
    "type": "node",
    "tag": {"name": "Neu Broderstorf", "traffic_sign": "city_limit"},
    "id": 1831881213,
    "version": 1,
    "changeset": 12370172,
    "lat": 54.0900666,
    "lon": 12.2539381,
    "user": "lafkor",
    "uid": 75625,
    "visible": True,
    "timestamp": datetime.datetime(2012, 7, 20, 9, 43, 19, tzinfo=datetime.timezone.utc),
}
{
    "type": "way",
    "tag": {"highway": "unclassified", "name": "Pastower Straße"},
    "id": 26659127,
    "user": "Masch",
    "uid": 55988,
    "visible": True,
    "version": 5,
    "changeset": 4142606,
    "timestamp": datetime.datetime(2010, 3, 16, 11, 47, 8, tzinfo=datetime.timezone.utc),
    "nd": [292403538, 298884289, 261728686]
}
{
    "type": "relation",
    "tag": {
        "name": "Küstenbus Linie 123",
        "network": "VVW",
        "operator": "Regionalverkehr Küste",
        "ref": "123",
        "route": "bus",
        "type": "route"
    },
    "id": 56688,
    "user": "kmvar",
    "uid": 56190,
    "visible": True,
    "version": 28,
    "changeset": 6947637,
    "timestamp": datetime.datetime(2011, 1, 12, 14, 23, 49, tzinfo=datetime.timezone.utc),
    "member": [
        {"type": "node", "ref": 294942404, "role": ""},
        {"type": "node", "ref": 364933006, "role": ""},
        {"type": "way", "ref": 4579143, "role": ""},
        {"type": "node", "ref": 249673494, "role": ""},
    ]
}

Reference


osmiter.iter_from_osm

iter_from_osm(  
    source: Union[str, bytes, os.PathLike, int, IO[bytes]],  
    file_format: Union[str, NoneType] = None,  
    filter_attrs: Union[Iterable[str], NoneType] = None) -> Iterator[dict]

Yields all items from provided source file.

If source is a str/bytes/os.PathLike (path) the format will be guess based on file extension. Otherwise, if source is an int (file descriptior) or a file-like object, the file_format argument must be provided.

File-like sources have to be opened in binary mode. Format has to be one of "xml", "gz", "bz2", "pbf".

osmiter spends most of its time parsing element attributes. If only specific attributes are going to be used, pass an Iterable (most prefereably a set) with wanted attributes to filter_attrs.

No matter what attributes you define in filter_attrs, some attributes are always parsed:

  • "id", "lat" and "lon": for nodes
  • "id": for ways and relations
  • "type", "ref" and "role": for members

filter_attrs is ignored for pbf files.


osmiter.iter_from_xml_buffer

iter_from_xml_buffer(
    buff: IO[bytes],
    filter_attrs: Union[Iterable[str], NoneType] = None) -> Iterator[dict]

Yields all items inside a given OSM XML buffer. filter_attrs is explained in osmiter.iter_from_osm documentation.


osmiter.iter_from_pbf_buffer

iter_from_pbf_buffer(buff: IO[bytes]) -> Iterator[dict]

Yields all items inside a given OSM PBF buffer.


osmiter.parser_xml.iter_from_xml_buffer

Same as osmiter.iter_from_xml_buffer.


osmiter.parser_xml.OSMError

An exception (inheriting from RuntimeException) used to represent issues with XML data.


osmiter.iter_from_pbf_buffer

iter_from_pbf_buffer(buff: BinaryIO) -> Iterator[dict]

Yields all items inside a given OSM PBF file.


osmiter.parser_pbf.iter_from_pbf_buffer

Same as osmiter.iter_from_pbf_buffer.


osmiter.parser_pbf.ParserPbf

Internal object used to parse PBF files. Don't use.


osmiter.parser_pbf.PBFError

An Exception (inheriting from RuntimeException) used to represent issues with OSM PBF files.


License

osmiter is provided under the MIT license, included in the license.md file.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

osmiter-1.3.1.tar.gz (16.6 kB view details)

Uploaded Source

Built Distribution

osmiter-1.3.1-py3-none-any.whl (17.6 kB view details)

Uploaded Python 3

File details

Details for the file osmiter-1.3.1.tar.gz.

File metadata

  • Download URL: osmiter-1.3.1.tar.gz
  • Upload date:
  • Size: 16.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.7

File hashes

Hashes for osmiter-1.3.1.tar.gz
Algorithm Hash digest
SHA256 96bf468b79a11926d5fa56e4b2543f104765cbe366221d1903e8d5ef9c91accc
MD5 ae2024861dc2f1f96ce794e4e5ae0c91
BLAKE2b-256 90fe9ff251765d6bdb979f645079d166f8741f0165b4b01e44303c618b1773f2

See more details on using hashes here.

File details

Details for the file osmiter-1.3.1-py3-none-any.whl.

File metadata

  • Download URL: osmiter-1.3.1-py3-none-any.whl
  • Upload date:
  • Size: 17.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.7

File hashes

Hashes for osmiter-1.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bbd26ed1532df84c407521a8589cd7f640a2c93b4b6390dd22cd3252f83eb08b
MD5 e549d8b1385c2651deb02a266ee198a9
BLAKE2b-256 127d09ce36209de8412df23dffa2e0c6326f19dff9a38fde4cea7368e812bb19

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page