Skip to content

Commit

Permalink
Merge pull request #818 from GIScience/reportremoval
Browse files Browse the repository at this point in the history
remove report endpoint
  • Loading branch information
mmerdes authored Sep 3, 2024
2 parents 487ef59 + 196662c commit c442365
Show file tree
Hide file tree
Showing 57 changed files with 32 additions and 1,395 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## Current Main

### Breaking Changes

- report endpoint: has been deleted ([#818])

[#818]: https://github.com/GIScience/ohsome-quality-api/pull/818

## Release 1.4.0

Expand Down
64 changes: 2 additions & 62 deletions ohsome_quality_api/api/api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import json
import logging
import os
from typing import Annotated, Any, Union
from typing import Any, Union

from fastapi import FastAPI, HTTPException, Path, Request, status
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
Expand All @@ -28,7 +28,6 @@
AttributeCompletenessRequest,
IndicatorDataRequest,
IndicatorRequest,
ReportRequest,
)
from ohsome_quality_api.api.response_models import (
AttributeMetadataResponse,
Expand All @@ -39,7 +38,6 @@
MetadataResponse,
ProjectMetadataResponse,
QualityDimensionMetadataResponse,
ReportMetadataResponse,
TopicMetadataResponse,
)
from ohsome_quality_api.attributes.definitions import get_attributes, load_attributes
Expand All @@ -64,10 +62,6 @@
get_quality_dimension,
get_quality_dimensions,
)
from ohsome_quality_api.reports.definitions import (
ReportEnum,
get_report_metadata,
)
from ohsome_quality_api.topics.definitions import (
TopicEnum,
get_topic_preset,
Expand Down Expand Up @@ -354,27 +348,6 @@ async def _post_indicator(
)


@app.post("/reports/{key}", include_in_schema=False)
async def post_report(
key: Annotated[
ReportEnum,
Path(
title="Report Key",
example="building-report",
),
],
parameters: ReportRequest,
) -> CustomJSONResponse:
geojson_object = await oqt.create_report(parameters, key=key.value)
response = empty_api_response()
response["attribution"]["text"] = get_class_from_key(
class_type="report",
key=key.value,
).attribution()
response.update(geojson_object)
return CustomJSONResponse(content=response, media_type=MEDIA_TYPE_GEOJSON)


@app.get("/metadata", tags=["metadata"], response_model=MetadataResponse)
async def metadata(project: ProjectEnum = DEFAULT_PROJECT) -> Any:
"""All metadata."""
Expand All @@ -386,7 +359,6 @@ async def metadata(project: ProjectEnum = DEFAULT_PROJECT) -> Any:
"quality_dimensions": get_quality_dimensions(),
"projects": get_project_metadata(),
"indicators": get_indicator_metadata(project=project),
# "reports": get_report_metadata(project=project),
"attributes": get_attributes(),
}
}
Expand Down Expand Up @@ -493,35 +465,3 @@ async def metadata_indicators_coverage(
) -> Any:
"""Get coverage geometry of an indicator by key."""
return await get_coverage(key.value, inverse)


@app.get(
"/metadata/reports",
tags=["metadata"],
response_model_exclude={
"result": {k.value: {"label_description": True} for k in ReportEnum}
},
include_in_schema=False,
)
async def metadata_reports(
project: ProjectEnum = DEFAULT_PROJECT,
) -> ReportMetadataResponse:
"""Get metadata of all indicators."""
if project == ProjectEnum.all:
project = None
return ReportMetadataResponse(result=get_report_metadata(project=project))


@app.get(
"/metadata/reports/{key}",
tags=["metadata"],
response_model_exclude={
"result": {k.value: {"label_description": True} for k in ReportEnum}
},
include_in_schema=False,
)
async def metadata_reports_by_key(key: ReportEnum) -> ReportMetadataResponse:
"""Get metadata of an indicator by key."""
return ReportMetadataResponse(
result={key.value: get_metadata("reports", hyphen_to_camel(key.value))}
)
5 changes: 0 additions & 5 deletions ohsome_quality_api/api/request_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,3 @@ class IndicatorDataRequest(BaseBpolys):
topic: TopicData = Field(..., title="Topic", alias="topic")
include_figure: bool = True
include_data: bool = False


class ReportRequest(BaseBpolys):
pass
# include_data: bool = False
14 changes: 0 additions & 14 deletions ohsome_quality_api/api/response_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
from ohsome_quality_api.projects.models import Project
from ohsome_quality_api.quality_dimensions.definitions import QualityDimensionEnum
from ohsome_quality_api.quality_dimensions.models import QualityDimension
from ohsome_quality_api.reports.definitions import ReportEnum
from ohsome_quality_api.reports.models import ReportMetadata
from ohsome_quality_api.topics.definitions import TopicEnum
from ohsome_quality_api.utils.helper import snake_to_lower_camel

