-
-
Notifications
You must be signed in to change notification settings - Fork 57
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Endpoint to conflate the submission with osm data #1594
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
479c4b6
feat: endpoint to conflate the submission with osm data
Sujanadh 29a342c
refactor: use postgresclient to get osm features using task geom
Sujanadh ffc9a32
Merge branch 'development' of github.com:hotosm/fmtm into feat/data-cβ¦
Sujanadh 4c7c55e
fix: update wrap_check_access to bypass check for public project
Sujanadh c4b73f5
refactor: remove filename from extra params when requesting data extrβ¦
Sujanadh 1aceae4
refactor: return DbUser and DbProject dict even if ProjectVisibility.β¦
spwoodcock File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,6 +21,7 @@ | |
import logging | ||
from asyncio import gather | ||
from datetime import datetime, timezone | ||
from io import BytesIO | ||
from random import getrandbits | ||
from typing import Optional, Union | ||
|
||
|
@@ -32,15 +33,20 @@ | |
from geoalchemy2.shape import from_shape, to_shape | ||
from geojson_pydantic import Feature, MultiPolygon, Polygon | ||
from geojson_pydantic import FeatureCollection as FeatCol | ||
from osm_fieldwork.data_models import data_models_path | ||
from osm_rawdata.postgres import PostgresClient | ||
from shapely.geometry import mapping, shape | ||
from shapely.geometry.base import BaseGeometry | ||
from shapely.ops import unary_union | ||
from sqlalchemy import text | ||
from sqlalchemy.exc import ProgrammingError | ||
from sqlalchemy.orm import Session | ||
|
||
from app.config import settings | ||
from app.models.enums import XLSFormType | ||
|
||
log = logging.getLogger(__name__) | ||
API_URL = settings.RAW_DATA_API_URL | ||
|
||
|
||
def timestamp(): | ||
|
@@ -785,3 +791,119 @@ def parse_featcol(features: Union[Feature, FeatCol, MultiPolygon, Polygon]): | |
elif isinstance(features, Feature): | ||
feat_col = geojson.FeatureCollection([feat_col]) | ||
return feat_col | ||
|
||
|
||
def get_osm_geometries(form_category, geometry): | ||
"""Request a snapshot based on the provided geometry. | ||
|
||
Args: | ||
form_category(str): feature category type (eg: buildings). | ||
geometry (str): The geometry data in JSON format. | ||
|
||
Returns: | ||
dict: The JSON response containing the snapshot data. | ||
""" | ||
config_filename = XLSFormType(form_category).name | ||
data_model = f"{data_models_path}/{config_filename}.yaml" | ||
|
||
with open(data_model, "rb") as data_model_yaml: | ||
extract_config = BytesIO(data_model_yaml.read()) | ||
|
||
pg = PostgresClient( | ||
"underpass", | ||
extract_config, | ||
auth_token=settings.RAW_DATA_API_AUTH_TOKEN | ||
if settings.RAW_DATA_API_AUTH_TOKEN | ||
else None, | ||
) | ||
return pg.execQuery( | ||
geometry, | ||
extra_params={ | ||
"outputType": "geojson", | ||
"bind_zip": True, | ||
"useStWithin": False, | ||
}, | ||
) | ||
|
||
|
||
def geometries_almost_equal( | ||
geom1: BaseGeometry, geom2: BaseGeometry, tolerance: float = 1e-6 | ||
) -> bool: | ||
"""Determine if two geometries are almost equal within a tolerance. | ||
|
||
Args: | ||
geom1 (BaseGeometry): First geometry. | ||
geom2 (BaseGeometry): Second geometry. | ||
tolerance (float): Tolerance level for almost equality. | ||
|
||
Returns: | ||
bool: True if geometries are almost equal else False. | ||
""" | ||
return geom1.equals_exact(geom2, tolerance) | ||
|
||
|
||
def check_partial_overlap(geom1: BaseGeometry, geom2: BaseGeometry) -> bool: | ||
"""Determine if two geometries have a partial overlap. | ||
|
||
Args: | ||
geom1 (BaseGeometry): First geometry. | ||
geom2 (BaseGeometry): Second geometry. | ||
|
||
Returns: | ||
bool: True if geometries have a partial overlap, else False. | ||
""" | ||
intersection = geom1.intersection(geom2) | ||
return not intersection.is_empty and ( | ||
0 < intersection.area < geom1.area and 0 < intersection.area < geom2.area | ||
) | ||
|
||
|
||
def conflate_features( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice! |
||
input_features: list, osm_features: list, remove_conflated=False, tolerance=1e-6 | ||
): | ||
"""Conflate input features with OSM features to identify overlaps. | ||
|
||
Args: | ||
input_features (list): A list of input features with geometries. | ||
osm_features (list): A list of OSM features with geometries. | ||
remove_conflated (bool): Flag to remove conflated features. | ||
tolerance (float): Tolerance level for almost equality. | ||
|
||
Returns: | ||
list: A list of features after conflation with OSM features. | ||
""" | ||
osm_geometries = [shape(feature["geometry"]) for feature in osm_features] | ||
return_features = [] | ||
|
||
for input_feature in input_features: | ||
input_geometry = shape(input_feature["geometry"]) | ||
is_duplicate = False | ||
is_partial_overlap = False | ||
|
||
for osm_feature, osm_geometry in zip( | ||
osm_features, osm_geometries, strict=False | ||
): | ||
if geometries_almost_equal(input_geometry, osm_geometry, tolerance): | ||
is_duplicate = True | ||
input_feature["properties"].update(osm_feature["properties"]) | ||
break | ||
|
||
if check_partial_overlap(input_geometry, osm_geometry): | ||
is_partial_overlap = True | ||
new_feature = { | ||
"type": "Feature", | ||
"geometry": mapping(osm_feature["geometry"]), | ||
"properties": osm_feature["properties"], | ||
} | ||
return_features.append(new_feature) | ||
break | ||
|
||
input_feature["properties"]["is_duplicate"] = is_duplicate | ||
input_feature["properties"]["is_partial_overlap"] = is_partial_overlap | ||
|
||
if (is_duplicate or is_partial_overlap) and remove_conflated is True: | ||
continue | ||
|
||
return_features.append(input_feature) | ||
|
||
return return_features |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe bind zip true and geojson are defaults on raw data api, but no harm being explicit π
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think its better to mention, as we won't know what are the default values.