Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .github/workflows/code-quality.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Code quality and tests, following OasisLMF's code-quality workflow:
# - ruff: pyflakes checks and docstring style (rules in pyproject.toml)
# - PEP8: fails if autopep8 would change any file
# - tests: the pytest suite
#
# To fix formatting locally:
# autopep8 --in-place --recursive --max-line-length 150 --ignore E402 --exclude OasisPiWind .
# ruff check --fix .

name: Code Quality

on:
pull_request:
push:
branches:
- main
- stable**

env:
max_line_length: 150
python_version: "3.12"

jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: ${{ env.python_version }}

- name: Install code quality tools
run: pip install --upgrade autopep8 ruff

- name: Lint (ruff)
if: ${{ ! cancelled() }}
run: ruff check --output-format full .

- name: Check PEP8 compliance
if: ${{ ! cancelled() }}
run: |
autopep8 --diff --exit-code --recursive --max-line-length ${{ env.max_line_length }} \
--ignore E402 --exclude OasisPiWind .

tests:
name: Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: ${{ env.python_version }}
cache: pip
cache-dependency-path: requirements.txt

- name: Install dependencies
run: pip install -r requirements.txt pytest

- name: Run tests
run: python -m pytest -q
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,24 @@ through the Keycloak admin console at `/auth/` (`keycloak` / `password`).
Edit `oidc/authentik/users.yaml` and re-run `./install.sh`, or add users
through the Authentik admin console at `/authentik/` (`akadmin` / `password`).

## Development

Pull requests run the **Code Quality** workflow (`.github/workflows/code-quality.yml`),
which mirrors OasisLMF's checks:

- `ruff check .` - pyflakes checks and docstring style (rules in `pyproject.toml`)
- `autopep8 --diff --exit-code` - PEP8 formatting, 150 character lines
- `pytest` - the test suite

To run them locally:

```bash
pip install -r requirements.txt pytest ruff autopep8
python -m pytest -q
ruff check --fix .
autopep8 --in-place --recursive --max-line-length 150 --ignore E402 --exclude OasisPiWind .
```

## Troubleshooting

Usually first thing to try before anything is clearing browser cache/cookies for the hostname.
Expand Down
9 changes: 4 additions & 5 deletions modules/authorisation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
'''
Module to handle authorisation.
'''
"""Module to handle authorisation."""
import os
import requests
from requests.exceptions import HTTPError
Expand Down Expand Up @@ -42,8 +40,9 @@ def logout():
def handle_login(skip_login=False):
"""Handle the redirect behaviour for login or initalise if login skipped.

Parameters:
skip_login (bool): If True, login user
Args:
skip_login (bool): If True, log in with the service credentials instead of
redirecting to the login page.
"""
if "client_interface" in st.session_state:
return
Expand Down
78 changes: 31 additions & 47 deletions modules/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


