Compare commits

..
Author SHA1 Message Date
Mats Paul Tončik e95e7bcaf0 Merge branch 'dev' into network
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-07 19:10:29 +02:00
Mats Paul Tončik e44040444f Fixed and optimized collaboration network generation with filtering
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-07 18:27:31 +02:00
farajollahi 0f7283f475 Merge pull request 'publications-filters-overview' (#115) from publications-filters-overview into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #115
2026-06-07 12:14:39 +02:00
farajollahi 33949bef75 Merge branch 'dev' into publications-filters-overview
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-07 12:10:01 +02:00
Mats Paul Tončik 0025bac51a Merge branch 'dev' into network
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 17:31:36 +02:00
Mats Paul Tončik 9f3066dbc4 Removed visible IDs from network
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 17:13:37 +02:00
farajollahi bc3f6b6a95 implement detail page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 17:09:39 +02:00
khalti 8774a425d8 Merge pull request 'feat(funding): show publication titles and improve UI' (#114) from ts-86-get-funding-by-author-clean into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #114
2026-06-06 16:42:38 +02:00
khalti 653c1745eb feat(funding): show publication titles and improve UI
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-06 16:38:45 +02:00
Kazgatari 0529db02d1 Added simple filter to remove some false entries when searching for a Person
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 14:24:57 +02:00
kuzko d951e60ecb Merge pull request 'merging_persons' (#113) from merging_persons into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #113
2026-06-06 13:18:08 +02:00
Kazgatari a5868a3107 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into merging_persons
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 13:14:30 +02:00
Kazgatari c3865a8660 remove openalex_id, change publication & citation to german
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-06 12:45:31 +02:00
Kazgatari 59a718aeaf fix rective topic search frontend 2026-06-06 12:19:16 +02:00
farajollahi fdb0cb3daa implement topics and institute filters
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 11:45:49 +02:00
Kazgatari ba296ef499 changed backend search filter & frontend topic search component (the topics are for now not in the frontend (fetched everytime to reflect changes))
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 11:20:25 +02:00
tischer 33f767dea3 Merge pull request 'person_interested_in shows top topics of works' (#112) from feature/person_interested_in into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #112
2026-06-06 09:52:59 +02:00
Steven Tischer 81e6d4436d show primary topic counts in interest tags
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-06 09:37:40 +02:00
Steven Tischer 2722c846f7 regenerate OpenAPI client from current service spec 2026-06-06 09:36:11 +02:00
Steven Tischer 3930e94b30 add primary topic counts endpoint for authors 2026-06-06 09:35:16 +02:00
Steven Tischer 39969fbaab add footnote to interest card for publication count 2026-06-06 08:16:18 +02:00
Steven Tischer 2a20e7bc33 update person to display scores in interest tags 2026-06-06 08:11:32 +02:00
genja 765c5c9509 regenerated openApi endpoints
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 21:56:49 +02:00
genja 5cfda2e5d6 fixed backed endpoints 2026-06-05 21:56:30 +02:00
genja eab0077347 little ui adjustment 2026-06-05 21:55:49 +02:00
genja 247d81381f endpoints directories fixed 2026-06-05 21:03:06 +02:00
genja bf0cac3299 fixed merging issues 2026-06-05 21:02:36 +02:00
genja 743353f511 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into merging_persons 2026-06-05 20:46:23 +02:00
genja 1a1bd0226c regenerated openApi endpoints 2026-06-05 18:49:00 +02:00
Kazgatari c77149dcc3 quick patch to revert previos refactor commit
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 16:28:37 +02:00
Kazgatari 5137601bc9 refactor search & added button to filter newest affiliation of institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 14:48:13 +02:00
Mats Paul Tončik f76d63a76c Added network table for institutions 2026-06-05 14:23:55 +02:00
genja e524d3d96c added first institutions filter
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 14:00:39 +02:00
genja 26940fd92d added personSeachWithFilters and + filter services 2026-06-05 13:59:38 +02:00
taguesokoudjou a769fcf380 Merge pull request 'ts-86-get-funding-by-author-clean' (#107) from ts-86-get-funding-by-author-clean into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #107
2026-06-05 12:53:58 +02:00
taguesokoudjou 941652209c Merge remote-tracking branch 'origin/dev' into ts-86-get-funding-by-author-clean
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 12:41:54 +02:00
erfanian b69608050e Merge PR #111: Add topic IDs to timeline response
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #111
2026-06-05 12:23:50 +02:00
spsaefan fffb362197 Add topic ids to timeline response
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-05 12:04:56 +02:00
genja 4aad221543 added track_total_hits field to elastic wrapper 2026-06-05 11:49:03 +02:00
Mats Paul Tončik e107657318 Added legend and clickable nodes to graph
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-05 10:52:08 +02:00
Mats Paul Tončik fe6f64cc8c Added summary cards for network
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 23:42:39 +02:00
genja 4c33a3e416 updated openApi config + generated endpoints
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 23:18:09 +02:00
genja b168378b11 fixed merging issues. 2026-06-04 23:17:14 +02:00
genja 3e6f2b80f2 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 23:06:52 +02:00
genja c08745c4b0 adjusted search logic by adding search term to query params 2026-06-04 22:59:02 +02:00
genja ff639ec74e adjusted UI for persons list 2026-06-04 22:57:21 +02:00
genja fce1ad74b3 search by institutions adjusted 2026-06-04 22:54:38 +02:00
genja ee991adf3a added page offset to person search 2026-06-04 22:33:28 +02:00
Mats Paul Tončik 736277d6ff Moved network filter to dialog component 2026-06-04 21:44:16 +02:00
kuzko 57c7dd6d5f Merge pull request 'feature/person-list' (#110) from feature/person-list into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #110
2026-06-04 21:20:17 +02:00
Kazgatari c37356a45a Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/person-list
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-04 21:13:26 +02:00
tischer a939755b8d Merge pull request 'style(person): improve layout and responsiveness of person component' (#109) from ui/improve_bio-position into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #109
2026-06-04 21:11:47 +02:00
Steven Tischer 625cbdc6d7 style(person): improve layout and responsiveness of person component
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-04 21:08:45 +02:00
tischer 372199573c Merge pull request 'fix/migrate_llm_to_vllm' (#108) from fix/migrate_llm_to_vllm into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #108
2026-06-04 20:40:09 +02:00
Steven Tischer 943b989ccb return error message if llm response is empty
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-04 20:35:58 +02:00
Steven Tischer 4fa84d1342 handle API connection errors in call function 2026-06-04 20:33:59 +02:00
Mats Paul Tončik 968b7a0723 Added loading indicator while resolving 2026-06-04 20:22:44 +02:00
Kazgatari c8ad000f7e Default University filter value
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 20:20:54 +02:00
Steven Tischer 1e000319d5 fix(backend/llm): update call function to use dynamic temperature and top_p parameters 2026-06-04 20:19:16 +02:00
Steven Tischer fc834eab6a fix(backend/llm): change api to openai api/vllm 2026-06-04 20:17:40 +02:00
Louis 4d9a3f24fa Make compact timeline details scrollable
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-04 20:16:13 +02:00
Kazgatari 5ef7204a07 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/person-list 2026-06-04 20:02:08 +02:00
Kazgatari b7082640bb Bakcend logic cleanup
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 19:53:01 +02:00
Kazgatari ce265ebbf9 fix double enter search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 19:00:24 +02:00
Louis 14b9ee0e50 Add URL state for research timeline view
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 18:51:41 +02:00
Kazgatari 08b3a0a585 fixed overview bug
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 18:45:36 +02:00
Kazgatari 87fa0e4a2d New feature branch merged with dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 18:01:16 +02:00
taguesokoudjou de4b7a9ff1 Fix funders pagination test
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 17:32:31 +02:00
tischer c30925e2ac Merge pull request 'fix(frontend/person): replace wrong orcid link prefix in profile component' (#106) from fix/replace_wrong_orcid_link_in_profile into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #106
2026-06-04 17:05:38 +02:00
Louis 8201913738 Fix research timeline API integration
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 16:46:42 +02:00
taguesokoudjou a4a9c58119 Merge remote-tracking branch 'origin/dev' into ts-89-get-funding-by-author-clean
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 16:43:11 +02:00
Louis 97db19f042 load research timeline via generated works API
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 15:42:36 +02:00
Steven Tischer d37140866b fix(frontend/person): replace wrong orcid link prefix in profile component
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-04 13:57:30 +02:00
genja 9a5c833b3a refactored for functionality 2026-06-04 13:44:06 +02:00
Louis 9dd47f4373 Merge remote-tracking branch 'origin/dev' into ts-85-topics-by-time-author 2026-06-04 13:18:45 +02:00
genja d4b40f5962 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 12:54:44 +02:00
genja 537199742b Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-04 12:53:43 +02:00
Steven Tischer ec2899fad9 refactor(backend/persons): move person logic and endpoints to own package
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 11:07:19 +02:00
taguesokoudjou 2dfaace34b Add funder publication URLs from Elasticsearch
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-04 10:43:25 +02:00
Steven Tischer 75514b7f57 fix(backend/elasticsearch): update get function to use query parameters instead of body
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-04 10:32:47 +02:00
Steven Tischer 9f5835a5d3 refactor(backend/persons): update person logic references to use persons_logic module 2026-06-04 10:31:21 +02:00
Steven Tischer a9822ca5ff refactor(backend/persons): move person logic from logic.py to seperate folder 2026-06-04 10:29:41 +02:00
tischer e7c17d1fa7 Merge pull request 'ts-82-author-overview-and-description' (#105) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #105
2026-06-04 10:04:40 +02:00
Steven Tischer e0015c3ea9 fix(backend/person_search): search failing due to unsupported search parameters
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-04 09:55:54 +02:00
Steven Tischer 547a82336e fix: add missing comma in elasticsearch search body parameter 2026-06-04 09:37:18 +02:00
Steven Tischer c409c1860d fix unsolved merge conflicts 2026-06-04 09:33:31 +02:00
Steven Tischer acee290e7f Merge branch 'dev' into ts-82-author-overview-and-description 2026-06-04 09:27:25 +02:00
Kazgatari 645ecebaad changing person search list 2026-06-03 22:15:27 +02:00
Louis 3b08118abe Merge dev into ts-85-topics-by-time-author 2026-06-03 20:43:06 +02:00
genja c24686258c added autocompletion for person search 2026-06-03 17:40:25 +02:00
khalti 8df18efd8f Personensuche in der Navigationsleiste hinzugefügt
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 10:46:24 +02:00
khalti d0d5a1b793 merge: Konflikte in person-funding Komponenten gelöst
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 10:06:07 +02:00
khalti e898f15583 feat: Personensuche in der Navigationsleiste hinzugefügt 2026-06-03 09:39:25 +02:00
taguesokoudjou fd09c5e08c Improve funding view pagination and UI styling
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-03 09:14:46 +02:00
taguesokoudjou b2996b07c6 Refine funding detail view by showing position stats per active filter
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 13:05:36 +02:00
taguesokoudjou 300a618cfd Open publication links directly as PDF with HTML fallback
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 12:52:50 +02:00
Mats Paul Tončik f35068761b Fixed elasticsearch client building
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 12:50:22 +02:00
taguesokoudjou 9c49191629 Persist funding tab state after reload via query params
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 12:35:44 +02:00
Mats Paul Tončik 4ce8f53e5e Updated elasticsearch url
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-02 12:27:55 +02:00
Mats Paul Tončik 6438efdda8 Merge branch 'dev' into network
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-02 12:21:26 +02:00
Mats Paul Tončik b6b5ab23bd Restructured end points
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 11:12:07 +02:00
genja b27e960e0a elastic client updated
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-02 11:08:01 +02:00
tischer 42db2222eb Merge pull request 'ts-82-author-overview-and-description' (#103) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #103
2026-06-02 10:57:59 +02:00
Mats Paul Tončik f09df855ee Updated gitignore
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-02 10:24:15 +02:00
Steven Tischer 2eb97bc4f7 feat(backend/search): enhance sorting logic in person list by adding works count as a secondary criterion
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-02 07:24:07 +02:00
taguesokoudjou 6fe70c8738 Update person funding frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 22:49:33 +02:00
taguesokoudjou 5294d26552 Refactor funders logic into separate module and add tests
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 22:21:50 +02:00
Louis 24ee9df743 Add compact research timeline view
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-01 20:56:45 +02:00
Louis 9a06211a0a Add year range filter to research timeline 2026-06-01 20:12:10 +02:00
Louis 0a32a2c191 Integrate primary topics into research timeline 2026-06-01 19:56:20 +02:00
khalti fac08044a8 Add Person funding View and API integration
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-01 14:02:25 +02:00
spsaefan 0a86a3f5bc Add primary topics to topic timeline
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-01 10:32:29 +02:00
Louis de571d47bd Connect research timeline to topics by time in backend
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-01 00:44:21 +02:00
Louis 644b111280 Keep research timeline legend centered 2026-06-01 00:25:05 +02:00
Louis aaead76390 Adapt research timeline to topic timeline data 2026-06-01 00:18:05 +02:00
Louis 96b3355f46 Add research timeline with dummy data 2026-06-01 00:01:01 +02:00
spsaefan 404386e153 Fix topic timeline response models
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-05-31 23:07:25 +02:00
genja 1409d801bf added fetching of orcid for persons dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-31 23:05:19 +02:00
genja fc356401e4 Merged with dev + optimized persons data loading for persons dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-31 22:56:20 +02:00
spsaefan 355361558e Adapt topics by time to refactored models
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-05-31 22:22:41 +02:00
genja adbd741268 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-05-31 11:36:35 +02:00
genja fe6dd1b3e6 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-05-31 11:18:35 +02:00
genja 7770bd3841 moved tags back into person overview 2026-05-31 11:16:48 +02:00
Mats Paul Tončik 92d4cd446f Added experimental filtering by min/max collaborations as well as institution and topic
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-05-31 11:14:08 +02:00
khalti ce4ccbf154 Add person funding frontend view
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-31 09:10:50 +02:00
Mats Paul Tončik f29b3da8ed Added filter to restrict amount of min/max collaborators per work 2026-05-31 00:28:29 +02:00
Mats Paul Tončik af39d73ba6 Moved graph to own component 2026-05-30 23:53:40 +02:00
Mats Paul Tončik d323b75e12 Updated graph such that it shows works too 2026-05-30 21:13:37 +02:00
Steven Tischer b67c667376 feat(person-list): implement sorting of persons by ranking based on institution and ORCID presence
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-30 11:26:05 +02:00
Steven Tischer 4415683874 feat(frontend/person-list): add distinguishing ID display for persons 2026-05-30 11:16:01 +02:00
Steven Tischer eba62aa568 feat(frontend/person-list): add result count display for persons in the list
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-30 11:01:34 +02:00
Steven Tischer 16b129b9f6 fix(backend/search): enhance search functionality for persons by adding match_phrase_prefix query 2026-05-30 10:59:14 +02:00
taguesokoudjou 22dd33c0a9 Add funders by author endpoint with position counts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-30 09:10:09 +02:00
Kazgatari 31b0ae6ee2 added * to work index in config
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 20:17:39 +02:00
kuzko 5b684c1c67 Merge pull request 'Full refactor (DB DTOs)' (#98) from refactor/DBModels into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #98
2026-05-29 19:58:44 +02:00
Kazgatari 16d99d7dca Full refactor
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-05-29 19:07:08 +02:00
kuzko 84ef2433ef Merge pull request 'feature/person-interesting' (#97) from feature/person-interesting into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #97
2026-05-29 17:05:44 +02:00
Steven Tischer 6b2c864df1 fix: add missing var start_time
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 14:33:56 +02:00
Steven Tischer 096fbb1604 Merge branch 'origin/ts-82-author-overview-and-description' into ts-82-author-overview-and-description
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 14:29:17 +02:00
Steven Tischer 6a715d2bec feat(backend/llm): enhance person bio generation prompt for detailed descriptions
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 14:19:55 +02:00
Kazgatari fd36eeedba change service to openai-generated service
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-05-29 13:43:55 +02:00
Steven Tischer 8fc5524ad4 feat(backend/llm): bio generation endpoint supports extra parameters for more details
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 13:40:05 +02:00
spsaefan 32cb67df72 Add topics by time endpoint
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-05-29 12:15:05 +02:00
spsaefan f2bca2f646 Add topic aggregation by year 2026-05-29 12:14:56 +02:00
spsaefan 3caa759e4f Add topic timeline response models 2026-05-29 12:14:38 +02:00
genja 3fefedc82d tiny import fix
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-29 05:13:29 +02:00
genja bea9682958 Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-05-29 05:11:06 +02:00
genja ddc2e33279 added shared state service, search bar is now active 2026-05-29 05:07:51 +02:00
genja d5b5a31d1a view adjusted for dynamic persons data from elastic 2026-05-29 05:07:07 +02:00
genja 708dd13ca0 regenerated open api services 2026-05-29 05:06:04 +02:00
genja 916ec5fa61 returned search functions by ID and Name separately 2026-05-29 05:05:01 +02:00
Kazgatari 011c14ee6a Experimental Signal based service injection
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 22:11:06 +02:00
genja 88210bf2a7 merged with dev 2026-05-28 19:30:46 +02:00
tischer 8ecf766aef Merge pull request 'feature/91-llm-elasticsearch-service' (#94) from feature/91-llm-elasticsearch-service into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #94
2026-05-28 16:59:34 +02:00
tischer 849d4fdab9 Merge branch 'dev' into feature/91-llm-elasticsearch-service
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 16:55:53 +02:00
Steven Tischer e6c66e90a6 feat(backend): update call function to use dynamic timeout parameter
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-05-28 16:45:09 +02:00
Steven Tischer 3e1a81e68b refactor(backend): integrate llm integration into generate_person_bio 2026-05-28 16:43:28 +02:00
Steven Tischer afd414e004 feat(backend): add centralized llm query function 2026-05-28 16:41:26 +02:00
Steven Tischer 28c79e113a refactor(backend): integrate elasticsearch service into search_persons function
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 16:38:35 +02:00
Steven Tischer 4a37c8d041 feat(backend): add centralized elasticsearch query function 2026-05-28 16:37:24 +02:00
Mats Paul Tončik 98504963f9 Merged with person publications 2026-05-28 16:01:25 +02:00
farajollahi fa9e043076 Merge pull request 'implement all works of author' (#93) from ts-get-all-author-works into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #93
2026-05-28 15:39:29 +02:00
farajollahi b753f7dd00 implement all works of author
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-05-28 15:34:36 +02:00
Steven Tischer 74f6ff7ef5 feat(backend): add time measurement to llm generation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 14:23:57 +02:00
Steven Tischer 45e02a72b4 feat(frontend): add static llm generated bio to profile 2026-05-28 14:23:08 +02:00
Steven Tischer a33e38eebb Merge branch 'dev' into ts-82-author-overview-and-description
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 13:28:00 +02:00
Marcus Handte 982e01a26a Fix case in build file.
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-05-28 11:11:24 +02:00
Mats Paul Tončik a3088062f0 Finished person collaboration graph prototype
aiis/pipeline/head There was a failure building this commit
2026-05-28 10:28:08 +02:00
farajollahi 4f3a427332 Merge pull request 'ts-83-User-Publications-filters' (#92) from ts-83-User-Publications-filters into dev
aiis/pipeline/head This commit looks good
Reviewed-on: nes/smartguide#92
2026-05-28 09:39:15 +02:00
genja 78e6b371e5 added get_person_by_id and search_person_by_name endpoints + pytests
aiis/pipeline/head This commit looks good
2026-05-27 18:40:38 +02:00
356 changed files with 32248 additions and 1432 deletions
+1 -1
View File
@@ -14,4 +14,4 @@ src/python/account/
*.pyc
node_modules/
angular-app/.angular
angular-app/.angular
View File
+1
View File
@@ -0,0 +1 @@
3.12
+3 -1
View File
@@ -14,7 +14,9 @@ RUN mkdir /test && \
"uvicorn~=0.29.0" \
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"
"python-multipart~=0.0.19"\
"elasticsearch~=9.4.0" \
"openai~=2.41.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+2 -2
View File
@@ -31,7 +31,7 @@ task exportOpenApiSpec(type: Exec) {
'--entrypoint', 'python',
"${imagePrefix}-service:${imageVersion}",
'-c',
"import json; from inse.service import app; open('/mnt/openapi/inse-service.openapi.json', 'w').write(json.dumps(app.openapi(), indent=2))"
"import json; from inse.main import app; open('/mnt/openapi/inse-service.openapi.json', 'w').write(json.dumps(app.openapi(), indent=2))"
}
task runServeContainer(type: Exec) {
@@ -40,8 +40,8 @@ task runServeContainer(type: Exec) {
}
task stopServeContainer(type: Exec) {
dependsOn runServeContainer
commandLine 'docker', 'stop', "${imageName}-service-serve"
ignoreExitValue true
}
task serve(type: Task) {
+22
View File
@@ -0,0 +1,22 @@
[project]
name = "service"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"cryptography~=42.0.0",
"dotenv>=0.9.9",
"elasticsearch~=9.4.0",
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
"pydantic~=2.7.1",
"pydantic-settings~=2.2.1",
"pyjwt~=2.8.0",
"pytest~=8.1.0",
"python-multipart~=0.0.19",
"pyyaml~=6.0.1",
"sqlalchemy~=2.0.0",
"uvicorn~=0.29.0",
]
+6
View File
@@ -0,0 +1,6 @@
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
+81 -33
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone account service that provides identity and access
token endpoints for authentication.
Standalone account service that provides identity and access
token endpoints for authentication.
"""
import logging
import fastapi
import typing
@@ -17,62 +18,109 @@ from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
logger = logging.getLogger(__name__)
app = fastapi.FastAPI(docs_url='/api',
title='My App Account Service',
version='1.0.0')
router = fastapi.APIRouter(
prefix="/inse-account",
tags=["INSE Account Service"],
responses={404: {"description": "Not found"}},
)
@app.post('/auth/id', responses={
HTTP_200_OK: {'model': model.IdentityGrant},
HTTP_400_BAD_REQUEST: {'model': None, 'description': 'Invalid request parameters.'},
HTTP_403_FORBIDDEN: {'model': None, 'description': 'Account login not successful.'},
HTTP_500_INTERNAL_SERVER_ERROR: {'model': None, 'description': 'Token generation failed.'}
})
async def get_identity_grant(username: typing.Annotated[str, fastapi.Form()], password: typing.Annotated[str, fastapi.Form()]):
@router.post(
"/auth/id",
responses={
HTTP_200_OK: {"model": model.IdentityGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {
"model": None,
"description": "Account login not successful.",
},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_identity_grant(
username: typing.Annotated[str, fastapi.Form()],
password: typing.Annotated[str, fastapi.Form()],
):
user = logic.validate_user(username, password)
if user is None:
logger.info('Invalid login attempt (%s).', username)
logger.info("Invalid login attempt (%s).", username)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 12 * 60 * 60
token = security.id_token(user, exp=exp)
account = model.AuthAccount(i=user.account, l=user.username, o=user.organization)
scope = model.AuthScope(t='ID', a=account, d=None, r=[])
grant = model.IdentityGrant(token_type='bearer', access_token=token, expires_in=exp, scope=scope)
logger.info('Identity token generated (%s).', username)
account = model.AuthAccount(
i=user.account, l=user.username, o=user.organization
)
scope = model.AuthScope(t="ID", a=account, d=None, r=[])
grant = model.IdentityGrant(
token_type="bearer", access_token=token, expires_in=exp, scope=scope
)
logger.info("Identity token generated (%s).", username)
return grant
except Exception as e:
logger.error('Token generation failed (%s).', username, exc_info=e)
logger.error("Token generation failed (%s).", username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@app.post('/auth/access', responses={
HTTP_200_OK: {'model': model.AccessGrant},
HTTP_400_BAD_REQUEST: {'model': None, 'description': 'Invalid request parameters.'},
HTTP_403_FORBIDDEN: {'model': None, 'description': 'Access not allowed.'},
HTTP_500_INTERNAL_SERVER_ERROR: {'model': None, 'description': 'Token generation failed.'}
})
async def get_access_grant(secret: typing.Annotated[str, fastapi.Form()], account: typing.Annotated[int, fastapi.Form()], organization: typing.Annotated[int, fastapi.Form()]):
@router.post(
"/auth/access",
responses={
HTTP_200_OK: {"model": model.AccessGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_access_grant(
secret: typing.Annotated[str, fastapi.Form()],
account: typing.Annotated[int, fastapi.Form()],
organization: typing.Annotated[int, fastapi.Form()],
):
principal = security.principal(secret)
if principal is None:
logger.info('Invalid access attempt without principal (%s).', account)
logger.info("Invalid access attempt without principal (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
user = logic.get_user(principal.account.login)
if user is None:
logger.info('Invalid access attempt without user (%s).', account)
logger.info("Invalid access attempt without user (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
if user.organization != organization or user.account != account:
logger.info('Invalid personation attempt (%s).', account)
logger.info("Invalid personation attempt (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 10 * 60
token = security.access_token(user, exp=exp)
refresh = security.refresh_token(user, exp=exp)
auth_account = model.AuthAccount(i=user.account, l=user.username, o=user.organization)
scope = model.AuthScope(t='ACCESS', a=auth_account, d=None, r=['SUPER_ADMIN'] if user.superadmin else ['UNI_ADMIN'])
grant = model.AccessGrant(token_type='bearer', access_token=token, expires_in=exp, scope=scope, refresh_token=refresh)
logger.info('Access token generated (%s).', user.username)
auth_account = model.AuthAccount(
i=user.account, l=user.username, o=user.organization
)
scope = model.AuthScope(
t="ACCESS",
a=auth_account,
d=None,
r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"],
)
grant = model.AccessGrant(
token_type="bearer",
access_token=token,
expires_in=exp,
scope=scope,
refresh_token=refresh,
)
logger.info("Access token generated (%s).", user.username)
return grant
except Exception as e:
logger.error('Token generation failed (%s).', user.username, exc_info=e)
logger.error("Token generation failed (%s).", user.username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@@ -0,0 +1,43 @@
from typing import Annotated, Optional
from fastapi import APIRouter, Body, Path, status
from inse.collaboration_network.schemas import (
CollaborationNetwork,
FilterProperties,
)
from inse.tags import Tags
import inse.collaboration_network.service as collaboration_network_service
router = APIRouter(
prefix="/api/person/network", tags=[Tags.PERSON_NETWORK]
)
@router.post(
"/{raw_user_id}",
summary="Get a person's collaboration network.",
description="Returns a person's collaboration network based on their works and co-authors.",
operation_id="getCollaborationNetwork",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": CollaborationNetwork,
},
status.HTTP_404_NOT_FOUND: {"description": "Person not found"},
},
)
async def get_collaboration_network(
raw_user_id: Annotated[str, Path(description="The raw user ID of the person.")],
filter_properties: Annotated[
Optional[FilterProperties],
Body(
description="The filter properties for the collaboration network.",
),
] = None,
) -> CollaborationNetwork:
return await collaboration_network_service.get_collaboration_network(
raw_user_id=raw_user_id,
filter_properties=filter_properties,
)
@@ -0,0 +1,273 @@
from enum import Enum
from typing import List, Optional, Set
from pydantic import BaseModel, Field
from inse.models.work_topic import WorkTopic
from inse.utils import extract_raw_topic_id
class InstitutionInformation(BaseModel):
raw_id: str = Field(
title="Raw Institution ID",
description="The raw institution ID of the institution.",
)
display_name: str = Field(
title="Institution Display Name",
description="The display name of the institution.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionInformation):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkTopicInformation(BaseModel):
raw_topic_id: str = Field(
title="Topic ID",
description="The ID of the topic.",
)
display_name: str = Field(
title="Topic Name",
description="The name of the topic.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkTopicInformation):
return self.raw_topic_id == value.raw_topic_id
return False
def __hash__(self) -> int:
return hash(self.raw_topic_id)
@classmethod
def from_topic(cls, topic: WorkTopic) -> "WorkTopicInformation":
"""Creates a WorkTopicInformation instance from a WorkTopic instance.
Args:
topic (WorkTopic): The WorkTopic instance to create the WorkTopicInformation from.
Returns:
WorkTopicInformation: The created WorkTopicInformation instance.
"""
return cls(
raw_topic_id=extract_raw_topic_id(str(topic.id)),
display_name=str(topic.display_name),
)
class CollaborationNetworkNodeType(str, Enum):
AUTHOR = "author"
INSTITUTION = "institution"
WORK = "work"
class FilterInformation(BaseModel):
min_possible_year: int = Field(
title="Minimum Year",
description="The minimum publication year of the works in the collaboration network.",
)
max_possible_year: int = Field(
title="Maximum Year",
description="The maximum publication year of the works in the collaboration network.",
)
institutions: List[InstitutionInformation] = Field(
title="Institutions",
description="The list of institutions associated with the works in the collaboration network.",
)
topics: List[WorkTopicInformation] = Field(
title="Topics",
description="The list of topics associated with the works in the collaboration network.",
)
class WorksFilterProperties(BaseModel):
start_year: int = Field(
default=0,
title="Start Year",
description="The start publication year for the works to include in the collaboration network.",
)
end_year: int = Field(
default=9999,
title="End Year",
description="The end publication year for the works to include in the collaboration network.",
)
allowed_topics: List[str] = Field(
default_factory=list,
title="Allowed Topics",
description="The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.",
)
min_contributors: int = Field(
default=1,
title="Minimum Contributors",
description="The minimum number of contributors required for a work to be included in the collaboration network.",
)
max_contributors: int = Field(
default=100,
title="Maximum Contributors",
description="The maximum number of contributors allowed for a work to be included in the collaboration network.",
)
class AuthorsFilterProperties(BaseModel):
allowed_institutions: List[str] = Field(
default_factory=list,
title="Allowed Institutions",
description="The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.",
)
min_collaborations: int = Field(
default=1,
title="Minimum Collaborations",
description="The minimum number of collaborations required for an author to be included in the collaboration network.",
)
max_collaborations: int = Field(
default=1000,
title="Maximum Collaborations",
description="The maximum number of collaborations allowed for an author to be included in the collaboration network.",
)
class FilterProperties(BaseModel):
filter_by: str = Field(
default="works",
title="Filter By",
description="The type of filter to apply when generating the collaboration network. Can be either 'works' or 'authors'. If 'works', the filter properties in the 'works_filter_properties' field will be used. If 'authors', the filter properties in the 'authors_filter_properties' field will be used.",
)
works_filter_properties: Optional[WorksFilterProperties] = Field(
title="Works Filter Properties",
description="The filter properties to apply when filtering works for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'works'.",
)
authors_filter_properties: Optional[AuthorsFilterProperties] = Field(
title="Authors Filter Properties",
description="The filter properties to apply when filtering authors for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'authors'.",
)
class CollaborationNetworkNode(BaseModel):
raw_id: str = Field(
title="Raw ID",
description="The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.",
)
display_name: str = Field(
title="Display Name", description="The display name of the node."
)
category: CollaborationNetworkNodeType = Field(
title="Category",
description="The category of the node, either 'author', 'institution', or 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class WorkNetworkNode(CollaborationNetworkNode):
publication_year: Optional[int] = Field(
title="Publication Year",
description="The publication year of the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
work_topics_information: Optional[Set[WorkTopicInformation]] = Field(
title="Work Topics Information",
description="The list of topic information associated with the work represented by this node. This field is only applicable if the category of the node is 'work'.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, WorkNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class AuthorNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, AuthorNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class InstitutionNetworkNode(CollaborationNetworkNode):
def __eq__(self, value: object) -> bool:
if isinstance(value, InstitutionNetworkNode):
return self.raw_id == value.raw_id
return False
def __hash__(self) -> int:
return hash(self.raw_id)
class CollaborationNetworkEdge(BaseModel):
raw_source_id: str = Field(
title="Source Raw ID",
description="The raw ID of the source node.",
)
raw_target_id: str = Field(
title="Target Raw ID",
description="The raw ID of the target node.",
)
def __eq__(self, value: object) -> bool:
if isinstance(value, CollaborationNetworkEdge):
return self.same_collaboration(self, value)
return False
def __hash__(self) -> int:
return hash((self.raw_source_id, self.raw_target_id))
@classmethod
def same_collaboration(
cls, edge1: "CollaborationNetworkEdge", edge2: "CollaborationNetworkEdge"
) -> bool:
"""Checks if two edges have the same source and target person IDs, regardless of order.
Args:
edge1 (CollaborationNetworkEdge): The first collaboration edge.
edge2 (CollaborationNetworkEdge): The second collaboration edge.
Returns:
bool: True if the edges have the same source and target person IDs (undirected), False otherwise.
"""
return (
edge1.raw_source_id == edge2.raw_source_id
and edge1.raw_target_id == edge2.raw_target_id
) or (
edge1.raw_source_id == edge2.raw_target_id
and edge1.raw_target_id == edge2.raw_source_id
)
class CollaborationNetwork(BaseModel):
raw_person_id: str = Field(
title="Raw Person ID",
description="The raw person ID of the person whose collaboration network this is.",
)
work_nodes: List[WorkNetworkNode] = Field(
title="Collaboration Network Work Nodes",
description="The work nodes in the collaboration network.",
)
author_nodes: List[AuthorNetworkNode] = Field(
title="Collaboration Network Author Nodes",
description="The author nodes in the collaboration network.",
)
institution_nodes: List[InstitutionNetworkNode] = Field(
title="Collaboration Network Institution Nodes",
description="The institution nodes in the collaboration network.",
)
collaboration_edges: List[CollaborationNetworkEdge] = Field(
title="Collaboration Network Edges",
description="The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I",
)
filter_information: FilterInformation = Field(
title="Filter Information",
description="The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network.",
)
@@ -0,0 +1,708 @@
from collections import defaultdict
import logging
from typing import List, Optional, Set, Tuple
from inse.collaboration_network.schemas import (
AuthorNetworkNode,
AuthorsFilterProperties,
CollaborationNetwork,
CollaborationNetworkEdge,
CollaborationNetworkNodeType,
FilterInformation,
FilterProperties,
InstitutionInformation,
InstitutionNetworkNode,
WorkNetworkNode,
WorkTopicInformation,
WorksFilterProperties,
)
from inse.works import logic as work_logic
from inse.works.model import Work
from inse.utils import (
extract_raw_author_id,
extract_raw_institution_id,
extract_raw_topic_id,
extract_raw_work_id,
)
from inse.models.author import Author
from inse.models.authorship import Authorship
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.institution import Institution
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_collaboration_network(
raw_user_id: str,
filter_properties: FilterProperties,
) -> CollaborationNetwork:
"""Generates a collaboration network for a given user ID based on the works associated with that user, and applies filtering to the network based on the specified filter properties, which may include criteria such as publication year range, allowed topics, minimum/maximum number of contributors, and minimum/maximum number of collaborations.
The function returns a collaboration network that includes the works, authors, and institutions that are relevant to the specified user and meet the filtering criteria defined in the filter properties.
Args:
raw_user_id (str): The raw user ID for whom to generate the collaboration network.
filter_properties (FilterProperties): The filter properties for the collaboration network.
Returns:
CollaborationNetwork: The collaboration network for the given user.
"""
raw_user_id = raw_user_id.strip().upper()
work_page = await work_logic.get_all_author_works(author_id=raw_user_id)
works: List[Work] = work_page.results or []
collaboration_network = build_collaboration_network(
raw_user_id=raw_user_id, works=works
)
if filter_properties.filter_by == "works":
if not filter_properties.works_filter_properties:
filter_properties.works_filter_properties = WorksFilterProperties()
return filter_collaboration_network_by_works(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
works_filter_properties=filter_properties.works_filter_properties,
)
elif filter_properties.filter_by == "authors":
if not filter_properties.authors_filter_properties:
filter_properties.authors_filter_properties = AuthorsFilterProperties()
return filter_collaboration_network_by_authors(
raw_user_id=raw_user_id,
collaboration_network=collaboration_network,
filter_properties=filter_properties.authors_filter_properties,
)
else:
logger.warning(
f"Invalid filter_by value in filter properties: {filter_properties.filter_by}. Expected 'works' or 'authors'. No additional filtering will be applied."
)
return collaboration_network
def filter_collaboration_network_by_authors(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
filter_properties: AuthorsFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified author filter properties, which may include criteria such as allowed institutions and minimum/maximum number of collaborations.
The function returns a new collaboration network that only includes authors that meet the specified criteria, along with their associated works and institutions.
Args:
raw_user_id (str): The raw user ID for whom to filter the collaboration network.
collaboration_network (CollaborationNetwork): The collaboration network to filter.
filter_properties (AuthorsFilterProperties): The filter properties for the author filtering.
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
logger.debug(
f"Filtering collaboration network for user {raw_user_id} with author filter properties: {filter_properties}"
)
all_author_nodes = set(collaboration_network.author_nodes)
remaining_author_ids = {node.raw_id for node in all_author_nodes}
remaining_institution_nodes = set(collaboration_network.institution_nodes)
logger.debug(f"Remaining author IDs before filtering: {remaining_author_ids}")
# 1. Filter author nodes based on allowed institutions in filter properties
if len(filter_properties.allowed_institutions) > 0:
logger.debug(
f"Filtering author nodes based on allowed institutions: {filter_properties.allowed_institutions}"
)
remaining_author_ids = {
edge.raw_source_id
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in filter_properties.allowed_institutions
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in filter_properties.allowed_institutions
}
logger.debug(
f"Remaining author IDs after filtering by allowed institutions: {remaining_author_ids}"
)
# 2. Filter out collaboration edges that are associated with author nodes that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
}
logger.debug(
f"Remaining work edges after filtering by allowed institutions: {len(remaining_work_edges)}"
)
works_per_author = defaultdict(set)
for edge in remaining_work_edges:
if (
edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("w")
):
works_per_author[edge.raw_source_id].add(edge.raw_target_id)
logger.debug(
f"Works per author after filtering by allowed institutions: {dict(works_per_author)}"
)
# 3. Filter out author that do not have enough collaborations based on the filter properties
remaining_author_ids = {
author_id
for author_id, work_ids in works_per_author.items()
if filter_properties.min_collaborations
<= len(work_ids)
<= filter_properties.max_collaborations
}
remaining_author_ids.add(raw_user_id) # main author always included
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in remaining_author_ids
}
remaining_institutions_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in remaining_author_ids
and edge.raw_target_id.lower().startswith("i")
}
# 4. Remove institution nodes that are not connected to any of the remaining author nodes
institution_ids_with_remaining_authors = {
edge.raw_target_id
for edge in remaining_institutions_edges
if edge.raw_source_id in remaining_author_ids
}
remaining_institution_nodes = {
node
for node in remaining_institution_nodes
if node.raw_id in institution_ids_with_remaining_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=collaboration_network.work_nodes,
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_work_edges)
+ list(remaining_institutions_edges),
filter_information=collaboration_network.filter_information,
)
def filter_collaboration_network_by_works(
raw_user_id: str,
collaboration_network: CollaborationNetwork,
works_filter_properties: WorksFilterProperties,
) -> CollaborationNetwork:
"""Filters the given collaboration network based on the specified works filter properties, which may include criteria such as publication year range, allowed topics, and minimum/maximum number of contributors.
The function returns a new collaboration network that only includes works that meet the specified criteria, along with their associated authors and institutions.
Args:
raw_user_id (str): _description_
collaboration_network (CollaborationNetwork): _description_
works_filter_properties (WorksFilterProperties): _description_
Returns:
CollaborationNetwork: The filtered collaboration network.
"""
if not works_filter_properties:
return collaboration_network
all_work_nodes = set(collaboration_network.work_nodes)
valid_work_ids = {node.raw_id for node in all_work_nodes}
# 1. Filter out works that are not in the specified year range or do not have allowed topics, and update valid_work_ids accordingly
valid_work_ids = filter_works_by_year_and_topic(
works=all_work_nodes,
filter_properties=works_filter_properties,
valid_work_ids=valid_work_ids,
)
# 2. Filter out works that do not have enough collaborators based on the filter properties, and update valid_work_ids accordingly
if (
works_filter_properties.min_contributors
or works_filter_properties.max_contributors
):
contributors_per_work = defaultdict(set)
for edge in collaboration_network.collaboration_edges:
if (
edge.raw_target_id.lower().startswith("w")
and edge.raw_target_id in valid_work_ids
):
contributors_per_work[edge.raw_target_id].add(edge.raw_source_id)
valid_work_ids = set()
for work_id, contributors in contributors_per_work.items():
contributors_count = len(contributors)
if has_enough_contributors(
contributors_count=contributors_count,
filter_properties=works_filter_properties,
):
valid_work_ids.add(work_id)
# 3. Filter out collaboration edges that are associated with works that have been filtered out
remaining_work_edges = {
edge
for edge in collaboration_network.collaboration_edges
if edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
}
# 4. Identify author nodes that are still valid based on their association with the remaining valid works
author_ids_with_valid_works = {edge.raw_source_id for edge in remaining_work_edges}
# 5. Identify institution nodes that are still valid based on their association with the remaining valid author nodes
institution_ids_with_valid_authors = {
edge.raw_target_id
for edge in collaboration_network.collaboration_edges
if edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
}
remaining_collaboration_edges = {
edge
for edge in collaboration_network.collaboration_edges
if (
edge.raw_target_id in valid_work_ids
and edge.raw_target_id.lower().startswith("w")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id.lower().startswith("i")
)
or (
edge.raw_source_id in author_ids_with_valid_works
and edge.raw_target_id in institution_ids_with_valid_authors
)
}
remaining_work_nodes = {
node
for node in collaboration_network.work_nodes
if node.raw_id in valid_work_ids
}
remaining_author_nodes = {
node
for node in collaboration_network.author_nodes
if node.raw_id in author_ids_with_valid_works
}
remaining_institution_nodes = {
node
for node in collaboration_network.institution_nodes
if node.raw_id in institution_ids_with_valid_authors
}
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(remaining_work_nodes),
author_nodes=list(remaining_author_nodes),
institution_nodes=list(remaining_institution_nodes),
collaboration_edges=list(remaining_collaboration_edges),
filter_information=collaboration_network.filter_information,
)
def filter_works_by_year_and_topic(
works: Set[WorkNetworkNode],
filter_properties: WorksFilterProperties,
valid_work_ids: Set[str],
):
"""Determines the set of valid work IDs by filtering the given set of works based on the specified year range and allowed topics defined in the filter properties.
Args:
works (Set[WorkNetworkNode]): The set of works to filter.
filter_properties (WorksFilterProperties): The filter properties containing the year range and allowed topics.
valid_work_ids (Set[str]): The set of valid work IDs to update.
Returns:
Set[str]: The updated set of valid work IDs.
"""
if not any(
[
filter_properties.start_year,
filter_properties.end_year,
filter_properties.allowed_topics,
]
):
return valid_work_ids
for work in works:
if not is_in_year_range(
year=work.publication_year or -1,
works_filter_properties=filter_properties,
) or not has_allowed_topic(work, filter_properties):
valid_work_ids.discard(work.raw_id)
return valid_work_ids
def is_in_year_range(year: int, works_filter_properties: WorksFilterProperties) -> bool:
"""Determines whether a given year falls within the specified year range defined in the filter properties.
Args:
year (int): The year to check.
works_filter_properties (WorksFilterProperties): The filter properties containing the year range.
Returns:
bool: True if the year falls within the specified range, False otherwise.
"""
# no year extracted, excluding work by default
if year == -1:
return False
if works_filter_properties.start_year and year < works_filter_properties.start_year:
return False
if works_filter_properties.end_year and year > works_filter_properties.end_year:
return False
return True
def has_allowed_topic(
work: WorkNetworkNode, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given work has at least one topic that is included in the allowed topics specified in the filter properties.
Args:
work (WorkNetworkNode): The work for which to check the topics.
filter_properties (WorksFilterProperties): The filter properties containing the allowed topics.
Returns:
bool: True if the work has at least one allowed topic, False otherwise.
"""
if len(filter_properties.allowed_topics) == 0:
return True
return any(
topic.raw_topic_id in filter_properties.allowed_topics
for topic in work.work_topics_information or set()
)
def has_enough_contributors(
contributors_count: int, filter_properties: WorksFilterProperties
) -> bool:
"""Determines whether a given number of contributors meets the specified minimum and maximum contributor requirements defined in the filter properties.
Args:
contributors_count (int): The number of contributors to check.
filter_properties (WorksFilterProperties): The filter properties containing the contributor requirements.
Returns:
bool: True if the contributor count meets the requirements, False otherwise.
"""
if filter_properties and contributors_count < filter_properties.min_contributors:
return False
if (
filter_properties.max_contributors
and contributors_count > filter_properties.max_contributors
):
return False
return True
def build_collaboration_network(
raw_user_id: str,
works: List[Work],
) -> CollaborationNetwork:
"""Builds a collaboration network for a given user ID based on the provided list of works.
Args:
raw_user_id (str): The raw ID of the user for whom to build the collaboration network.
works (List[Work]): The list of works for which to build the collaboration network.
Returns:
CollaborationNetwork: The built collaboration network.
"""
min_possible_year = float("inf")
max_possible_year = float("-inf")
work_nodes: Set[WorkNetworkNode] = set()
all_author_nodes: Set[AuthorNetworkNode] = set()
all_institution_nodes: Set[InstitutionNetworkNode] = set()
all_collaboration_edges: Set[CollaborationNetworkEdge] = set()
work_topics_information: Set[WorkTopicInformation] = set()
for work in works:
work_node, author_nodes, institution_nodes, collaboration_edges = process_work(
work=work
)
if not work_node:
continue
min_possible_year = min(
min_possible_year, work_node.publication_year or float("inf")
)
max_possible_year = max(
max_possible_year, work_node.publication_year or float("-inf")
)
work_topics_information.update(work_node.work_topics_information or set())
work_nodes.add(work_node)
all_author_nodes.update(author_nodes)
all_institution_nodes.update(institution_nodes)
all_collaboration_edges.update(collaboration_edges)
return CollaborationNetwork(
raw_person_id=raw_user_id,
work_nodes=list(work_nodes),
author_nodes=list(all_author_nodes),
institution_nodes=list(all_institution_nodes),
collaboration_edges=list(all_collaboration_edges),
filter_information=FilterInformation(
min_possible_year=int(min_possible_year),
max_possible_year=int(max_possible_year),
institutions=sorted(
{
InstitutionInformation(
raw_id=institution.raw_id, display_name=institution.display_name
)
for institution in all_institution_nodes
},
key=lambda inst: inst.display_name,
),
topics=sorted(
work_topics_information, key=lambda topic: topic.display_name
),
),
)
def process_work(
work: Work,
) -> Tuple[
Optional[WorkNetworkNode],
Set[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given work to extract the associated work node, author nodes, institution nodes, and collaboration edges for the collaboration network.
Args:
work (Work): The work to process.
Returns:
Tuple[ Optional[WorkNetworkNode], Set[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated work node, author nodes, institution nodes, and collaboration edges.
"""
year = get_work_year(work)
topics_information = extract_topics_information(work=work)
work_node = create_work_node(
work=work, year=year, work_topics_information=topics_information
)
if not work_node:
return None, set(), set(), set()
authorships = work.authorships
if not authorships:
return work_node, set(), set(), set()
author_nodes: Set[AuthorNetworkNode] = set()
institution_nodes: Set[InstitutionNetworkNode] = set()
collaboration_edges: Set[CollaborationNetworkEdge] = set()
for authorship in authorships:
author_node, institution_nodes, associated_institution_edges = (
process_authorship(authorship=authorship)
)
if not author_node:
continue
work_author_edge = CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=work_node.raw_id,
)
author_nodes.add(author_node)
collaboration_edges.add(work_author_edge)
institution_nodes.update(institution_nodes)
collaboration_edges.update(associated_institution_edges)
return (
work_node,
author_nodes,
institution_nodes,
collaboration_edges,
)
def get_work_year(work: Work) -> int:
"""Extracts the publication year from a given work.
Args:
work (Work): The work from which to extract the publication year.
Returns:
int: The publication year of the work, or -1 if it cannot be extracted.
"""
if not work.publication_year:
return -1
try:
return int(work.publication_year)
except ValueError:
return -1
def create_work_node(
work: Work, year: int, work_topics_information: Set[WorkTopicInformation]
) -> Optional[WorkNetworkNode]:
"""Creates a collaboration network node representing a work based on the provided work data, publication year, and topic information.
Args:
work (Work): The work from which to create the collaboration network node.
year (int): The publication year of the work.
work_topics_information (Set[WorkTopicInformation]): The topic information of the work.
Returns:
Optional[WorkNetworkNode]: The collaboration network node representing the work, or None if the work data is invalid.
"""
if not work or not work.id or not work.display_name:
return None
work_id = extract_raw_work_id(work.id)
display_name = work.display_name
return WorkNetworkNode(
raw_id=work_id,
display_name=display_name,
category=CollaborationNetworkNodeType.WORK,
publication_year=year,
work_topics_information=work_topics_information,
)
def extract_topics_information(work: Work) -> Set[WorkTopicInformation]:
"""Extracts the topic information from a given work and returns it as a set of WorkTopicInformation objects.
Args:
work (Work): The work from which to extract topic information.
Returns:
Set[WorkTopicInformation]: A set of WorkTopicInformation objects representing the topics of the work.
"""
topics_information: Set[WorkTopicInformation] = set()
for topic in work.topics or []:
if not topic.id or not topic.display_name:
continue
raw_topic_id = extract_raw_topic_id(topic.id)
topics_information.add(
WorkTopicInformation(
raw_topic_id=raw_topic_id, display_name=topic.display_name
)
)
return topics_information
def process_authorship(
authorship: Authorship,
) -> Tuple[
Optional[AuthorNetworkNode],
Set[InstitutionNetworkNode],
Set[CollaborationNetworkEdge],
]:
"""Processes a given authorship to extract the associated author node, institution nodes, and collaboration edges.
Args:
authorship (Authorship): The authorship data to process.
Returns:
Tuple[ Optional[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated author node, institution nodes, and collaboration edges.
"""
author = authorship.author
if not author or not author.id or not author.display_name:
return None, set(), set()
author_node = create_author_node(author)
if not author_node:
return None, set(), set()
institution_nodes: Set[InstitutionNetworkNode] = set()
for institution in authorship.institutions or []:
institution_id = extract_raw_institution_id(institution.id or "")
if not institution_id or not institution.display_name:
continue
institution_node = create_institution_node(institution)
if institution_node:
institution_nodes.add(institution_node)
associated_institution_edges = create_associated_institution_edges(
author_node=author_node, institution_nodes=institution_nodes
)
return author_node, institution_nodes, associated_institution_edges
def create_associated_institution_edges(
author_node: AuthorNetworkNode,
institution_nodes: Set[InstitutionNetworkNode],
) -> Set[CollaborationNetworkEdge]:
"""Creates a set of collaboration network edges representing the associations between an author and their affiliated institutions.
Args:
author_node (AuthorNetworkNode): The collaboration network node representing the author.
institution_nodes (Set[InstitutionNetworkNode]): A set of collaboration network nodes representing the institutions affiliated with the author.
Returns:
Set[CollaborationNetworkEdge]: A set of collaboration network edges representing the associations between the author and their affiliated institutions.
"""
return {
CollaborationNetworkEdge(
raw_source_id=author_node.raw_id,
raw_target_id=institution_node.raw_id,
)
for institution_node in institution_nodes
}
def create_author_node(
author: Author | DehydratedAuthor,
) -> Optional[AuthorNetworkNode]:
"""Creates a collaboration network node representing an author based on the provided author data.
Args:
author (Author | DehydratedAuthor): The author data from which to create the collaboration network node.
Returns:
Optional[AuthorNetworkNode]: The collaboration network node representing the author, or None if the author data is invalid.
"""
if not author or not author.id or not author.display_name:
return None
author_id = extract_raw_author_id(author.id)
display_name = author.display_name
return AuthorNetworkNode(
raw_id=author_id,
display_name=display_name,
category=CollaborationNetworkNodeType.AUTHOR,
)
def create_institution_node(
institution: Institution | DehydratedInstitution,
) -> Optional[InstitutionNetworkNode]:
"""Creates a collaboration network node representing an institution based on the provided institution data.
Args:
institution (Institution | DehydratedInstitution): The institution data from which to create the collaboration network node.
Returns:
Optional[InstitutionNetworkNode]: The collaboration network node representing the institution, or None if the institution data is invalid.
"""
if not institution or not institution.id or not institution.display_name:
return None
institution_id = extract_raw_institution_id(institution.id)
display_name = institution.display_name
return InstitutionNetworkNode(
raw_id=institution_id,
display_name=display_name,
category=CollaborationNetworkNodeType.INSTITUTION,
)
+49 -14
View File
@@ -1,34 +1,69 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the configuration properties
that can be adjusted via environment variables.
This module contains the configuration properties
that can be adjusted via environment variables.
"""
from functools import lru_cache
import logging
from typing import Dict, List, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
load_dotenv()
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix='inse_')
# database config
database_url: str = 'sqlite:///../data/inse-sqlite.db'
database_url: str = "sqlite:///../data/inse-sqlite.db"
database_debug: bool = False
database_init: bool = True
# authorization config
# authorization config
auth_disabled: bool = False
auth_standalone: bool = True
auth_secret: str = 'change-me-to-a-secure-secret-key'
auth_secret: str = "change-me-to-a-secure-secret-key"
# OpenAlex works search config
openalex_works_search_base_url: str = 'https://project.nes.uni-due.de/elastic'
openalex_works_search_index: str = 'openalex-works'
openalex_works_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=='
openalex_works_search_base_url: str = "https://project.nes.uni-due.de/elastic"
# IMPORTANT: wildcard * needed to query all work indices
openalex_works_search_index: str = "openalex-works*"
openalex_works_api_key: str = (
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
)
openalex_works_search_timeout_seconds: float = 30.0
llm_api_url: str = 'https://project.nes.uni-due.de/llm2/api/generate'
llm_api_token: str = 'c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212'
llm_model: str = 'gemma4:e4b'
elasticsearch_url: str = 'https://project.nes.uni-due.de/elastic/'
elasticsearch_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=='
# OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org"
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# LLM config
llm_api_url: Optional[str] = None
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# elasticsearch config
elasticsearch_url: Optional[str] = None
elasticsearch_api_key: Optional[str] = None
model_config = SettingsConfigDict(env_file=".env")
allowed_origins: List[str] = ["http://localhost:4200"]
servers: List[Dict[str, str]] = [
{"url": "http://localhost:8000", "description": "Local development server"},
]
settings = Settings()
@lru_cache
def get_settings() -> Settings:
return settings
logger.info(f"Database URL: {settings.database_url}.")
logger.info(f"Serves at: {settings.servers}.")
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Funders domain package.
"""
@@ -0,0 +1,160 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for funded-publication searches in the OpenAlex works index.
"""
from typing import Any
import httpx
from .. import config
class MissingApiKeyError(Exception):
pass
class FundedPublicationsSearchClient:
def __init__(
self,
base_url: str | None = None,
index: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@staticmethod
def indexed_author_id(author_id: str) -> str:
short_id = author_id.strip().removeprefix("https://openalex.org/")
return f"https://openalex.org/{short_id}"
def publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
*,
funded_only: bool = False,
) -> dict[str, Any]:
indexed_author_id = self.indexed_author_id(author_id)
must: list[dict[str, Any]] = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": indexed_author_id,
},
},
},
},
]
if funded_only:
must.append(self._has_funding_clause())
return {
"from": (page - 1) * size,
"size": size,
"track_total_hits": True,
"_source": self._publication_source_fields(),
"query": {
"bool": {
"must": must,
},
},
}
@staticmethod
def _publication_source_fields() -> list[str]:
return [
"id",
"doi",
"title",
"display_name",
"publication_year",
"primary_location.landing_page_url",
"primary_location.pdf_url",
"best_oa_location.landing_page_url",
"best_oa_location.pdf_url",
"open_access.oa_url",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"funders.id",
"funders.display_name",
"funders.ror",
"awards.id",
"awards.funder_id",
"awards.funder_display_name",
"awards.funder_award_id",
]
@staticmethod
def _has_funding_clause() -> dict[str, Any]:
return {
"bool": {
"should": [
{
"nested": {
"path": "funders",
"query": {
"bool": {
"should": [
{"exists": {"field": "funders.id"}},
{"exists": {"field": "funders.display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
{
"nested": {
"path": "awards",
"query": {
"bool": {
"should": [
{"exists": {"field": "awards.funder_id"}},
{"exists": {"field": "awards.funder_display_name"}},
],
"minimum_should_match": 1,
},
},
},
},
],
"minimum_should_match": 1,
},
}
def funded_publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
) -> dict[str, Any]:
return self.publications_by_author_query(author_id, page, size, funded_only=True)
async def search(self, payload: dict[str, Any]) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{self.index}/_search",
headers={"Authorization": f"ApiKey {self.api_key}"},
json=payload,
)
response.raise_for_status()
return response.json()
+305
View File
@@ -0,0 +1,305 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for author funding based on publication works.
"""
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from .elastic_search_client import MissingApiKeyError
logger = logging.getLogger(__name__)
_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"})
_ES_PAGE_SIZE = 500
_MAX_ES_PAGES = 100
async def get_publications_by_author_id(
author_id: str,
page: int = 1,
page_size: int = 20,
client: FundedPublicationsSearchClient | None = None,
) -> model.PublicationsByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
total_works, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
funded_hits = [
hit for hit in all_hits
if _publication_has_funder_data(hit.get("_source", {}))
]
start = (page - 1) * page_size
end = start + page_size
return model.PublicationsByAuthorResponse(
author_id=FundedPublicationsSearchClient.indexed_author_id(author_id),
page=page,
page_size=page_size,
total_works=total_works,
total=len(funded_hits),
results_count=len(funded_hits[start:end]),
results=funded_hits[start:end],
)
async def get_funders_by_author_id(
author_id: str,
client: FundedPublicationsSearchClient | None = None,
) -> model.FundersByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
funder_counts: dict[str, dict[str, Any]] = {}
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
author_name = _get_author_name(author_id)
try:
_, all_hits = await _fetch_all_author_work_hits(
search_client,
author_id,
funded_only=True,
)
_collect_funders_from_publications(all_hits, author_id, funder_counts)
if not funder_counts:
logger.info(
"No funders aggregated for author %s from Elasticsearch.",
normalized_author_id,
)
funders = sorted(
funder_counts.values(),
key=lambda entry: entry["publication_count"],
reverse=True,
)
return model.FundersByAuthorResponse(
author_id=normalized_author_id,
author_name=author_name,
funder_count=len(funders),
funders=[model.FunderByAuthor.model_validate(entry) for entry in funders],
)
except ValidationError as exc:
logger.exception("Funders response could not be validated for author %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Funders response could not be parsed.",
) from exc
async def _fetch_all_author_work_hits(
search_client: FundedPublicationsSearchClient,
author_id: str,
*,
funded_only: bool = False,
page_size: int = _ES_PAGE_SIZE,
) -> tuple[int, list[dict]]:
page = 1
total_works = 0
all_hits: list[dict] = []
while page <= _MAX_ES_PAGES:
data = await _search_funded_publications(
search_client,
author_id,
page,
page_size,
funded_only=funded_only,
)
total_works, hits = _parse_publication_search_response(data)
all_hits.extend(hits)
if not hits or page * page_size >= total_works:
break
page += 1
if page > _MAX_ES_PAGES and page * page_size < total_works:
logger.warning(
"Stopped pagination for author %s at %s pages (total works: %s).",
author_id,
_MAX_ES_PAGES,
total_works,
)
return total_works, all_hits
async def _search_funded_publications(
search_client: FundedPublicationsSearchClient,
author_id: str,
page: int,
page_size: int,
*,
funded_only: bool = False,
) -> dict:
try:
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex works search request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
hits = data.get("hits", {})
total = hits.get("total", 0)
if isinstance(total, dict):
total = total.get("value", 0)
results = hits.get("hits", [])
for hit in results:
_add_publication_url(hit.get("_source", {}))
return total, results
def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = person_logic.search_persons(author_id=short_author_id)
if not search_result.results:
return None
return search_result.results[0].display_name
def _get_author_position_in_publication(publication: dict, author_id: str) -> str:
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
for authorship in publication.get("authorships", []):
author = authorship.get("author", {})
if author.get("id") == normalized_author_id:
position = authorship.get("author_position", "unknown")
if position in _VALID_AUTHOR_POSITIONS:
return position
return "unknown"
return "unknown"
def _publication_has_funder_data(publication: dict) -> bool:
for funder in publication.get("funders", []):
if funder.get("id") or funder.get("display_name"):
return True
for award in publication.get("awards", []):
if award.get("funder_id") or award.get("funder_display_name"):
return True
return False
def _add_publication_url(publication: dict) -> None:
publication["publication_url"] = _resolve_publication_url(publication)
def _resolve_publication_url(publication: dict) -> str | None:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
open_access = publication.get("open_access") or {}
for url in (
primary_location.get("pdf_url"),
best_oa_location.get("pdf_url"),
primary_location.get("landing_page_url"),
best_oa_location.get("landing_page_url"),
open_access.get("oa_url"),
):
if url:
return url
doi = publication.get("doi")
if doi:
return doi if doi.startswith("http") else f"https://doi.org/{doi}"
return publication.get("id")
def _collect_funders_from_publications(
results: list[dict],
author_id: str,
funder_counts: dict[str, dict[str, Any]],
) -> None:
for hit in results:
publication = hit.get("_source", {})
if not _publication_has_funder_data(publication):
continue
publication_id = publication.get("id")
publication_url = publication.get("publication_url") or _resolve_publication_url(publication)
author_position = _get_author_position_in_publication(publication, author_id)
publication_funders: set[tuple[str, str | None, str | None]] = set()
for funder in publication.get("funders", []):
funder_id = funder.get("id")
funder_name = funder.get("display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for award in publication.get("awards", []):
funder_id = award.get("funder_id")
funder_name = award.get("funder_display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for key, funder_id, funder_name in publication_funders:
if key not in funder_counts:
funder_counts[key] = {
"funder_id": funder_id,
"funder_name": funder_name,
"publication_count": 0,
"author_position_count": {
"first": 0,
"middle": 0,
"last": 0,
"unknown": 0,
},
"publication_ids": {
"first": [],
"middle": [],
"last": [],
"unknown": [],
},
"publication_urls": {},
"publication_titles": {},
}
entry = funder_counts[key]
entry["publication_count"] += 1
entry["author_position_count"][author_position] += 1
entry["publication_ids"][author_position].append(publication_id)
if publication_id and publication_url:
entry["publication_urls"][publication_id] = publication_url
if publication_id:
title = publication.get("display_name") or publication.get("title") or publication_id
entry["publication_titles"][publication_id] = title
+44
View File
@@ -0,0 +1,44 @@
from typing import Any
from pydantic import BaseModel
class PublicationsByAuthorResponse(BaseModel):
author_id: str
page: int
page_size: int
total_works: int
total: int
results_count: int
results: list[dict[str, Any]]
class PublicationIdsByAuthorPosition(BaseModel):
first: list[str] = []
middle: list[str] = []
last: list[str] = []
unknown: list[str] = []
class AuthorPositionCount(BaseModel):
first: int = 0
middle: int = 0
last: int = 0
unknown: int = 0
class FunderByAuthor(BaseModel):
funder_id: str | None = None
funder_name: str | None = None
publication_count: int
author_position_count: AuthorPositionCount
publication_ids: PublicationIdsByAuthorPosition
publication_urls: dict[str, str] = {}
publication_titles: dict[str, str] = {}
class FundersByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
funder_count: int
funders: list[FunderByAuthor]
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for author publications and funding.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from . import logic
from . import model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
@router.get(
"/{author_id}/publications",
operation_id="getPublicationsByAuthor",
response_model=model.PublicationsByAuthorResponse,
summary="Get funded publications by author.",
)
async def get_publications_by_author(
author_id: str,
page: Annotated[int, Query(ge=1)] = 1,
page_size: Annotated[int, Query(ge=1, le=1000)] = 200,
):
return await logic.get_publications_by_author_id(author_id, page, page_size)
@router.get(
"/{author_id}/funders",
operation_id="getFundersByAuthor",
response_model=model.FundersByAuthorResponse,
summary="Get funding organizations by author.",
)
async def get_funders_by_author(author_id: str):
return await logic.get_funders_by_author_id(author_id)
+263
View File
@@ -0,0 +1,263 @@
import json
import httpx
import pytest
from fastapi import HTTPException
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def _funded_publication_hit(
work_id: str,
*,
funder_id: str | None = "https://openalex.org/F123",
funder_name: str | None = "Example Funder",
author_position: str = "first",
award_funder_id: str | None = None,
award_funder_name: str | None = None,
pdf_url: str | None = None,
) -> dict:
source: dict = {
"id": work_id,
"primary_location": {
"pdf_url": pdf_url,
},
"authorships": [
{
"author": {
"id": "https://openalex.org/A5023888391",
"display_name": "Example Author",
},
"author_position": author_position,
}
],
"funders": [],
"awards": [],
}
if funder_id or funder_name:
source["funders"].append(
{
"id": funder_id,
"display_name": funder_name,
}
)
if award_funder_id or award_funder_name:
source["awards"].append(
{
"funder_id": award_funder_id,
"funder_display_name": award_funder_name,
}
)
return {"_source": source}
@pytest.mark.anyio
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
assert payload["from"] == 0
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Funder A",
author_position="first",
pdf_url="https://example.org/w1.pdf",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
author_position="last",
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert response.author_id == "https://openalex.org/A5023888391"
assert response.author_name == "Example Author"
assert response.funder_count == 1
assert response.funders[0].funder_id == "https://openalex.org/F123"
assert response.funders[0].funder_name == "Funder A"
assert response.funders[0].publication_count == 2
assert response.funders[0].author_position_count.first == 1
assert response.funders[0].author_position_count.last == 1
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
@pytest.mark.anyio
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
requested_pages: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
size = payload["size"]
offset = payload["from"]
page = offset // size + 1
requested_pages.append(page)
total = size + 1
if page == 1:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{i}",
funder_id=f"https://openalex.org/F{i}",
funder_name=f"Funder {i}",
)
for i in range(1, size + 1)
]
else:
hits = [
_funded_publication_hit(
f"https://openalex.org/W{total}",
funder_id=f"https://openalex.org/F{total}",
funder_name=f"Funder {total}",
)
]
return httpx.Response(
200,
json={
"hits": {
"total": {"value": total},
"hits": hits,
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert requested_pages == [1, 2]
assert response.funder_count > 1
funder_names = {funder.funder_name for funder in response.funders}
assert "Funder 1" in funder_names
@pytest.mark.anyio
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Bundesministerium",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 1
assert response.funders[0].funder_name == "Bundesministerium"
assert response.funders[0].publication_count == 1
@pytest.mark.anyio
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={"hits": {"total": {"value": 0}, "hits": []}},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5093075883", client=client)
assert response.funder_count == 0
assert response.funders == []
@pytest.mark.anyio
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(api_key="")
with pytest.raises(HTTPException) as exc:
await logic.get_funders_by_author_id("A5023888391", client=client)
assert exc.value.status_code == 503
@@ -0,0 +1 @@
"""Institution lookup module."""
+309
View File
@@ -0,0 +1,309 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for OpenAlex institutions.
"""
import logging
from copy import deepcopy
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.institutions_list_response import InstitutionsListResponse
from .search_client import OpenAlexInstitutionsClient
logger = logging.getLogger(__name__)
_VALID_INSTITUTION_TYPES = {
"education",
"healthcare",
"company",
"archive",
"nonprofit",
"government",
"facility",
"other",
}
async def list_institutions(
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
client: OpenAlexInstitutionsClient | None = None,
) -> InstitutionsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
openalex_client = client or OpenAlexInstitutionsClient()
try:
data = await openalex_client.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
except httpx.HTTPStatusError as exc:
status_code = exc.response.status_code
detail = "OpenAlex institutions request failed."
try:
error_body = exc.response.json()
detail = error_body.get("message") or error_body.get("error") or detail
except ValueError:
if exc.response.text:
detail = exc.response.text
raise HTTPException(status_code=status_code, detail=detail) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex institutions request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions request failed.",
) from exc
try:
normalized_data = _normalize_institutions_response(data)
return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse()
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions response could not be parsed.",
) from exc
async def autocomplete_institutions(
*,
query: str,
country_code: str | None = None,
institution_type: str | None = None,
limit: int = 10,
client: OpenAlexInstitutionsClient | None = None,
) -> AutocompleteResponse:
filters = []
if country_code:
filters.append(f"country_code:{country_code}")
if institution_type:
filters.append(f"type:{institution_type}")
response = await list_institutions(
search=query,
filter=",".join(filters) if filters else None,
sort="works_count:desc",
per_page=limit,
page=1,
select=(
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
),
client=client,
)
results = []
for institution in response.results or []:
if not institution.id or not institution.display_name:
continue
hint_parts = []
if institution.geo:
if institution.geo.city:
hint_parts.append(institution.geo.city)
if institution.geo.country:
hint_parts.append(institution.geo.country)
elif institution.country_code:
hint_parts.append(institution.country_code)
if institution.type:
hint_parts.append(institution.type)
results.append(
AutocompleteResponseResultsInner(
id=institution.id,
display_name=institution.display_name,
hint=" · ".join(hint_parts) if hint_parts else None,
cited_by_count=institution.cited_by_count,
works_count=institution.works_count,
entity_type="institution",
external_id=institution.ror,
)
)
return AutocompleteResponse(
meta=AutocompleteResponseMeta(
count=response.meta.count if response.meta else len(results),
db_response_time_ms=(
response.meta.db_response_time_ms if response.meta else None
),
),
results=results,
)
def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
normalized = deepcopy(data)
meta = normalized.get("meta")
if isinstance(meta, dict):
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
meta[field] = _int_or_none(meta.get(field))
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
for institution in normalized.get("results") or []:
if not isinstance(institution, dict):
continue
for field in [
"id",
"ror",
"display_name",
"country_code",
"homepage_url",
"image_url",
"image_thumbnail_url",
"works_api_url",
]:
institution[field] = _str_or_none(institution.get(field))
institution_type = institution.get("type")
if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES:
institution["type"] = None
else:
institution["type"] = _str_or_none(institution_type)
institution["display_name_acronyms"] = _str_list_or_none(
institution.get("display_name_acronyms")
)
institution["display_name_alternatives"] = _str_list_or_none(
institution.get("display_name_alternatives")
)
institution["lineage"] = _str_list_or_none(institution.get("lineage"))
institution["works_count"] = _int_or_none(institution.get("works_count"))
institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count"))
institution["created_date"] = _date_str_or_none(institution.get("created_date"))
institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date"))
summary_stats = institution.get("summary_stats")
if isinstance(summary_stats, dict):
summary_stats["2yr_mean_citedness"] = _number_or_none(
summary_stats.get("2yr_mean_citedness")
)
summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index"))
summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index"))
geo = institution.get("geo")
if isinstance(geo, dict):
for field in [
"city",
"geonames_city_id",
"region",
"country_code",
"country",
]:
geo[field] = _str_or_none(geo.get(field))
geo["latitude"] = _number_or_none(geo.get("latitude"))
geo["longitude"] = _number_or_none(geo.get("longitude"))
ids = institution.get("ids")
if isinstance(ids, dict):
for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]:
ids[field] = _str_or_none(ids.get(field))
ids["mag"] = _int_or_none(ids.get("mag"))
for counts_by_year in institution.get("counts_by_year") or []:
if not isinstance(counts_by_year, dict):
continue
for field in ["year", "works_count", "cited_by_count"]:
counts_by_year[field] = _int_or_none(counts_by_year.get(field))
for group in normalized.get("group_by") or []:
if not isinstance(group, dict):
continue
group["key"] = _str_or_none(group.get("key"))
group["key_display_name"] = _str_or_none(group.get("key_display_name"))
group["count"] = _int_or_none(group.get("count"))
return normalized
def _str_or_none(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, bool):
return str(value).lower()
return str(value)
def _str_list_or_none(value: Any) -> list[str] | None:
if value is None:
return None
if not isinstance(value, list):
return None
return [_str_or_none(item) for item in value if item is not None]
def _int_or_none(value: Any) -> int | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(float(value))
except ValueError:
return None
return None
def _number_or_none(value: Any) -> int | float | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return value
if isinstance(value, str):
try:
number = float(value)
except ValueError:
return None
return int(number) if number.is_integer() else number
return None
def _date_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
return text[:10]
def _datetime_str_or_none(value: Any) -> str | None:
text = _str_or_none(value)
if not text:
return None
if len(text) == 10:
return f"{text}T00:00:00Z"
return text
@@ -0,0 +1,95 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for OpenAlex institutions.
"""
from typing import Any
import httpx
from .. import config
class OpenAlexInstitutionsClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds
self.transport = transport
def list_institutions_params(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": per_page}
if search:
params["search"] = search
if filter:
params["filter"] = filter
if sort:
params["sort"] = sort
if group_by:
params["group_by"] = group_by
if cursor:
params["cursor"] = cursor
elif page is not None:
params["page"] = page
if sample is not None:
params["sample"] = sample
if select:
params["select"] = select
if self.api_key:
params["api_key"] = self.api_key
return params
async def list_institutions(
self,
*,
search: str | None = None,
filter: str | None = None,
sort: str | None = None,
group_by: str | None = None,
per_page: int = 25,
page: int | None = 1,
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.get(
"/institutions",
params=self.list_institutions_params(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
),
)
response.raise_for_status()
return response.json()
@@ -0,0 +1,108 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from . import logic
router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
@router.get(
"/autocomplete",
operation_id="autocompleteInstitutions",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns institution options for autocomplete inputs.",
)
async def autocomplete_institutions(
query: Annotated[
str,
Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1),
],
country_code: Annotated[
str | None,
Query(alias="countryCode", description="Optional ISO country code filter."),
] = None,
institution_type: Annotated[
str | None,
Query(alias="type", description="Optional institution type filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
):
return await logic.autocomplete_institutions(
query=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
)
@router.get(
"",
operation_id="listInstitutions",
response_model=InstitutionsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex institutions.",
)
async def list_institutions(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'Duisburg Essen'."),
] = None,
filter: Annotated[
str | None,
Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'country_code'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
@@ -0,0 +1,236 @@
import httpx
import pytest
from fastapi import HTTPException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_list_institutions_maps_openalex_response_to_model():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
"homepage_url": "https://www.uni-due.de",
"image_url": "https://example.org/image.jpg",
"image_thumbnail_url": "https://example.org/thumb.jpg",
"display_name_acronyms": ["UDE"],
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
"works_count": 123,
"cited_by_count": 456,
"summary_stats": {
"2yr_mean_citedness": 1.5,
"h_index": 42,
"i10_index": 99,
},
"geo": {
"city": "Duisburg",
"geonames_city_id": "2934691",
"region": "North Rhine-Westphalia",
"country_code": "DE",
"country": "Germany",
"latitude": 51.4344,
"longitude": 6.7623,
},
"lineage": ["https://openalex.org/I123"],
"ids": {
"openalex": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"mag": 123,
"grid": "grid.12345.6",
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
"wikidata": "https://www.wikidata.org/wiki/Q317070",
},
"counts_by_year": [
{
"year": 2024,
"works_count": 12,
"cited_by_count": 34,
}
],
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
"created_date": "2023-12-25",
"updated_date": "2023-11-07T05:31:56Z",
}
],
"group_by": [
{
"key": "DE",
"key_display_name": "Germany",
"count": 1,
}
],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_institutions(search="Duisburg Essen", client=client)
assert result.meta.count == 1
institution = result.results[0]
assert institution.display_name == "University of Duisburg-Essen"
assert institution.summary_stats.h_index == 42
assert institution.geo.country == "Germany"
assert institution.ids.mag == 123
assert institution.counts_by_year[0].year == 2024
assert result.group_by[0].key_display_name == "Germany"
@pytest.mark.anyio
async def test_list_institutions_rejects_sample_with_sort():
with pytest.raises(HTTPException) as exc_info:
await logic.list_institutions(sample=10, sort="works_count:desc")
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_list_institutions_accepts_practical_openalex_type_variants():
def handler(_: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": 123,
"ror": 456,
"display_name": "Example Institute",
"country_code": 789,
"type": "unknown-openalex-type",
"display_name_acronyms": ["EI", 123],
"display_name_alternatives": "not-a-list",
"works_count": "12",
"cited_by_count": "34.0",
"summary_stats": {
"2yr_mean_citedness": "1.25",
"h_index": "10.0",
"i10_index": True,
},
"geo": {
"city": 123,
"geonames_city_id": 12345,
"latitude": "51.4",
"longitude": "6",
},
"ids": {"openalex": 123, "mag": "123"},
"counts_by_year": [
{
"year": "2024",
"works_count": "12.0",
"cited_by_count": False,
}
],
"created_date": "2023-12-25T10:11:12Z",
"updated_date": "2023-12-25",
}
],
"group_by": [{"key": True, "count": 1}],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.list_institutions(client=client)
assert result.results[0].id == "123"
assert result.results[0].ror == "456"
assert result.results[0].country_code == "789"
assert result.results[0].type is None
assert result.results[0].display_name_acronyms == ["EI", "123"]
assert result.results[0].display_name_alternatives is None
assert result.results[0].works_count == 12
assert result.results[0].cited_by_count == 34
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
assert result.results[0].summary_stats.h_index == 10
assert result.results[0].summary_stats.i10_index is None
assert result.results[0].geo.city == "123"
assert result.results[0].geo.geonames_city_id == "12345"
assert result.results[0].geo.latitude == 51.4
assert result.results[0].geo.longitude == 6
assert result.results[0].ids.openalex == "123"
assert result.results[0].ids.mag == 123
assert result.results[0].counts_by_year[0].year == 2024
assert result.results[0].counts_by_year[0].works_count == 12
assert result.results[0].counts_by_year[0].cited_by_count is None
assert result.group_by[0].key == "true"
@pytest.mark.anyio
async def test_autocomplete_institutions_returns_frontend_options():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["search"] == "Duisburg Essen"
assert request.url.params["filter"] == "country_code:DE,type:education"
assert request.url.params["sort"] == "works_count:desc"
assert request.url.params["per_page"] == "5"
assert request.url.params["select"] == (
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
)
return httpx.Response(
200,
json={
"meta": {"count": 1, "db_response_time_ms": 12},
"results": [
{
"id": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
"works_count": 123,
"cited_by_count": 456,
"geo": {
"city": "Duisburg",
"country": "Germany",
},
}
],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.autocomplete_institutions(
query="Duisburg Essen",
country_code="DE",
institution_type="education",
limit=5,
client=client,
)
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
assert len(result.results) == 1
option = result.results[0]
assert option.id == "https://openalex.org/I123"
assert option.display_name == "University of Duisburg-Essen"
assert option.hint == "Duisburg · Germany · education"
assert option.works_count == 123
assert option.cited_by_count == 456
assert option.entity_type == "institution"
assert option.external_id == "https://ror.org/04mz5ra38"
@@ -0,0 +1,77 @@
import httpx
import pytest
from inse.institutions.search_client import OpenAlexInstitutionsClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def test_list_institutions_params_include_openalex_query_parameters():
client = OpenAlexInstitutionsClient(api_key="test-key")
params = client.list_institutions_params(
search="Duisburg Essen",
filter="country_code:DE,type:education",
sort="works_count:desc",
group_by="country_code",
per_page=10,
page=2,
select="id,display_name",
)
assert params == {
"search": "Duisburg Essen",
"filter": "country_code:DE,type:education",
"sort": "works_count:desc",
"group_by": "country_code",
"per_page": 10,
"page": 2,
"select": "id,display_name",
"api_key": "test-key",
}
def test_list_institutions_params_prefers_cursor_over_page():
client = OpenAlexInstitutionsClient(api_key="test-key")
params = client.list_institutions_params(cursor="*", page=3)
assert params["cursor"] == "*"
assert "page" not in params
@pytest.mark.anyio
async def test_list_institutions_calls_openalex_institutions_endpoint():
def handler(request: httpx.Request) -> httpx.Response:
assert request.method == "GET"
assert request.url.path == "/institutions"
assert request.url.params["search"] == "Duisburg Essen"
assert request.url.params["api_key"] == "test-key"
return httpx.Response(
200,
json={
"meta": {"count": 1, "page": 1, "per_page": 25},
"results": [
{
"id": "https://openalex.org/I123",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
}
],
},
)
client = OpenAlexInstitutionsClient(
base_url="https://api.openalex.org",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await client.list_institutions(search="Duisburg Essen")
assert result["meta"]["count"] == 1
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
@@ -0,0 +1,80 @@
from typing import Any, Optional
import httpx
from .. import config
def search(
index: str,
query_field: str = None,
query_value: str = None,
query: dict = None,
source = None,
size: int = None,
offset:int = None,
sort: list = None,
body: dict = None,
track_total_hits = False
) -> dict[str, Any]:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
if body is not None:
payload = body
elif query is not None:
payload = {"query": query}
if source is not None:
payload["_source"] = source
if size is not None:
payload["size"] = size
if offset is not None:
payload["from"] = offset
if sort is not None:
payload["sort"] = sort
if track_total_hits:
payload["track_total_hits"] = True
else:
payload = {
"query": {
"query_string": {
"default_field": query_field,
"query": query_value
}
}
}
with httpx.Client() as client:
response = client.post(
f"{config.settings.elasticsearch_url}/{index}/_search",
json=payload,
headers=headers
)
response.raise_for_status()
return response.json()
def get(
index: str,
doc_id: str,
source: list = None,
) -> dict[str, Any]:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
with httpx.Client() as client:
response = client.get(
f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}",
params=params,
headers=headers
)
response.raise_for_status()
return response.json()
+40
View File
@@ -0,0 +1,40 @@
from openai import OpenAI, APIConnectionError
from .. import config
def call(
system_prompt: str,
user_prompt: str,
model: str = None,
timeout: int = 30,
temperature: float = 1.0,
top_p: float = 0.95,
) -> str:
if model is None:
model = config.settings.llm_model
client = OpenAI(
base_url=config.settings.llm_api_url,
api_key=config.settings.llm_api_key,
timeout=timeout,
)
try:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
)
except APIConnectionError:
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
return response.choices[0].message.content or (
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
)
+126 -153
View File
@@ -1,18 +1,16 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the business logic for our
web service.
This module defines the business logic for our
web service.
"""
from typing import List
from typing import TypeVar
from typing import Optional
from typing import Type
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy import delete
from sqlalchemy import insert
from sqlalchemy import update
from sqlalchemy import func
import logging
import httpx
@@ -21,7 +19,17 @@ from . import schema
from . import model
from . import config
from inse.models.topic import Topic
from inse.models.topic_subfield import TopicSubfield
from inse.models.topic_field import TopicField
from inse.models.topic_domain import TopicDomain
logger = logging.getLogger(__name__)
topic_cache_filename: str = "topic_hierarchy_cache.json"
S = TypeVar('S', bound=schema.Base)
@@ -30,7 +38,15 @@ M = TypeVar('M', bound=model.BaseModel)
def filter_none():
return True
def get_page(db: Session, schema_type: Type[S], model_type: Type[M], offset: int, limit: int, filter=filter_none) -> model.Page[M]:
def get_page(
db: Session,
schema_type: Type[S],
model_type: Type[M],
offset: int,
limit: int,
filter=filter_none,
) -> model.Page[M]:
result = model.Page[model_type]()
result.offset = offset
result.total = get_count(db, schema_type, filter)
@@ -41,51 +57,67 @@ def get_page(db: Session, schema_type: Type[S], model_type: Type[M], offset: int
result.elements = []
return result
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
def get_elements(db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none) -> List[S]:
return db.scalars(select(schema_type).where(filter).offset(offset).limit(limit)).all()
def get_elements(
db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none
) -> List[S]:
return db.scalars(
select(schema_type).where(filter).offset(offset).limit(limit)
).all()
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
return db.scalars(select(schema_type).where(schema_type.id == element_id).limit(1)).first()
return db.scalars(
select(schema_type).where(schema_type.id == element_id).limit(1)
).first()
def delete_element(db: Session, schema_type: Type[S], element_id: int):
element = get_element(db, schema_type, element_id)
db.delete(element)
def insert_element(db: Session, value: S) -> S:
db.add(value)
db.flush()
db.refresh(value)
return value
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file. """
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
current_dir = os.path.dirname(__file__)
cache_path = os.path.join(current_dir, "..", "data", topic_cache_filename)
with open(cache_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as exc:
logger.warning("Failed to load topic hierarchy cache: %s", exc)
return {}
def build_topic_cache(page_size: int = 200,
save_json: bool = True) -> dict:
def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict:
"""
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
Arguments:
page_size (int): Number of topics to fetch per request (default: 200)
save_json (bool): Whether to save the cache as a JSON file (default: True)
Returns:
taxonomy_cache (dict): The topic hierarchy dictionary.
"""
output_filename: str = "topic_hierarchy_cache.json"
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
"Content-Type": "application/json",
}
taxonomy_cache = {}
@@ -93,12 +125,12 @@ def build_topic_cache(page_size: int = 200,
with httpx.Client(timeout=30.0) as client:
while True:
payload = {
"query": {"match_all": {}},
"from": offset,
"size": page_size
}
response = client.post(config.settings.elasticsearch_url + '/openalex-topics/_search', json=payload, headers=headers)
payload = {"query": {"match_all": {}}, "from": offset, "size": page_size}
response = client.post(
config.settings.elasticsearch_url + "/openalex-topics/_search",
json=payload,
headers=headers,
)
response.raise_for_status()
data = response.json()
@@ -116,7 +148,7 @@ def build_topic_cache(page_size: int = 200,
"topic_id": source.get("id") or hit.get("_id", ""),
"subfield": source.get("subfield", {}).get("display_name", ""),
"field": source.get("field", {}).get("display_name", ""),
"domain": source.get("domain", {}).get("display_name", "")
"domain": source.get("domain", {}).get("display_name", ""),
}
offset += len(hits)
@@ -134,13 +166,14 @@ def build_topic_cache(page_size: int = 200,
return taxonomy_cache
def get_topics_from_cache(topic_names: List[str]) -> List[model.Topic]:
def get_topics_from_cache(topic_names: List[str]) -> List[Topic]:
"""
Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models.
Arguments:
topic_names (List[str]): A list of topic names to retrieve.
Returns:
List[model.Topic]: A list of Topic models.
List[Topic]: A list of Topic models.
"""
cache = _load_topic_cache()
topics = []
@@ -148,15 +181,24 @@ def get_topics_from_cache(topic_names: List[str]) -> List[model.Topic]:
data = cache.get(name)
if not data:
continue
topics.append(model.Topic(
id=data.get("topic_id", ""),
name=name,
subfield=data.get("subfield", ""),
field=data.get("field", ""),
domain=data.get("domain", "")
))
subfield_name = data.get("subfield", "")
field_name = data.get("field", "")
domain_name = data.get("domain", "")
topics.append(
Topic(
id=data.get("topic_id", ""),
display_name=name,
works_count=data.get("count", 1),
subfield=TopicSubfield(display_name=subfield_name)
if subfield_name
else None,
field=TopicField(display_name=field_name) if field_name else None,
domain=TopicDomain(display_name=domain_name) if domain_name else None,
)
)
return topics
def count_topic_hierarchy(topic_names: List[str]) -> dict:
"""
Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache.
@@ -166,12 +208,7 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
dict: A dictionary containing the counts of each hierarchy level.
"""
cache = _load_topic_cache()
counts = {
"topics": {},
"subfields": {},
"fields": {},
"domains": {}
}
counts = {"topics": {}, "subfields": {}, "fields": {}, "domains": {}}
for name in topic_names:
data = cache.get(name)
@@ -194,120 +231,56 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
return counts
### persons
def search_persons(author_id: Optional[str] = None, query: Optional[str] = None,
include: Optional[set[str]] = None) -> model.PersonSearchResult:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
if author_id:
query_field = "_id"
query_value = author_id
elif query:
query_field = "display_name"
query_value = query
else:
return "Either author_id or query must be provided"
payload = {
"query": {
"query_string": {
"default_field": query_field,
"query": query_value
}
}
}
with httpx.Client() as client:
response = client.post(config.settings.elasticsearch_url + '/openalex-authors/_search', json=payload, headers=headers)
response.raise_for_status()
data = response.json()
include_set = {tag.strip().lower() for tag in include} if include else set()
persons = []
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
affiliations = []
for aff in source.get("affiliations", []):
institution = aff.get("institution", {})
affiliations.append(model.Affiliation(
institution=institution.get("display_name", ""),
country_code=institution.get("country_code", "")
))
topics = [t.get("display_name", "") for t in source.get("topics", [])]
person_data = {
"id": hit.get("_id", ""),
"name": source.get("display_name", ""),
"works_count": source.get("works_count", 0),
"cited_by_count": source.get("cited_by_count", 0),
"affiliations": affiliations,
"topics": topics
}
# Include optional fields based on the include_set
if "topics_full" in include_set:
person_data["topics_full"] = source.get("topics", [])
if "topic_share" in include_set:
person_data["topic_share"] = source.get("topic_share", [])
if "summary_stats" in include_set:
person_data["summary_stats"] = source.get("summary_stats")
if "ids" in include_set:
person_data["ids"] = source.get("ids")
if "last_known_institutions" in include_set:
person_data["last_known_institutions"] = source.get("last_known_institutions", [])
if "sources" in include_set:
person_data["sources"] = source.get("sources", [])
if "counts_by_year" in include_set:
person_data["counts_by_year"] = source.get("counts_by_year", [])
if "works_api_url" in include_set:
person_data["works_api_url"] = source.get("works_api_url")
if "dates" in include_set:
person_data["dates"] = {
"created_date": source.get("created_date"),
"updated_date": source.get("updated_date")
}
if "cited_by_count_boost" in include_set:
person_data["cited_by_count_boost"] = source.get("cited_by_count_boost")
persons.append(model.Person(**person_data))
return model.PersonSearchResult(persons=persons)
def generate_person_bio(author_id: str) -> str:
search_result = search_persons(author_id=author_id)
if not search_result.persons:
return "No person found."
if len(search_result.persons) > 1:
return "Multiple persons found, cannot generate bio."
person = search_result.persons[0]
person_json = json.dumps(person.model_dump())
system_prompt = "Erstelle eine Beschreibung der Person in 3-5 Sätzen. Gebe nur die Beschreibung zurück, ohne Einleitung oder Schluss."
user_prompt = f"Daten zur Person:\n{person_json}"
headers = {
"Authorization": f"Bearer {config.settings.llm_api_token}",
"Content-Type": "application/json"
}
payload = {
"model": config.settings.llm_model,
"prompt": f"{system_prompt}\n{user_prompt}",
"stream": False
}
with httpx.Client(timeout=30.0) as client:
response = client.post(config.settings.llm_api_url, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("response", "")
def get_topic_hierarchy() -> dict:
"""
Builds and returns a hierarchical tree structure of topics:
Domains -> Fields -> Subfields -> Topics
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({
"id": topic_id,
"name": topic_name
})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
for f_name, f_subfields in d_fields.items():
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({
"name": sf_name,
"topics": sf_topics
})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({
"name": f_name,
"subfields": formatted_subfields
})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({
"name": d_name,
"fields": formatted_fields
})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
+40 -10
View File
@@ -1,26 +1,56 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the bootstrapping code
for fastapi that loads the service and the
webapp.
This module contains the bootstrapping code
for fastapi that loads the service and the
webapp.
"""
import logging
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from inse.collaboration_network.router import router as collaboration_network_router
from inse.institutions.service import router as institutions_service_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from . import config
from . import service
from . import webapp
from .account import service as account
from .service import router as service_router
from .account.service import router as account_router
logger = logging.getLogger(__name__)
### startup
app = FastAPI(redoc_url=None, docs_url=None)
app.mount("/inse-service", service.app)
app.mount("/inse-webapp", webapp.app)
app.mount("/inse-account", account.app)
settings = config.get_settings()
app = FastAPI(
redoc_url=None,
title="Innovation Search Engine API",
description="API for the Innovation Search Engine (INSE) application.",
version="0.1.0",
servers=settings.servers,
)
app.include_router(collaboration_network_router)
app.include_router(institutions_service_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
app.include_router(service_router)
app.include_router(account_router)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(404)
async def redirect(_, __):
-35
View File
@@ -36,40 +36,5 @@ class Page(BaseModel, Generic[T]):
class ItemPage(Page[Item]):
pass
class Topic(BaseModel):
id: str = Field(description="The openalex topic id.")
name: str = Field(description="The topic name.")
subfield: str = Field(description="The subfield of the topic.")
field: str = Field(description="The field of the topic.")
domain: str = Field(description="The domain of the topic.")
class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.")
class Affiliation(BaseModel):
institution: str = Field(description="Institution name.")
country_code: Optional[str] = Field(default=None, description="Country code.")
class Person(BaseModel):
id: str = Field(description="The person id.")
name: str = Field(description="The person name.")
works_count: int = Field(description="Number of works.")
cited_by_count: int = Field(description="Number of citations.")
affiliations: List[Affiliation] = Field(default=[], description="Affiliations.")
topics: List[str] = Field(default=[], description="Research topics.")
# Optional detailed information
topics_full: Optional[List[dict]] = Field(default=None, description="Detailed topics with hierarchy.")
topic_share: Optional[List[dict]] = Field(default=None, description="Topic share distribution.")
summary_stats: Optional[dict] = Field(default=None, description="Summary statistics.")
ids: Optional[dict] = Field(default=None, description="External identifiers.")
last_known_institutions: Optional[List[dict]] = Field(default=None, description="Last known institutions.")
sources: Optional[List[dict]] = Field(default=None, description="Sources list.")
counts_by_year: Optional[List[dict]] = Field(default=None, description="Counts by year.")
works_api_url: Optional[str] = Field(default=None, description="Works API URL.")
dates: Optional[dict] = Field(default=None, description="Created and updated dates.")
cited_by_count_boost: Optional[int] = Field(default=None, description="Cited by count boost.")
class PersonSearchResult(BaseModel):
persons: List[Person] = Field(default=[], description="List of found persons.")
Binary file not shown.
+128
View File
@@ -0,0 +1,128 @@
# coding: utf-8
# flake8: noqa
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
# import models into model package
from inse.models.author import Author
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.author_ids import AuthorIds
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.author_summary_stats import AuthorSummaryStats
from inse.models.author_topics_inner import AuthorTopicsInner
from inse.models.authors_list_response import AuthorsListResponse
from inse.models.authorship import Authorship
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.award import Award
from inse.models.award_full import AwardFull
from inse.models.award_full_funder import AwardFullFunder
from inse.models.awards_list_response import AwardsListResponse
from inse.models.concept import Concept
from inse.models.concept_ids import ConceptIds
from inse.models.concepts_list_response import ConceptsListResponse
from inse.models.continent import Continent
from inse.models.continent_ids import ContinentIds
from inse.models.continents_list_response import ContinentsListResponse
from inse.models.countries_list_response import CountriesListResponse
from inse.models.country import Country
from inse.models.country_continent import CountryContinent
from inse.models.country_ids import CountryIds
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_funder import DehydratedFunder
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.dehydrated_source import DehydratedSource
from inse.models.domain import Domain
from inse.models.domain_fields_inner import DomainFieldsInner
from inse.models.domain_ids import DomainIds
from inse.models.domains_list_response import DomainsListResponse
from inse.models.error import Error
from inse.models.fields_list_response import FieldsListResponse
from inse.models.funder import Funder
from inse.models.funder_ids import FunderIds
from inse.models.funders_list_response import FundersListResponse
from inse.models.get_changefile200_response import GetChangefile200Response
from inse.models.get_changefile200_response_meta import GetChangefile200ResponseMeta
from inse.models.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
from inse.models.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
from inse.models.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
from inse.models.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
from inse.models.group_by_result import GroupByResult
from inse.models.institution import Institution
from inse.models.institution_geo import InstitutionGeo
from inse.models.institution_ids import InstitutionIds
from inse.models.institution_type import InstitutionType
from inse.models.institution_types_list_response import InstitutionTypesListResponse
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.models.keyword import Keyword
from inse.models.keywords_list_response import KeywordsListResponse
from inse.models.language import Language
from inse.models.languages_list_response import LanguagesListResponse
from inse.models.license import License
from inse.models.licenses_list_response import LicensesListResponse
from inse.models.list_changefiles200_response import ListChangefiles200Response
from inse.models.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
from inse.models.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
from inse.models.location import Location
from inse.models.meta import Meta
from inse.models.model_field import ModelField
from inse.models.open_access import OpenAccess
from inse.models.publisher import Publisher
from inse.models.publisher_ids import PublisherIds
from inse.models.publisher_parent_publisher import PublisherParentPublisher
from inse.models.publishers_list_response import PublishersListResponse
from inse.models.rate_limit_response import RateLimitResponse
from inse.models.rate_limit_response_rate_limit import RateLimitResponseRateLimit
from inse.models.rate_limit_response_rate_limit_endpoint_costs_usd import RateLimitResponseRateLimitEndpointCostsUsd
from inse.models.sdg import Sdg
from inse.models.sdg_ids import SdgIds
from inse.models.sdgs_list_response import SdgsListResponse
from inse.models.source import Source
from inse.models.source_ids import SourceIds
from inse.models.source_type import SourceType
from inse.models.source_types_list_response import SourceTypesListResponse
from inse.models.sources_list_response import SourcesListResponse
from inse.models.subfield import Subfield
from inse.models.subfield_domain import SubfieldDomain
from inse.models.subfield_field import SubfieldField
from inse.models.subfields_list_response import SubfieldsListResponse
from inse.models.text_classification_response import TextClassificationResponse
from inse.models.text_classification_response_meta import TextClassificationResponseMeta
from inse.models.topic import Topic
from inse.models.topic_domain import TopicDomain
from inse.models.topic_field import TopicField
from inse.models.topic_ids import TopicIds
from inse.models.topic_subfield import TopicSubfield
from inse.models.topics_list_response import TopicsListResponse
from inse.models.work import Work
from inse.models.work_biblio import WorkBiblio
from inse.models.work_citation_normalized_percentile import WorkCitationNormalizedPercentile
from inse.models.work_cited_by_percentile_year import WorkCitedByPercentileYear
from inse.models.work_counts_by_year_inner import WorkCountsByYearInner
from inse.models.work_has_content import WorkHasContent
from inse.models.work_ids import WorkIds
from inse.models.work_keyword import WorkKeyword
from inse.models.work_mesh_inner import WorkMeshInner
from inse.models.work_sustainable_development_goals_inner import WorkSustainableDevelopmentGoalsInner
from inse.models.work_topic import WorkTopic
from inse.models.work_topic_domain import WorkTopicDomain
from inse.models.work_topic_field import WorkTopicField
from inse.models.work_topic_subfield import WorkTopicSubfield
from inse.models.work_type import WorkType
from inse.models.work_types_list_response import WorkTypesListResponse
from inse.models.works_list_response import WorksListResponse
from inse.models.work_page import WorkPage
from inse.models.lsf_person import LsfPerson
+166
View File
@@ -0,0 +1,166 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.author_ids import AuthorIds
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.author_summary_stats import AuthorSummaryStats
from inse.models.work_topic import WorkTopic
from inse.models.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Author(BaseModel):
"""
A person who creates scholarly works
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this author.")
orcid: Optional[StrictStr] = Field(default=None, description="The ORCID ID for this author. This is the Canonical External ID for authors.")
display_name: Optional[StrictStr] = Field(default=None, description="The name of the author as a single string.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Other ways this author's name has been displayed.")
longest_name: Optional[StrictStr] = Field(default=None, description="The longest name variant found for this author across all their works.")
parsed_longest_name: Optional[AuthorParsedLongestName] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works this author has created.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="The total number of works that cite a work this author has created.")
summary_stats: Optional[AuthorSummaryStats] = None
affiliations: Optional[List[AuthorAffiliationsInner]] = Field(default=None, description="List of affiliations this author has claimed in their publications. Each object has:")
last_known_institutions: Optional[List[DehydratedInstitution]] = Field(default=None, description="This author's last known institutional affiliations. Each item is a dehydrated Institution object.")
topics: Optional[List[WorkTopic]] = None
counts_by_year: Optional[List[AuthorCountsByYearInner]] = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
ids: Optional[AuthorIds] = None
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that will get you a list of all this author's works.")
created_date: Optional[date] = Field(default=None, description="When this author was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this author was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "orcid", "display_name", "display_name_alternatives", "longest_name", "parsed_longest_name", "works_count", "cited_by_count", "summary_stats", "affiliations", "last_known_institutions", "topics", "counts_by_year", "ids", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Author from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of parsed_longest_name
if self.parsed_longest_name:
_dict['parsed_longest_name'] = self.parsed_longest_name.to_dict()
# override the default output from pydantic by calling `to_dict()` of summary_stats
if self.summary_stats:
_dict['summary_stats'] = self.summary_stats.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in affiliations (list)
_items = []
if self.affiliations:
for _item_affiliations in self.affiliations:
if _item_affiliations:
_items.append(_item_affiliations.to_dict())
_dict['affiliations'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in last_known_institutions (list)
_items = []
if self.last_known_institutions:
for _item_last_known_institutions in self.last_known_institutions:
if _item_last_known_institutions:
_items.append(_item_last_known_institutions.to_dict())
_dict['last_known_institutions'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in topics (list)
_items = []
if self.topics:
for _item_topics in self.topics:
if _item_topics:
_items.append(_item_topics.to_dict())
_dict['topics'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in counts_by_year (list)
_items = []
if self.counts_by_year:
for _item_counts_by_year in self.counts_by_year:
if _item_counts_by_year:
_items.append(_item_counts_by_year.to_dict())
_dict['counts_by_year'] = _items
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Author from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"orcid": obj.get("orcid"),
"display_name": obj.get("display_name"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"longest_name": obj.get("longest_name"),
"parsed_longest_name": AuthorParsedLongestName.from_dict(obj["parsed_longest_name"]) if obj.get("parsed_longest_name") is not None else None,
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"summary_stats": AuthorSummaryStats.from_dict(obj["summary_stats"]) if obj.get("summary_stats") is not None else None,
"affiliations": [AuthorAffiliationsInner.from_dict(_item) for _item in obj["affiliations"]] if obj.get("affiliations") is not None else None,
"last_known_institutions": [DehydratedInstitution.from_dict(_item) for _item in obj["last_known_institutions"]] if obj.get("last_known_institutions") is not None else None,
"topics": [WorkTopic.from_dict(_item) for _item in obj["topics"]] if obj.get("topics") is not None else None,
"counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None,
"ids": AuthorIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,99 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorAffiliationsInner(BaseModel):
"""
AuthorAffiliationsInner
""" # noqa: E501
institution: Optional[DehydratedInstitution] = Field(
default=None,
description="[Dehydrated institution](/api-reference/institutions#the-dehydratedinstitution-object)",
)
years: Optional[List[StrictInt]] = None
__properties: ClassVar[List[str]] = ["institution", "years"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorAffiliationsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of institution
if self.institution:
_dict["institution"] = self.institution.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorAffiliationsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate(
{
"institution": DehydratedInstitution.from_dict(obj["institution"])
if obj.get("institution") is not None
else None,
"years": obj.get("years"),
}
)
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorCountsByYearInner(BaseModel):
"""
AuthorCountsByYearInner
""" # noqa: E501
year: Optional[StrictInt] = None
works_count: Optional[StrictInt] = None
cited_by_count: Optional[StrictInt] = None
__properties: ClassVar[List[str]] = ["year", "works_count", "cited_by_count"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorCountsByYearInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorCountsByYearInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"year": obj.get("year"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count")
})
return _obj
+105
View File
@@ -0,0 +1,105 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
orcid: Optional[StrictStr] = None
scopus: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "orcid", "scopus"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
openalex_val = obj.get("openalex")
if openalex_val is not None and not isinstance(openalex_val, str):
openalex_val = str(openalex_val)
orcid_val = obj.get("orcid")
if orcid_val is not None and not isinstance(orcid_val, str):
orcid_val = str(orcid_val)
scopus_val = obj.get("scopus")
if scopus_val is not None and not isinstance(scopus_val, str):
scopus_val = str(scopus_val)
_obj = cls.model_validate({
"openalex": openalex_val,
"orcid": orcid_val,
"scopus": scopus_val
})
return _obj
@@ -0,0 +1,97 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorParsedLongestName(BaseModel):
"""
The longest name parsed into its component parts.
""" # noqa: E501
first: Optional[StrictStr] = Field(default=None, description="First name (lowercased).")
middle: Optional[StrictStr] = Field(default=None, description="Middle name or initial (lowercased).")
last: Optional[StrictStr] = Field(default=None, description="Last name (lowercased).")
suffix: Optional[StrictStr] = Field(default=None, description="Name suffix (e.g., Jr., III).")
nickname: Optional[StrictStr] = Field(default=None, description="Nickname, if any.")
__properties: ClassVar[List[str]] = ["first", "middle", "last", "suffix", "nickname"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorParsedLongestName from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorParsedLongestName from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"first": obj.get("first"),
"middle": obj.get("middle"),
"last": obj.get("last"),
"suffix": obj.get("suffix"),
"nickname": obj.get("nickname")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorSummaryStats(BaseModel):
"""
Citation metrics:
""" # noqa: E501
var_2yr_mean_citedness: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="2yr_mean_citedness")
h_index: Optional[StrictInt] = None
i10_index: Optional[StrictInt] = None
__properties: ClassVar[List[str]] = ["2yr_mean_citedness", "h_index", "i10_index"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorSummaryStats from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorSummaryStats from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"2yr_mean_citedness": obj.get("2yr_mean_citedness"),
"h_index": obj.get("h_index"),
"i10_index": obj.get("i10_index")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorTopicsInner(BaseModel):
"""
AuthorTopicsInner
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
count: Optional[StrictInt] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "count"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorTopicsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorTopicsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"count": obj.get("count")
})
return _obj
@@ -0,0 +1,113 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author import Author
from inse.models.group_by_result import GroupByResult
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AuthorsListResponse(BaseModel):
"""
AuthorsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Author]] = None
group_by: Optional[List[GroupByResult]] = None
__properties: ClassVar[List[str]] = ["meta", "results", "group_by"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AuthorsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in group_by (list)
_items = []
if self.group_by:
for _item_group_by in self.group_by:
if _item_group_by:
_items.append(_item_group_by.to_dict())
_dict['group_by'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AuthorsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Author.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None,
"group_by": [GroupByResult.from_dict(_item) for _item in obj["group_by"]] if obj.get("group_by") is not None else None
})
return _obj
+123
View File
@@ -0,0 +1,123 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Authorship(BaseModel):
"""
Author and their affiliation for a work
""" # noqa: E501
author_position: Optional[StrictStr] = Field(default=None, description="Position in author list")
author: Optional[DehydratedAuthor] = Field(default=None, description="[Dehydrated author](/api-reference/authors#the-dehydratedauthor-object)")
institutions: Optional[List[DehydratedInstitution]] = Field(default=None, description="[Dehydrated institutions](/api-reference/institutions#the-dehydratedinstitution-object)")
countries: Optional[List[StrictStr]] = Field(default=None, description="Country codes of affiliations")
is_corresponding: Optional[StrictBool] = Field(default=None, description="Whether this is the corresponding author")
raw_author_name: Optional[StrictStr] = Field(default=None, description="Author name as it appears in the work")
raw_affiliation_strings: Optional[List[StrictStr]] = None
__properties: ClassVar[List[str]] = ["author_position", "author", "institutions", "countries", "is_corresponding", "raw_author_name", "raw_affiliation_strings"]
@field_validator('author_position')
def author_position_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['first', 'middle', 'last']):
raise ValueError("must be one of enum values ('first', 'middle', 'last')")
return value
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Authorship from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of author
if self.author:
_dict['author'] = self.author.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in institutions (list)
_items = []
if self.institutions:
for _item_institutions in self.institutions:
if _item_institutions:
_items.append(_item_institutions.to_dict())
_dict['institutions'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Authorship from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"author_position": obj.get("author_position"),
"author": DehydratedAuthor.from_dict(obj["author"]) if obj.get("author") is not None else None,
"institutions": [DehydratedInstitution.from_dict(_item) for _item in obj["institutions"]] if obj.get("institutions") is not None else None,
"countries": obj.get("countries"),
"is_corresponding": obj.get("is_corresponding"),
"raw_author_name": obj.get("raw_author_name"),
"raw_affiliation_strings": obj.get("raw_affiliation_strings")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AutocompleteResponse(BaseModel):
"""
AutocompleteResponse
""" # noqa: E501
meta: Optional[AutocompleteResponseMeta] = None
results: Optional[List[AutocompleteResponseResultsInner]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AutocompleteResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AutocompleteResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": AutocompleteResponseMeta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [AutocompleteResponseResultsInner.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,91 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AutocompleteResponseMeta(BaseModel):
"""
AutocompleteResponseMeta
""" # noqa: E501
count: Optional[StrictInt] = None
db_response_time_ms: Optional[StrictInt] = None
__properties: ClassVar[List[str]] = ["count", "db_response_time_ms"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AutocompleteResponseMeta from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AutocompleteResponseMeta from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"count": obj.get("count"),
"db_response_time_ms": obj.get("db_response_time_ms")
})
return _obj
@@ -0,0 +1,101 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AutocompleteResponseResultsInner(BaseModel):
"""
AutocompleteResponseResultsInner
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
hint: Optional[StrictStr] = None
cited_by_count: Optional[StrictInt] = None
works_count: Optional[StrictInt] = None
entity_type: Optional[StrictStr] = None
external_id: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "hint", "cited_by_count", "works_count", "entity_type", "external_id"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AutocompleteResponseResultsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AutocompleteResponseResultsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"hint": obj.get("hint"),
"cited_by_count": obj.get("cited_by_count"),
"works_count": obj.get("works_count"),
"entity_type": obj.get("entity_type"),
"external_id": obj.get("external_id")
})
return _obj
+99
View File
@@ -0,0 +1,99 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Award(BaseModel):
"""
Award
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
funder_award_id: Optional[StrictStr] = None
funder_id: Optional[StrictStr] = None
funder_display_name: Optional[StrictStr] = None
doi: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "funder_award_id", "funder_id", "funder_display_name", "doi"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Award from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Award from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"funder_award_id": obj.get("funder_award_id"),
"funder_id": obj.get("funder_id"),
"funder_display_name": obj.get("funder_display_name"),
"doi": obj.get("doi")
})
return _obj
+140
View File
@@ -0,0 +1,140 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from inse.models.award_full_funder import AwardFullFunder
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AwardFull(BaseModel):
"""
Research grant or funding award
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this award.")
display_name: Optional[StrictStr] = Field(default=None, description="The name of the award, if available.")
description: Optional[StrictStr] = Field(default=None, description="A description of the award, if available.")
funder_award_id: Optional[StrictStr] = Field(default=None, description="The funder's internal ID for this award.")
funder: Optional[AwardFullFunder] = None
funded_outputs: Optional[List[StrictStr]] = Field(default=None, description="OpenAlex IDs of works funded by this award (first 100).")
funded_outputs_count: Optional[StrictInt] = Field(default=None, description="Total number of works funded by this award.")
amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The funding amount, if available.")
currency: Optional[StrictStr] = Field(default=None, description="The currency of the funding amount, if available.")
funding_type: Optional[StrictStr] = Field(default=None, description="The type of funding, if available.")
funder_scheme: Optional[StrictStr] = Field(default=None, description="The funder's scheme or program, if available.")
start_date: Optional[date] = Field(default=None, description="Start date of the award (ISO 8601), if available.")
end_date: Optional[date] = Field(default=None, description="End date of the award (ISO 8601), if available.")
start_year: Optional[StrictInt] = Field(default=None, description="Start year of the award, if available.")
end_year: Optional[StrictInt] = Field(default=None, description="End year of the award, if available.")
landing_page_url: Optional[StrictStr] = Field(default=None, description="URL to the award's landing page, if available.")
doi: Optional[StrictStr] = Field(default=None, description="DOI for this award, if available.")
provenance: Optional[StrictStr] = Field(default=None, description="The source of this award data.")
lead_investigator: Optional[Dict[str, Any]] = Field(default=None, description="The lead investigator for this award, if available.")
co_lead_investigator: Optional[Dict[str, Any]] = Field(default=None, description="The co-lead investigator, if available.")
investigators: Optional[List[Any]] = Field(default=None, description="List of investigators on this award, if available.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works funded by this award.")
created_date: Optional[date] = Field(default=None, description="When this award was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this award was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "funder_award_id", "funder", "funded_outputs", "funded_outputs_count", "amount", "currency", "funding_type", "funder_scheme", "start_date", "end_date", "start_year", "end_year", "landing_page_url", "doi", "provenance", "lead_investigator", "co_lead_investigator", "investigators", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AwardFull from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of funder
if self.funder:
_dict['funder'] = self.funder.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AwardFull from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"description": obj.get("description"),
"funder_award_id": obj.get("funder_award_id"),
"funder": AwardFullFunder.from_dict(obj["funder"]) if obj.get("funder") is not None else None,
"funded_outputs": obj.get("funded_outputs"),
"funded_outputs_count": obj.get("funded_outputs_count"),
"amount": obj.get("amount"),
"currency": obj.get("currency"),
"funding_type": obj.get("funding_type"),
"funder_scheme": obj.get("funder_scheme"),
"start_date": obj.get("start_date"),
"end_date": obj.get("end_date"),
"start_year": obj.get("start_year"),
"end_year": obj.get("end_year"),
"landing_page_url": obj.get("landing_page_url"),
"doi": obj.get("doi"),
"provenance": obj.get("provenance"),
"lead_investigator": obj.get("lead_investigator"),
"co_lead_investigator": obj.get("co_lead_investigator"),
"investigators": obj.get("investigators"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AwardFullFunder(BaseModel):
"""
The [funder](/api-reference/funders) of this award
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
doi: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "doi"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AwardFullFunder from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AwardFullFunder from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"doi": obj.get("doi")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.award_full import AwardFull
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class AwardsListResponse(BaseModel):
"""
AwardsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[AwardFull]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of AwardsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of AwardsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [AwardFull.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+124
View File
@@ -0,0 +1,124 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.concept_ids import ConceptIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Concept(BaseModel):
"""
Legacy research area taxonomy (deprecated)
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this concept.")
display_name: Optional[StrictStr] = Field(default=None, description="The name of the concept.")
description: Optional[StrictStr] = Field(default=None, description="A description of this concept.")
level: Optional[StrictInt] = Field(default=None, description="The hierarchical level (0 = top level, higher = more specific).")
wikidata: Optional[StrictStr] = Field(default=None, description="The Wikidata ID for this concept.")
ids: Optional[ConceptIds] = None
image_url: Optional[StrictStr] = Field(default=None, description="URL for an image representing this concept.")
image_thumbnail_url: Optional[StrictStr] = Field(default=None, description="Smaller version of `image_url`.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this concept.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works tagged with this concept.")
ancestors: Optional[List[Any]] = Field(default=None, description="Parent concepts in the hierarchy.")
related_concepts: Optional[List[Any]] = Field(default=None, description="Related concepts with similarity scores.")
counts_by_year: Optional[List[Any]] = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works tagged with this concept.")
created_date: Optional[date] = Field(default=None, description="When this concept was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this concept was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "level", "wikidata", "ids", "image_url", "image_thumbnail_url", "works_count", "cited_by_count", "ancestors", "related_concepts", "counts_by_year", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Concept from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Concept from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"description": obj.get("description"),
"level": obj.get("level"),
"wikidata": obj.get("wikidata"),
"ids": ConceptIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"image_url": obj.get("image_url"),
"image_thumbnail_url": obj.get("image_thumbnail_url"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"ancestors": obj.get("ancestors"),
"related_concepts": obj.get("related_concepts"),
"counts_by_year": obj.get("counts_by_year"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,95 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ConceptIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
wikipedia: Optional[StrictStr] = None
mag: Optional[StrictInt] = None
__properties: ClassVar[List[str]] = ["openalex", "wikidata", "wikipedia", "mag"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ConceptIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ConceptIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"wikidata": obj.get("wikidata"),
"wikipedia": obj.get("wikipedia"),
"mag": obj.get("mag")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.concept import Concept
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ConceptsListResponse(BaseModel):
"""
ConceptsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Concept]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ConceptsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ConceptsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Concept.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+116
View File
@@ -0,0 +1,116 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.continent_ids import ContinentIds
from inse.models.domain_fields_inner import DomainFieldsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Continent(BaseModel):
"""
Geographic continent (7 total)
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this continent (uses Wikidata Q-IDs).")
display_name: Optional[StrictStr] = Field(default=None, description="The name of the continent.")
description: Optional[StrictStr] = Field(default=None, description="A brief description of the continent.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Alternate names for this continent.")
countries: Optional[List[DomainFieldsInner]] = Field(default=None, description="The countries within this continent. Each object has `id` and `display_name`.")
ids: Optional[ContinentIds] = None
created_date: Optional[date] = Field(default=None, description="When this continent was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this continent was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "display_name_alternatives", "countries", "ids", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Continent from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in countries (list)
_items = []
if self.countries:
for _item_countries in self.countries:
if _item_countries:
_items.append(_item_countries.to_dict())
_dict['countries'] = _items
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Continent from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"description": obj.get("description"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"countries": [DomainFieldsInner.from_dict(_item) for _item in obj["countries"]] if obj.get("countries") is not None else None,
"ids": ContinentIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,91 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ContinentIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "wikidata"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ContinentIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ContinentIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"wikidata": obj.get("wikidata")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.continent import Continent
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ContinentsListResponse(BaseModel):
"""
ContinentsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Continent]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ContinentsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ContinentsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Continent.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.country import Country
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class CountriesListResponse(BaseModel):
"""
CountriesListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Country]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of CountriesListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of CountriesListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Country.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+126
View File
@@ -0,0 +1,126 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.country_continent import CountryContinent
from inse.models.country_ids import CountryIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Country(BaseModel):
"""
Geographic country
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this country.")
display_name: Optional[StrictStr] = Field(default=None, description="The full name of the country.")
country_code: Optional[StrictStr] = Field(default=None, description="ISO 3166-1 alpha-2 country code.")
description: Optional[StrictStr] = Field(default=None, description="A brief description of the country.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Alternate names for this country.")
continent: Optional[CountryContinent] = None
is_global_south: Optional[StrictBool] = Field(default=None, description="Whether this country is part of the Global South.")
ids: Optional[CountryIds] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works with authors affiliated with institutions in this country.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works from this country.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works from authors in this country.")
authors_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all authors with affiliations in this country.")
institutions_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all institutions in this country.")
created_date: Optional[date] = Field(default=None, description="When this country was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this country was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "country_code", "description", "display_name_alternatives", "continent", "is_global_south", "ids", "works_count", "cited_by_count", "works_api_url", "authors_api_url", "institutions_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Country from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of continent
if self.continent:
_dict['continent'] = self.continent.to_dict()
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Country from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"country_code": obj.get("country_code"),
"description": obj.get("description"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"continent": CountryContinent.from_dict(obj["continent"]) if obj.get("continent") is not None else None,
"is_global_south": obj.get("is_global_south"),
"ids": CountryIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"authors_api_url": obj.get("authors_api_url"),
"institutions_api_url": obj.get("institutions_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,91 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class CountryContinent(BaseModel):
"""
The [continent](/api-reference/continents)
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of CountryContinent from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of CountryContinent from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name")
})
return _obj
@@ -0,0 +1,95 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class CountryIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
iso: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
wikipedia: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "iso", "wikidata", "wikipedia"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of CountryIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of CountryIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"iso": obj.get("iso"),
"wikidata": obj.get("wikidata"),
"wikipedia": obj.get("wikipedia")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DehydratedAuthor(BaseModel):
"""
[Dehydrated Author](/api-reference/authors#the-dehydratedauthor-object) — reduced-field version used in nested contexts
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
orcid: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "orcid"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DehydratedAuthor from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DehydratedAuthor from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"orcid": obj.get("orcid")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DehydratedFunder(BaseModel):
"""
[Dehydrated Funder](/api-reference/funders) — reduced-field version used in nested contexts
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
ror: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "ror"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DehydratedFunder from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DehydratedFunder from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"ror": obj.get("ror")
})
return _obj
@@ -0,0 +1,99 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DehydratedInstitution(BaseModel):
"""
[Dehydrated Institution](/api-reference/institutions#the-dehydratedinstitution-object) — reduced-field version used in nested contexts
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
ror: Optional[StrictStr] = None
country_code: Optional[StrictStr] = Field(default=None, description="[Country](/api-reference/countries) code")
type: Optional[StrictStr] = Field(default=None, description="The [institution type](/api-reference/institution-types)")
lineage: Optional[List[StrictStr]] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "ror", "country_code", "type", "lineage"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DehydratedInstitution from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DehydratedInstitution from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"ror": obj.get("ror"),
"country_code": obj.get("country_code"),
"type": obj.get("type"),
"lineage": obj.get("lineage")
})
return _obj
@@ -0,0 +1,109 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DehydratedSource(BaseModel):
"""
[Dehydrated Source](/api-reference/sources#the-dehydratedsource-object) — reduced-field version used in nested contexts
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
issn_l: Optional[StrictStr] = None
issn: Optional[List[StrictStr]] = None
is_oa: Optional[StrictBool] = None
is_in_doaj: Optional[StrictBool] = None
is_core: Optional[StrictBool] = None
host_organization: Optional[StrictStr] = None
host_organization_name: Optional[StrictStr] = None
host_organization_lineage: Optional[List[StrictStr]] = None
type: Optional[StrictStr] = Field(default=None, description="The [source type](/api-reference/source-types)")
__properties: ClassVar[List[str]] = ["id", "display_name", "issn_l", "issn", "is_oa", "is_in_doaj", "is_core", "host_organization", "host_organization_name", "host_organization_lineage", "type"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DehydratedSource from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DehydratedSource from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"issn_l": obj.get("issn_l"),
"issn": obj.get("issn"),
"is_oa": obj.get("is_oa"),
"is_in_doaj": obj.get("is_in_doaj"),
"is_core": obj.get("is_core"),
"host_organization": obj.get("host_organization"),
"host_organization_name": obj.get("host_organization_name"),
"host_organization_lineage": obj.get("host_organization_lineage"),
"type": obj.get("type")
})
return _obj
+131
View File
@@ -0,0 +1,131 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.domain_fields_inner import DomainFieldsInner
from inse.models.domain_ids import DomainIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Domain(BaseModel):
"""
Top-level category in the topic hierarchy (4 total)
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this domain.")
display_name: Optional[StrictStr] = Field(default=None, description="The English-language label of the domain.")
description: Optional[StrictStr] = Field(default=None, description="A description of this domain.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Alternate names for this domain.")
fields: Optional[List[DomainFieldsInner]] = Field(default=None, description="The fields within this domain. Each object has `id` and `display_name`.")
siblings: Optional[List[DomainFieldsInner]] = Field(default=None, description="Other domains at the same level. Each object has `id` and `display_name`.")
ids: Optional[DomainIds] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with topics in this domain.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works in this domain.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works tagged with this domain.")
created_date: Optional[date] = Field(default=None, description="When this domain was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this domain was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "display_name_alternatives", "fields", "siblings", "ids", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Domain from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in fields (list)
_items = []
if self.fields:
for _item_fields in self.fields:
if _item_fields:
_items.append(_item_fields.to_dict())
_dict['fields'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in siblings (list)
_items = []
if self.siblings:
for _item_siblings in self.siblings:
if _item_siblings:
_items.append(_item_siblings.to_dict())
_dict['siblings'] = _items
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Domain from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"description": obj.get("description"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"fields": [DomainFieldsInner.from_dict(_item) for _item in obj["fields"]] if obj.get("fields") is not None else None,
"siblings": [DomainFieldsInner.from_dict(_item) for _item in obj["siblings"]] if obj.get("siblings") is not None else None,
"ids": DomainIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,91 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DomainFieldsInner(BaseModel):
"""
DomainFieldsInner
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "display_name"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DomainFieldsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DomainFieldsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DomainIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
wikipedia: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "wikidata", "wikipedia"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DomainIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DomainIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"wikidata": obj.get("wikidata"),
"wikipedia": obj.get("wikipedia")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.domain import Domain
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class DomainsListResponse(BaseModel):
"""
DomainsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Domain]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DomainsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DomainsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Domain.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+91
View File
@@ -0,0 +1,91 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Error(BaseModel):
"""
Error
""" # noqa: E501
error: Optional[StrictStr] = Field(default=None, description="Error type")
message: Optional[StrictStr] = Field(default=None, description="Human-readable error message")
__properties: ClassVar[List[str]] = ["error", "message"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Error from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Error from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"error": obj.get("error"),
"message": obj.get("message")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.meta import Meta
from inse.models.model_field import ModelField
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class FieldsListResponse(BaseModel):
"""
FieldsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[ModelField]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of FieldsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of FieldsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [ModelField.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+132
View File
@@ -0,0 +1,132 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.funder_ids import FunderIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Funder(BaseModel):
"""
An organization that funds research
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this funder.")
display_name: Optional[StrictStr] = Field(default=None, description="The primary name of the funder.")
alternate_titles: Optional[List[StrictStr]] = Field(default=None, description="A list of alternate titles for this funder.")
country_code: Optional[StrictStr] = Field(default=None, description="ISO two-letter country code where this funder is located.")
description: Optional[StrictStr] = Field(default=None, description="A short description from Wikidata.")
homepage_url: Optional[StrictStr] = Field(default=None, description="URL for this funder's primary homepage.")
image_url: Optional[StrictStr] = Field(default=None, description="URL for an image representing this funder (usually from Wikimedia).")
image_thumbnail_url: Optional[StrictStr] = Field(default=None, description="Smaller version of `image_url`.")
grants_count: Optional[StrictInt] = Field(default=None, description="The number of grants linked to this funder.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works linked to this funder.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works linked to this funder.")
ids: Optional[FunderIds] = None
counts_by_year: Optional[List[AuthorCountsByYearInner]] = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
works_api_url: Optional[StrictStr] = None
created_date: Optional[date] = Field(default=None, description="When this funder was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this funder was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "alternate_titles", "country_code", "description", "homepage_url", "image_url", "image_thumbnail_url", "grants_count", "works_count", "cited_by_count", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Funder from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in counts_by_year (list)
_items = []
if self.counts_by_year:
for _item_counts_by_year in self.counts_by_year:
if _item_counts_by_year:
_items.append(_item_counts_by_year.to_dict())
_dict['counts_by_year'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Funder from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"alternate_titles": obj.get("alternate_titles"),
"country_code": obj.get("country_code"),
"description": obj.get("description"),
"homepage_url": obj.get("homepage_url"),
"image_url": obj.get("image_url"),
"image_thumbnail_url": obj.get("image_thumbnail_url"),
"grants_count": obj.get("grants_count"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"ids": FunderIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None,
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,97 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class FunderIds(BaseModel):
"""
External identifiers for this funder:
""" # noqa: E501
openalex: Optional[StrictStr] = None
ror: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
crossref: Optional[StrictStr] = None
doi: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "ror", "wikidata", "crossref", "doi"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of FunderIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of FunderIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"ror": obj.get("ror"),
"wikidata": obj.get("wikidata"),
"crossref": obj.get("crossref"),
"doi": obj.get("doi")
})
return _obj
@@ -0,0 +1,113 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.funder import Funder
from inse.models.group_by_result import GroupByResult
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class FundersListResponse(BaseModel):
"""
FundersListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Funder]] = None
group_by: Optional[List[GroupByResult]] = None
__properties: ClassVar[List[str]] = ["meta", "results", "group_by"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of FundersListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in group_by (list)
_items = []
if self.group_by:
for _item_group_by in self.group_by:
if _item_group_by:
_items.append(_item_group_by.to_dict())
_dict['group_by'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of FundersListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Funder.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None,
"group_by": [GroupByResult.from_dict(_item) for _item in obj["group_by"]] if obj.get("group_by") is not None else None
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.get_changefile200_response_meta import GetChangefile200ResponseMeta
from inse.models.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200Response(BaseModel):
"""
GetChangefile200Response
""" # noqa: E501
meta: Optional[GetChangefile200ResponseMeta] = None
results: Optional[List[GetChangefile200ResponseResultsInner]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200Response from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200Response from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": GetChangefile200ResponseMeta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [GetChangefile200ResponseResultsInner.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,92 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200ResponseMeta(BaseModel):
"""
GetChangefile200ResponseMeta
""" # noqa: E501
count: Optional[StrictInt] = Field(default=None, description="Number of entity types with changes")
var_date: Optional[date] = Field(default=None, description="The changefile date", alias="date")
__properties: ClassVar[List[str]] = ["count", "date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseMeta from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseMeta from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"count": obj.get("count"),
"date": obj.get("date")
})
return _obj
@@ -0,0 +1,97 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200ResponseResultsInner(BaseModel):
"""
GetChangefile200ResponseResultsInner
""" # noqa: E501
entity: Optional[StrictStr] = Field(default=None, description="The entity type (e.g., works, authors, institutions)")
records: Optional[StrictInt] = Field(default=None, description="Number of created or modified records")
formats: Optional[GetChangefile200ResponseResultsInnerFormats] = None
__properties: ClassVar[List[str]] = ["entity", "records", "formats"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of formats
if self.formats:
_dict['formats'] = self.formats.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"entity": obj.get("entity"),
"records": obj.get("records"),
"formats": GetChangefile200ResponseResultsInnerFormats.from_dict(obj["formats"]) if obj.get("formats") is not None else None
})
return _obj
@@ -0,0 +1,99 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
from inse.models.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200ResponseResultsInnerFormats(BaseModel):
"""
GetChangefile200ResponseResultsInnerFormats
""" # noqa: E501
jsonl: Optional[GetChangefile200ResponseResultsInnerFormatsJsonl] = None
parquet: Optional[GetChangefile200ResponseResultsInnerFormatsParquet] = None
__properties: ClassVar[List[str]] = ["jsonl", "parquet"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormats from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of jsonl
if self.jsonl:
_dict['jsonl'] = self.jsonl.to_dict()
# override the default output from pydantic by calling `to_dict()` of parquet
if self.parquet:
_dict['parquet'] = self.parquet.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormats from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"jsonl": GetChangefile200ResponseResultsInnerFormatsJsonl.from_dict(obj["jsonl"]) if obj.get("jsonl") is not None else None,
"parquet": GetChangefile200ResponseResultsInnerFormatsParquet.from_dict(obj["parquet"]) if obj.get("parquet") is not None else None
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200ResponseResultsInnerFormatsJsonl(BaseModel):
"""
GetChangefile200ResponseResultsInnerFormatsJsonl
""" # noqa: E501
size_bytes: Optional[StrictInt] = Field(default=None, description="File size in bytes")
size_display: Optional[StrictStr] = Field(default=None, description="Human-readable file size")
url: Optional[StrictStr] = Field(default=None, description="Download URL for gzipped JSONL file")
__properties: ClassVar[List[str]] = ["size_bytes", "size_display", "url"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormatsJsonl from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormatsJsonl from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"size_bytes": obj.get("size_bytes"),
"size_display": obj.get("size_display"),
"url": obj.get("url")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GetChangefile200ResponseResultsInnerFormatsParquet(BaseModel):
"""
GetChangefile200ResponseResultsInnerFormatsParquet
""" # noqa: E501
size_bytes: Optional[StrictInt] = Field(default=None, description="File size in bytes")
size_display: Optional[StrictStr] = Field(default=None, description="Human-readable file size")
url: Optional[StrictStr] = Field(default=None, description="Download URL for Parquet file")
__properties: ClassVar[List[str]] = ["size_bytes", "size_display", "url"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormatsParquet from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GetChangefile200ResponseResultsInnerFormatsParquet from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"size_bytes": obj.get("size_bytes"),
"size_display": obj.get("size_display"),
"url": obj.get("url")
})
return _obj
@@ -0,0 +1,93 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class GroupByResult(BaseModel):
"""
GroupByResult
""" # noqa: E501
key: Optional[StrictStr] = Field(default=None, description="The group key value")
key_display_name: Optional[StrictStr] = Field(default=None, description="Human-readable name for the key")
count: Optional[StrictInt] = Field(default=None, description="Number of results in this group")
__properties: ClassVar[List[str]] = ["key", "key_display_name", "count"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of GroupByResult from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of GroupByResult from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"key": obj.get("key"),
"key_display_name": obj.get("key_display_name"),
"count": obj.get("count")
})
return _obj
+158
View File
@@ -0,0 +1,158 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.author_summary_stats import AuthorSummaryStats
from inse.models.institution_geo import InstitutionGeo
from inse.models.institution_ids import InstitutionIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Institution(BaseModel):
"""
A university, research organization, or other affiliation
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this institution.")
ror: Optional[StrictStr] = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
display_name: Optional[StrictStr] = Field(default=None, description="The primary name of the institution.")
country_code: Optional[StrictStr] = Field(default=None, description="ISO two-letter country code where this institution is located.")
type: Optional[StrictStr] = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.")
homepage_url: Optional[StrictStr] = Field(default=None, description="URL for the institution's primary homepage.")
image_url: Optional[StrictStr] = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).")
image_thumbnail_url: Optional[StrictStr] = Field(default=None, description="Smaller version of `image_url`.")
display_name_acronyms: Optional[List[StrictStr]] = Field(default=None, description="Acronyms or initialisms for this institution.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Other names people may use for this institution.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works created by authors affiliated with this institution.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works from authors affiliated with this institution.")
summary_stats: Optional[AuthorSummaryStats] = None
geo: Optional[InstitutionGeo] = None
lineage: Optional[List[StrictStr]] = Field(default=None, description="OpenAlex IDs including this institution and any parent institutions.")
ids: Optional[InstitutionIds] = None
counts_by_year: Optional[List[AuthorCountsByYearInner]] = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that will get you a list of all works affiliated with this institution.")
created_date: Optional[date] = Field(default=None, description="When this institution was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"]
@field_validator('type')
def type_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']):
raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')")
return value
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Institution from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of summary_stats
if self.summary_stats:
_dict['summary_stats'] = self.summary_stats.to_dict()
# override the default output from pydantic by calling `to_dict()` of geo
if self.geo:
_dict['geo'] = self.geo.to_dict()
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in counts_by_year (list)
_items = []
if self.counts_by_year:
for _item_counts_by_year in self.counts_by_year:
if _item_counts_by_year:
_items.append(_item_counts_by_year.to_dict())
_dict['counts_by_year'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Institution from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"ror": obj.get("ror"),
"display_name": obj.get("display_name"),
"country_code": obj.get("country_code"),
"type": obj.get("type"),
"homepage_url": obj.get("homepage_url"),
"image_url": obj.get("image_url"),
"image_thumbnail_url": obj.get("image_thumbnail_url"),
"display_name_acronyms": obj.get("display_name_acronyms"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"summary_stats": AuthorSummaryStats.from_dict(obj["summary_stats"]) if obj.get("summary_stats") is not None else None,
"geo": InstitutionGeo.from_dict(obj["geo"]) if obj.get("geo") is not None else None,
"lineage": obj.get("lineage"),
"ids": InstitutionIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None,
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,101 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class InstitutionGeo(BaseModel):
"""
Location information:
""" # noqa: E501
city: Optional[StrictStr] = None
geonames_city_id: Optional[StrictStr] = None
region: Optional[StrictStr] = None
country_code: Optional[StrictStr] = None
country: Optional[StrictStr] = None
latitude: Optional[Union[StrictFloat, StrictInt]] = None
longitude: Optional[Union[StrictFloat, StrictInt]] = None
__properties: ClassVar[List[str]] = ["city", "geonames_city_id", "region", "country_code", "country", "latitude", "longitude"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstitutionGeo from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstitutionGeo from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"city": obj.get("city"),
"geonames_city_id": obj.get("geonames_city_id"),
"region": obj.get("region"),
"country_code": obj.get("country_code"),
"country": obj.get("country"),
"latitude": obj.get("latitude"),
"longitude": obj.get("longitude")
})
return _obj
@@ -0,0 +1,99 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class InstitutionIds(BaseModel):
"""
External identifiers:
""" # noqa: E501
openalex: Optional[StrictStr] = None
ror: Optional[StrictStr] = None
mag: Optional[StrictInt] = None
grid: Optional[StrictStr] = None
wikipedia: Optional[StrictStr] = None
wikidata: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["openalex", "ror", "mag", "grid", "wikipedia", "wikidata"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstitutionIds from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstitutionIds from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"openalex": obj.get("openalex"),
"ror": obj.get("ror"),
"mag": obj.get("mag"),
"grid": obj.get("grid"),
"wikipedia": obj.get("wikipedia"),
"wikidata": obj.get("wikidata")
})
return _obj
@@ -0,0 +1,102 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class InstitutionType(BaseModel):
"""
Type of institution
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
works_count: Optional[StrictInt] = None
cited_by_count: Optional[StrictInt] = None
works_api_url: Optional[StrictStr] = None
created_date: Optional[date] = None
updated_date: Optional[datetime] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstitutionType from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstitutionType from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.institution_type import InstitutionType
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class InstitutionTypesListResponse(BaseModel):
"""
InstitutionTypesListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[InstitutionType]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstitutionTypesListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstitutionTypesListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [InstitutionType.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,113 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.group_by_result import GroupByResult
from inse.models.institution import Institution
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class InstitutionsListResponse(BaseModel):
"""
InstitutionsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Institution]] = None
group_by: Optional[List[GroupByResult]] = None
__properties: ClassVar[List[str]] = ["meta", "results", "group_by"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of InstitutionsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in group_by (list)
_items = []
if self.group_by:
for _item_group_by in self.group_by:
if _item_group_by:
_items.append(_item_group_by.to_dict())
_dict['group_by'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of InstitutionsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Institution.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None,
"group_by": [GroupByResult.from_dict(_item) for _item in obj["group_by"]] if obj.get("group_by") is not None else None
})
return _obj
+102
View File
@@ -0,0 +1,102 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Keyword(BaseModel):
"""
A keyword identified from works' topics
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this keyword.")
display_name: Optional[StrictStr] = Field(default=None, description="The English-language label of the keyword.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this keyword.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="The total citations to works tagged with this keyword.")
works_api_url: Optional[StrictStr] = None
created_date: Optional[date] = Field(default=None, description="When this keyword was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this keyword was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Keyword from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Keyword from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,113 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.group_by_result import GroupByResult
from inse.models.keyword import Keyword
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class KeywordsListResponse(BaseModel):
"""
KeywordsListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Keyword]] = None
group_by: Optional[List[GroupByResult]] = None
__properties: ClassVar[List[str]] = ["meta", "results", "group_by"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of KeywordsListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in group_by (list)
_items = []
if self.group_by:
for _item_group_by in self.group_by:
if _item_group_by:
_items.append(_item_group_by.to_dict())
_dict['group_by'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of KeywordsListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Keyword.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None,
"group_by": [GroupByResult.from_dict(_item) for _item in obj["group_by"]] if obj.get("group_by") is not None else None
})
return _obj
+102
View File
@@ -0,0 +1,102 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Language(BaseModel):
"""
Language of scholarly works
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this language (uses ISO 639-1 codes).")
display_name: Optional[StrictStr] = Field(default=None, description="The name of the language.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works written in this language.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works in this language.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works in this language.")
created_date: Optional[date] = Field(default=None, description="When this language was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this language was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Language from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Language from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.language import Language
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class LanguagesListResponse(BaseModel):
"""
LanguagesListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[Language]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of LanguagesListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of LanguagesListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [Language.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
+106
View File
@@ -0,0 +1,106 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class License(BaseModel):
"""
Open access license
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
url: Optional[StrictStr] = None
description: Optional[StrictStr] = None
works_count: Optional[StrictInt] = None
cited_by_count: Optional[StrictInt] = None
works_api_url: Optional[StrictStr] = None
created_date: Optional[date] = None
updated_date: Optional[datetime] = None
__properties: ClassVar[List[str]] = ["id", "display_name", "url", "description", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of License from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of License from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"url": obj.get("url"),
"description": obj.get("description"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.license import License
from inse.models.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class LicensesListResponse(BaseModel):
"""
LicensesListResponse
""" # noqa: E501
meta: Optional[Meta] = None
results: Optional[List[License]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of LicensesListResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of LicensesListResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": Meta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [License.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,103 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
from inse.models.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ListChangefiles200Response(BaseModel):
"""
ListChangefiles200Response
""" # noqa: E501
meta: Optional[ListChangefiles200ResponseMeta] = None
results: Optional[List[ListChangefiles200ResponseResultsInner]] = None
__properties: ClassVar[List[str]] = ["meta", "results"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ListChangefiles200Response from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of meta
if self.meta:
_dict['meta'] = self.meta.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in results (list)
_items = []
if self.results:
for _item_results in self.results:
if _item_results:
_items.append(_item_results.to_dict())
_dict['results'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ListChangefiles200Response from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"meta": ListChangefiles200ResponseMeta.from_dict(obj["meta"]) if obj.get("meta") is not None else None,
"results": [ListChangefiles200ResponseResultsInner.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None
})
return _obj
@@ -0,0 +1,89 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ListChangefiles200ResponseMeta(BaseModel):
"""
ListChangefiles200ResponseMeta
""" # noqa: E501
count: Optional[StrictInt] = Field(default=None, description="Number of available changefile dates")
__properties: ClassVar[List[str]] = ["count"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ListChangefiles200ResponseMeta from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ListChangefiles200ResponseMeta from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"count": obj.get("count")
})
return _obj
@@ -0,0 +1,92 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ListChangefiles200ResponseResultsInner(BaseModel):
"""
ListChangefiles200ResponseResultsInner
""" # noqa: E501
var_date: Optional[date] = Field(default=None, description="The changefile date (YYYY-MM-DD)", alias="date")
url: Optional[StrictStr] = Field(default=None, description="URL to get details and download links for this date")
__properties: ClassVar[List[str]] = ["date", "url"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ListChangefiles200ResponseResultsInner from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ListChangefiles200ResponseResultsInner from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"date": obj.get("date"),
"url": obj.get("url")
})
return _obj
+119
View File
@@ -0,0 +1,119 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.dehydrated_source import DehydratedSource
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Location(BaseModel):
"""
Where a work is hosted
""" # noqa: E501
is_oa: Optional[StrictBool] = Field(default=None, description="Whether this location provides open access")
landing_page_url: Optional[StrictStr] = Field(default=None, description="URL to the landing page")
pdf_url: Optional[StrictStr] = Field(default=None, description="Direct URL to PDF")
source: Optional[DehydratedSource] = Field(default=None, description="[Dehydrated source](/api-reference/sources#the-dehydratedsource-object)")
license: Optional[StrictStr] = Field(default=None, description="The [license](/api-reference/licenses) (e.g., cc-by)")
license_id: Optional[StrictStr] = None
version: Optional[StrictStr] = Field(default=None, description="Version of the work at this location")
is_accepted: Optional[StrictBool] = None
is_published: Optional[StrictBool] = None
__properties: ClassVar[List[str]] = ["is_oa", "landing_page_url", "pdf_url", "source", "license", "license_id", "version", "is_accepted", "is_published"]
@field_validator('version')
def version_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['publishedVersion', 'acceptedVersion', 'submittedVersion']):
raise ValueError("must be one of enum values ('publishedVersion', 'acceptedVersion', 'submittedVersion')")
return value
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Location from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of source
if self.source:
_dict['source'] = self.source.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Location from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"is_oa": obj.get("is_oa"),
"landing_page_url": obj.get("landing_page_url"),
"pdf_url": obj.get("pdf_url"),
"source": DehydratedSource.from_dict(obj["source"]) if obj.get("source") is not None else None,
"license": obj.get("license"),
"license_id": obj.get("license_id"),
"version": obj.get("version"),
"is_accepted": obj.get("is_accepted"),
"is_published": obj.get("is_published")
})
return _obj
@@ -0,0 +1,72 @@
from typing import List, Optional
from pydantic import BaseModel, Field, StrictStr
class Function(BaseModel):
facility: StrictStr = Field(description="The facility of the function.")
function: StrictStr = Field(description="The name of the function.")
class LsfPerson(BaseModel):
lsf_id: StrictStr = Field(description="The LSF ID of the person.")
name: StrictStr = Field(description="The name of the person.")
firstname: StrictStr = Field(description="The first name of the person.")
surname: StrictStr = Field(description="The last name of the person.")
title: Optional[StrictStr] = Field(
default=None, description="The title of the person."
)
location: Optional[StrictStr] = Field(
default=None, description="The location of the person."
)
room: Optional[StrictStr] = Field(
default=None, description="The room of the person."
)
telefon: Optional[StrictStr] = Field(
default=None, description="The telephone number of the person."
)
telefax: Optional[StrictStr] = Field(
default=None, description="The telefax number of the person."
)
mail: Optional[StrictStr] = Field(
default=None, description="The email address of the person."
)
website: Optional[StrictStr] = Field(
default=None, description="The website of the person."
)
affiliation_university: Optional[StrictStr] = Field(
default=None, description="The university affiliation of the person."
)
affiliation_faculty: Optional[StrictStr] = Field(
default=None, description="The faculty affiliation of the person."
)
affiliation_institute: Optional[StrictStr] = Field(
default=None, description="The institute affiliation of the person."
)
affiliation_chair: Optional[StrictStr] = Field(
default=None, description="The chair affiliation of the person."
)
functions: List[Function] = Field(description="The functions of the person.")
@classmethod
def from_dict(cls, data: dict) -> "LsfPerson":
functions_data = data.get("functions", [])
functions = [Function(**func) for func in functions_data]
return cls(
lsf_id=data.get("lsf_id", ""),
name=data.get("name", ""),
firstname=data.get("firstname", ""),
surname=data.get("surname", ""),
title=data.get("title"),
location=data.get("location"),
room=data.get("room"),
telefon=data.get("telefon"),
telefax=data.get("telefax"),
mail=data.get("mail"),
website=data.get("website"),
affiliation_university=data.get("affiliation_university"),
affiliation_faculty=data.get("affiliation_faculty"),
affiliation_institute=data.get("affiliation_institute"),
affiliation_chair=data.get("affiliation_chair"),
functions=functions,
)
+101
View File
@@ -0,0 +1,101 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Meta(BaseModel):
"""
Metadata about the query results
""" # noqa: E501
count: Optional[StrictInt] = Field(default=None, description="Total number of results matching the query")
db_response_time_ms: Optional[StrictInt] = Field(default=None, description="Database response time in milliseconds")
page: Optional[StrictInt] = Field(default=None, description="Current page number")
per_page: Optional[StrictInt] = Field(default=None, description="Number of results per page")
next_cursor: Optional[StrictStr] = Field(default=None, description="Cursor for the next page (when using cursor pagination)")
groups_count: Optional[StrictInt] = Field(default=None, description="Number of groups when using group_by")
cost_usd: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Cost of this request in USD")
__properties: ClassVar[List[str]] = ["count", "db_response_time_ms", "page", "per_page", "next_cursor", "groups_count", "cost_usd"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Meta from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Meta from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"count": obj.get("count"),
"db_response_time_ms": obj.get("db_response_time_ms"),
"page": obj.get("page"),
"per_page": obj.get("per_page"),
"next_cursor": obj.get("next_cursor"),
"groups_count": obj.get("groups_count"),
"cost_usd": obj.get("cost_usd")
})
return _obj
+137
View File
@@ -0,0 +1,137 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.domain_fields_inner import DomainFieldsInner
from inse.models.domain_ids import DomainIds
from inse.models.work_topic_domain import WorkTopicDomain
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class ModelField(BaseModel):
"""
Second-level category in the topic hierarchy (26 total)
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this field.")
display_name: Optional[StrictStr] = Field(default=None, description="The English-language label of the field.")
description: Optional[StrictStr] = Field(default=None, description="A description of this field.")
display_name_alternatives: Optional[List[StrictStr]] = Field(default=None, description="Alternate names for this field.")
domain: Optional[WorkTopicDomain] = None
subfields: Optional[List[DomainFieldsInner]] = Field(default=None, description="The subfields within this field. Each object has `id` and `display_name`.")
siblings: Optional[List[DomainFieldsInner]] = Field(default=None, description="Other fields at the same level. Each object has `id` and `display_name`.")
ids: Optional[DomainIds] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with topics in this field.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works in this field.")
works_api_url: Optional[StrictStr] = Field(default=None, description="A URL that returns all works tagged with this field.")
created_date: Optional[date] = Field(default=None, description="When this field was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this field was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "display_name_alternatives", "domain", "subfields", "siblings", "ids", "works_count", "cited_by_count", "works_api_url", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ModelField from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of domain
if self.domain:
_dict['domain'] = self.domain.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in subfields (list)
_items = []
if self.subfields:
for _item_subfields in self.subfields:
if _item_subfields:
_items.append(_item_subfields.to_dict())
_dict['subfields'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in siblings (list)
_items = []
if self.siblings:
for _item_siblings in self.siblings:
if _item_siblings:
_items.append(_item_siblings.to_dict())
_dict['siblings'] = _items
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ModelField from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"description": obj.get("description"),
"display_name_alternatives": obj.get("display_name_alternatives"),
"domain": WorkTopicDomain.from_dict(obj["domain"]) if obj.get("domain") is not None else None,
"subfields": [DomainFieldsInner.from_dict(_item) for _item in obj["subfields"]] if obj.get("subfields") is not None else None,
"siblings": [DomainFieldsInner.from_dict(_item) for _item in obj["siblings"]] if obj.get("siblings") is not None else None,
"ids": DomainIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"works_api_url": obj.get("works_api_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj
+105
View File
@@ -0,0 +1,105 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class OpenAccess(BaseModel):
"""
Open access information
""" # noqa: E501
is_oa: Optional[StrictBool] = Field(default=None, description="Whether this work is open access")
oa_status: Optional[StrictStr] = Field(default=None, description="Open access status")
oa_url: Optional[StrictStr] = Field(default=None, description="Best open access URL")
any_repository_has_fulltext: Optional[StrictBool] = Field(default=None, description="Whether any repository has the full text")
__properties: ClassVar[List[str]] = ["is_oa", "oa_status", "oa_url", "any_repository_has_fulltext"]
@field_validator('oa_status')
def oa_status_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['diamond', 'gold', 'hybrid', 'bronze', 'green', 'closed']):
raise ValueError("must be one of enum values ('diamond', 'gold', 'hybrid', 'bronze', 'green', 'closed')")
return value
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of OpenAccess from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of OpenAccess from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"is_oa": obj.get("is_oa"),
"oa_status": obj.get("oa_status"),
"oa_url": obj.get("oa_url"),
"any_repository_has_fulltext": obj.get("any_repository_has_fulltext")
})
return _obj
+132
View File
@@ -0,0 +1,132 @@
# coding: utf-8
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.publisher_ids import PublisherIds
from inse.models.publisher_parent_publisher import PublisherParentPublisher
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Publisher(BaseModel):
"""
An organization that publishes scholarly works
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this publisher.")
display_name: Optional[StrictStr] = Field(default=None, description="The primary name of the publisher.")
alternate_titles: Optional[List[StrictStr]] = Field(default=None, description="Alternate titles for this publisher (including translations).")
country_codes: Optional[List[StrictStr]] = Field(default=None, description="ISO two-letter country codes where the publisher is primarily located.")
hierarchy_level: Optional[StrictInt] = Field(default=None, description="The hierarchy level for this publisher. Level 0 has no parent publishers.")
parent_publisher: Optional[PublisherParentPublisher] = None
lineage: Optional[List[StrictStr]] = Field(default=None, description="OpenAlex IDs including this publisher and any parent publishers.")
works_count: Optional[StrictInt] = Field(default=None, description="The number of works published by this publisher.")
cited_by_count: Optional[StrictInt] = Field(default=None, description="Total citations to works linked to this publisher.")
sources_api_url: Optional[StrictStr] = Field(default=None, description="A URL that will get you a list of all sources published by this publisher.")
ids: Optional[PublisherIds] = None
counts_by_year: Optional[List[AuthorCountsByYearInner]] = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.")
created_date: Optional[date] = Field(default=None, description="When this publisher was added to OpenAlex (ISO 8601 date).")
updated_date: Optional[datetime] = Field(default=None, description="When this publisher was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "display_name", "alternate_titles", "country_codes", "hierarchy_level", "parent_publisher", "lineage", "works_count", "cited_by_count", "sources_api_url", "ids", "counts_by_year", "created_date", "updated_date"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Publisher from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of parent_publisher
if self.parent_publisher:
_dict['parent_publisher'] = self.parent_publisher.to_dict()
# override the default output from pydantic by calling `to_dict()` of ids
if self.ids:
_dict['ids'] = self.ids.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in counts_by_year (list)
_items = []
if self.counts_by_year:
for _item_counts_by_year in self.counts_by_year:
if _item_counts_by_year:
_items.append(_item_counts_by_year.to_dict())
_dict['counts_by_year'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Publisher from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
"alternate_titles": obj.get("alternate_titles"),
"country_codes": obj.get("country_codes"),
"hierarchy_level": obj.get("hierarchy_level"),
"parent_publisher": PublisherParentPublisher.from_dict(obj["parent_publisher"]) if obj.get("parent_publisher") is not None else None,
"lineage": obj.get("lineage"),
"works_count": obj.get("works_count"),
"cited_by_count": obj.get("cited_by_count"),
"sources_api_url": obj.get("sources_api_url"),
"ids": PublisherIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None,
"counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None,
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
})
return _obj

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