Compare commits

...
247 Commits
Author SHA1 Message Date
Brian Bjarke Jensen 70492acafe Merge pull request '#67_unittests_for_DTOs' (#69) from #67_unittests_for_DTOs into main
Reviewed-on: #69
2025-04-16 00:35:07 +02:00
brian 06913064c3 added unittests for repositories DTO base class
Code Quality Pipeline / Check Code (pull_request) Successful in 2m44s
2025-04-15 22:24:02 +00:00
brian 7190b6c438 removed unused setting 2025-04-15 22:22:20 +00:00
Brian Bjarke Jensen 7ce7a368c7 Merge pull request 'object_based_docstore_approach' (#68) from object_based_docstore_approach into main
Reviewed-on: #68
2025-04-16 00:03:23 +02:00
brian a2b818bbcc updated ignored packages
Code Quality Pipeline / Check Code (pull_request) Successful in 3m20s
2025-04-15 21:56:45 +00:00
brian 08062ad87d removed unused packages 2025-04-15 21:56:33 +00:00
brian 7176dfdf90 added env vars back in
Code Quality Pipeline / Check Code (pull_request) Failing after 2m22s
2025-03-18 19:34:03 +00:00
brian 6399b88ade clarified comment 2025-03-18 19:33:50 +00:00
brian c5bcd09bba removed already defined environment variable 2025-03-18 19:30:12 +00:00
brian 7d8af1c582 changed returned class type 2025-03-18 19:28:12 +00:00
brian a379270add removed deprecated modules 2025-03-18 19:21:17 +00:00
brian 0b54ccaadb removed unused variable 2025-03-18 19:12:51 +00:00
brian ac8ca830e1 manually set needed environment variables in conftest
Code Quality Pipeline / Check Code (pull_request) Failing after 3m9s
2025-03-18 19:12:06 +00:00
brian 49d2c48d31 explicitly adding local env vars to file
Code Quality Pipeline / Check Code (pull_request) Failing after 2m41s
2025-03-18 15:34:39 +00:00
brian 280dbb579e added more explicit env var loading
Code Quality Pipeline / Check Code (pull_request) Failing after 3m45s
2025-03-17 22:46:52 +00:00
brian ab7e346939 tried loading github env file
Code Quality Pipeline / Check Code (pull_request) Failing after 3m9s
2025-03-17 22:32:06 +00:00
brian ad82ad4591 added explicit check for necessary env vars
Code Quality Pipeline / Check Code (pull_request) Failing after 3m7s
2025-03-17 22:19:14 +00:00
brian 400706e730 moved env var checks
Code Quality Pipeline / Check Code (pull_request) Failing after 3m21s
2025-03-17 22:09:48 +00:00
brian 096ffd56e9 added explicit env var checking
Code Quality Pipeline / Check Code (pull_request) Failing after 3m18s
2025-03-17 21:54:52 +00:00
brian 790204af6a updated logical check
Code Quality Pipeline / Check Code (pull_request) Failing after 3m18s
2025-03-17 21:48:43 +00:00
brian 14a4125688 updated to give full list of missing env vars
Code Quality Pipeline / Check Code (pull_request) Failing after 3m23s
2025-03-17 21:44:13 +00:00
brian 62519c371e removed explicitly setting env vars 2025-03-17 21:41:42 +00:00
brian 9c8089d091 tried explicit export statements
Code Quality Pipeline / Check Code (pull_request) Failing after 3m17s
2025-03-17 21:34:17 +00:00
brian 77a3219f39 fixed path variable
Code Quality Pipeline / Check Code (pull_request) Failing after 3m21s
2025-03-17 21:13:21 +00:00
brian 66370a33c2 tried to add if-statement to load_dotenv to see if this disturbs CI tests 2025-03-17 21:12:19 +00:00
brian 5870c3b0a3 added no chache-option to poetry 2025-03-17 21:11:52 +00:00
brian e9340f17c4 print out env vars for debugging
Code Quality Pipeline / Check Code (pull_request) Failing after 3m18s
2025-03-17 20:57:43 +00:00
brian 282fee0806 fixed spelling mistake 2025-03-17 20:57:30 +00:00
brian 33d30941a6 updated to run locally
Code Quality Pipeline / Check Code (pull_request) Failing after 3m23s
2025-03-17 18:06:46 +00:00
brian cb8d17cbc3 fixed poetry path
Code Quality Pipeline / Check Code (pull_request) Failing after 9m3s
2025-03-10 19:25:12 +00:00
brian df2c2b7e5f corrected spelling mistake
Code Quality Pipeline / Check Code (pull_request) Failing after 2m38s
2025-03-10 19:17:42 +00:00
brian 6756ae4871 updated github action versions
Code Quality Pipeline / Check Code (pull_request) Failing after 1m6s
2025-03-10 19:13:37 +00:00
brian fa30aae3a8 changed torch version
Code Quality Pipeline / Check Code (pull_request) Failing after 1m46s
2025-03-10 18:44:54 +00:00
brian 15f3944d27 corrected poetry version
Code Quality Pipeline / Check Code (pull_request) Failing after 1m47s
2025-03-10 18:38:43 +00:00
brian e6b73fe4fc corrected python version
Code Quality Pipeline / Check Code (pull_request) Failing after 1m47s
2025-03-08 21:47:11 +00:00
brian 1f72a2db8d added hook 'check-added-large-files' 2025-03-08 21:46:21 +00:00
brian a610bf4d89 downgraded python for torch compatibility 2025-03-08 21:29:06 +00:00
brian 9af3d9bc54 update pre-commit
Code Quality Pipeline / Check Code (pull_request) Failing after 1m45s
2025-03-08 21:19:18 +00:00
brian bbbeb403a8 Revert "updated packages"
Code Quality Pipeline / Check Code (pull_request) Failing after 57s
This reverts commit 62b6224de7.
2025-03-06 22:46:26 +00:00
brian 9be7ec9e2e redid lock file 2025-03-06 22:45:42 +00:00
brian a6c717a401 Revert "uninstalled testcontainers"
This reverts commit a18b4d304c.
2025-03-06 22:45:18 +00:00
brian 4db59d2801 added mongo endpoint 2025-03-06 22:44:06 +00:00
brian 3a0c1e9067 Revert "added env var for CI testing"
This reverts commit a2f892e35c.
2025-03-06 22:43:19 +00:00
brian 5a8350d0ad downgraded torch
Code Quality Pipeline / Check Code (pull_request) Failing after 1m49s
2025-03-06 22:30:04 +00:00
brian 62b6224de7 updated packages
Code Quality Pipeline / Check Code (pull_request) Failing after 1m53s
2025-03-06 22:16:50 +00:00
brian 68bfff87a7 poetry disappeared
Code Quality Pipeline / Check Code (pull_request) Failing after 40s
2025-03-06 22:11:11 +00:00
brian ac21c7a111 removed mypy overrides for testcontainers
Code Quality Pipeline / Check Code (pull_request) Failing after 37s
2025-03-06 22:03:04 +00:00
brian a18b4d304c uninstalled testcontainers 2025-03-06 22:02:32 +00:00
brian a2f892e35c added env var for CI testing 2025-03-06 22:02:21 +00:00
brian 4bcfbbed0a removed usage of testcontainers 2025-03-06 22:02:06 +00:00
brian 31be0d7aac added check for poetry installation
Code Quality Pipeline / Check Code (pull_request) Failing after 3m16s
2025-03-06 21:34:14 +00:00
brian d4c9738db4 next try
Code Quality Pipeline / Check Code (pull_request) Failing after 1m24s
2025-03-06 21:29:52 +00:00
brian 813daa0c90 next attempt
Code Quality Pipeline / Check Code (pull_request) Failing after 24s
2025-03-06 21:22:52 +00:00
brian 29bf41c7da next try
Code Quality Pipeline / Check Code (pull_request) Failing after 24s
2025-03-06 21:16:06 +00:00
brian d9bd5be46d again again
Code Quality Pipeline / Check Code (pull_request) Failing after 22s
2025-03-06 21:06:50 +00:00
brian c2a2c34967 again
Code Quality Pipeline / Check Code (pull_request) Failing after 23s
2025-03-06 21:04:24 +00:00
brian 9e66981d3e next attempt
Code Quality Pipeline / Check Code (pull_request) Failing after 9s
2025-03-06 21:02:17 +00:00
brian 6840ac72f1 try again with poetry
Code Quality Pipeline / Check Code (pull_request) Failing after 36s
2025-03-06 20:56:59 +00:00
brian ee304f1a75 yet another attempt at installing poetry
Code Quality Pipeline / Check Code (pull_request) Failing after 23s
2025-03-06 20:36:42 +00:00
brian 4827a3f7dd next attempt at installing poetry
Code Quality Pipeline / Check Code (pull_request) Failing after 39s
2025-03-06 20:26:56 +00:00
brian d92051f5c4 new attempt at installing poetry
Code Quality Pipeline / Check Code (pull_request) Failing after 23s
2025-03-06 20:23:16 +00:00
brian 10ce0d9124 updated to recommended CI install method
Code Quality Pipeline / Check Code (pull_request) Failing after 23s
2025-03-06 20:19:52 +00:00
brian 88a20c4b0b corrected type hints
Code Quality Pipeline / Check Code (pull_request) Failing after 1m48s
2025-02-28 22:54:53 +00:00
brian 090a1cd8bb added integration tests and repository pattern for image, model and visual communication DTOs
Code Quality Pipeline / Check Code (pull_request) Failing after 3m21s
2025-02-28 22:24:52 +00:00
brian ac6a305da8 fixed spelling 2025-01-07 17:50:17 +00:00
brian cbedc395bc corrected spelling 2025-01-07 17:48:10 +00:00
brian 0c762b55b2 corrected comment spelling 2025-01-06 17:32:33 +00:00
brian 99b5820ae6 renamed module 2025-01-06 17:15:48 +00:00
Brian Bjarke Jensen 8214bd2669 Merge pull request 'object_based_datastore' (#65) from object_based_datastore into main
Reviewed-on: http://192.168.1.2:3000/brian/visual_critical_discourse_analysis/pulls/65
2025-01-06 14:48:25 +01:00
brian aff0ae8fc6 fixed types
Code Quality Pipeline / Check Code (pull_request) Successful in 3m15s
2025-01-06 13:42:21 +00:00
brian 16ad2b80ee updated tests to match new interface
Code Quality Pipeline / Check Code (pull_request) Failing after 3m5s
2025-01-06 11:34:02 +00:00
brian 88698dd735 fixed relative import paths 2025-01-06 11:29:54 +00:00
brian f28bff7e47 implemented new interface 2025-01-06 11:29:31 +00:00
brian 9ee27b65a8 removed unused files 2025-01-06 11:27:26 +00:00
brian de4f984110 added minio-specific interface 2025-01-06 11:26:47 +00:00
brian 3b677e5e97 fixed bug in context manager definition 2025-01-06 11:26:23 +00:00
brian 226fb1a206 defined interface 2025-01-06 11:22:34 +00:00
brian 7a1e17c29f updated to raise proper error 2025-01-06 11:21:36 +00:00
brian f52720685e fixed relative import 2025-01-06 11:21:08 +00:00
Brian Bjarke Jensen a3da7b048d Merge pull request 'tests_for_datastore' (#63) from tests_for_datastore into main
Reviewed-on: #63
2024-12-21 17:31:12 +01:00
brian f61eb59afb installed coverage package and included coverage report in CI
Code Quality Pipeline / Check Code (pull_request) Successful in 2m35s
2024-12-21 16:27:48 +00:00
brian a430366bbe updated variable name for clarity
Code Quality Pipeline / Check Code (pull_request) Failing after 2m21s
2024-12-21 16:09:23 +00:00
brian 06d9753c46 added CI vars for tests
Code Quality Pipeline / Check Code (pull_request) Failing after 2m22s
2024-12-21 16:03:04 +00:00
brian 4e6499cee3 next attempt at using repo vars
Code Quality Pipeline / Check Code (pull_request) Failing after 2m59s
2024-12-21 15:55:31 +00:00
brian 7da3482366 updated to use env var from CI
Code Quality Pipeline / Check Code (pull_request) Failing after 2m49s
2024-12-20 23:46:23 +00:00
brian 7b3374d451 fixed tests running against server db
Code Quality Pipeline / Check Code (pull_request) Failing after 3m23s
2024-12-20 23:33:43 +00:00
brian b17c1745ab fixed bug referencing object in minio incorrectly 2024-12-20 23:31:33 +00:00
brian db4ce6b425 fixed bug referencing unset variable on exception 2024-12-20 23:15:55 +00:00
brian aa6a097e4f updated to use server db for testing 2024-12-20 22:40:53 +00:00
brian 150a213ae2 fixed bug when putting data 2024-12-20 22:39:53 +00:00
brian d860b71b1a attempt at showing the determined minio endpoint
Code Quality Pipeline / Check Code (pull_request) Failing after 2m48s
2024-12-19 22:18:58 +00:00
brian 1a3ee96932 added fix to allow running Minio container in CI
Code Quality Pipeline / Check Code (pull_request) Failing after 2m47s
2024-12-19 22:11:07 +00:00
brian 8e366f26bc updated port mapping
Code Quality Pipeline / Check Code (pull_request) Failing after 3m26s
2024-12-19 21:58:15 +00:00
brian 8a602264e6 mypy ignore testcontainers missing imports
Code Quality Pipeline / Check Code (pull_request) Failing after 3m14s
2024-12-19 16:01:52 +00:00
brian 99d5c88c8d fixed argument types 2024-12-19 16:01:29 +00:00
brian c9da7378a1 commented out more unused imports
Code Quality Pipeline / Check Code (pull_request) Failing after 2m11s
2024-12-19 15:41:28 +00:00
brian b2773ecf09 commented out unused imports
Code Quality Pipeline / Check Code (pull_request) Failing after 1m35s
2024-12-19 15:38:49 +00:00
brian 084a13426a commented out unused tests temporarily
Code Quality Pipeline / Check Code (pull_request) Failing after 2m11s
2024-12-19 15:34:11 +00:00
brian 499996329f added fixtures 2024-12-19 15:33:25 +00:00
brian ce08ee4ccd added function to compare images 2024-11-25 16:37:52 +00:00
brian cbbb044177 updated integration tests 2024-11-16 19:46:37 +00:00
brian c630498168 vulture ignore test folders 2024-11-16 19:46:18 +00:00
brian f9d23c5bd4 added type-specific unittests 2024-11-16 18:50:28 +00:00
brian 3fa79faa9e shortened variable name 2024-11-16 18:39:25 +00:00
brian 556e26f21d added unittests for base functions 2024-11-16 18:27:59 +00:00
brian 01ee4664ff implemented base functions 2024-11-16 18:18:13 +00:00
brian 169e0531d9 started making unittest 2024-11-08 22:32:27 +00:00
brian 3c46275015 updated input check 2024-11-08 22:29:33 +00:00
brian 0b86acd1a9 began adding tests 2024-11-08 22:29:03 +00:00
brian cddfced177 added unittest 2024-11-08 22:27:58 +00:00
brian 53d179663b added unittest 2024-11-08 21:05:20 +00:00
brian 6be837025b moved files 2024-11-08 21:03:53 +00:00
brian 2854f74db4 installed package for generating coverage report 2024-10-28 19:44:16 +00:00
brian 462f7c79b4 added step to print coverage report 2024-10-28 19:43:56 +00:00
brian 0c9537975c updated bucket name 2024-10-28 19:43:37 +00:00
brian 10bfac73bd extended tests 2024-10-25 17:19:47 +00:00
brian bdf3e73ba9 updated for more general use 2024-10-25 17:19:15 +00:00
brian 42400d6f32 updated for readability 2024-10-25 17:18:53 +00:00
brian 0676011f98 implemented new more general function 2024-10-25 17:10:03 +00:00
brian e189b7c1f7 updated for more general use 2024-10-25 17:09:43 +00:00
brian dc535167fa started making tests 2024-10-25 09:27:01 +00:00
brian b722ddcb83 installed new packages for testing 2024-10-25 09:26:10 +00:00
brian b755a81ef9 simplified code 2024-10-25 09:25:52 +00:00
brian ae18041d6e simplified code 2024-10-24 16:46:35 +00:00
brian d8e3d077e3 moved files into src folder 2024-10-24 16:40:26 +00:00
Brian Bjarke Jensen b54e2ed541 Merge pull request 'renamed module' (#61) from rename_module_datastore into main
Reviewed-on: #61
2024-10-24 18:23:23 +02:00
brian 30f37b6ca5 renamed module
Code Quality Pipeline / Check Code (pull_request) Successful in 2m40s
2024-10-24 16:19:52 +00:00
Brian Bjarke Jensen 860150905d Merge pull request 'rename_shared_module_database' (#57) from rename_shared_module_database into main
Reviewed-on: #57
2024-10-20 22:37:30 +02:00
brian 66c3f38dba added ignore for internal module
Code Quality Pipeline / Check Code (pull_request) Successful in 2m43s
2024-10-20 20:32:14 +00:00
brian 1a6cf69346 moved code 2024-10-20 20:21:16 +00:00
brian 6f06485776 updated imports 2024-10-20 20:18:20 +00:00
brian c7fd78dcf8 removed unused code 2024-10-20 20:18:14 +00:00
brian 7a8eb93c48 updated imports 2024-10-20 20:15:19 +00:00
brian 4ba68d056b moved definitions of data classes into module where used 2024-10-20 20:08:37 +00:00
brian ba7a7299c2 removed unused class 2024-10-20 20:05:47 +00:00
brian 6dba06704c moved definition of exception to separate folder 2024-10-20 20:04:48 +00:00
brian 20831c9bc3 renamed file 2024-10-20 20:02:36 +00:00
brian e2338ad710 renamed module 2024-10-20 20:00:13 +00:00
Brian Bjarke Jensen d1ee43e135 Merge pull request 'unittest_for_shared_utils' (#55) from unittest_for_shared_utils into main
Reviewed-on: #55
2024-10-20 21:43:05 +02:00
brian 909f8f220c added tests for setup_logging function
Code Quality Pipeline / Check Code (pull_request) Successful in 2m19s
2024-10-20 19:36:50 +00:00
brian 7fa88166ee fixed log not being set 2024-10-20 19:36:31 +00:00
Brian Bjarke Jensen 321defb7ff Merge pull request 'add_check_env_function' (#54) from add_check_env_function into main
Reviewed-on: #54
2024-10-20 20:57:20 +02:00
brian 00f1c07cfa updated filenames to avoid accidental running during test
Code Quality Pipeline / Check Code (pull_request) Successful in 2m12s
2024-10-20 18:52:00 +00:00
brian 312f525a46 fixed argument for check_env function
Code Quality Pipeline / Check Code (pull_request) Failing after 2m25s
2024-10-20 18:46:32 +00:00
brian 78363988f7 updated static variable name 2024-10-20 18:44:04 +00:00
brian b109ddb2b8 added step to run pytest
Code Quality Pipeline / Check Code (pull_request) Failing after 2m46s
2024-10-20 18:35:53 +00:00
brian 5b446a9f2f updated deprecated pydantic config 2024-10-20 18:34:06 +00:00
brian b462056e24 changed folder name to avoid accidental running during test 2024-10-20 18:30:59 +00:00
brian bdc0535ea4 added tests for check_env function 2024-10-20 18:30:12 +00:00
brian 5a1de4f2b2 added package pytest 2024-10-20 18:29:01 +00:00
brian 4e499da168 moved hardcoded values into main script 2024-10-20 18:28:23 +00:00
brian 8bfdec067b fixed import 2024-10-20 18:27:31 +00:00
Brian Bjarke Jensen 9d45f8a32b Merge pull request 'ci_pull_request_pipeline' (#51) from ci_pull_request_pipeline into main
Reviewed-on: http://192.168.1.2:3000/brian/visual_critical_discourse_analysis/pulls/51
2024-10-20 00:17:23 +02:00
brian 082ccf8382 updated to trigger on published release
Code Quality Pipeline / Check Code (pull_request) Successful in 3m2s
2024-10-19 22:16:34 +00:00
brian 8f10c16f3b added pull request ci script 2024-10-19 22:11:53 +00:00
Brian Bjarke Jensen 5a674603ca Merge pull request 'image_through_model' (#49) from image_through_model into main
Reviewed-on: http://192.168.1.2:3000/brian/visual_critical_discourse_analysis/pulls/49
2024-10-20 00:10:26 +02:00
brian ba0fc050fe fixed mypy types
CI Pipeline / Test (pull_request) Successful in 2m23s
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Successful in 7m3s
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Successful in 6m13s
2024-10-19 21:37:08 +00:00
brian 7fc4d20262 added types for checking 2024-10-19 20:11:49 +00:00
brian d6036a95a3 fixed deprecated import 2024-10-19 20:09:32 +00:00
brian 14ccaace95 mypy fixed types 2024-10-19 20:03:54 +00:00
brian 6d327bee22 fixed type bug 2024-10-19 19:55:58 +00:00
brian 270dc8e4d1 fixed type 2024-10-19 19:54:40 +00:00
brian e49a0c37a6 ensure env var set 2024-10-19 19:45:42 +00:00
brian a0726857a0 ensure env var set 2024-10-19 19:45:16 +00:00
brian bf44947024 added utility script
CI Pipeline / Test (pull_request) Failing after 2m31s
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Has been skipped
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Has been skipped
2024-10-19 19:15:41 +00:00
brian 4f22b9755c updated import 2024-10-19 19:15:20 +00:00
brian ae3ac714d4 added placeholder files for training and validation files 2024-10-19 19:14:56 +00:00
brian ad069269ac added settings for resnet18-based model 2024-10-19 19:14:34 +00:00
brian a54e7bbbb4 installed packages 2024-10-19 19:13:45 +00:00
brian 1f62054f36 installed packages 2024-10-19 19:13:35 +00:00
brian 59048a6862 added model training script 2024-10-19 19:12:21 +00:00
brian a4764b8fc5 added ignore for training run folder 2024-10-19 19:11:02 +00:00
brian bf4cc9c483 ensure non-empty input 2024-10-19 19:10:33 +00:00
brian f35cdefc21 removed deprecated dependency 2024-10-19 19:08:51 +00:00
Brian Bjarke Jensen 493da70ba4 updated to do prediction and print result 2024-07-28 23:22:40 +02:00
Brian Bjarke Jensen b415137e25 added method to instantiate from prediction dict 2024-07-28 23:19:51 +02:00
Brian Bjarke Jensen cead3d24c8 added from_tensor method 2024-07-28 23:13:15 +02:00
Brian Bjarke Jensen 0bfbb1920c fixed conversion of classes 2024-07-28 23:12:06 +02:00
Brian Bjarke Jensen 164102557e removed unused import 2024-07-28 23:10:15 +02:00
Brian Bjarke Jensen cf923a228d updated model name reference 2024-07-28 21:37:28 +02:00
Brian Bjarke Jensen 9f4a09a18c fixed definition of layers 2024-07-28 21:36:21 +02:00
Brian Bjarke Jensen 849b59e575 removed double connection to minio 2024-07-28 21:34:56 +02:00
Brian Bjarke Jensen 4a7e33b527 updated referenced model name 2024-07-28 21:32:16 +02:00
Brian Bjarke Jensen e5fad6d765 added function to generate and save new model 2024-07-28 21:31:48 +02:00
Brian Bjarke Jensen be6833ac6a added option to download weights 2024-07-28 21:25:24 +02:00
Brian Bjarke Jensen 6541a47668 added option to download resnet18 weights 2024-07-28 21:19:47 +02:00
Brian Bjarke Jensen 96ccdb5c90 moved file for clarity 2024-07-28 21:16:32 +02:00
Brian Bjarke Jensen 6e9c0a2626 fixed number of inputs 2024-07-28 21:13:51 +02:00
Brian Bjarke Jensen 396bf29f32 updated function name 2024-07-28 21:08:51 +02:00
Brian Bjarke Jensen 05774364fc renamed function for clarity 2024-07-28 21:08:27 +02:00
Brian Bjarke Jensen 74a9538feb renamed function for clarity 2024-07-28 21:05:15 +02:00
Brian Bjarke Jensen 9423c3378a fixed dockerfile syntax 2024-07-28 21:02:59 +02:00
Brian Bjarke Jensen e6fdbfe0b0 changed to not download pretrained weights for ResNet18 2024-07-28 21:01:19 +02:00
Brian Bjarke Jensen 6c354b23bd test run prediction on image 2024-07-27 21:41:29 +02:00
Brian Bjarke Jensen 3ad6c161b1 added new modules 2024-07-27 21:40:38 +02:00
Brian Bjarke Jensen a1ff6a6f33 moved for clarity 2024-07-27 21:40:17 +02:00
Brian Bjarke Jensen cf4f67d7a5 installed tqdm 2024-07-27 21:38:18 +02:00
Brian Bjarke Jensen 7c968db8ac renamed file for clarity 2024-07-27 21:18:39 +02:00
Brian Bjarke Jensen e656cd4e12 remove unneeded code for running in docker container 2024-07-27 21:08:47 +02:00
Brian Bjarke Jensen 8b1893b30a implemented load_model function 2024-07-24 09:13:28 +02:00
Brian Bjarke Jensen 96d868a40c added function to load model 2024-07-24 09:12:07 +02:00
Brian Bjarke Jensen e698d058ff removed debug log 2024-07-24 09:11:01 +02:00
Brian Bjarke Jensen 8aafbdae6c fixed hardcoded path 2024-07-24 09:10:37 +02:00
Brian Bjarke Jensen ec4162e34d removed newline char 2024-07-22 23:50:55 +02:00
Brian Bjarke Jensen 99b7067cfe added container resource limits 2024-07-22 23:48:01 +02:00
Brian Bjarke Jensen e62435cf22 added full model load script 2024-07-22 23:47:39 +02:00
Brian Bjarke Jensen 3560a61277 added model name loader 2024-07-22 23:47:11 +02:00
Brian Bjarke Jensen 7f0cbea937 added model name link file 2024-07-22 23:46:15 +02:00
Brian Bjarke Jensen 31156eea54 updated classes 2024-07-22 23:45:54 +02:00
Brian Bjarke Jensen ef11c33675 used buffered download 2024-07-22 23:45:19 +02:00
Brian Bjarke Jensen 89aecfdef7 updated to use new io functions 2024-07-14 11:16:35 +02:00
Brian Bjarke Jensen 68e04c7653 fixed bucket name checking bug 2024-07-14 11:16:13 +02:00
Brian Bjarke Jensen a12f8c46e8 added model io functions 2024-07-14 11:15:56 +02:00
Brian Bjarke Jensen ff88dc1719 refactor for readability 2024-07-14 11:13:23 +02:00
Brian Bjarke Jensen 6502ea043a rearranged imports 2024-07-14 10:47:04 +02:00
Brian Bjarke Jensen 9cd4f70194 refactor for readability and implement new get_image function 2024-07-14 00:10:22 +02:00
Brian Bjarke Jensen 2cf55efcb3 added checking if buckets exist 2024-07-13 23:45:57 +02:00
Brian Bjarke Jensen d55adf87ac added buckets exist check 2024-07-13 23:42:42 +02:00
Brian Bjarke Jensen a621525d9e updated to fit new workflow 2024-07-13 23:36:26 +02:00
Brian Bjarke Jensen ba1ba027f0 moved files 2024-07-13 23:35:15 +02:00
Brian Bjarke Jensen 24e1c44f5e fixed double reference 2024-07-13 23:34:57 +02:00
Brian Bjarke Jensen 94801efa6a added isort and flake8 black compatibility 2024-07-13 23:33:43 +02:00
Brian Bjarke Jensen 4f7e8150e9 added image specific io functions 2024-07-13 23:30:22 +02:00
Brian Bjarke Jensen e9b5250e95 script to move images to subfolder in minio 2024-07-13 23:29:28 +02:00
Brian Bjarke Jensen c1f38e3d77 moved functions to shared folder 2024-07-13 23:28:57 +02:00
Brian Bjarke Jensen 9a107c7bb7 added model instantiation test 2024-07-13 22:38:23 +02:00
Brian Bjarke Jensen 74d7307219 moved to shared folder 2024-07-13 22:36:45 +02:00
Brian Bjarke Jensen bdd0dfff10 updated to not get vulture error 2024-07-13 22:36:27 +02:00
Brian Bjarke Jensen e913bb28cc removed autopep 2024-07-13 22:34:30 +02:00
Brian Bjarke Jensen f9b845abd9 testing pre-commits 2024-07-13 22:31:22 +02:00
Brian Bjarke Jensen d46ad01e1d updated checks 2024-07-13 22:31:03 +02:00
Brian Bjarke Jensen 8d887b40b3 Merge pull request 'move_images_to_minio' (#44) from move_images_to_minio into main
Reviewed-on: #44
2024-06-19 14:57:32 +02:00
Brian Bjarke Jensen 2ee5ab2b9c added env var check
CI Pipeline / Test (pull_request) Successful in 2m7s
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Successful in 16s
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Successful in 15s
2024-06-16 00:06:28 +02:00
Brian Bjarke Jensen 962d028c07 added minio env vars
CI Pipeline / Test (pull_request) Successful in 2m15s
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Successful in 17s
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Successful in 15s
2024-06-15 23:59:39 +02:00
Brian Bjarke Jensen eaca23f27a updated to use new class
CI Pipeline / Test (pull_request) Successful in 2m7s
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Successful in 6m26s
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Successful in 5m40s
2024-06-15 23:18:27 +02:00
Brian Bjarke Jensen 0bd4008e72 updated to use new class 2024-06-15 23:17:28 +02:00
Brian Bjarke Jensen 123cab2500 updated to use new functions 2024-06-15 23:16:42 +02:00
Brian Bjarke Jensen d09cb9dd20 added delete function 2024-06-15 23:15:31 +02:00
Brian Bjarke Jensen e1075b3551 ignore outdated class reference 2024-06-15 23:14:55 +02:00
Brian Bjarke Jensen d537cdf11d updated to use new vis com class
CI Pipeline / Test (pull_request) Failing after 2m12s
CI Pipeline / Build and Publish (./Dockerfile.web_ui, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/web_ui) (pull_request) Has been skipped
CI Pipeline / Build and Publish (./Dockerfile.model, ${{ vars.docker_repo_url }}/${{ gitea.repository }}/model) (pull_request) Has been skipped
2024-06-15 16:31:35 +02:00
Brian Bjarke Jensen b8061466ce updated to use new vis com class 2024-06-15 16:31:19 +02:00
Brian Bjarke Jensen 119282fee9 tested loading images from minio 2024-06-15 16:20:16 +02:00
Brian Bjarke Jensen 2e060f0776 updated to match images being stored in minio 2024-06-15 16:19:51 +02:00
Brian Bjarke Jensen 9d0648f3c1 transferred images from mongo to minio 2024-06-15 16:19:04 +02:00
Brian Bjarke Jensen b093154193 silenced noisy modules 2024-06-15 16:15:45 +02:00
Brian Bjarke Jensen f3aab68d5f added minio interface 2024-06-15 16:14:43 +02:00
Brian Bjarke Jensen 0ebf7e6ce1 updated logging formatting 2024-06-15 13:00:28 +02:00
133 changed files with 5119 additions and 2332 deletions
+2 -3
View File
@@ -1,9 +1,8 @@
name: CI Pipeline name: CI Pipeline
run-name: ${{ gitea.actor }} is running the CI Pipeline run-name: ${{ gitea.actor }} is running the CI Pipeline
on: on:
pull_request: release:
branches: types: [published]
- main
jobs: jobs:
test: test:
name: Test name: Test
+50
View File
@@ -0,0 +1,50 @@
name: Code Quality Pipeline
on:
pull_request:
branches:
- main
jobs:
job:
name: Check Code
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Environment
uses: https://github.com/actions/setup-python@v5
with:
python-version: "3.12"
architecture: "x64"
- name: Setup poetry
env:
POETRY_VERSION: 2.1.1
POETRY_HOME: /opt/poetry
POETRY_NO_INTERACTION: 1
POETRY_NO_CACHE: 1
run: |
curl -sSL https://install.python-poetry.org | python3 -
export PATH=$POETRY_HOME/bin:$PATH
poetry --version
- name: Install Dependencies
env:
PIP_INDEX_URL: ${{ vars.PIP_INDEX_URL }}
PIP_TRUSTED_HOST: ${{ vars.PIP_TRUSTED_HOST }}
run: |
/opt/poetry/bin/poetry install
- name: PEP8 Check
run: |
/opt/poetry/bin/poetry run flake8 . --benchmark
- name: Type Check
run: |
/opt/poetry/bin/poetry run mypy .
- name: Pytest & Calculate Coverage
env:
MINIO_ENDPOINT: ${{ vars.MINIO_ENDPOINT }}
MINIO_ACCESS_KEY: ${{ vars.MINIO_ACCESS_KEY }}
MINIO_SECRET_KEY: ${{ secrets.MINIO_SECRET_KEY }}
MONGO_ENDPOINT: ${{ vars.MONGO_ENDPOINT }}
run: |
/opt/poetry/bin/poetry run coverage run -m pytest .
- name: Coverage Report
run: |
/opt/poetry/bin/poetry run coverage report -m
+3
View File
@@ -177,3 +177,6 @@ ipython_config.py
# Remove previous ipynb_checkpoints # Remove previous ipynb_checkpoints
# git rm -r .ipynb_checkpoints/ # git rm -r .ipynb_checkpoints/
# Logging data
runs/*
+30 -15
View File
@@ -1,37 +1,33 @@
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0 rev: v5.0.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
- id: end-of-file-fixer - id: end-of-file-fixer
- id: check-yaml - id: check-yaml
- id: check-added-large-files
- id: debug-statements - id: debug-statements
- id: double-quote-string-fixer - id: double-quote-string-fixer
- id: name-tests-test - id: name-tests-test
- id: requirements-txt-fixer
- repo: https://github.com/asottile/setup-cfg-fmt - repo: https://github.com/asottile/setup-cfg-fmt
rev: v2.5.0 rev: v2.7.0
hooks: hooks:
- id: setup-cfg-fmt - id: setup-cfg-fmt
- repo: https://github.com/asottile/reorder-python-imports - repo: https://github.com/pre-commit/mirrors-isort
rev: v3.12.0 rev: v5.10.1
hooks: hooks:
- id: reorder-python-imports - id: isort
exclude: ^(pre_commit/resources/|testing/resources/python3_hooks_repo/) language_version: python3.10
args: [--py39-plus, --add-import, 'from __future__ import annotations'] args: [ --tc ]
- repo: https://github.com/asottile/add-trailing-comma - repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0 rev: v3.1.0
hooks: hooks:
- id: add-trailing-comma - id: add-trailing-comma
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v3.15.1 rev: v3.19.1
hooks: hooks:
- id: pyupgrade - id: pyupgrade
args: [--py39-plus] args: [--py39-plus]
- repo: https://github.com/hhatto/autopep8
rev: v2.0.4
hooks:
- id: autopep8
- repo: https://github.com/PyCQA/flake8 - repo: https://github.com/PyCQA/flake8
rev: 7.0.0 rev: 7.0.0
hooks: hooks:
@@ -40,8 +36,27 @@ repos:
additional_dependencies: additional_dependencies:
- "pyproject-flake8" - "pyproject-flake8"
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0 rev: v1.15.0
hooks: hooks:
- id: mypy - id: mypy
additional_dependencies: [types-all]
exclude: ^testing/resources/ exclude: ^testing/resources/
- repo: https://github.com/psf/black
rev: 25.1.0
hooks:
- id: black
language_version: python3.12
args: [ --skip-string-normalization ]
- repo: https://github.com/myint/docformatter
rev: v1.5.0
hooks:
- id: docformatter
name: docformatter
description: 'Formats docstrings to follow PEP 257.'
entry: docformatter
language: python
types: [ python ]
- repo: https://github.com/jendrikseipp/vulture
rev: 'v2.14'
hooks:
- id: vulture
entry: vulture . --min-confidence 90 --exclude */.venv/*.py,*/tests/*.py
+2 -2
View File
@@ -1,5 +1,5 @@
# build stage # build stage
FROM python:3.12-slim-bookworm as BUILDER FROM python:3.12-slim-bookworm AS builder
# set environment variables # set environment variables
ENV PYTHONUNBUFFERED=1 \ ENV PYTHONUNBUFFERED=1 \
@@ -44,7 +44,7 @@ COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}" ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"
# create home directory and app user # create home directory and app user
RUN mkdir -p /home/app RUN mkdir -p $APP_HOME
# add code while changing ownership # add code while changing ownership
WORKDIR $APP_HOME WORKDIR $APP_HOME
+1 -1
View File
@@ -1,5 +1,5 @@
# build stage # build stage
FROM python:3.12-slim-bookworm as BUILDER FROM python:3.12-slim-bookworm AS builder
# set environment variables # set environment variables
ENV PYTHONUNBUFFERED=1 \ ENV PYTHONUNBUFFERED=1 \
@@ -5,8 +5,8 @@ from pathlib import Path
from dotenv import load_dotenv from dotenv import load_dotenv
from shared.database import connect from shared.docstore import connect_mongodb
from shared.database.classes import VisualCommunication from shared.docstore.classes import VisualCommunication
if __name__ == '__main__': if __name__ == '__main__':
# prepare env vars # prepare env vars
@@ -15,7 +15,7 @@ if __name__ == '__main__':
load_dotenv(env_path) load_dotenv(env_path)
os.environ['MONGO_HOST'] = 'localhost' os.environ['MONGO_HOST'] = 'localhost'
# connect to database # connect to database
collection, db, client = connect() collection, db, client = connect_mongodb()
print(client.server_info()) print(client.server_info())
# download images # download images
data = None data = None

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

+9
View File
@@ -0,0 +1,9 @@
from shared.docstore.classes import ModelData
if __name__ == '__main__':
# instantiate data object
vis_com_list = [ModelData.from_random() for i in range(3)]
# generate random predictions
[vis_com.from_random() for vis_com in vis_com_list]
for vis_com in vis_com_list:
print(vis_com)
@@ -5,8 +5,7 @@ from pathlib import Path
from dotenv import load_dotenv from dotenv import load_dotenv
from shared.database import connect from shared.docstore import connect_mongodb, count_documents
from shared.database import count_documents
if __name__ == '__main__': if __name__ == '__main__':
# prepare env vars # prepare env vars
@@ -15,7 +14,7 @@ if __name__ == '__main__':
load_dotenv(env_path) load_dotenv(env_path)
os.environ['MONGO_HOST'] = 'localhost' os.environ['MONGO_HOST'] = 'localhost'
# connect to database # connect to database
collection, db, client = connect() collection, db, client = connect_mongodb()
# get visual communication # get visual communication
num_docs = count_documents( num_docs = count_documents(
collection=collection, collection=collection,
@@ -5,8 +5,7 @@ from pathlib import Path
from dotenv import load_dotenv from dotenv import load_dotenv
from shared.database import connect from shared.docstore import connect_mongodb, count_documents
from shared.database import count_documents
if __name__ == '__main__': if __name__ == '__main__':
# prepare env vars # prepare env vars
@@ -15,7 +14,7 @@ if __name__ == '__main__':
load_dotenv(env_path) load_dotenv(env_path)
os.environ['MONGO_HOST'] = 'localhost' os.environ['MONGO_HOST'] = 'localhost'
# connect to database # connect to database
collection, db, client = connect() collection, db, client = connect_mongodb()
# get visual communication # get visual communication
num_docs = count_documents( num_docs = count_documents(
collection=collection, collection=collection,
+5
View File
@@ -9,3 +9,8 @@ services:
- ../server.env - ../server.env
environment: environment:
- ENV=TEST - ENV=TEST
deploy:
resources:
limits:
cpus: '2.000'
memory: 8G
+14
View File
@@ -0,0 +1,14 @@
{
"datasets": {
"train": {
"filelist": "datasets/train.csv"
},
"val": {
"filelist": "datasets/val.csv"
}
},
"backbone": {
"class": "model.src.models.VisualCommunicationModel",
"model_name": "pretrained"
}
}
-5
View File
@@ -1,5 +0,0 @@
from __future__ import annotations
from .connect import connect
from .get import get
from .put import put
-30
View File
@@ -1,30 +0,0 @@
"""Definition of connect function."""
from __future__ import annotations
import os
from minio import Minio
def connect(
) -> Minio:
"""Connect to MinIO server"""
minio_endpoint = os.getenv('MINIO_ENDPOINT', default=None)
assert isinstance(minio_endpoint, str)
minio_access_key = os.getenv('MINIO_ACCESS_KEY', default=None)
assert isinstance(minio_access_key, str)
minio_secret_key = os.getenv('MINIO_SECRET_KEY', default=None)
assert isinstance(minio_secret_key, str)
minio_bucket_name = os.getenv('MINIO_BUCKET_NAME', default=None)
assert isinstance(minio_bucket_name, str)
# connect client
client = Minio(
endpoint=minio_endpoint,
access_key=minio_access_key,
secret_key=minio_secret_key,
secure=False,
)
# ensure bucket exists
if not client.bucket_exists(bucket_name=minio_bucket_name):
client.make_bucket(bucket_name=minio_bucket_name)
return client
-27
View File
@@ -1,27 +0,0 @@
"""Definition of get function."""
from __future__ import annotations
import os
from io import BytesIO
from minio import Minio
def get(
client: Minio,
object_name: str,
) -> BytesIO:
"""Get buffer from bucket in MinIO."""
assert isinstance(client, Minio)
assert isinstance(object_name, str)
bucket_name = os.getenv('MINIO_BUCKET_NAME', default=None)
assert isinstance(bucket_name, str)
# get buffer
try:
response = client.get_object(bucket_name, object_name)
buffer = BytesIO(response.data)
finally:
response.close()
response.release_conn()
buffer.seek(0)
return buffer
-30
View File
@@ -1,30 +0,0 @@
"""Definition of put function."""
from __future__ import annotations
import os
from io import BytesIO
from minio import Minio
def put(
client: Minio,
buffer: BytesIO,
object_name: str,
) -> None:
"""Put buffer in bucket in MinIO."""
assert isinstance(client, Minio)
assert isinstance(buffer, BytesIO)
assert isinstance(object_name, str)
bucket_name = os.getenv('MINIO_BUCKET_NAME', default=None)
assert isinstance(bucket_name, str)
# prepare for saving
num_bytes = buffer.tell()
buffer.seek(0)
# send data to bucket
client.put_object(
bucket_name=bucket_name,
object_name=object_name,
length=num_bytes,
data=buffer,
)
-146
View File
@@ -1,146 +0,0 @@
from __future__ import annotations
import random
from io import BytesIO
from torch import Tensor
from torch.utils.data import Dataset
from torchvision.io import read_image
from torchvision.transforms import ColorJitter
from torchvision.transforms import InterpolationMode
from torchvision.transforms import Normalize
from torchvision.transforms.functional import hflip
from torchvision.transforms.functional import pad
from torchvision.transforms.functional import resize
from torchvision.transforms.functional import rotate
from shared.database import connect
# resnet18 original normalization values
RESNET_NORMALIZE_MEAN = [0.485, 0.456, 0.406]
RESNET_NORMALIZE_STD = [0.229, 0.224, 0.225]
class VCDADataset(Dataset):
def __init__(
self,
data_name_list: list[str],
do_augment: bool = False,
random_annotations: bool = False,
normalize_mean: list[float] = RESNET_NORMALIZE_MEAN,
normalize_std: list[float] = RESNET_NORMALIZE_STD,
):
super().__init__()
self.data_name_list = data_name_list
self.do_augment = do_augment
self.random_annotations = random_annotations
self.normalize_mean = normalize_mean
self.normalize_std = normalize_std
# prepare augmentation functions
self.normalize = Normalize(
mean=normalize_mean,
std=normalize_std,
)
self.color_jitter = ColorJitter(
brightness=1e-1,
contrast=8e-2,
saturation=8e-2,
)
# connect to database
collection, _, _ = connect()
self.collection = collection
def __len__(self):
return len(self.data_name_list)
def __getitem__(self, idx):
# get image from database
name = self.data_name_list[idx]
query = {
'name': name,
}
projection = {
'_id': False,
'image': True,
}
img_bytes = self.collection.find_one(
filter=query,
projection=projection,
)
img = self.load_image(img_bytes)
if self.do_augment:
img = self.augment(img)
return img
def load_image(
self,
data: bytes,
) -> Tensor:
"""Load images tensor from bytes."""
assert isinstance(data, bytes)
img = read_image(BytesIO(data))
img /= 255 # normalize 8-bit image
img = self.square_pad(img)
img = resize(
img=img,
size=(512, 512),
interpolation=InterpolationMode.BICUBIC,
)
return img
@staticmethod
def square_pad(
img: Tensor,
) -> Tensor:
"""
Pads image to a square with side length
equal to the largest side of the input image.
"""
assert isinstance(img, Tensor)
# B, nc, w, h = img.shape
h = img.shape[-2]
w = img.shape[-1]
if h == w:
return img
max_wh = max([h, w])
hp = int((max_wh - w) / 2)
vp = int((max_wh - h) / 2)
padding = (hp, vp, hp, vp)
return pad(img, padding, 0, 'constant')
def augment(
self,
img: Tensor,
) -> Tensor:
"""
Augment image with random horizontal flips,
rotations and color jitter.
"""
assert isinstance(img, Tensor)
# left-right flip
if random.random() >= 0.5:
img = hflip(img)
# rotation
rnd = random.random()
if rnd < 0.25:
img = rotate(img, angle=90)
if rnd < 0.5:
img = rotate(img, angle=180)
if rnd < 0.75:
img = rotate(img, angle=270)
# color jitter
img = self.color_jitter(img)
return img
def reverse_normalise(
self,
img: Tensor,
) -> Tensor:
"""
Reverse normalization to get an image
that can be interpreted by humans.
"""
assert isinstance(img, Tensor)
img *= Tensor(self.normalize_std).reshape((3, 1, 1))
img += Tensor(self.normalize_mean).reshape((3, 1, 1))
return img
View File
View File
+30 -32
View File
@@ -1,45 +1,43 @@
"""Main script to be run by service.""" """Main script to be run by service."""
from __future__ import annotations
from hashlib import md5 import json
from io import BytesIO import logging
from traceback import print_exc
import torch import torch
from data_store import connect
from data_store import put
from models import VisualCommunicationModel from models import VisualCommunicationModel
from torchinfo import summary from tqdm import tqdm
from utils import check_env from utils import DEVICE, VCDADataset, load_model
from shared.utils import setup_logging from shared.utils import setup_logging
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if __name__ == '__main__': if __name__ == '__main__':
# check that environment variables are set
check_env()
# setup logging # setup logging
setup_logging() setup_logging()
# instantiate model # instantiate model
model = VisualCommunicationModel().to(DEVICE) model: VisualCommunicationModel = load_model()
# show model weights model.eval()
summary(model) # setup dataset
# for param in model.parameters(): dataset = VCDADataset(
# logging.info(param.data) data_name_list=[
# save model to buffer '02dbaf48d713e4e6d3a6b98fd2dc866e',
buffer = BytesIO() ],
torch.save(model.state_dict(), buffer) do_augment=False,
print(f"buffer size: {len(buffer.getvalue())}")
# calculate buffer hash
hash_str = md5(buffer.getbuffer()).hexdigest()
print(f"hash string: {hash_str}")
# connect to minio
client = connect()
# put buffer in minio bucket
put(
client=client,
buffer=buffer,
object_name=hash_str,
) )
print('saved to Minio')
# make prediction
with torch.no_grad():
for i in tqdm(range(len(dataset))):
try:
# get image
image = dataset[i]
image = torch.unsqueeze(image, 0) # add artificial batch dimension
image = image.to(DEVICE)
# make prediction
pred: dict = model(image)
except Exception:
print_exc()
continue
else:
print(json.dumps(pred, indent=4))
logging.debug('finished')
+1
View File
@@ -0,0 +1 @@
2bbe2be17a663f4299657378ac5e993e
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
+8 -10
View File
@@ -1,26 +1,24 @@
from __future__ import annotations from torch import nn
import torch.nn as nn
class FullyConnectedModel(nn.Module): class FullyConnectedModel(nn.Module):
"""Fully connected layers model template for intrepreting feature space-
output from ResNet18 head."""
def __init__(self, num_out_features: int): def __init__(self, num_out_features: int):
super().__init__() super().__init__()
# define layers # define layers
self.fc1 = nn.Linear(in_features=16*16*512, out_features=512) self.fc1 = nn.Linear(in_features=512, out_features=128)
self.af1 = nn.ReLU() self.af1 = nn.ReLU()
self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2 = nn.Linear(in_features=128, out_features=32)
self.af2 = nn.ReLU() self.af2 = nn.ReLU()
self.fc3 = nn.Linear(in_features=128, out_features=32) self.fc3 = nn.Linear(in_features=32, out_features=num_out_features)
self.af3 = nn.ReLU()
self.fc4 = nn.Linear(in_features=32, out_features=num_out_features)
def forward(self, x): def forward(self, x):
"""Pass input through model."""
x = self.fc1(x) x = self.fc1(x)
x = self.af1(x) x = self.af1(x)
x = self.fc2(x) x = self.fc2(x)
x = self.af2(x) x = self.af2(x)
x = self.fc3(x) x = self.fc3(x)
x = self.af3(x)
x = self.fc4(x)
return x return x
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
+7 -3
View File
@@ -5,11 +5,15 @@ import torchvision
class ResNet18Head(nn.Module): class ResNet18Head(nn.Module):
def __init__(self): def __init__(self, download_resnet_weights: bool = False):
super().__init__() super().__init__()
# copy out parts from ResNet18 with weights # copy out parts from ResNet18 with weights
if download_resnet_weights:
weights = torchvision.models.ResNet18_Weights.IMAGENET1K_V1
else:
weights = None
resnet18 = torchvision.models.resnet18( resnet18 = torchvision.models.resnet18(
weights=torchvision.models.ResNet18_Weights.IMAGENET1K_V1, weights=weights,
) )
# save relevant layers # save relevant layers
self.conv1 = resnet18.conv1 self.conv1 = resnet18.conv1
@@ -21,7 +25,7 @@ class ResNet18Head(nn.Module):
self.layer3 = resnet18.layer3 self.layer3 = resnet18.layer3
self.layer4 = resnet18.layer4 self.layer4 = resnet18.layer4
self.avgpool = resnet18.avgpool self.avgpool = resnet18.avgpool
self.flat = nn.Flatten() # size 512 self.flat = nn.Flatten() # size 512
def forward(self, x): def forward(self, x):
x = self.conv1(x) x = self.conv1(x)
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
+20 -84
View File
@@ -1,4 +1,5 @@
"""Definition of VisualCommunicationModel class.""" """Definition of VisualCommunicationModel class."""
from __future__ import annotations from __future__ import annotations
from torch import nn from torch import nn
@@ -15,26 +16,15 @@ from .point_of_view import PointOfViewTail
from .resnet18_head import ResNet18Head from .resnet18_head import ResNet18Head
from .salience import SalienceTail from .salience import SalienceTail
from .visual_syntax import VisualSyntaxTail from .visual_syntax import VisualSyntaxTail
from shared.dto import AngleData
from shared.dto import ContactData
from shared.dto import DistanceData
from shared.dto import FramingData
from shared.dto import InformationValueData
from shared.dto import ModalityColorData
from shared.dto import ModalityDepthData
from shared.dto import ModalityLightingData
from shared.dto import PointOfViewData
from shared.dto import SalienceData
from shared.dto import VisualSyntaxData
class VisualCommunicationModel(nn.Module): class VisualCommunicationModel(nn.Module):
"""Visual communication model.""" """Visual communication model."""
def __init__(self): def __init__(self, download_resnet_weights: bool = False):
super().__init__() super().__init__()
# store other models # store other models
self.resnet_head = ResNet18Head() self.resnet_head = ResNet18Head(download_resnet_weights)
self.visual_syntax_tail = VisualSyntaxTail() self.visual_syntax_tail = VisualSyntaxTail()
self.contact_tail = ContactTail() self.contact_tail = ContactTail()
self.angle_tail = AngleTail() self.angle_tail = AngleTail()
@@ -47,76 +37,22 @@ class VisualCommunicationModel(nn.Module):
self.framing_tail = FramingTail() self.framing_tail = FramingTail()
self.salience_tail = SalienceTail() self.salience_tail = SalienceTail()
def forward(self, x): def forward(self, x) -> dict:
"""Calculate model output on data.""" """Calculate model output on data."""
# generate visual representation # generate visual representation
vis_rep = self.resnet_head(x) features = self.resnet_head(x)
# prepare result map # make predictions
results = {} prediction_dict = {
# predict visual syntax 'visual_syntax': self.visual_syntax_tail(features),
results['visual_syntax'] = VisualSyntaxData.from_list( 'contact': self.contact_tail(features),
self.visual_syntax_tail( 'angle': self.angle_tail(features),
vis_rep, 'point_of_view': self.point_of_view_tail(features),
).cpu(), 'distance': self.distance_tail(features),
) 'modality_lighting': self.modality_lighting_tail(features),
# predict contact 'modality_color': self.modality_color_tail(features),
results['contact'] = ContactData.from_list( 'modality_depth': self.modality_depth_tail(features),
self.contact_tail( 'information_value': self.information_value_tail(features),
vis_rep, 'framing': self.framing_tail(features),
).cpu(), 'salience': self.salience_tail(features),
) }
# predict angle return prediction_dict
results['angle'] = AngleData.from_list(
self.angle_tail(
vis_rep,
).cpu(),
)
# predict point of view
results['point_of_view'] = PointOfViewData.from_list(
self.point_of_view_tail(
vis_rep,
).cpu(),
)
# predict distance
results['distance'] = DistanceData.from_list(
self.distance_tail(
vis_rep,
).cpu(),
)
# predict modality lighting
results['modality_lighting'] = ModalityLightingData.from_list(
self.modality_lighting_tail(
vis_rep,
).cpu(),
)
# predict modality color
results['modality_color'] = ModalityColorData.from_list(
self.modality_color_tail(
vis_rep,
).cpu(),
)
# predict modality depth
results['modality_depth'] = ModalityDepthData.from_list(
self.modality_depth_tail(
vis_rep,
).cpu(),
)
# predict information value
results['information_value'] = InformationValueData.from_list(
self.information_value_tail(
vis_rep,
).cpu(),
)
# predict framing
results['framing'] = FramingData.from_list(
self.framing_tail(
vis_rep,
).cpu(),
)
# predict salience
results['salience'] = SalienceData.from_list(
self.salience_tail(
vis_rep,
).cpu(),
)
return results
-2
View File
@@ -1,5 +1,3 @@
from __future__ import annotations
from .fully_connected import FullyConnectedModel from .fully_connected import FullyConnectedModel
+3 -3
View File
@@ -1,3 +1,3 @@
from __future__ import annotations from .get_class import get_class
from .load_model import DEVICE, load_model
from .check_env import check_env from .vcda_dataset import VCDADataset
-25
View File
@@ -1,25 +0,0 @@
"""Definition of check_env function."""
from __future__ import annotations
import os
def check_env() -> None:
"""Check necessary environment variables are set."""
necesasary_var_list = {
'MONGO_HOST',
'MONGO_DB',
'MONGO_COLLECTION',
'MONGO_USER',
'MONGO_PASSWORD',
'MINIO_ENDPOINT',
'MINIO_ACCESS_KEY',
'MINIO_SECRET_KEY',
}
for env_var in necesasary_var_list:
# ensure env var set
assert (
env_var in os.environ
), (
f"environment variable not set: {env_var}"
)
+11
View File
@@ -0,0 +1,11 @@
from importlib import import_module
from torch.nn import Module
def get_class(path: str) -> Module:
parts = path.split('.')
module_path = '.'.join(parts[:-1])
class_name = parts[-1]
module = import_module(module_path)
return getattr(module, class_name)
+19
View File
@@ -0,0 +1,19 @@
"""Definition of get_model_name function."""
import logging
from pathlib import Path
def get_model_name(
path: Path,
) -> str:
"""Get model name from model_name file."""
assert isinstance(path, Path)
assert path.exists(), f'{path} does not exist'
# read file contents
with open(file=path, encoding='utf-8') as fh:
model_name = fh.read()
# remove newline character
model_name = model_name.strip()
logging.debug('finished')
return model_name
+37
View File
@@ -0,0 +1,37 @@
"""Definition of load_model function."""
import logging
from pathlib import Path
import torch
from model.src.models import VisualCommunicationModel
from shared.repositories import ModelRepository
from .get_model_name import get_model_name
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def load_model() -> VisualCommunicationModel:
"""Instantiate model with weights loaded from latest model saved in
MinIO."""
# instantiate model
model = VisualCommunicationModel()
# get model object name
model_name_path = Path('model_name.txt')
model_object_name = get_model_name(path=model_name_path)
logging.info('using model: %s', model_object_name)
# load model data
with ModelRepository() as repo:
model_data = repo.get_data(model_object_name)
if model_data is None:
raise FileNotFoundError(f'model {model_object_name} not found')
model_checkpoint = torch.load(model_data.buffer)
model.load_state_dict(model_checkpoint)
# clean memory
model_checkpoint.clear()
# move model to selected device
model = model.to(DEVICE)
logging.debug('finished')
return model
@@ -6,7 +6,7 @@ import torch
import torch.nn as nn import torch.nn as nn
from dataloader import VCDADataset # noqa: F401 from dataloader import VCDADataset # noqa: F401
from .models import VisualCommunicationModel from ..models import VisualCommunicationModel
PRE_WARMUP_LR = 1e-10 PRE_WARMUP_LR = 1e-10
POST_WARMUP_LR = 1e-5 POST_WARMUP_LR = 1e-5
+134
View File
@@ -0,0 +1,134 @@
"""Definition of Visual Critial Discourse Analysis dataloader."""
import random
from PIL import Image
from torch import Tensor
from torch.utils.data import Dataset
from torchvision.transforms import ColorJitter, InterpolationMode, Normalize
from torchvision.transforms.functional import (
hflip,
pad,
resize,
rotate,
to_pil_image,
to_tensor,
)
from shared.repositories import ImageRepository
# resnet18 original normalization values
RESNET_NORMALIZE_MEAN = [0.485, 0.456, 0.406]
RESNET_NORMALIZE_STD = [0.229, 0.224, 0.225]
class VCDADataset(Dataset):
"""VCDA dataset class."""
def __init__(
self,
data_name_list: list[str],
do_augment: bool = False,
random_annotations: bool = False,
):
super().__init__()
self.data_name_list = data_name_list
self.do_augment = do_augment
self.random_annotations = random_annotations
self.normalize_mean = RESNET_NORMALIZE_MEAN
self.normalize_std = RESNET_NORMALIZE_STD
# prepare augmentation functions
self.normalize = Normalize(
mean=self.normalize_mean,
std=self.normalize_std,
)
self.color_jitter = ColorJitter(
brightness=1e-1,
contrast=8e-2,
saturation=8e-2,
)
def __len__(self):
return len(self.data_name_list)
def __getitem__(self, idx):
# get image from database
image_name = self.data_name_list[idx]
with ImageRepository() as repo:
image_data = repo.get_data(image_name)
assert image_data is not None
tensor = self.image_to_tensor(image_data.image)
if self.do_augment:
tensor = self.augment(tensor)
return tensor
def image_to_tensor(
self,
image: Image.Image,
) -> Tensor:
"""Load images tensor from bytes."""
tensor = to_tensor(image)
tensor /= 255 # normalize 8-bit image
tensor = self.square_pad(tensor=tensor)
tensor = resize(
img=tensor,
size=(512, 512),
interpolation=InterpolationMode.BICUBIC,
)
return tensor
@staticmethod
def square_pad(
tensor: Tensor,
) -> Tensor:
"""Pads image to a square with side length equal to the largest side of
the input image."""
assert isinstance(tensor, Tensor)
# B, nc, w, h = img.shape
h = tensor.shape[-2]
w = tensor.shape[-1]
if h == w:
return tensor
max_wh = max([h, w])
hp = int((max_wh - w) / 2)
vp = int((max_wh - h) / 2)
padding = (hp, vp, hp, vp)
tensor = pad(tensor, padding, 0, 'constant')
return tensor
def augment(
self,
tensor: Tensor,
) -> Tensor:
"""Augment image with random horizontal flips, rotations and color
jitter."""
assert isinstance(tensor, Tensor)
# left-right flip
if random.random() >= 0.5:
tensor = hflip(tensor)
# rotation
rnd = random.random()
if rnd < 0.25:
tensor = rotate(tensor, angle=90)
if rnd < 0.5:
tensor = rotate(tensor, angle=180)
if rnd < 0.75:
tensor = rotate(tensor, angle=270)
# color jitter
tensor = self.color_jitter(tensor)
return tensor
def reverse_normalise(
self,
tensor: Tensor,
) -> Image.Image:
"""Reverse normalization to get an image that can be interpreted by
humans."""
assert isinstance(tensor, Tensor)
tensor *= Tensor(self.normalize_std).reshape((3, 1, 1))
tensor += Tensor(self.normalize_mean).reshape((3, 1, 1))
image = to_pil_image(
pic=tensor,
mode='RGB',
)
return image
+163
View File
@@ -0,0 +1,163 @@
import json
import os
from argparse import ArgumentParser
from datetime import datetime, timezone
from pathlib import Path
import torch
from dotenv import load_dotenv
from ignite.engine import Events, create_supervised_evaluator, create_supervised_trainer
from ignite.handlers import global_step_from_engine
from ignite.handlers.checkpoint import Checkpoint
from ignite.handlers.param_scheduler import create_lr_scheduler_with_warmup
from ignite.handlers.tensorboard_logger import TensorboardLogger
from ignite.handlers.tqdm_logger import ProgressBar
from ignite.metrics import Average, Loss, RunningAverage
from torch import nn
from torch.optim.lr_scheduler import ExponentialLR
from torch.utils.data import DataLoader
from model.src.utils import VCDADataset, get_class
def parse_arguments():
parser = ArgumentParser()
parser.add_argument('-c', '--config', type=Path, required=True)
parser.add_argument('-d', '--device', type=str, default='cpu')
parser.add_argument('-b', '--batch-size', type=int, default=32)
parser.add_argument('--epochs', type=int, default=50)
parser.add_argument('--epoch-length', type=int, default=128)
parser.add_argument('--checkpoint', type=Path)
parser.add_argument('--lr', type=float, default=1e-5)
parser.add_argument('--lr-gamma', type=float, default=0.95)
parser.add_argument('--lr-warmup-start', type=float, default=1e-8)
parser.add_argument('--lr-warmup-duration', type=int, default=5)
parser.add_argument('--train-seed', type=int, default=1312)
parser.add_argument('--val-seed', type=int, default=1313)
parser.add_argument('--loader-workers', type=int, default=8)
return parser.parse_args()
args = parse_arguments()
load_dotenv('server.env')
# read model config
with open(args.config) as fh:
config = json.load(fh)
model_name = args.config.stem
run_name = datetime.now(timezone.utc).strftime('%Y-%m-%d-%H%M') + '_' + model_name
device = torch.device(args.device)
# create model
model_class = get_class(config['backbone']['class'])
model = model_class().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
loss_fn = nn.CrossEntropyLoss()
# create datasets and loaders
with open('model/src/dataset/train.csv', encoding='utf-8') as fh:
train_data_name_list = fh.read().split('\n')
train_dataset = VCDADataset(
data_name_list=train_data_name_list,
)
train_loader = DataLoader(dataset=train_dataset, num_workers=args.loader_workers)
with open('model/src/dataset/val.csv', encoding='utf-8') as fh:
val_data_name_list = fh.read().split('\n')
val_dataset = VCDADataset(data_name_list=val_data_name_list)
val_loader = DataLoader(dataset=val_dataset, num_workers=args.loader_workers)
# create trainer and evaluator
trainer = create_supervised_trainer(
model=model,
optimizer=optimizer,
loss_fn=loss_fn,
device=device,
)
Average(output_transform=lambda x: x).attach(trainer, name='loss')
RunningAverage(output_transform=lambda x: x, alpha=0.5).attach(
trainer,
'running_avg_loss',
)
ProgressBar(desc='Train', ncols=80).attach(trainer, ['running_avg_loss'])
val_metrics = {
'loss': Loss(loss_fn=loss_fn, device=device),
}
evaluator = create_supervised_evaluator(
model=model,
metrics=val_metrics, # type: ignore
device=device,
)
ProgressBar(desc='Val', ncols=80).attach(evaluator)
# create lr scheduler
lr_scheduler = ExponentialLR(
optimizer=optimizer,
gamma=args.lr_gamma,
)
lr_handler = create_lr_scheduler_with_warmup(
lr_scheduler=lr_scheduler,
warmup_start_value=args.lr_warmup_start,
warmup_duration=args.lr_warmup_duration,
warmup_end_value=args.lr,
)
trainer.add_event_handler(Events.EPOCH_STARTED, lr_handler)
# log metrics to TensorBoard
@trainer.on(Events.EPOCH_COMPLETED)
def evaluate():
evaluator.run(val_loader, epoch_length=args.val_epoch_length)
tb_logger = TensorboardLogger(log_dir=f'runs/logs/{run_name}')
tb_logger.attach_opt_params_handler(
engine=trainer,
event_name=Events.EPOCH_COMPLETED,
optimizer=optimizer,
)
for tag, engine in [('train', trainer), ('val', evaluator)]:
tb_logger.attach_output_handler(
engine,
event_name=Events.EPOCH_COMPLETED,
tag=tag,
metric_names='all',
global_step_transform=global_step_from_engine(trainer),
)
# Set up checkpoint saving
to_save = {
'model': model,
'optimizer': optimizer,
'trainer': trainer,
'lr_scheduler': lr_scheduler,
'lr_handler': lr_handler,
}
checkpoint_handler = Checkpoint(
to_save,
f'runs/checkpoints/{run_name}',
n_saved=3,
filename_prefix='best',
score_function=lambda engine: -engine.state.metrics['loss'],
score_name='neg_val_loss',
global_step_transform=global_step_from_engine(trainer),
)
evaluator.add_event_handler(Events.COMPLETED, checkpoint_handler)
if args.checkpoint:
Checkpoint.load_objects(to_load=to_save, checkpoint=str(args.checkpoint))
# save model config
os.makedirs('runs/configs/', exist_ok=True)
with open(f'runs/configs/{run_name}.json', 'w', encoding='utf-8') as fh:
json.dump(config, fh)
# start training
trainer.run(
train_loader,
max_epochs=args.epochs,
epoch_length=args.epoch_length,
)
tb_logger.close()
+124
View File
@@ -0,0 +1,124 @@
"""Script to move all images from MongoDB to MinIO."""
from __future__ import annotations
import logging
from pathlib import Path
from bson import ObjectId
from dotenv import load_dotenv
from pymongo.collection import Collection
from shared.datastore import Datastore
from shared.docstore import connect_mongodb
from shared.docstore.src.classes import VisualCommunication
from shared.utils import check_env, setup_logging
from web_ui.src.main import NECESSARY_ENV_VAR_LIST
def list_mongo_document_ids(
collection: Collection,
) -> list[ObjectId]:
"""Get list of all VisualCommunication documents in MongoDB."""
# prepare query
query = collection.find(
filter={},
projection={'_id': True},
)
# execute query
res_list = list(query)
logging.debug('got %s document(s)', len(res_list))
# convert result
id_list = [elem['_id'] for elem in res_list]
return id_list
def get_visual_communication(
collection: Collection,
doc_id: ObjectId,
) -> VisualCommunication:
"""Get image from MongoDB."""
# prepare query
query = collection.find(
filter={'_id': doc_id},
projection={'_id': False},
)
# execute query
res_list = list(query)
logging.debug('got %s document(s)', len(res_list))
# convert result
vis_com = VisualCommunication.model_validate(res_list[0])
return vis_com
def update_visual_communication(
collection: Collection,
vis_com: VisualCommunication,
) -> None:
"""Update VisualCommunication document in MongoDB."""
try:
collection.update_one(
filter={
'name': vis_com.name,
},
update={
'$set': vis_com.model_dump(),
},
)
except Exception as exc:
logging.error('failed saving %s', vis_com.name)
logging.debug(exc)
raise exc
if __name__ == '__main__':
# load in env file
env_path = Path(__file__).parent.parent / 'server.env'
assert env_path.exists()
load_dotenv(env_path)
# ensure env vars set
check_env(NECESSARY_ENV_VAR_LIST)
# setup logging
setup_logging()
# connect to minIO
datastore = Datastore()
datastore.connect()
assert datastore._client is not None
# connect to MongoDB
collection, db, client = connect_mongodb()
# list documents in mongoDB
id_list = list_mongo_document_ids(collection)
for doc_id in id_list:
try:
# get image from MongoDB
vis_com = get_visual_communication(collection, doc_id)
except Exception as exc:
logging.debug(exc)
logging.error('failed getting image from document: %s', doc_id)
continue
try:
# get image
image = vis_com.get_image(
minio_client=datastore._client,
)
# put buffer in minio
object_name = datastore.put_image(
image=image,
)
except Exception as exc:
logging.debug(exc)
logging.error('failed saving image to minio')
continue
# update visual communication in mongodb
try:
vis_com.image = None # type: ignore
vis_com.object_name = object_name
update_visual_communication(collection, vis_com)
except Exception as exc:
logging.debug(exc)
logging.error(
'failed updating visual communication %s',
vis_com.name,
)
continue
logging.debug('updated visual communication %s', vis_com.name)
Generated
+1898 -797
View File
File diff suppressed because it is too large Load Diff
+20 -2
View File
@@ -20,6 +20,11 @@ types-requests = "^2.32.0.20240602"
types-retry = "^0.9.9.4" types-retry = "^0.9.9.4"
flake8-pyproject = "^1.2.3" flake8-pyproject = "^1.2.3"
pandas-stubs = "^2.2.2.240603" pandas-stubs = "^2.2.2.240603"
types-tqdm = "^4.66.0.20240417"
pytest = "^8.3.3"
testcontainers = "^4.8.2"
coverage = "^7.6.4"
pytest-cov = "^6.0.0"
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]
@@ -27,13 +32,17 @@ pandas = "^2.2.1"
selenium = "^4.18.1" selenium = "^4.18.1"
webdriver-manager = "^4.0.1" webdriver-manager = "^4.0.1"
retry = "^0.9.2" retry = "^0.9.2"
pre-commit = "^4.1.0"
[tool.poetry.group.model.dependencies] [tool.poetry.group.model.dependencies]
torch = "^2.2.1" torch = "^2.0.0"
torchvision = "^0.17.1" torchvision = "^0.17.1"
torchinfo = "^1.8.0" torchinfo = "^1.8.0"
minio = "^7.2.7" minio = "^7.2.7"
tqdm = "^4.66.4"
pytorch-ignite = "^0.5.1"
tensorboard = "^2.17.1"
[tool.poetry.group.shared.dependencies] [tool.poetry.group.shared.dependencies]
@@ -59,8 +68,13 @@ priority = "primary"
requires = ["poetry-core"] requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api" build-backend = "poetry.core.masonry.api"
[tool.isort]
profile = "black"
[tool.flake8] [tool.flake8]
per-file-ignores = "__init__.py:F401" per-file-ignores = "__init__.py:F401"
max-line-length = 88
extend-ignore = "E203"
[tool.mypy] [tool.mypy]
exclude = "image_download" exclude = "image_download"
@@ -98,9 +112,13 @@ module = "utils.*"
ignore_missing_imports = true ignore_missing_imports = true
[[tool.mypy.overrides]] [[tool.mypy.overrides]]
module = "data_store.*" module = "shared.datastore.*"
ignore_missing_imports = true ignore_missing_imports = true
[[tool.mypy.overrides]] [[tool.mypy.overrides]]
module = "models.*" module = "models.*"
ignore_missing_imports = true ignore_missing_imports = true
[[tool.mypy.overrides]]
module = "shared.docstore.*"
ignore_missing_imports = true
-13
View File
@@ -1,13 +0,0 @@
"""Database module content."""
from __future__ import annotations
from .classes.dataset import Dataset
from .classes.exceptions import NoDocumentFoundException
from .classes.visual_communication import VisualCommunication
from .utils.connect import connect
from .utils.count_documents import count_documents
from .utils.get_visual_communication import get_visual_communication
from .utils.list_names import list_names
from .utils.upsert_annotation import upsert_annotation
from .utils.upsert_prediction import upsert_prediction
from .utils.upsert_visual_communication import upsert_visual_communication
-6
View File
@@ -1,6 +0,0 @@
"""Database classes module content."""
from __future__ import annotations
from .dataset import Dataset
from .exceptions import NoDocumentFoundException
from .visual_communication import VisualCommunication
-71
View File
@@ -1,71 +0,0 @@
"""Definition of database Dataset class."""
from __future__ import annotations
import logging
import random
from datetime import datetime
from datetime import UTC
from pydantic import BaseModel
from pydantic import Field
from pymongo.collection import Collection
class Dataset(BaseModel):
"""Database Dataset model."""
create_time: datetime = Field(default_factory=lambda: datetime.now(UTC))
train_names: list[str]
test_names: list[str]
validation_names: list[str]
@classmethod
def fraction_map(cls) -> dict[str, float]:
"""Dict with train, test and validation fractions."""
# define map
split_map = {
'train': 0.7,
'test': 0.2,
'validation': 0.1,
}
# sanity check
assert sum(split_map.values()) == 1.0
return split_map
@classmethod
def new_from_name_list(
cls,
name_list: list[str],
) -> Dataset:
"""Generate new dataset from list of filenames."""
# calculate split fractions
fraction_map = cls.fraction_map()
num_total = len(name_list)
num_validation = round(num_total * fraction_map['validation'])
num_test = round(num_total * fraction_map['test'])
# split data
validation_name_list = random.choices(name_list, k=num_validation)
name_list = [
name for name in name_list if name not in validation_name_list
]
test_name_list = random.choices(name_list, k=num_test)
train_name_list = [
name for name in name_list if name not in test_name_list
]
# instantiate object
dataset = Dataset(
train_names=train_name_list,
test_names=test_name_list,
validation_names=validation_name_list,
)
logging.debug('finished')
return dataset
def save(
self,
collection: Collection,
) -> None:
"""Save dataset to database."""
res = collection.insert_one(
document=self.model_dump(),
)
logging.debug('inserted document: %s', res)
-6
View File
@@ -1,6 +0,0 @@
"""Definition of database exception."""
from __future__ import annotations
class NoDocumentFoundException(Exception):
"""Database exception for when no documents are found."""
@@ -1,85 +0,0 @@
"""Definition of VisualCommunication model."""
from __future__ import annotations
import logging
from base64 import b64decode
from base64 import b64encode
from io import BytesIO
from pathlib import Path
from PIL import Image
from pydantic import BaseModel
from pydantic import field_serializer
from pydantic import field_validator
from shared.dto import ModelData
class VisualCommunication(BaseModel):
"""Visual communication model."""
name: str
image: Image.Image
annotation: ModelData | None = None
prediction: ModelData | None = None
class Config:
"""BaseModel configuration."""
arbitrary_types_allowed = True
@classmethod
def classname(cls) -> str:
"""Return classname."""
return cls.__name__
@classmethod
def from_file(cls, path: Path) -> VisualCommunication:
"""Instantiate from file."""
name = path.stem
image = Image.open(path)
image.load()
return VisualCommunication(name=name, image=image)
@classmethod
def decode_image(cls, content: str) -> Image.Image:
"""Extract image from webencoded content."""
_, content_data = content.split(',')
return Image.open(BytesIO(b64decode(content_data)))
@field_serializer('image')
@classmethod
def serialize_image(cls, image: Image.Image) -> bytes: # type: ignore
"""Convert image to bytes for storage in database."""
buffer = BytesIO()
image.save(buffer, format='JPEG')
return buffer.getvalue()
@field_validator('image', mode='before')
@classmethod
def convert_to_image(
cls,
image: Image.Image | BytesIO | bytes,
) -> Image.Image:
"""Convert bytes input from database into image."""
if isinstance(image, bytes):
image = BytesIO(image)
if isinstance(image, BytesIO):
image = Image.open(image)
return image
def __repr__(self) -> str:
return f"{self.classname()}(name='{self.name}')"
def webencoded_image(self) -> str:
"""Convert image to be displayed on webpage."""
# convert images to bytes string
buffer = BytesIO()
self.image.save(buffer, format='png')
img_enc = b64encode(buffer.getvalue()).decode('utf-8')
return f"data:image/png;base64, {img_enc}"
def generate_random_prediction(self, force: bool = False) -> None:
"""Generate random prediction values."""
if not force and self.prediction is not None:
logging.warning('set force=True to overwrite existing values.')
self.prediction = ModelData.from_random()
-4
View File
@@ -1,4 +0,0 @@
"""Database utils module content."""
from __future__ import annotations
from .connect import connect
-33
View File
@@ -1,33 +0,0 @@
"""
Definition of function to connect to database
using environment variables.
"""
from __future__ import annotations
import logging
import os
from dotenv import load_dotenv
from pymongo import MongoClient
def connect():
"""Connect to MongoDB using env vars."""
# load env vars
load_dotenv()
necessary_env_vars = [
'MONGO_HOST',
'MONGO_DB',
'MONGO_COLLECTION',
]
for env_var in necessary_env_vars:
assert env_var in os.environ, f"{env_var} not found"
# connect to database
client = MongoClient(os.getenv('MONGO_HOST'))
db = client[os.getenv('MONGO_DB')]
# extract collection
collection = db[os.getenv('MONGO_COLLECTION')]
# set unique index on "name"
collection.create_index('name', unique=True)
logging.debug('finished')
return collection, db, client
-21
View File
@@ -1,21 +0,0 @@
"""Definition of function to count documents in database."""
from __future__ import annotations
from pymongo.collection import Collection
def count_documents(
collection: Collection,
only_with_annotation: bool = False,
) -> int:
"""
Get the total number of documents
in database that matches the filters.
"""
assert isinstance(collection, Collection)
assert isinstance(only_with_annotation, bool)
# build query
query = {}
if only_with_annotation:
query['annotation'] = {'$ne': None}
return collection.count_documents(filter=query)
-13
View File
@@ -1,13 +0,0 @@
from __future__ import annotations
from typing import Literal
from pymongo.collection import Collection
def get_dataset(
collection: Collection,
type: Literal['train', 'test', 'validation'],
) -> list[str]:
"""Get list of data names for the corresponding type."""
return []
@@ -1,39 +0,0 @@
"""Definition of function to get visual communication from database."""
from __future__ import annotations
import logging
from pymongo.collection import Collection
from shared.database import NoDocumentFoundException
from shared.database import VisualCommunication
def get_visual_communication(
collection: Collection,
with_annotation: bool = False,
) -> VisualCommunication:
"""Get a random visual communication from the database."""
query = {}
if with_annotation:
query['annotation'] = {'$ne': None}
else:
query['annotation'] = {'$eq': None}
data = collection.aggregate(
pipeline=[
{
'$match': query, # find using filters
},
{
'$sample': {
'size': 1, # get one random
},
},
],
)
data_list = list(data) # read data from cursor object
if len(data_list) == 0:
raise NoDocumentFoundException()
vis_com = VisualCommunication.model_validate(data_list[0])
logging.debug('finished')
return vis_com
-31
View File
@@ -1,31 +0,0 @@
"""
Definition of function to list names
of all visual communication documents in database.
"""
from __future__ import annotations
from pymongo.collection import Collection
def list_names(
collection: Collection,
only_with_annotation: bool = True,
) -> list[str]:
"""List the names of entries that match the filters."""
assert isinstance(collection, Collection)
assert isinstance(only_with_annotation, bool)
# build query
query = {}
if only_with_annotation:
query['annotation'] = {'$ne': None}
# execute query
res_list = collection.find(
filter=query,
projection={
'_id': False,
'name': True,
},
)
# extract information
name_list = [elem['name'] for elem in res_list]
return name_list
-36
View File
@@ -1,36 +0,0 @@
from __future__ import annotations
import logging
from pymongo.collection import Collection
from shared.database import Dataset
def save_dataset(
collection: Collection,
dataset: Dataset,
) -> None:
"""Save dataset to database."""
res = collection.insert_one(
document=dataset.model_dump(),
)
logging.debug('inserted document: %s', res)
if __name__ == '__main__':
from dotenv import load_dotenv
load_dotenv('local.env')
from shared.database import list_names, connect
# connect to database
collection, db, client = connect()
print(client.server_info())
name_list = list_names(collection=collection, only_with_annotation=True)
ds = Dataset.new_from_name_list(name_list=name_list)
print(ds)
# save_dataset(
# collection=collection,
# dataset=ds
# )
@@ -1,30 +0,0 @@
from __future__ import annotations
import logging
from pymongo.collection import Collection
from shared.dto import ModelData
def upsert_annotation(
collection: Collection,
vis_com_name: str,
annotations: ModelData,
) -> None:
"""Upserts annotation data in the database."""
query = {
'name': vis_com_name,
}
update = {
'$set': {
'annotation': annotations.model_dump(),
},
}
res = collection.update_one(
filter=query,
update=update,
upsert=True,
)
logging.info('upserted document: %s', res)
logging.info('finished')
@@ -1,30 +0,0 @@
from __future__ import annotations
import logging
from pymongo.collection import Collection
from shared.dto import ModelData
def upsert_prediction(
collection: Collection,
vis_com_name: str,
predictions: ModelData,
) -> None:
"""Upsert prediction data in the database."""
query = {
'name': vis_com_name,
}
update = {
'$set': {
'prediction': predictions.model_dump(),
},
}
res = collection.update_one(
filter=query,
update=update,
upsert=True,
)
logging.debug('upserted document: %s', res)
logging.info('finished')
@@ -1,23 +0,0 @@
from __future__ import annotations
from pymongo.collection import Collection
from shared.database import VisualCommunication
def upsert_visual_communication(
collection: Collection,
visual_communication_list: list[VisualCommunication],
) -> bool:
"""
Upsert VisualCommunication object in the database.
Returns bool stating success.
"""
response = collection.insert_many(
[
vis_com.model_dump()
for vis_com
in visual_communication_list
],
)
return response.acknowledged
-15
View File
@@ -1,15 +0,0 @@
"""Data transfer objects module content."""
from __future__ import annotations
from .angle import AngleData
from .contact import ContactData
from .distance import DistanceData
from .framing import FramingData
from .information_value import InformationValueData
from .modality_color import ModalityColorData
from .modality_depth import ModalityDepthData
from .modality_lighting import ModalityLightingData
from .model_data import ModelData
from .point_of_view import PointOfViewData
from .salience import SalienceData
from .visual_syntax import VisualSyntaxData
-11
View File
@@ -1,11 +0,0 @@
"""Definition of Angle data model."""
from __future__ import annotations
from .data_model import DataModel
class AngleData(DataModel):
"""Angle data model."""
high: float
eye_level: float
low: float
-11
View File
@@ -1,11 +0,0 @@
"""Definition of ContactData data model."""
from __future__ import annotations
from .data_model import DataModel
class ContactData(DataModel):
"""ContactData data model."""
offer: float
demand: float
-67
View File
@@ -1,67 +0,0 @@
"""Definition of DataModel base class."""
from __future__ import annotations
import random
from pydantic import BaseModel
from pydantic import ValidationError
class DataModel(BaseModel):
"""DataModel base class."""
@classmethod
def classname(cls) -> str:
"""Return classname."""
return cls.__name__
@classmethod
def list_fields(cls) -> list[str]:
"""List options that are stored as attributes."""
return list(cls.model_fields.keys())
@classmethod
def from_random(cls):
"""Instantiate with random numbers."""
kwargs = {field: random.random() for field in cls.list_fields()}
return cls(**kwargs)
@classmethod
def from_choice(cls, option: str):
"""Instantiate from choice."""
if option is None:
raise ValidationError()
assert isinstance(option, str), 'option is not a string'
allowed_options_list = cls.list_fields()
assert option in allowed_options_list, \
f"{option} is not among allowed fields {allowed_options_list}"
kwargs = {field: 0 for field in cls.list_fields()}
kwargs[option] = 1
return cls(**kwargs)
@classmethod
def from_list(cls, data_list: list[float]):
"""Instantiate from list of values."""
kwargs = {key: val for key, val in zip(cls.list_fields(), data_list)}
return cls(**kwargs)
def __repr__(self) -> str:
model_dict = self.model_dump()
model_repr_str = f"{self.classname()}("
model_repr_str += ', '.join([
f"{field}={value:.3f}"
for field, value
in model_dict.items()
])
model_repr_str += ')'
return model_repr_str
def highest_score_field(self) -> str:
"""Return name of field with highest score."""
model_dict = self.model_dump()
return max(model_dict, key=lambda k: model_dict[k])
def highest_score_value(self) -> float:
"""Return value of field with highest score."""
model_dict = self.model_dump()
return max(model_dict.values())
-12
View File
@@ -1,12 +0,0 @@
"""Definition of DistanceData data model."""
from __future__ import annotations
from .data_model import DataModel
class DistanceData(DataModel):
"""DistanceData data model."""
long: float
medium: float
close: float
-13
View File
@@ -1,13 +0,0 @@
"""Definition of FramingData data model."""
from __future__ import annotations
from .data_model import DataModel
class FramingData(DataModel):
"""FramingData data model."""
frame_lines: float
empty_space: float
colour_contrast: float
form_contrast: float
-12
View File
@@ -1,12 +0,0 @@
"""Definition of InformationValueData data model."""
from __future__ import annotations
from .data_model import DataModel
class InformationValueData(DataModel):
"""InformationValueData data model."""
given_new: float
ideal_real: float
central_marginal: float
-12
View File
@@ -1,12 +0,0 @@
"""Definition of ModalityColorData data model."""
from __future__ import annotations
from .data_model import DataModel
class ModalityColorData(DataModel):
"""ModalityColorData data model."""
high: float
medium: float
low: float
-12
View File
@@ -1,12 +0,0 @@
"""Definition of ModalityDepthData data model."""
from __future__ import annotations
from .data_model import DataModel
class ModalityDepthData(DataModel):
"""ModalityDepthData data model."""
high: float
medium: float
low: float
-12
View File
@@ -1,12 +0,0 @@
"""Definition of ModalityLightingData data model."""
from __future__ import annotations
from .data_model import DataModel
class ModalityLightingData(DataModel):
"""ModalityLightingData data model."""
high: float
medium: float
low: float
-82
View File
@@ -1,82 +0,0 @@
"""Definition of ModelData data model."""
from __future__ import annotations
from .angle import AngleData
from .contact import ContactData
from .data_model import DataModel
from .distance import DistanceData
from .framing import FramingData
from .information_value import InformationValueData
from .modality_color import ModalityColorData
from .modality_depth import ModalityDepthData
from .modality_lighting import ModalityLightingData
from .point_of_view import PointOfViewData
from .salience import SalienceData
from .visual_syntax import VisualSyntaxData
class ModelData(DataModel):
"""ModelData model for data IO with combined ML model."""
visual_syntax: VisualSyntaxData
contact: ContactData
angle: AngleData
point_of_view: PointOfViewData
distance: DistanceData
modality_lighting: ModalityLightingData
modality_color: ModalityColorData
modality_depth: ModalityDepthData
information_value: InformationValueData
framing: FramingData
salience: SalienceData
@classmethod
def from_random(cls) -> ModelData:
"""Instantiate with random numbers."""
kwargs = {
field: field_info.annotation.from_random() # type: ignore
for field, field_info
in cls.model_fields.items()
}
return cls(**kwargs)
@classmethod
def from_annotations(
cls,
visual_syntax: str,
contact: str,
angle: str,
point_of_view: str,
distance: str,
modality_lighting: str,
modality_color: str,
modality_depth: str,
information_value: str,
framing: str,
salience: str,
) -> ModelData:
"""Instantiate from annotation."""
kwargs = {
'visual_syntax': VisualSyntaxData
.from_choice(visual_syntax),
'contact': ContactData
.from_choice(contact),
'angle': AngleData
.from_choice(angle),
'point_of_view': PointOfViewData
.from_choice(point_of_view),
'distance': DistanceData
.from_choice(distance),
'modality_lighting': ModalityLightingData
.from_choice(modality_lighting),
'modality_color': ModalityColorData
.from_choice(modality_color),
'modality_depth': ModalityDepthData
.from_choice(modality_depth),
'information_value': InformationValueData
.from_choice(information_value),
'framing': FramingData
.from_choice(framing),
'salience': SalienceData
.from_choice(salience),
}
return cls(**kwargs)
-11
View File
@@ -1,11 +0,0 @@
"""Definition of PointOfViewData data model."""
from __future__ import annotations
from .data_model import DataModel
class PointOfViewData(DataModel):
"""PointOfViewData data model."""
frontal: float
oblique: float
-14
View File
@@ -1,14 +0,0 @@
"""Definition of SalienceData data model."""
from __future__ import annotations
from .data_model import DataModel
class SalienceData(DataModel):
"""SalienceData data model."""
size: float
colour: float
tone: float
form: float
positioning: float
+8
View File
@@ -0,0 +1,8 @@
from .src import ImageRepository, ModelRepository, VisualCommunicationRepository
from .src.dto import (
HexadecimalString,
ImageData,
ModelData,
VisualCommunicationData,
VisualCommunicationValues,
)
+3
View File
@@ -0,0 +1,3 @@
from .image_repository import ImageRepository
from .model_repository import ModelRepository
from .visual_communication_repository import VisualCommunicationRepository
+7
View File
@@ -0,0 +1,7 @@
from .hexadecimal_string import HexadecimalString
from .image_data import ImageData
from .model_data import ModelData
from .visual_communication_data import (
VisualCommunicationData,
VisualCommunicationValues,
)
@@ -0,0 +1,37 @@
"""Definition of BytesIO Pydantic Annotation."""
from io import BytesIO
from typing import Any
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
class BytesIOPydanticAnnotation:
"""Pydantic annotation that defines input validation, as well as general
and json serialization."""
@classmethod
def validate_input(cls, v: Any, handler) -> BytesIO:
"""Pydantic-related function to validate input on instantiation."""
if isinstance(v, BytesIO):
return v
s = handler(v)
return BytesIO(s)
@classmethod
def __get_pydantic_core_schema__(
cls,
source_type,
_handler,
) -> core_schema.CoreSchema:
assert source_type is BytesIO
return core_schema.no_info_wrap_validator_function(
function=cls.validate_input,
schema=core_schema.str_schema(),
serialization=core_schema.to_string_ser_schema(),
)
@classmethod
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
return handler(core_schema.str_schema())
@@ -0,0 +1,24 @@
"""Definition of Checksum DTO."""
from __future__ import annotations
import re
class HexadecimalString(str):
"""Hexadecimal-string class."""
def __new__(cls, string):
# ensure proper input format
pattern = r'[0-9-a-fA-F]{32}'
match = re.match(pattern, string)
if match is None:
raise ValueError(f'format does not match a hexadecimal-string: {string}')
return super().__new__(cls, string)
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}('{self}')"
def __reduce__(self):
return self.__class__, (self,)
@@ -0,0 +1,38 @@
"""Definition of HexadecimalString Pydantic Annotation."""
from typing import Any
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
from .hexadecimal_string import HexadecimalString
class HexadecimalStringPydanticAnnotation:
"""Pydantic annotation that defines input validation, as well as general
and json serialization."""
@classmethod
def validate_input(cls, v: Any, handler) -> HexadecimalString:
"""Pydantic-related function to validate input on instantiation."""
if isinstance(v, HexadecimalString):
return v
s = handler(v)
return HexadecimalString(s)
@classmethod
def __get_pydantic_core_schema__(
cls,
source_type,
_handler,
) -> core_schema.CoreSchema:
assert source_type is HexadecimalString
return core_schema.no_info_wrap_validator_function(
function=cls.validate_input,
schema=core_schema.str_schema(),
serialization=core_schema.to_string_ser_schema(),
)
@classmethod
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
return handler(core_schema.str_schema())
+16
View File
@@ -0,0 +1,16 @@
"""Definition of VisualData DTO."""
from typing import Annotated
from PIL import Image
from pydantic import Field
from .image_pydantic_annotation import ImagePydanticAnnotation
from .type_checking_base_model import TypeCheckingBaseModel
class ImageData(TypeCheckingBaseModel):
"""Visual data class."""
image: Annotated[Image.Image, ImagePydanticAnnotation]
name: str = Field(min_length=1)
@@ -0,0 +1,37 @@
"""Definition of BytesIO Pydantic Annotation."""
from typing import Any
from PIL import Image
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
class ImagePydanticAnnotation:
"""Pydantic annotation that defines input validation, as well as general
and json serialization."""
@classmethod
def validate_input(cls, v: Any, handler) -> Image.Image:
"""Pydantic-related function to validate input on instantiation."""
if isinstance(v, Image.Image):
return v
s = handler(v)
return Image.open(s)
@classmethod
def __get_pydantic_core_schema__(
cls,
source_type,
_handler,
) -> core_schema.CoreSchema:
assert source_type is Image.Image
return core_schema.no_info_wrap_validator_function(
function=cls.validate_input,
schema=core_schema.str_schema(),
serialization=core_schema.to_string_ser_schema(),
)
@classmethod
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
return handler(core_schema.str_schema())
+60
View File
@@ -0,0 +1,60 @@
"""Definition of ModelData DTO."""
from __future__ import annotations
from hashlib import md5
from io import BytesIO
from typing import Annotated
import torch
from pydantic import Field
from .bytes_io_pydantic_annotation import BytesIOPydanticAnnotation
from .hexadecimal_string import HexadecimalString
from .hexadecimal_string_pydantic_annotation import HexadecimalStringPydanticAnnotation
from .type_checking_base_model import TypeCheckingBaseModel
class ModelData(TypeCheckingBaseModel):
"""Model Data DTO."""
buffer: Annotated[BytesIO, BytesIOPydanticAnnotation]
buffer_checksum: Annotated[HexadecimalString, HexadecimalStringPydanticAnnotation]
class_name: str = Field(
min_length=1,
description='name of model class to generate data.',
)
@staticmethod
def calculate_checksum(buffer: BytesIO) -> HexadecimalString:
"""Calculate buffer checksum."""
checksum = md5(buffer.getbuffer()).hexdigest()
return HexadecimalString(checksum)
@staticmethod
def model_to_buffer(model: torch.nn.Module) -> BytesIO:
"""Save model to buffer."""
assert isinstance(model, torch.nn.Module)
buffer = BytesIO()
torch.save(model.state_dict(), buffer)
return buffer
@classmethod
def from_model(cls, model: torch.nn.Module) -> ModelData:
"""Instantiate from torch module."""
assert isinstance(model, torch.nn.Module)
# get model name
class_name = type(model).__name__
# save data to buffer
buffer = cls.model_to_buffer(model)
buffer = BytesIO()
torch.save(model.state_dict(), buffer)
# calculate checksum
buffer_checksum = cls.calculate_checksum(buffer)
# instantiate from buffer
data = cls(
buffer=buffer,
buffer_checksum=buffer_checksum,
class_name=class_name,
)
return data
@@ -0,0 +1,11 @@
"""Definition of TypeCheckingBaseModel class."""
from pydantic import BaseModel, ConfigDict
class TypeCheckingBaseModel(BaseModel):
"""BaseModel with added type checking on input types."""
model_config = ConfigDict(
frozen=True, # ensure data immutability
)
@@ -0,0 +1,2 @@
from .visual_communication_data import VisualCommunicationData
from .visual_communication_values import VisualCommunicationValues
@@ -0,0 +1,11 @@
"""Definition of AngleValues DTO."""
from .values_model import ValuesModel
class AngleValues(ValuesModel):
"""Angle values DTO."""
high: float
eye_level: float
low: float
@@ -0,0 +1,10 @@
"""Definition of ContactValues DTO."""
from .values_model import ValuesModel
class ContactValues(ValuesModel):
"""Contact values DTO."""
offer: float
demand: float
@@ -0,0 +1,11 @@
"""Definition of DistanceValues DTO."""
from .values_model import ValuesModel
class DistanceValues(ValuesModel):
"""Distance values DTO."""
long: float
medium: float
close: float
@@ -0,0 +1,12 @@
"""Definition of FramingValues DTO."""
from .values_model import ValuesModel
class FramingValues(ValuesModel):
"""Framing values DTO."""
frame_lines: float
empty_space: float
colour_contrast: float
form_contrast: float
@@ -0,0 +1,11 @@
"""Definition of InformationValueValues DTO."""
from .values_model import ValuesModel
class InformationValueValues(ValuesModel):
"""Information value values DTO."""
given_new: float
ideal_real: float
central_marginal: float
@@ -0,0 +1,11 @@
"""Definition of ModalityColorValues DTO."""
from .values_model import ValuesModel
class ModalityColorValues(ValuesModel):
"""Modality color values DTO."""
high: float
medium: float
low: float
@@ -0,0 +1,11 @@
"""Definition of ModalityDepthValues DTO."""
from .values_model import ValuesModel
class ModalityDepthValues(ValuesModel):
"""Modality depth values DTO."""
high: float
medium: float
low: float
@@ -0,0 +1,11 @@
"""Definition of ModalityLightingValues DTO."""
from .values_model import ValuesModel
class ModalityLightingValues(ValuesModel):
"""Modality lighting values DTO."""
high: float
medium: float
low: float
@@ -0,0 +1,10 @@
"""Definition of PointOfViewValues DTO."""
from .values_model import ValuesModel
class PointOfViewValues(ValuesModel):
"""Point-of-view values DTO."""
frontal: float
oblique: float
@@ -0,0 +1,13 @@
"""Definition of SalienceValues DTO."""
from .values_model import ValuesModel
class SalienceValues(ValuesModel):
"""Salience values DTO."""
size: float
colour: float
tone: float
form: float
positioning: float
@@ -0,0 +1,60 @@
"""Definition of ValuesModel base class."""
from __future__ import annotations
import random
from pydantic import BaseModel, ConfigDict
from torch import Tensor
class ValuesModel(BaseModel):
"""ValuesModel base class."""
model_config = ConfigDict(
validate_assignment=True, # argument type checking
frozen=True, # ensure data immutability
)
@classmethod
def list_fields(cls) -> list[str]:
"""List options that are stored as attributes."""
return list(cls.model_fields.keys())
@classmethod
def from_random(cls):
"""Instantiate with random numbers."""
kwargs = {field: random.random() for field in cls.list_fields()}
return cls(**kwargs)
@classmethod
def from_choice(cls, option: str) -> ValuesModel:
"""Instantiate from choice."""
assert isinstance(option, str)
assert len(option) > 0
allowed_options_list = cls.list_fields()
if option not in allowed_options_list:
raise ValueError(f'option {option} must be in {allowed_options_list}')
# generate field values
kwargs = {field: 0 for field in allowed_options_list}
# set chosen value to max probability
kwargs[option] = 1
return cls(**kwargs)
@classmethod
def from_tensor(cls, tensor: Tensor):
"""Instantiate from list of values."""
assert tensor.size(dim=0) == 1, f'tensor batch larger than 1: {tensor}'
data_list = [float(t.item()) for t in tensor[0]]
kwargs = dict(zip(cls.list_fields(), data_list))
return cls(**kwargs)
def highest_score_field(self) -> str:
"""Return name of field with highest score."""
model_dict = self.model_dump()
return max(model_dict, key=lambda k: model_dict[k])
def highest_score_value(self) -> float:
"""Return value of field with highest score."""
model_dict = self.model_dump()
return max(model_dict.values())
@@ -0,0 +1,14 @@
"""Definition of VisualCommunicationData DTO."""
from pydantic import Field
from ..type_checking_base_model import TypeCheckingBaseModel
from .visual_communication_values import VisualCommunicationValues
class VisualCommunicationData(TypeCheckingBaseModel):
"""Visual communication data class."""
name: str = Field(min_length=1)
annotation: VisualCommunicationValues | None = None
prediction: VisualCommunicationValues | None = None

Some files were not shown because too many files have changed in this diff Show More