Skip to content

Commit

Permalink
process input parameter with polygon
Browse files Browse the repository at this point in the history
  • Loading branch information
N-Clerkx committed Dec 18, 2023
1 parent 2f2fc95 commit 31635e4
Show file tree
Hide file tree
Showing 10 changed files with 112 additions and 29 deletions.
Empty file.
44 changes: 37 additions & 7 deletions App/functions/report-python-cloud-run/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from io import BytesIO
import json
import os

from shapely import Polygon # type: ignore
from shapely.geometry import shape # type: ignore
from flask import Flask, make_response, request
from flask import Flask, make_response, request, render_template
import urllib

from report.report import (
create_report_html,
Expand All @@ -16,12 +16,25 @@
app = Flask(__name__)


@app.route("/")
@app.route("/", methods=["GET"])
def return_report():
polygon_str = POLYGON_DEFAULT
geo: dict = json.loads(polygon_str)
polygon: Polygon = shape(geo)
web_page_content = create_report_html(polygon=polygon, stac_root=STAC_ROOT_DEFAULT)
"""Return a report for the given polygon"""
polygon_str = request.args.get("polygon")

if not polygon_str:
polygon_str = POLYGON_DEFAULT

origin = request.headers.get("Referer")
if not origin:
stac_root = STAC_ROOT_DEFAULT
else:
stac_root = origin + "/STAC/catalog.json"
# polygon_str = POLYGON_DEFAULT
polygon = shape(json.loads(polygon_str))
if not isinstance(polygon, Polygon):
raise ValueError("Invalid polygon")

web_page_content = create_report_html(polygon=polygon, stac_root=stac_root)
pdf_object = create_report_pdf(web_page_content)

response = make_response(pdf_object.getvalue())
Expand All @@ -30,5 +43,22 @@ def return_report():
return response


@app.route("/html")
def return_html():
"""Return a report for the given polygon"""
polygon_str = request.data.decode("utf-8")
if not polygon_str:
polygon_str = POLYGON_DEFAULT
# polygon_str = POLYGON_DEFAULT
geo = json.loads(polygon_str)
polygon = shape(geo)
if not isinstance(polygon, Polygon):
raise ValueError("Invalid polygon")

web_page_content = create_report_html(polygon=polygon, stac_root=STAC_ROOT_DEFAULT)

return render_template(web_page_content)


if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
12 changes: 5 additions & 7 deletions App/functions/report-python-cloud-run/report/datasets/esl.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import base64
from io import BytesIO, StringIO
import matplotlib

matplotlib.use("Agg")
from matplotlib import colors
from matplotlib import pyplot as plt

plt.rcParams["svg.fonttype"] = "none"
import numpy as np
import xarray as xr

import geopandas as gpd
import geopandas as gpd # type: ignore

from .utils import plot_to_base64
from .datasetcontent import DatasetContent


Expand Down Expand Up @@ -98,7 +99,4 @@ def create_esl_plot(xarr):
plt.colorbar(im1, cax=cax) # Similar to fig.colorbar(im, cax = cax)
cax.set_title("ESL in meters")
#
imgdata = BytesIO()
fig.savefig(imgdata, format="png")

return base64.b64encode(imgdata.getbuffer()).decode("ascii")
return plot_to_base64(fig)
19 changes: 19 additions & 0 deletions App/functions/report-python-cloud-run/report/datasets/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import base64
from io import BytesIO
from matplotlib import pyplot as plt


def plot_to_base64(fig: plt.Figure) -> str:
"""Convert a matplotlib figure to base64"""
img = BytesIO()
fig.savefig(img, format="png", bbox_inches="tight")

return base64.b64encode(img.getbuffer()).decode("ascii")


def plot_to_svg(fig: plt.Figure) -> str:
"""Convert a matplotlib figure to svg"""
img = BytesIO()
fig.savefig(img, format="svg", bbox_inches="tight")

return img.getvalue().decode("ascii")
23 changes: 8 additions & 15 deletions App/functions/report-python-cloud-run/report/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,27 @@
STAC_ROOT_DEFAULT = "https://raw.githubusercontent.com/openearth/global-coastal-atlas/subsidence_etienne/STAC/data/current/catalog.json"


@dataclass
class WebPageContent:
html: str
css: str


@dataclass
class ReportContent:
datasets: list[DatasetContent]


def create_report_html(polygon: Polygon, stac_root: str) -> WebPageContent:
def create_report_html(polygon: Polygon, stac_root: str) -> str:
htmlpath = Path(__file__).parent / Path("template.html.jinja")
csspath = Path(__file__).parent / Path("template.css")

with htmlpath.open() as f:
template = jinja2.Template(f.read())

data = generate_report_content(polygon=polygon, stac_root=stac_root)
html = template.render(data=data)
css: str = csspath.read_bytes().decode()
html = template.render(data=data, css=css)

return WebPageContent(html=html, css=css)
return html


def create_report_pdf(page_content: WebPageContent) -> BytesIO:
story = fitz.Story(html=page_content.html, user_css=page_content.css)
def create_report_pdf(page_content: str) -> BytesIO:
story = fitz.Story(html=page_content)

MEDIABOX = fitz.paper_rect("A4") # output page format: Letter
WHERE = MEDIABOX + (36, 36, -36, -36) # leave borders of 0.5 inches
Expand Down Expand Up @@ -87,8 +81,7 @@ def generate_report_content(polygon: Polygon, stac_root: str) -> ReportContent:
[2.3915028831735015, 51.7360381463356],
]
)

pdf = create_report_pdf(
create_report_html(polygon=polygon, stac_root=STAC_ROOT_DEFAULT)
)
html = create_report_html(polygon=polygon, stac_root=STAC_ROOT_DEFAULT)
print(html)
pdf = create_report_pdf(html)
print(pdf.getvalue())
5 changes: 5 additions & 0 deletions App/functions/report-python-cloud-run/report/template.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
html,
body {
margin: 0;
padding: 0;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
<style>
{{ css }}
</style>

<h1>Coastal report</h1>
<p>In this report some coastal characteristics of the selected area are explained.</p>

Expand Down
Empty file.
34 changes: 34 additions & 0 deletions App/functions/report-python-cloud-run/tests/main_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os
import pytest

import main # type: ignore


@pytest.fixture
def client():
main.app.testing = True
return main.app.test_client()


# def test_handler_no_env_variable(client):
# r = client.get("/")

# assert r.data.decode() == "Hello World!"
# assert r.status_code == 200


def test_main_handler(client):
r = client.get(
"/?polygon=%7B%22coordinates%22%3A%5B%5B%5B4.4548747899694945%2C53.1816853031429%5D%2C%5B4.156603653116093%2C52.553604613949375%5D%2C%5B3.2409806283587557%2C51.753524628396576%5D%2C%5B3.442140232282071%2C51.404367273499105%5D%2C%5B4.343890180908346%2C51.274368422568756%5D%2C%5B4.732336312623886%2C52.09148048735997%5D%2C%5B5.197084363068569%2C52.86878161448763%5D%2C%5B5.238703591466617%2C53.11095934419029%5D%2C%5B4.4548747899694945%2C53.1816853031429%5D%5D%5D%2C%22type%22%3A%22Polygon%22%7D"
)

# assert r.data.decode() == "Hello World!"
assert r.status_code == 200


# def test_handler_with_env_variable(client):
# os.environ["NAME"] = "Foo"
# r = client.get("/")

# assert r.data.decode() == "Hello Foo!"
# assert r.status_code == 200
Empty file.

0 comments on commit 31635e4

Please sign in to comment.