From 8fbfd4be897873294ffa71c51cd1b5efe3da230f Mon Sep 17 00:00:00 2001 From: Guille Date: Mon, 10 Jun 2024 06:31:49 +0200 Subject: [PATCH] implement idf generator --- hub_api/config.py | 67 ------------------- hub_api/energy_plus/idf_generator.py | 39 ++++++++++- hub_api/energy_plus/tmp/.gitignore | 2 + hub_api/helpers/session_helper.py | 8 ++- .../workflow/insel_montly_energy_balance.py | 4 +- 5 files changed, 49 insertions(+), 71 deletions(-) create mode 100644 hub_api/energy_plus/tmp/.gitignore diff --git a/hub_api/config.py b/hub_api/config.py index 3cb6a00..e69de29 100644 --- a/hub_api/config.py +++ b/hub_api/config.py @@ -1,67 +0,0 @@ -""" -Config -SPDX - License - Identifier: LGPL - 3.0 - or -later -Copyright © 2023 Project Peter Yefi peteryefi@gmail.com -""" -import distutils -import os -import platform -from pathlib import Path - -import hub.helpers.dictionaries -from hub.persistence.db_control import DBControl -from hub.persistence.repository import Repository -from hub.catalog_factories.energy_systems_catalog_factory import EnergySystemsCatalogFactory - - -class Config: - - def __init__(self): - dotenv_path = "{}/.local/etc/hub_api/.env".format(os.path.expanduser('~')) - if platform.system() == 'Linux': - dotenv_path = Path(dotenv_path).resolve() - - environment = 'PROD' - database_name = 'montreal_retrofit' - self._database = DBControl(db_name=database_name, app_env=environment, dotenv_path=dotenv_path) - self._repository = Repository(db_name=database_name, app_env=environment, dotenv_path=dotenv_path) - self._energy_systems_catalog = EnergySystemsCatalogFactory('montreal_custom').catalog - self._dictionaries = { - 'pluto': hub.helpers.dictionaries.Dictionaries().pluto_function_to_hub_function, - 'htf': hub.helpers.dictionaries.Dictionaries().hft_function_to_hub_function, - 'montreal': hub.helpers.dictionaries.Dictionaries().montreal_function_to_hub_function, - 'alkis': hub.helpers.dictionaries.Dictionaries().alkis_function_to_hub_function, - 'eilat': hub.helpers.dictionaries.Dictionaries().eilat_function_to_hub_function - } - - @property - def database(self): - return self._database - - @property - def repository(self): - return self._repository - - @property - def energy_systems_catalog(self): - return self._energy_systems_catalog - - @staticmethod - def max_file_size(): - return 10 * 1024 * 1024 # 10 MB - - @property - def function_dictionary(self, dictionary): - return self._dictionaries[dictionary] - - @property - def insel(self): - return distutils.spawn.find_executable('insel') - - @property - def sra(self): - return distutils.spawn.find_executable('sra') - - @property - def base_uri(self): - return self._base_uri diff --git a/hub_api/energy_plus/idf_generator.py b/hub_api/energy_plus/idf_generator.py index 182fcf1..dc89a68 100644 --- a/hub_api/energy_plus/idf_generator.py +++ b/hub_api/energy_plus/idf_generator.py @@ -1,14 +1,51 @@ +import json +import os +from pathlib import Path + +from flask import request, Response, make_response, send_file from flask_restful import Resource +from hub.city_model_structure.city import City +from hub.exports.energy_building_exports_factory import EnergyBuildingsExportsFactory +from hub.version import __version__ as version from hub_api.config import Config +from hub_api.helpers.session_helper import refresh_session, session class IdfGenerator(Resource, Config): def __init__(self): + self._tmp_path = (Path(__file__).parent / 'tmp').resolve() super().__init__() def post(self): """ API call generate the IDF file for the input data """ - raise NotImplementedError() + session_id = request.headers.get('session-id', None) + token = request.headers.get('token', None) + application_uuid = request.headers.get('application-uuid', None) + _session = refresh_session(session_id, token, application_uuid) + if _session is None: + return Response(json.dumps({'error': 'unauthorized'}), status=403) + else: + token = _session['token'] + application_id = session(session_id)['application_id'] + user_id = session(session_id)['user_id'] + tmp_path = (self._tmp_path / token).resolve() + try: + os.mkdir(tmp_path) + except FileExistsError: + pass + payload = request.get_json() + for key, value in payload.items(): + db_city = self.database.get_city(self.database.building(value, user_id, application_id, key).city_id) + if version != db_city.hub_release: + return Response(json.dumps({ + 'error': 'The selected building belongs to an old hub release and cannot be loaded.' + }), status=422) + idf_file = tmp_path/db_city.name + city = City.load_compressed(db_city.pickle_path, idf_file) + EnergyBuildingsExportsFactory('idf', city, tmp_path, target_buildings=[value]).export() + response = make_response(send_file(idf_file)) + response.headers['token'] = token + return response diff --git a/hub_api/energy_plus/tmp/.gitignore b/hub_api/energy_plus/tmp/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/hub_api/energy_plus/tmp/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/hub_api/helpers/session_helper.py b/hub_api/helpers/session_helper.py index 7424a8a..48c8030 100644 --- a/hub_api/helpers/session_helper.py +++ b/hub_api/helpers/session_helper.py @@ -8,6 +8,7 @@ import shutil import time import uuid from copy import deepcopy +from glob import glob from pathlib import Path sessions = {} @@ -32,8 +33,13 @@ def expired_sessions_collector(session_timeout_duration): if _expire < datetime.datetime.now(): print("session for user: ", _sessions[session_uuid]['user'], "expired.") response_path = (Path(__file__).parent.parent / f'response_files/{session_uuid}').resolve() - shutil.rmtree(response_path) + if response_path.exists(): + shutil.rmtree(response_path) del sessions[session_uuid] + existing_directories = glob(f'{Path(__file__).parent.parent.resolve()}/response_files/*') + for directory in existing_directories: + if directory not in _sessions.keys(): + shutil.rmtree(directory) time.sleep(60 * int(session_timeout_duration)) diff --git a/hub_api/workflow/insel_montly_energy_balance.py b/hub_api/workflow/insel_montly_energy_balance.py index efe0c6b..8f20030 100644 --- a/hub_api/workflow/insel_montly_energy_balance.py +++ b/hub_api/workflow/insel_montly_energy_balance.py @@ -49,10 +49,10 @@ class InselMonthlyEnergyBalance(Resource, Config): def _citygml(self, file_path): # try: year_of_construction_field = request.form.get('year_of_construction_field') - if year_of_construction_field is '': + if year_of_construction_field == '': year_of_construction_field = None function_field = request.form.get('function_field') - if function_field is '': + if function_field == '': function_field = None function_dictionary = self._dictionaries[request.form.get('function_to_hub')] return GeometryFactory('citygml',