def tar_to_zip(tar_bytes):
'''Repack a (gzipped) tar archive as a zip archive, keeping paths.'''
"""Repack a (gzipped) tar archive as a zip archive, keeping paths."""
out = io.BytesIO()
with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode='r:*') as tar, \
zipfile.ZipFile(out, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
Expand All @@ -29,9 +29,7 @@ def tar_to_zip(tar_bytes):


class JsonEndpointInterface:
'''
Abstract class for handling a endpoint of the Oasis APIClient restricted to json output.
'''
"""Abstract class for handling a endpoint of the Oasis APIClient restricted to json output."""

def __init__(self, client, endpoint_name='portfolios'):
self.endpoint = getattr(client, endpoint_name)
Expand All @@ -41,9 +39,7 @@ def get(self, ID=None):


class SettingsTemplateInterface:
'''
Class for handling interactions with the SettingsTemplateEndpoint of the Oasis APIClient
'''
"""Class for handling interactions with the SettingsTemplateEndpoint of the Oasis APIClient"""

def __init__(self, client):
self.endpoint = getattr(client, 'setting_templates', None)
Expand All @@ -60,10 +56,9 @@ def get_contents(self, model_pk, ID):


class EndpointInterface:
'''
Abstract class for handling a endpoint of the Oasis APIClient. Includes
"""Abstract class for handling a endpoint of the Oasis APIClient. Includes
handling both file and json endpoints.
'''
"""

def __init__(self, client, endpoint_name='portfolios'):
self.endpoint = getattr(client, endpoint_name)
Expand Down Expand Up @@ -92,9 +87,7 @@ def get_file(self, ID, filename, df=False):


class ModelsEndpointInterface(EndpointInterface):
'''
Interface for models endpoint of the Oasis APIClient.
'''
"""Interface for models endpoint of the Oasis APIClient."""

def __init__(self, client):
super().__init__(client, endpoint_name='models')
Expand All @@ -103,17 +96,14 @@ def __init__(self, client):


class AnalysesEndpointInterface(EndpointInterface):
'''
Interface for analyses endpoint of the Oasis APIClient.
'''
"""Interface for analyses endpoint of the Oasis APIClient."""

def __init__(self, client):
super().__init__(client, endpoint_name='analyses')
self.settings = JsonEndpointInterface(self.endpoint, endpoint_name='settings')

def get_traceback(self, ID, error_type='input_generation'):
'''
Get the contents of the traceback file if it exists
"""Get the contents of the traceback file if it exists

Parameters
----------
Expand All @@ -125,7 +115,7 @@ def get_traceback(self, ID, error_type='input_generation'):
Returns
-------
`str` contents of traceback file or `None` if the file does not exist.
'''
"""
traceback_endpoint = error_type + '_traceback_file'

try:
Expand All @@ -134,12 +124,11 @@ def get_traceback(self, ID, error_type='input_generation'):
logger.error(e)
return None


def cancel(self, ID):
return self.endpoint.cancel(ID)

def sub_tasks(self, ID):
'''Sub-tasks of an analysis run (name, status, ...); [] if unavailable.'''
"""Sub-tasks of an analysis run (name, status, ...); [] if unavailable."""
try:
return self.endpoint.sub_task_list(ID).json() or []
except (HTTPError, ValueError) as e:
Expand All @@ -151,9 +140,7 @@ def delete(self, ID):


class PortfoliosEndpointInterface(EndpointInterface):
'''
Interface for portfolios endpoint of the Oasis APIClient.
'''
"""Interface for portfolios endpoint of the Oasis APIClient."""

def __init__(self, client):
super().__init__(client, "portfolios")
Expand All @@ -179,7 +166,7 @@ def get_reinsurance_scope_file(self, ID, df=False):
}

def upload_file(self, ID, file_type, file_bytes, filename):
'''Attach (or replace) one of the portfolio's OED files.'''
"""Attach (or replace) one of the portfolio's OED files."""
assert file_type in self.FILE_TYPES, f'Unknown portfolio file type {file_type}'
content_type = 'application/octet-stream' if filename.endswith('.parquet') else 'text/csv'
return getattr(self.endpoint, file_type).upload_byte(ID, file_bytes, filename, content_type)
Expand All @@ -196,18 +183,21 @@ def delete(self, ID):

def create(self, name, location_file=None, accounts_file=None,
reinsurance_info_file=None, reinsurance_scope_file=None):
'''
Create a portfolio using the `UploadedFile` objects created when using the `st.file_uploader`.
"""Create a portfolio using the `UploadedFile` objects created when using the `st.file_uploader`.

Parameters
----------
name : str
Name for the assigned portfolio
location_file : UploadedFile
OED location file.
accounts_file : UploadedFile
OED accounts file.
reinsurance_info_file : UploadedFile
OED reinsurance info file.
reinsurance_scope_file : UploadedFile
reinsurance_scope_file : UploadedFile
'''
OED reinsurance scope file.
"""

def prepare_upload_f(fname, upload):
if upload is None:
Expand All @@ -223,22 +213,21 @@ def prepare_upload_f(fname, upload):
ri_scope_f = prepare_upload_f('reinsurance_scope_file', reinsurance_scope_file)

return self.client.upload_inputs(portfolio_name=name,
location_fp=location_f,
accounts_fp=accounts_f,
ri_info_fp=ri_info_f,
ri_scope_fp=ri_scope_f)
location_fp=location_f,
accounts_fp=accounts_f,
ri_info_fp=ri_info_f,
ri_scope_fp=ri_scope_f)


class ClientInterface:
'''
Wrapper interface around the Oasis APIClient.
"""Wrapper interface around the Oasis APIClient.

Attributes:
client: Instance of the `APIClient` from `oasislmf.platform_api.client`.
portfolios: Interface for managing portfolios.
analyses: Interface for managing analyses.
models: Interface for managing models.
'''
"""

def __init__(self, client=None, auth_type=None, username=None, password=None, access_token=None, refresh_token=None, client_id=None, client_secret=None):
api_url = os.environ.get('API_URL', 'http://localhost:8000')
Expand All @@ -265,8 +254,7 @@ def create_analysis(self, portfolio_id, model_id, analysis_name):
return resp

def create_and_generate_analysis(self, portfolio_id, model_id, analysis_name):
'''Create the analysis and run input generation.
'''
"""Create the analysis and run input generation."""
resp = self.create_analysis(portfolio_id, model_id, analysis_name)
resp = self.generate(resp["id"])

Expand All @@ -276,27 +264,23 @@ def upload_settings(self, analysis_id, analysis_settings):
self.client.upload_settings(analysis_id, analysis_settings)

def run(self, analysis_id):
'''Run the analysis specified by `analysis_id`.
'''
"""Run the analysis specified by `analysis_id`."""
return self.client.analyses.run(analysis_id)

def generate(self, analysis_id):
'''Run input generation of `analysis_id`.
'''
"""Run input generation of `analysis_id`."""
return self.client.analyses.generate(analysis_id)

def generate_and_run(self, analysis_id):
'''Generate input files and run the analysis specified by `analysis_id`.
'''
"""Generate input files and run the analysis specified by `analysis_id`."""
return self.client.analyses.generate_and_run(analysis_id)

def download_output_zip(self, analysis_id):
'''Analysis outputs as zip bytes (the API serves a .tar.gz).'''
"""Analysis outputs as zip bytes (the API serves a .tar.gz)."""
return tar_to_zip(self.download_output(analysis_id))

def download_output(self, analysis_id):
'''Retrieve the output files from a given analysis specified by `analysis_id`.
'''
"""Retrieve the output files from a given analysis specified by `analysis_id`."""
with tempfile.TemporaryDirectory() as tmpdir:
self.client.download_output(analysis_id, download_path=tmpdir)
fname = os.listdir(tmpdir)[0]
Expand Down
6 changes: 4 additions & 2 deletions modules/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
logger = logging.getLogger(__name__)
OASIS_UI_CONFIG = "ui-config.json"


class UIConfig():
"""Class to hold config information for the UI. Loads the infomation from
OASIS_UI_CONFIG environment variabel (defaults to `ui-config.json`).
Expand All @@ -17,6 +18,7 @@ class UIConfig():
of exposure sets the model should correspond to.
skip_login (bool): If True skip the login redirection.
"""

def __init__(self):
config_path = os.getenv("OASIS_UI_CONFIG", OASIS_UI_CONFIG)

Expand All @@ -35,10 +37,10 @@ def __init__(self):


def retrieve_ui_config():
'''Retrieve ui config.
"""Retrieve ui config.

First checks `session_state` and if not present loads from file.
'''
"""
if 'ui-config' in st.session_state:
logger.info("Loading ui-config from session_state.")
return st.session_state['ui-config']
Expand Down
3 changes: 2 additions & 1 deletion modules/rerun.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import streamlit as st


class RefreshHandler:
q_name = "refresh_1"
refresh_bool = "refreshing"
Expand Down Expand Up @@ -56,7 +57,7 @@ def update_queue(self):
st.rerun()

def run_every(self):
run_every=None
run_every = None
if not RefreshHandler.queue_empty():
run_every = self.interval

Expand Down
Loading
Loading