From 2233e8b865352032563a36eddc57b87d24984cb7 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 10 Sep 2024 09:12:52 +0100 Subject: [PATCH] Add mangrove_data route to backend --- backend/app.py | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/backend/app.py b/backend/app.py index c56b9b4..4faf5d1 100644 --- a/backend/app.py +++ b/backend/app.py @@ -1,6 +1,7 @@ from flask import Flask, g, jsonify, request, json, Response, send_from_directory, abort from flask_cors import CORS import orjson, os +import pandas as pd import datetime import time @@ -47,7 +48,7 @@ def business_growth(): # Parse args from request latest_date = request.args.get("latest_date") - country_names = request.args.get("countries") # change this line + country_names = request.args.get("countries") cumulative_period_type = request.args.get("cumulative_period_type") # Open json locally @@ -160,6 +161,32 @@ def get_json(filename): return jsonify(sorted_data) +@app.route("/mangrove_data/", methods=["GET"]) +def mangrove_data(method): + + with open("../data/dev/final__wdpa_pid_mangrove_diff_stats.json", "rb") as f: + data = orjson.loads(f.read()) + + if method == "countries": + df = pd.read_json(json.dumps(data)) + countries = df[["year", "country", "n_pixels", "diff", "cumulative_diff"]] + countriesAgg = countries.groupby(["year", "country"]).agg( + {"n_pixels": "sum", "diff": "sum", "cumulative_diff": "sum"} + ) + countriesAgg["year0_pixels"] = ( + countriesAgg["n_pixels"] - countriesAgg["cumulative_diff"] + ) + countriesAgg["pct_diff"] = ( + 100 + * (countriesAgg["n_pixels"] - countriesAgg["year0_pixels"]) + / countriesAgg["year0_pixels"] + ).round(2) + countriesLatest = countriesAgg.loc[[2020]].reset_index().set_index("country") + return Response( + countriesLatest.to_json(orient="index"), mimetype="application/json" + ) + + @app.route("/download/", methods=["GET"]) def download_file(filename): try: @@ -168,5 +195,16 @@ def download_file(filename): abort(404) +@app.route("/cog", methods=["GET"]) +def serve_cog(): + year = request.args.get("year") + pid = request.args.get("pid") # change this line + dir = f"{FILES_DIRECTORY}/cog/{year}/" + try: + return send_from_directory(dir, f"{pid}.tif", as_attachment=True) + except FileNotFoundError: + abort(404) + + if __name__ == "__main__": app.run()