Expand Down Expand Up @@ -123,18 +121,6 @@ class IndicatorMetadataCoverageResponse(
model_config = ConfigDict(title="Indicator Coverage", extra="allow")


class ReportMetadataResponse(BaseResponse):
result: dict[str, ReportMetadata]

@field_validator("result")
@classmethod
def check_report_dict(cls, value):
assert len(value) > 0
for key in value.keys():
ReportEnum(key)
return value


class Metadata(BaseConfig):
indicators: dict[str, IndicatorMetadata]
topics: dict[str, TopicMetadata]
Expand Down
28 changes: 12 additions & 16 deletions ohsome_quality_api/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import yaml

from ohsome_quality_api.indicators.models import IndicatorMetadata
from ohsome_quality_api.reports.models import ReportMetadata
from ohsome_quality_api.topics.definitions import load_topic_presets
from ohsome_quality_api.utils.helper import (
camel_to_hyphen,
Expand Down Expand Up @@ -51,19 +50,19 @@ class Color(Enum):


def load_metadata(
module_name: Literal["indicators", "reports"],
) -> dict[str, IndicatorMetadata | ReportMetadata]:
"""Read metadata of all indicators or reports from YAML files.
module_name: Literal["indicators"],
) -> dict[str, IndicatorMetadata]:
"""Read metadata of all indicators from YAML files.
Those text files are located in the directory of each indicator/report.
Those text files are located in the directory of each indicator.
Args:
module_name: Either indicators or reports.
module_name: indicators.
Returns:
A Dict with the class names of the indicators/reports
A Dict with the class names of the indicators
as keys and metadata as values.
"""
assert module_name == "indicators" or module_name == "reports"
assert module_name == "indicators"
directory = get_module_dir("ohsome_quality_api.{}".format(module_name))
files = glob.glob(directory + "/**/metadata.yaml", recursive=True)
raw = {}
Expand All @@ -75,22 +74,19 @@ def load_metadata(
case "indicators":
for k, v in raw.items():
metadata[k] = IndicatorMetadata(**v)
case "reports":
for k, v in raw.items():
metadata[k] = ReportMetadata(**v)
return metadata


def get_metadata(
module_name: Literal["indicators", "reports"], class_name: str
) -> IndicatorMetadata | ReportMetadata:
"""Get metadata of an indicator or report based on its class name.
module_name: Literal["indicators"], class_name: str
) -> IndicatorMetadata:
"""Get metadata of an indicator based on its class name.
This is implemented outside the metadata class to be able to access metadata of all
indicators/reports without instantiating of those.
indicators without instantiating of those.
Args:
module_name: Either indicators or reports.
module_name: indicators.
class_name: Class name of an indicator (camel case).
"""
metadata = load_metadata(module_name)
Expand Down
49 changes: 1 addition & 48 deletions ohsome_quality_api/oqt.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
"""Controller for computing Indicators and Reports."""
"""Controller for computing Indicators."""

import logging
from typing import Coroutine

from geojson import Feature, FeatureCollection

from ohsome_quality_api.api.request_models import (
ReportRequest,
)
from ohsome_quality_api.indicators.base import BaseIndicator as Indicator
from ohsome_quality_api.reports.base import BaseReport as Report
from ohsome_quality_api.topics.definitions import get_topic_preset
from ohsome_quality_api.topics.models import BaseTopic as Topic
from ohsome_quality_api.topics.models import TopicData, TopicDefinition
from ohsome_quality_api.utils.helper import get_class_from_key
Expand Down Expand Up @@ -50,22 +45,6 @@ async def create_indicator(
return await gather_with_semaphore(tasks)


async def create_report(parameters: ReportRequest, key: str) -> FeatureCollection:
"""Create report(s) for features of a GeoJSON FeatureCollection."""
bpolys = parameters.bpolys
features = []
for i, feature in enumerate(bpolys.features):
if "id" not in feature.keys():
feature["id"] = i
validate_area(feature)
# Reports for a FeatureCollection are not created asynchronously (as it is
# the case with indicators), because indicators of a report are created
# asynchronously
report = await _create_report(key, feature)
features.append(report.as_feature())
return FeatureCollection(features=features)


async def _create_indicator(
key: str,
feature: Feature,
Expand Down Expand Up @@ -97,29 +76,3 @@ async def _create_indicator(
indicator.result.figure = None

return indicator


async def _create_report(key: str, feature: Feature) -> Report:
"""Create a Report.
Aggregates all indicator results and calculates an overall quality score.
Indicators for a Report are created asynchronously utilizing semaphores.
"""

logging.info("Creating Report...")
logging.info("Report key: {0:4}".format(key))
logging.info("Feature id: {0:4}".format(feature.get("id", "None")))

report_class = get_class_from_key(class_type="report", key=key)
report = report_class(feature=feature)

tasks: list[Coroutine] = []
for indicator_key, topic_key in report.indicator_topic:
topic = get_topic_preset(topic_key)
tasks.append(_create_indicator(indicator_key, feature, topic))

report.indicators = await gather_with_semaphore(tasks)
report.combine_indicators()

return report
Empty file.
Loading

0 comments on commit c442365

Please sign in to comment.