implement idf generator

This commit is contained in:
Guille Gutierrez 2024-06-10 06:31:49 +02:00
parent 3be3121922
commit 8fbfd4be89
5 changed files with 49 additions and 71 deletions

View File

@ -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

View File

@ -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 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.config import Config
from hub_api.helpers.session_helper import refresh_session, session
class IdfGenerator(Resource, Config): class IdfGenerator(Resource, Config):
def __init__(self): def __init__(self):
self._tmp_path = (Path(__file__).parent / 'tmp').resolve()
super().__init__() super().__init__()
def post(self): def post(self):
""" """
API call generate the IDF file for the input data 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

2
hub_api/energy_plus/tmp/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -8,6 +8,7 @@ import shutil
import time import time
import uuid import uuid
from copy import deepcopy from copy import deepcopy
from glob import glob
from pathlib import Path from pathlib import Path
sessions = {} sessions = {}
@ -32,8 +33,13 @@ def expired_sessions_collector(session_timeout_duration):
if _expire < datetime.datetime.now(): if _expire < datetime.datetime.now():
print("session for user: ", _sessions[session_uuid]['user'], "expired.") print("session for user: ", _sessions[session_uuid]['user'], "expired.")
response_path = (Path(__file__).parent.parent / f'response_files/{session_uuid}').resolve() 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] 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)) time.sleep(60 * int(session_timeout_duration))

View File

@ -49,10 +49,10 @@ class InselMonthlyEnergyBalance(Resource, Config):
def _citygml(self, file_path): def _citygml(self, file_path):
# try: # try:
year_of_construction_field = request.form.get('year_of_construction_field') 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 year_of_construction_field = None
function_field = request.form.get('function_field') function_field = request.form.get('function_field')
if function_field is '': if function_field == '':
function_field = None function_field = None
function_dictionary = self._dictionaries[request.form.get('function_to_hub')] function_dictionary = self._dictionaries[request.form.get('function_to_hub')]
return GeometryFactory('citygml', return GeometryFactory('citygml',