From cae87c69827bd8c031dea978f72ad9e80af39113 Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Wed, 7 Aug 2024 00:14:33 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc 1.0.0, Speakeasy CLI 1.355.0 --- document/.gitattributes | 2 + document/.gitignore | 8 + document/.speakeasy/gen.lock | 109 +++ document/.vscode/settings.json | 6 + document/CONTRIBUTING.md | 26 + document/README.md | 410 +++++++++- document/RELEASES.md | 10 +- document/USAGE.md | 72 +- document/docs/models/context.md | 10 + .../docs/models/convertdocumentrequest.md | 10 + .../docs/models/convertdocumentresponse.md | 8 + document/docs/models/custommargins.md | 11 + .../models/documentgenerationv2request.md | 12 + .../models/documentgenerationv2response.md | 15 + ...umentgenerationv2responseoutputdocument.md | 9 + ...nerationv2responseschemasoutputdocument.md | 9 + ...mentgenerationv2responsevariablepayload.md | 10 + document/docs/models/docxoutput.md | 9 + document/docs/models/errorcode.md | 18 + document/docs/models/erroroutput.md | 10 + .../docs/models/generatedocumentv2request.md | 10 + document/docs/models/inputdocument.md | 10 + .../invalidcustomvariableerrordetail.md | 10 + document/docs/models/invalidvariables.md | 11 + document/docs/models/jobstatus.md | 13 + document/docs/models/mode.md | 14 + document/docs/models/outputdocument.md | 9 + document/docs/models/outputformat.md | 10 + document/docs/models/pdfoutput.md | 9 + document/docs/models/s3reference.md | 9 + document/docs/models/security.md | 8 + document/docs/models/suggestedmargins.md | 11 + document/docs/models/templatedocument.md | 11 + document/docs/models/templatesettings.md | 17 + document/docs/models/utils/retryconfig.md | 24 + document/docs/models/variablepayload.md | 10 + document/docs/sdks/documents/README.md | 144 ++++ document/docs/sdks/epilot/README.md | 12 + document/gen.yaml | 43 +- document/poetry.toml | 2 + document/py.typed | 1 + document/pylintrc | 70 +- document/pyproject.toml | 55 ++ document/scripts/compile.sh | 83 ++ document/scripts/publish.sh | 5 + document/setup.py | 39 - document/src/epilot/__init__.py | 3 - document/src/epilot/documents.py | 61 -- document/src/epilot/models/__init__.py | 2 - .../src/epilot/models/operations/__init__.py | 5 - .../models/operations/generatedocument.py | 63 -- document/src/epilot/models/shared/__init__.py | 6 - .../src/epilot/models/shared/s3reference.py | 15 - document/src/epilot/models/shared/security.py | 11 - document/src/epilot/sdk.py | 73 -- document/src/epilot/utils/__init__.py | 4 - document/src/epilot/utils/retries.py | 118 --- document/src/epilot/utils/utils.py | 735 ------------------ document/src/epilot_document/__init__.py | 5 + .../src/epilot_document/_hooks/__init__.py | 5 + .../epilot_document/_hooks/registration.py | 13 + .../src/epilot_document/_hooks/sdkhooks.py | 57 ++ document/src/epilot_document/_hooks/types.py | 76 ++ document/src/epilot_document/basesdk.py | 253 ++++++ document/src/epilot_document/documents.py | 357 +++++++++ document/src/epilot_document/httpclient.py | 78 ++ .../src/epilot_document/models/__init__.py | 16 + .../models/convertdocumentrequest.py | 43 + .../models/convertdocumentresponse.py | 28 + .../models/documentgenerationv2request.py | 64 ++ .../models/documentgenerationv2response.py | 109 +++ .../src/epilot_document/models/errorcode.py | 18 + .../src/epilot_document/models/erroroutput.py | 37 + .../models/generatedocumentv2op.py | 43 + .../invalidcustomvariableerrordetail.py | 66 ++ .../src/epilot_document/models/s3reference.py | 16 + .../src/epilot_document/models/sdkerror.py | 22 + .../src/epilot_document/models/security.py | 16 + .../models/templatesettings.py | 85 ++ document/src/epilot_document/py.typed | 1 + document/src/epilot_document/sdk.py | 100 +++ .../src/epilot_document/sdkconfiguration.py | 48 ++ .../src/epilot_document/types/__init__.py | 21 + .../src/epilot_document/types/basemodel.py | 39 + .../src/epilot_document/utils/__init__.py | 84 ++ .../src/epilot_document/utils/annotations.py | 19 + document/src/epilot_document/utils/enums.py | 34 + .../epilot_document/utils/eventstreaming.py | 178 +++++ document/src/epilot_document/utils/forms.py | 207 +++++ document/src/epilot_document/utils/headers.py | 136 ++++ document/src/epilot_document/utils/logger.py | 16 + .../src/epilot_document/utils/metadata.py | 118 +++ .../src/epilot_document/utils/queryparams.py | 203 +++++ .../epilot_document/utils/requestbodies.py | 66 ++ document/src/epilot_document/utils/retries.py | 216 +++++ .../src/epilot_document/utils/security.py | 168 ++++ .../src/epilot_document/utils/serializers.py | 181 +++++ document/src/epilot_document/utils/url.py | 150 ++++ document/src/epilot_document/utils/values.py | 128 +++ 99 files changed, 4806 insertions(+), 1224 deletions(-) create mode 100644 document/.gitattributes create mode 100644 document/.gitignore create mode 100644 document/.speakeasy/gen.lock create mode 100644 document/.vscode/settings.json create mode 100644 document/CONTRIBUTING.md mode change 100755 => 100644 document/USAGE.md create mode 100644 document/docs/models/context.md create mode 100644 document/docs/models/convertdocumentrequest.md create mode 100644 document/docs/models/convertdocumentresponse.md create mode 100644 document/docs/models/custommargins.md create mode 100644 document/docs/models/documentgenerationv2request.md create mode 100644 document/docs/models/documentgenerationv2response.md create mode 100644 document/docs/models/documentgenerationv2responseoutputdocument.md create mode 100644 document/docs/models/documentgenerationv2responseschemasoutputdocument.md create mode 100644 document/docs/models/documentgenerationv2responsevariablepayload.md create mode 100644 document/docs/models/docxoutput.md create mode 100644 document/docs/models/errorcode.md create mode 100644 document/docs/models/erroroutput.md create mode 100644 document/docs/models/generatedocumentv2request.md create mode 100644 document/docs/models/inputdocument.md create mode 100644 document/docs/models/invalidcustomvariableerrordetail.md create mode 100644 document/docs/models/invalidvariables.md create mode 100644 document/docs/models/jobstatus.md create mode 100644 document/docs/models/mode.md create mode 100644 document/docs/models/outputdocument.md create mode 100644 document/docs/models/outputformat.md create mode 100644 document/docs/models/pdfoutput.md create mode 100644 document/docs/models/s3reference.md create mode 100644 document/docs/models/security.md create mode 100644 document/docs/models/suggestedmargins.md create mode 100644 document/docs/models/templatedocument.md create mode 100644 document/docs/models/templatesettings.md create mode 100644 document/docs/models/utils/retryconfig.md create mode 100644 document/docs/models/variablepayload.md create mode 100644 document/docs/sdks/documents/README.md create mode 100644 document/docs/sdks/epilot/README.md create mode 100644 document/poetry.toml create mode 100644 document/py.typed mode change 100755 => 100644 document/pylintrc create mode 100644 document/pyproject.toml create mode 100755 document/scripts/compile.sh create mode 100755 document/scripts/publish.sh delete mode 100755 document/setup.py delete mode 100755 document/src/epilot/__init__.py delete mode 100755 document/src/epilot/documents.py delete mode 100755 document/src/epilot/models/__init__.py delete mode 100755 document/src/epilot/models/operations/__init__.py delete mode 100755 document/src/epilot/models/operations/generatedocument.py delete mode 100755 document/src/epilot/models/shared/__init__.py delete mode 100755 document/src/epilot/models/shared/s3reference.py delete mode 100755 document/src/epilot/models/shared/security.py delete mode 100755 document/src/epilot/sdk.py delete mode 100755 document/src/epilot/utils/__init__.py delete mode 100755 document/src/epilot/utils/retries.py delete mode 100755 document/src/epilot/utils/utils.py create mode 100644 document/src/epilot_document/__init__.py create mode 100644 document/src/epilot_document/_hooks/__init__.py create mode 100644 document/src/epilot_document/_hooks/registration.py create mode 100644 document/src/epilot_document/_hooks/sdkhooks.py create mode 100644 document/src/epilot_document/_hooks/types.py create mode 100644 document/src/epilot_document/basesdk.py create mode 100644 document/src/epilot_document/documents.py create mode 100644 document/src/epilot_document/httpclient.py create mode 100644 document/src/epilot_document/models/__init__.py create mode 100644 document/src/epilot_document/models/convertdocumentrequest.py create mode 100644 document/src/epilot_document/models/convertdocumentresponse.py create mode 100644 document/src/epilot_document/models/documentgenerationv2request.py create mode 100644 document/src/epilot_document/models/documentgenerationv2response.py create mode 100644 document/src/epilot_document/models/errorcode.py create mode 100644 document/src/epilot_document/models/erroroutput.py create mode 100644 document/src/epilot_document/models/generatedocumentv2op.py create mode 100644 document/src/epilot_document/models/invalidcustomvariableerrordetail.py create mode 100644 document/src/epilot_document/models/s3reference.py create mode 100644 document/src/epilot_document/models/sdkerror.py create mode 100644 document/src/epilot_document/models/security.py create mode 100644 document/src/epilot_document/models/templatesettings.py create mode 100644 document/src/epilot_document/py.typed create mode 100644 document/src/epilot_document/sdk.py create mode 100644 document/src/epilot_document/sdkconfiguration.py create mode 100644 document/src/epilot_document/types/__init__.py create mode 100644 document/src/epilot_document/types/basemodel.py create mode 100644 document/src/epilot_document/utils/__init__.py create mode 100644 document/src/epilot_document/utils/annotations.py create mode 100644 document/src/epilot_document/utils/enums.py create mode 100644 document/src/epilot_document/utils/eventstreaming.py create mode 100644 document/src/epilot_document/utils/forms.py create mode 100644 document/src/epilot_document/utils/headers.py create mode 100644 document/src/epilot_document/utils/logger.py create mode 100644 document/src/epilot_document/utils/metadata.py create mode 100644 document/src/epilot_document/utils/queryparams.py create mode 100644 document/src/epilot_document/utils/requestbodies.py create mode 100644 document/src/epilot_document/utils/retries.py create mode 100644 document/src/epilot_document/utils/security.py create mode 100644 document/src/epilot_document/utils/serializers.py create mode 100644 document/src/epilot_document/utils/url.py create mode 100644 document/src/epilot_document/utils/values.py diff --git a/document/.gitattributes b/document/.gitattributes new file mode 100644 index 000000000..4d75d5900 --- /dev/null +++ b/document/.gitattributes @@ -0,0 +1,2 @@ +# This allows generated code to be indexed correctly +*.py linguist-generated=false \ No newline at end of file diff --git a/document/.gitignore b/document/.gitignore new file mode 100644 index 000000000..477b77290 --- /dev/null +++ b/document/.gitignore @@ -0,0 +1,8 @@ +.venv/ +venv/ +src/*.egg-info/ +__pycache__/ +.pytest_cache/ +.python-version +.DS_Store +pyrightconfig.json diff --git a/document/.speakeasy/gen.lock b/document/.speakeasy/gen.lock new file mode 100644 index 000000000..86bda48b1 --- /dev/null +++ b/document/.speakeasy/gen.lock @@ -0,0 +1,109 @@ +lockVersion: 2.0.0 +id: 02056ef4-33bb-4494-9d26-5cec9ca37e38 +management: + docChecksum: 54703d64df72ed498ad03376ecd4b21f + docVersion: 1.0.0 + speakeasyVersion: 1.355.0 + generationVersion: 2.387.0 + releaseVersion: 1.3.0 + configChecksum: 79066fa1e09c11f2aefedb883dff7263 + repoURL: https://github.com/epilot-dev/sdk-python.git + repoSubDirectory: document + installationURL: https://github.com/epilot-dev/sdk-python.git#subdirectory=document +features: + python: + additionalDependencies: 1.0.0 + additionalProperties: 1.0.0 + constsAndDefaults: 1.0.2 + core: 5.3.4 + defaultEnabledRetries: 0.2.0 + envVarSecurityUsage: 0.3.1 + flattening: 3.0.0 + globalSecurity: 3.0.1 + globalSecurityCallbacks: 1.0.0 + globalSecurityFlattening: 1.0.0 + globalServerURLs: 3.0.0 + responseFormat: 1.0.0 + retries: 3.0.0 + sdkHooks: 1.0.0 +generatedFiles: + - src/epilot_document/sdkconfiguration.py + - src/epilot_document/documents.py + - src/epilot_document/sdk.py + - .vscode/settings.json + - poetry.toml + - py.typed + - pylintrc + - pyproject.toml + - scripts/compile.sh + - scripts/publish.sh + - src/epilot_document/__init__.py + - src/epilot_document/basesdk.py + - src/epilot_document/httpclient.py + - src/epilot_document/py.typed + - src/epilot_document/types/__init__.py + - src/epilot_document/types/basemodel.py + - src/epilot_document/utils/__init__.py + - src/epilot_document/utils/annotations.py + - src/epilot_document/utils/enums.py + - src/epilot_document/utils/eventstreaming.py + - src/epilot_document/utils/forms.py + - src/epilot_document/utils/headers.py + - src/epilot_document/utils/logger.py + - src/epilot_document/utils/metadata.py + - src/epilot_document/utils/queryparams.py + - src/epilot_document/utils/requestbodies.py + - src/epilot_document/utils/retries.py + - src/epilot_document/utils/security.py + - src/epilot_document/utils/serializers.py + - src/epilot_document/utils/url.py + - src/epilot_document/utils/values.py + - src/epilot_document/models/sdkerror.py + - src/epilot_document/models/convertdocumentresponse.py + - src/epilot_document/models/s3reference.py + - src/epilot_document/models/convertdocumentrequest.py + - src/epilot_document/models/documentgenerationv2response.py + - src/epilot_document/models/templatesettings.py + - src/epilot_document/models/erroroutput.py + - src/epilot_document/models/invalidcustomvariableerrordetail.py + - src/epilot_document/models/errorcode.py + - src/epilot_document/models/generatedocumentv2op.py + - src/epilot_document/models/documentgenerationv2request.py + - src/epilot_document/models/security.py + - src/epilot_document/models/__init__.py + - docs/models/outputdocument.md + - docs/models/convertdocumentresponse.md + - docs/models/s3reference.md + - docs/models/inputdocument.md + - docs/models/outputformat.md + - docs/models/convertdocumentrequest.md + - docs/models/documentgenerationv2responseoutputdocument.md + - docs/models/docxoutput.md + - docs/models/jobstatus.md + - docs/models/documentgenerationv2responseschemasoutputdocument.md + - docs/models/pdfoutput.md + - docs/models/documentgenerationv2responsevariablepayload.md + - docs/models/documentgenerationv2response.md + - docs/models/custommargins.md + - docs/models/suggestedmargins.md + - docs/models/templatesettings.md + - docs/models/erroroutput.md + - docs/models/invalidvariables.md + - docs/models/context.md + - docs/models/invalidcustomvariableerrordetail.md + - docs/models/errorcode.md + - docs/models/mode.md + - docs/models/generatedocumentv2request.md + - docs/models/templatedocument.md + - docs/models/variablepayload.md + - docs/models/documentgenerationv2request.md + - docs/models/security.md + - docs/sdks/epilot/README.md + - docs/models/utils/retryconfig.md + - docs/sdks/documents/README.md + - USAGE.md + - .gitattributes + - src/epilot_document/_hooks/sdkhooks.py + - src/epilot_document/_hooks/types.py + - src/epilot_document/_hooks/__init__.py + - CONTRIBUTING.md diff --git a/document/.vscode/settings.json b/document/.vscode/settings.json new file mode 100644 index 000000000..8d79f0abb --- /dev/null +++ b/document/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "python.testing.pytestArgs": ["tests", "-vv"], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true, + "pylint.args": ["--rcfile=pylintrc"] +} diff --git a/document/CONTRIBUTING.md b/document/CONTRIBUTING.md new file mode 100644 index 000000000..d585717fc --- /dev/null +++ b/document/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to This Repository + +Thank you for your interest in contributing to this repository. Please note that this repository contains generated code. As such, we do not accept direct changes or pull requests. Instead, we encourage you to follow the guidelines below to report issues and suggest improvements. + +## How to Report Issues + +If you encounter any bugs or have suggestions for improvements, please open an issue on GitHub. When reporting an issue, please provide as much detail as possible to help us reproduce the problem. This includes: + +- A clear and descriptive title +- Steps to reproduce the issue +- Expected and actual behavior +- Any relevant logs, screenshots, or error messages +- Information about your environment (e.g., operating system, software versions) + - For example can be collected using the `npx envinfo` command from your terminal if you have Node.js installed + +## Issue Triage and Upstream Fixes + +We will review and triage issues as quickly as possible. Our goal is to address bugs and incorporate improvements in the upstream source code. Fixes will be included in the next generation of the generated code. + +## Contact + +If you have any questions or need further assistance, please feel free to reach out by opening an issue. + +Thank you for your understanding and cooperation! + +The Maintainers diff --git a/document/README.md b/document/README.md index d9f5437d5..119fd8550 100755 --- a/document/README.md +++ b/document/README.md @@ -1,53 +1,405 @@ # epilot-document - + ## SDK Installation +PIP ```bash pip install git+https://github.com/epilot-dev/sdk-python.git#subdirectory=document ``` - +Poetry +```bash +poetry add git+https://github.com/epilot-dev/sdk-python.git#subdirectory=document +``` + + + ## SDK Example Usage - + +### Example + +```python +# Synchronous Example +import epilot_document +from epilot_document import Epilot + +s = Epilot( + epilot_auth="", +) + + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: + # handle response + pass +``` + +
+ +The same SDK client can also be used to make asychronous requests by importing asyncio. +```python +# Asynchronous Example +import asyncio +import epilot_document +from epilot_document import Epilot + +async def main(): + s = Epilot( + epilot_auth="", + ) + res = await s.documents.convert_document_async(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", + }) + if res is not None: + # handle response + pass + +asyncio.run(main()) +``` + + + +## Available Resources and Operations + +### [documents](docs/sdks/documents/README.md) + +* [convert_document](docs/sdks/documents/README.md#convert_document) - convertDocument +* [generate_document_v2](docs/sdks/documents/README.md#generate_document_v2) - generateDocumentV2 + + + +## Retries + +Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK. + +To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: +```python +from epilot.utils import BackoffStrategy, RetryConfig +import epilot_document +from epilot_document import Epilot + +s = Epilot( + epilot_auth="", +) + + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}, + RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) + +if res is not None: + # handle response + pass + +``` + +If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: +```python +from epilot.utils import BackoffStrategy, RetryConfig +import epilot_document +from epilot_document import Epilot + +s = Epilot( + retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), + epilot_auth="", +) + + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: + # handle response + pass + +``` + + + +## Error Handling + +Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error. If Error objects are specified in your OpenAPI Spec, the SDK will raise the appropriate Error type. + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +### Example + +```python +import epilot_document +from epilot_document import Epilot, models + +s = Epilot( + epilot_auth="", +) + +res = None +try: + res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +except models.SDKError as e: + # handle exception + raise(e) + +if res is not None: + # handle response + pass + +``` + + + +## Server Selection + +### Select Server by Index + +You can override the default server globally by passing a server index to the `server_idx: int` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers: + +| # | Server | Variables | +| - | ------ | --------- | +| 0 | `https://document.sls.epilot.io` | None | + +#### Example + ```python -import epilot -from epilot.models import operations, shared +import epilot_document +from epilot_document import Epilot -s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", - ), +s = Epilot( + server_idx=0, + epilot_auth="", ) -req = operations.GenerateDocumentRequestBody( - context_entity_id="bcd0aab9-b544-42b0-8bfb-6d449d02eacc", - language="de", - template_document=operations.GenerateDocumentRequestBodyTemplateDocument( - filename="my-template-{{order.order_number}}.docx", - s3ref=shared.S3Reference( - bucket="document-api-prod", - key="uploads/my-template.pdf", - ), - ), - user_id="100321", +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: + # handle response + pass + +``` + + +### Override Server URL Per-Client + +The default server can also be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: +```python +import epilot_document +from epilot_document import Epilot + +s = Epilot( + server_url="https://document.sls.epilot.io", + epilot_auth="", ) - -res = s.documents.generate_document(req) -if res.generate_document_200_application_json_object is not None: + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: # handle response + pass + ``` - + - -## SDK Available Operations + +## Custom HTTP Client + +The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. + +For example, you could specify a header for every request that this sdk makes as follows: +```python +from epilot_document import Epilot +import httpx + +http_client = httpx.Client(headers={"x-custom-header": "someValue"}) +s = Epilot(client=http_client) +``` + +or you could wrap the client with your own custom logic: +```python +from epilot_document import Epilot +from epilot_document.httpclient import AsyncHttpClient +import httpx + +class CustomClient(AsyncHttpClient): + client: AsyncHttpClient + + def __init__(self, client: AsyncHttpClient): + self.client = client + + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + request.headers["Client-Level-Header"] = "added by client" + + return await self.client.send( + request, stream=stream, auth=auth, follow_redirects=follow_redirects + ) + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + return self.client.build_request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + +s = Epilot(async_client=CustomClient(httpx.AsyncClient())) +``` + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security scheme globally: + +| Name | Type | Scheme | +| ------------- | ------------- | ------------- | +| `epilot_auth` | http | HTTP Bearer | + +To authenticate with the API the `null` parameter must be set when initializing the SDK client instance. For example: +```python +import epilot_document +from epilot_document import Epilot + +s = Epilot( + epilot_auth="", +) + + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: + # handle response + pass + +``` + + + +## Debugging + +To emit debug logs for SDK requests and responses you can pass a logger object directly into your SDK object. + +```python +from epilot_document import Epilot +import logging + +logging.basicConfig(level=logging.DEBUG) +s = Epilot(debug_logger=logging.getLogger("epilot_document")) +``` + + -### documents -* `generate_document` - generateDocument - ### SDK Generated by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks) diff --git a/document/RELEASES.md b/document/RELEASES.md index a6066d95f..8e338f4be 100644 --- a/document/RELEASES.md +++ b/document/RELEASES.md @@ -34,4 +34,12 @@ Based on: ### Changes Based on: - OpenAPI Doc 1.0.0 https://docs.api.epilot.io/document.yaml -- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy \ No newline at end of file +- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy + +## 2024-08-07 00:14:25 +### Changes +Based on: +- OpenAPI Doc 1.0.0 https://docs.api.epilot.io/document.yaml +- Speakeasy CLI 1.355.0 (2.387.0) https://github.com/speakeasy-api/speakeasy +### Generated +- [python v1.3.0] document \ No newline at end of file diff --git a/document/USAGE.md b/document/USAGE.md old mode 100755 new mode 100644 index 7b2b27cc9..fbab9cba9 --- a/document/USAGE.md +++ b/document/USAGE.md @@ -1,31 +1,57 @@ - + ```python -import epilot -from epilot.models import operations, shared +# Synchronous Example +import epilot_document +from epilot_document import Epilot -s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", - ), +s = Epilot( + epilot_auth="", ) -req = operations.GenerateDocumentRequestBody( - context_entity_id="bcd0aab9-b544-42b0-8bfb-6d449d02eacc", - language="de", - template_document=operations.GenerateDocumentRequestBodyTemplateDocument( - filename="my-template-{{order.order_number}}.docx", - s3ref=shared.S3Reference( - bucket="document-api-prod", - key="uploads/my-template.pdf", - ), - ), - user_id="100321", -) - -res = s.documents.generate_document(req) +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) -if res.generate_document_200_application_json_object is not None: +if res is not None: # handle response + pass +``` + +
+ +The same SDK client can also be used to make asychronous requests by importing asyncio. +```python +# Asynchronous Example +import asyncio +import epilot_document +from epilot_document import Epilot + +async def main(): + s = Epilot( + epilot_auth="", + ) + res = await s.documents.convert_document_async(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", + }) + if res is not None: + # handle response + pass + +asyncio.run(main()) ``` - \ No newline at end of file + \ No newline at end of file diff --git a/document/docs/models/context.md b/document/docs/models/context.md new file mode 100644 index 000000000..9ba0bf487 --- /dev/null +++ b/document/docs/models/context.md @@ -0,0 +1,10 @@ +# Context + +Context for the error + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `invalid_variables` | List[[models.InvalidVariables](../models/invalidvariables.md)] | :heavy_minus_sign: | List of invalid variables | \ No newline at end of file diff --git a/document/docs/models/convertdocumentrequest.md b/document/docs/models/convertdocumentrequest.md new file mode 100644 index 000000000..44e911d41 --- /dev/null +++ b/document/docs/models/convertdocumentrequest.md @@ -0,0 +1,10 @@ +# ConvertDocumentRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +| `input_document` | [models.InputDocument](../models/inputdocument.md) | :heavy_check_mark: | Input document | | +| `output_format` | [models.OutputFormat](../models/outputformat.md) | :heavy_check_mark: | Output format of the document | | +| `output_filename` | *Optional[str]* | :heavy_minus_sign: | Filename of the output document (optional) | converted.pdf | \ No newline at end of file diff --git a/document/docs/models/convertdocumentresponse.md b/document/docs/models/convertdocumentresponse.md new file mode 100644 index 000000000..e3a639814 --- /dev/null +++ b/document/docs/models/convertdocumentresponse.md @@ -0,0 +1,8 @@ +# ConvertDocumentResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `output_document` | [Optional[models.OutputDocument]](../models/outputdocument.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/document/docs/models/custommargins.md b/document/docs/models/custommargins.md new file mode 100644 index 000000000..c1239ece1 --- /dev/null +++ b/document/docs/models/custommargins.md @@ -0,0 +1,11 @@ +# CustomMargins + +Custom margins for the document + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------- | ------------------- | ------------------- | ------------------- | ------------------- | +| `bottom` | *Optional[float]* | :heavy_minus_sign: | Bottom margin in cm | 2.54 | +| `top` | *Optional[float]* | :heavy_minus_sign: | Top margin in cm | 2.54 | \ No newline at end of file diff --git a/document/docs/models/documentgenerationv2request.md b/document/docs/models/documentgenerationv2request.md new file mode 100644 index 000000000..cc9e70099 --- /dev/null +++ b/document/docs/models/documentgenerationv2request.md @@ -0,0 +1,12 @@ +# DocumentGenerationV2Request + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `template_document` | [models.TemplateDocument](../models/templatedocument.md) | :heavy_check_mark: | Input template document | | +| `context_entity_id` | *Optional[str]* | :heavy_minus_sign: | Entity to use for variable context | bcd0aab9-b544-42b0-8bfb-6d449d02eacc | +| `template_settings` | [Optional[models.TemplateSettings]](../models/templatesettings.md) | :heavy_minus_sign: | Template Settings for document generation | | +| `user_id` | *Optional[str]* | :heavy_minus_sign: | User Id for variable context | 100321 | +| `variable_payload` | [Optional[models.VariablePayload]](../models/variablepayload.md) | :heavy_minus_sign: | Custom values for variables in the template. Takes the higher precedence than others. | | \ No newline at end of file diff --git a/document/docs/models/documentgenerationv2response.md b/document/docs/models/documentgenerationv2response.md new file mode 100644 index 000000000..4e415ac55 --- /dev/null +++ b/document/docs/models/documentgenerationv2response.md @@ -0,0 +1,15 @@ +# DocumentGenerationV2Response + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `docx_output` | [Optional[models.DocxOutput]](../models/docxoutput.md) | :heavy_minus_sign: | N/A | +| `error_output` | [Optional[models.ErrorOutput]](../models/erroroutput.md) | :heavy_minus_sign: | N/A | +| `job_id` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `job_status` | [Optional[models.JobStatus]](../models/jobstatus.md) | :heavy_minus_sign: | Status of the job | +| `message` | *Optional[str]* | :heavy_minus_sign: | A message explaining the progress | +| `pdf_output` | [Optional[models.PdfOutput]](../models/pdfoutput.md) | :heavy_minus_sign: | N/A | +| `template_settings` | [Optional[models.TemplateSettings]](../models/templatesettings.md) | :heavy_minus_sign: | Template Settings for document generation | +| `variable_payload` | [Optional[models.DocumentGenerationV2ResponseVariablePayload]](../models/documentgenerationv2responsevariablepayload.md) | :heavy_minus_sign: | List of variables and its corresponding replaced values from the document template | \ No newline at end of file diff --git a/document/docs/models/documentgenerationv2responseoutputdocument.md b/document/docs/models/documentgenerationv2responseoutputdocument.md new file mode 100644 index 000000000..fa81e6045 --- /dev/null +++ b/document/docs/models/documentgenerationv2responseoutputdocument.md @@ -0,0 +1,9 @@ +# DocumentGenerationV2ResponseOutputDocument + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `filename` | *Optional[str]* | :heavy_minus_sign: | Generated document filename for DOCX | my-template-OR-001.docx | +| `s3ref` | [Optional[models.S3Reference]](../models/s3reference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/document/docs/models/documentgenerationv2responseschemasoutputdocument.md b/document/docs/models/documentgenerationv2responseschemasoutputdocument.md new file mode 100644 index 000000000..f8c86b94e --- /dev/null +++ b/document/docs/models/documentgenerationv2responseschemasoutputdocument.md @@ -0,0 +1,9 @@ +# DocumentGenerationV2ResponseSchemasOutputDocument + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `filename` | *Optional[str]* | :heavy_minus_sign: | Generated document filename for PDF | my-template-OR-001.pdf | +| `s3ref` | [Optional[models.S3Reference]](../models/s3reference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/document/docs/models/documentgenerationv2responsevariablepayload.md b/document/docs/models/documentgenerationv2responsevariablepayload.md new file mode 100644 index 000000000..b606333e9 --- /dev/null +++ b/document/docs/models/documentgenerationv2responsevariablepayload.md @@ -0,0 +1,10 @@ +# DocumentGenerationV2ResponseVariablePayload + +List of variables and its corresponding replaced values from the document template + + +## Fields + +| Field | Type | Required | Description | +| ----------------------- | ----------------------- | ----------------------- | ----------------------- | +| `additional_properties` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/document/docs/models/docxoutput.md b/document/docs/models/docxoutput.md new file mode 100644 index 000000000..205230a55 --- /dev/null +++ b/document/docs/models/docxoutput.md @@ -0,0 +1,9 @@ +# DocxOutput + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `output_document` | [Optional[models.DocumentGenerationV2ResponseOutputDocument]](../models/documentgenerationv2responseoutputdocument.md) | :heavy_minus_sign: | N/A | {
"s3ref": {
"bucket": "document-api-preview-prod",
"key": "preview/my-template.docx"
}
} | +| `preview_url` | *Optional[str]* | :heavy_minus_sign: | Pre-signed S3 GET URL for DOCX preview | https://document-api-prod.s3.eu-central-1.amazonaws.com/preview/my-template-OR-001.docx | \ No newline at end of file diff --git a/document/docs/models/errorcode.md b/document/docs/models/errorcode.md new file mode 100644 index 000000000..a82a5f847 --- /dev/null +++ b/document/docs/models/errorcode.md @@ -0,0 +1,18 @@ +# ErrorCode + +Error codes for document generation: +- PARSE_ERROR - Error while parsing the document. Normally related with a bad template using the wrong DocxTemplater syntax. +- DOC_TO_PDF_CONVERT_ERROR - Error while converting the document to PDF. Normally related with a ConvertAPI failure. +- INTERNAL_ERROR - Internal error. Please contact support. +- INVALID_TEMPLATE_FORMAT - Invalid template format (only .docx is supported). This can happen due to a bad word file or an unsupported file extension. + + + +## Values + +| Name | Value | +| -------------------------- | -------------------------- | +| `PARSE_ERROR` | PARSE_ERROR | +| `DOC_TO_PDF_CONVERT_ERROR` | DOC_TO_PDF_CONVERT_ERROR | +| `INTERNAL_ERROR` | INTERNAL_ERROR | +| `INVALID_TEMPLATE_FORMAT` | INVALID_TEMPLATE_FORMAT | \ No newline at end of file diff --git a/document/docs/models/erroroutput.md b/document/docs/models/erroroutput.md new file mode 100644 index 000000000..cbcf878d1 --- /dev/null +++ b/document/docs/models/erroroutput.md @@ -0,0 +1,10 @@ +# ErrorOutput + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `error_code` | [Optional[models.ErrorCode]](../models/errorcode.md) | :heavy_minus_sign: | Error codes for document generation:
- PARSE_ERROR - Error while parsing the document. Normally related with a bad template using the wrong DocxTemplater syntax.
- DOC_TO_PDF_CONVERT_ERROR - Error while converting the document to PDF. Normally related with a ConvertAPI failure.
- INTERNAL_ERROR - Internal error. Please contact support.
- INVALID_TEMPLATE_FORMAT - Invalid template format (only .docx is supported). This can happen due to a bad word file or an unsupported file extension.
| +| `error_details` | List[[models.InvalidCustomVariableErrorDetail](../models/invalidcustomvariableerrordetail.md)] | :heavy_minus_sign: | N/A | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | Error message | \ No newline at end of file diff --git a/document/docs/models/generatedocumentv2request.md b/document/docs/models/generatedocumentv2request.md new file mode 100644 index 000000000..e295c4b7e --- /dev/null +++ b/document/docs/models/generatedocumentv2request.md @@ -0,0 +1,10 @@ +# GenerateDocumentV2Request + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `document_generation_v2_request` | [Optional[models.DocumentGenerationV2Request]](../models/documentgenerationv2request.md) | :heavy_minus_sign: | N/A | +| `job_id` | *Optional[str]* | :heavy_minus_sign: | Job ID for tracking the status of document generation action | +| `mode` | [Optional[models.Mode]](../models/mode.md) | :heavy_minus_sign: | Type of mode used for document generation flow:
- partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document.
- full_generation, goes through all the steps for the full generation of final document
| \ No newline at end of file diff --git a/document/docs/models/inputdocument.md b/document/docs/models/inputdocument.md new file mode 100644 index 000000000..6463cfbed --- /dev/null +++ b/document/docs/models/inputdocument.md @@ -0,0 +1,10 @@ +# InputDocument + +Input document + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| `s3ref` | [models.S3Reference](../models/s3reference.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/document/docs/models/invalidcustomvariableerrordetail.md b/document/docs/models/invalidcustomvariableerrordetail.md new file mode 100644 index 000000000..6627cb879 --- /dev/null +++ b/document/docs/models/invalidcustomvariableerrordetail.md @@ -0,0 +1,10 @@ +# InvalidCustomVariableErrorDetail + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| `__pydantic_extra__` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | +| `context` | [Optional[models.Context]](../models/context.md) | :heavy_minus_sign: | Context for the error | +| `explanation` | *Optional[str]* | :heavy_minus_sign: | Explanation for the error | \ No newline at end of file diff --git a/document/docs/models/invalidvariables.md b/document/docs/models/invalidvariables.md new file mode 100644 index 000000000..399213a5a --- /dev/null +++ b/document/docs/models/invalidvariables.md @@ -0,0 +1,11 @@ +# InvalidVariables + +Invalid variable + + +## Fields + +| Field | Type | Required | Description | +| ------------------------- | ------------------------- | ------------------------- | ------------------------- | +| `error` | *Optional[str]* | :heavy_minus_sign: | Explanation for the error | +| `variable` | *Optional[str]* | :heavy_minus_sign: | Variable name | \ No newline at end of file diff --git a/document/docs/models/jobstatus.md b/document/docs/models/jobstatus.md new file mode 100644 index 000000000..4f9e1f419 --- /dev/null +++ b/document/docs/models/jobstatus.md @@ -0,0 +1,13 @@ +# JobStatus + +Status of the job + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `STARTED` | STARTED | +| `PROCESSING` | PROCESSING | +| `SUCCESS` | SUCCESS | +| `FAILED` | FAILED | \ No newline at end of file diff --git a/document/docs/models/mode.md b/document/docs/models/mode.md new file mode 100644 index 000000000..deeaaef48 --- /dev/null +++ b/document/docs/models/mode.md @@ -0,0 +1,14 @@ +# Mode + +Type of mode used for document generation flow: +- partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. +- full_generation, goes through all the steps for the full generation of final document + + + +## Values + +| Name | Value | +| -------------------- | -------------------- | +| `PARTIAL_GENERATION` | partial_generation | +| `FULL_GENERATION` | full_generation | \ No newline at end of file diff --git a/document/docs/models/outputdocument.md b/document/docs/models/outputdocument.md new file mode 100644 index 000000000..9b3e84556 --- /dev/null +++ b/document/docs/models/outputdocument.md @@ -0,0 +1,9 @@ +# OutputDocument + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `preview_url` | *Optional[str]* | :heavy_minus_sign: | Pre-signed URL for the converted document | https://document-api-prod.s3.eu-central-1.amazonaws.com/preview/converted.pdf | +| `s3ref` | [Optional[models.S3Reference]](../models/s3reference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/document/docs/models/outputformat.md b/document/docs/models/outputformat.md new file mode 100644 index 000000000..aa3dd7128 --- /dev/null +++ b/document/docs/models/outputformat.md @@ -0,0 +1,10 @@ +# OutputFormat + +Output format of the document + + +## Values + +| Name | Value | +| ----- | ----- | +| `PDF` | pdf | \ No newline at end of file diff --git a/document/docs/models/pdfoutput.md b/document/docs/models/pdfoutput.md new file mode 100644 index 000000000..9138b1959 --- /dev/null +++ b/document/docs/models/pdfoutput.md @@ -0,0 +1,9 @@ +# PdfOutput + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | +| `output_document` | [Optional[models.DocumentGenerationV2ResponseSchemasOutputDocument]](../models/documentgenerationv2responseschemasoutputdocument.md) | :heavy_minus_sign: | N/A | {
"s3ref": {
"bucket": "document-api-preview-prod",
"key": "preview/my-template.pdf"
}
} | +| `preview_url` | *Optional[str]* | :heavy_minus_sign: | Pre-signed S3 GET URL for PDF preview | https://document-api-prod.s3.eu-central-1.amazonaws.com/preview/my-template-OR-001.pdf | \ No newline at end of file diff --git a/document/docs/models/s3reference.md b/document/docs/models/s3reference.md new file mode 100644 index 000000000..ef2fc6fcd --- /dev/null +++ b/document/docs/models/s3reference.md @@ -0,0 +1,9 @@ +# S3Reference + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------- | ----------------------- | ----------------------- | ----------------------- | ----------------------- | +| `bucket` | *str* | :heavy_check_mark: | N/A | document-api-prod | +| `key` | *str* | :heavy_check_mark: | N/A | uploads/my-template.pdf | \ No newline at end of file diff --git a/document/docs/models/security.md b/document/docs/models/security.md new file mode 100644 index 000000000..5eebea96d --- /dev/null +++ b/document/docs/models/security.md @@ -0,0 +1,8 @@ +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `epilot_auth` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/document/docs/models/suggestedmargins.md b/document/docs/models/suggestedmargins.md new file mode 100644 index 000000000..e0d311051 --- /dev/null +++ b/document/docs/models/suggestedmargins.md @@ -0,0 +1,11 @@ +# SuggestedMargins + +Suggested margins for the document + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------- | ------------------- | ------------------- | ------------------- | ------------------- | +| `bottom` | *Optional[float]* | :heavy_minus_sign: | Bottom margin in cm | 2.54 | +| `top` | *Optional[float]* | :heavy_minus_sign: | Top margin in cm | 2.54 | \ No newline at end of file diff --git a/document/docs/models/templatedocument.md b/document/docs/models/templatedocument.md new file mode 100644 index 000000000..668e9896d --- /dev/null +++ b/document/docs/models/templatedocument.md @@ -0,0 +1,11 @@ +# TemplateDocument + +Input template document + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `filename` | *Optional[str]* | :heavy_minus_sign: | Document original filename | my-template-{{order.order_number}}.docx | +| `s3ref` | [Optional[models.S3Reference]](../models/s3reference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/document/docs/models/templatesettings.md b/document/docs/models/templatesettings.md new file mode 100644 index 000000000..0e35a9cb6 --- /dev/null +++ b/document/docs/models/templatesettings.md @@ -0,0 +1,17 @@ +# TemplateSettings + +Template Settings for document generation + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `custom_margins` | [Optional[models.CustomMargins]](../models/custommargins.md) | :heavy_minus_sign: | Custom margins for the document | | +| `display_margin_guidelines` | *Optional[bool]* | :heavy_minus_sign: | Display margin guidelines (applicable to partial generation only) | true | +| `enable_data_table_margin_autofix` | *Optional[bool]* | :heavy_minus_sign: | Enable data table margin autofix | false | +| `enabled_template_settings_persistence` | *Optional[bool]* | :heavy_minus_sign: | Enables the persistance of template settings | false | +| `file_entity_id` | *Optional[str]* | :heavy_minus_sign: | The file entity id, used when persisting a new template version with updated settings | 1a2b3c4d-5e6f-7g8h-9i0j-1k2l3m4n5o6p | +| `misconfigured_margins` | *Optional[bool]* | :heavy_minus_sign: | An indication that the page margins are misconfigured | false | +| `suggested_margins` | [Optional[models.SuggestedMargins]](../models/suggestedmargins.md) | :heavy_minus_sign: | Suggested margins for the document | | +| `template_with_datatable` | *Optional[bool]* | :heavy_minus_sign: | A flag that indicates whether the template has 1 or more data tables in it | false | \ No newline at end of file diff --git a/document/docs/models/utils/retryconfig.md b/document/docs/models/utils/retryconfig.md new file mode 100644 index 000000000..69dd549ec --- /dev/null +++ b/document/docs/models/utils/retryconfig.md @@ -0,0 +1,24 @@ +# RetryConfig + +Allows customizing the default retry configuration. Only usable with methods that mention they support retries. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | +| `strategy` | `*str*` | The retry strategy to use. | `backoff` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | +| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | --------- | ----------------------------------------- | -------- | +| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | +| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | +| `max_elapsed_time` | `*int*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/document/docs/models/variablepayload.md b/document/docs/models/variablepayload.md new file mode 100644 index 000000000..98429bcef --- /dev/null +++ b/document/docs/models/variablepayload.md @@ -0,0 +1,10 @@ +# VariablePayload + +Custom values for variables in the template. Takes the higher precedence than others. + + +## Fields + +| Field | Type | Required | Description | +| ----------------------- | ----------------------- | ----------------------- | ----------------------- | +| `additional_properties` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/document/docs/sdks/documents/README.md b/document/docs/sdks/documents/README.md new file mode 100644 index 000000000..4bbc41978 --- /dev/null +++ b/document/docs/sdks/documents/README.md @@ -0,0 +1,144 @@ +# Documents +(*documents*) + +## Overview + +Document Generation + +### Available Operations + +* [convert_document](#convert_document) - convertDocument +* [generate_document_v2](#generate_document_v2) - generateDocumentV2 + +## convert_document + +Converts a document to a different format. + +Supported input document types: +- .docx + +Supported output document types: +- .pdf + + +### Example Usage + +```python +import epilot_document +from epilot_document import Epilot + +s = Epilot( + epilot_auth="", +) + + +res = s.documents.convert_document(request={ + "input_document": { + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "output_format": epilot_document.OutputFormat.PDF, + "output_filename": "converted.pdf", +}) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `request` | [models.ConvertDocumentRequest](../../models/convertdocumentrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[models.ConvertDocumentResponse](../../models/convertdocumentresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## generate_document_v2 + +Builds document generated from input document with variables. + +Supported input document types: +- .docx + +Supported output document types: +- .pdf +- .docx but limited to only text based variables + +Uses [Template Variables API](https://docs.epilot.io/api/template-variables) to replace variables in the document. + + +### Example Usage + +```python +from epilot_document import Epilot + +s = Epilot( + epilot_auth="", +) + + +res = s.documents.generate_document_v2(document_generation_v2_request={ + "template_document": { + "filename": "my-template-{{order.order_number}}.docx", + "s3ref": { + "bucket": "document-api-prod", + "key": "uploads/my-template.pdf", + }, + }, + "context_entity_id": "bcd0aab9-b544-42b0-8bfb-6d449d02eacc", + "template_settings": { + "custom_margins": { + "bottom": 2.54, + "top": 2.54, + }, + "display_margin_guidelines": True, + "enable_data_table_margin_autofix": False, + "enabled_template_settings_persistence": False, + "file_entity_id": "1a2b3c4d-5e6f-7g8h-9i0j-1k2l3m4n5o6p", + "misconfigured_margins": False, + "suggested_margins": { + "bottom": 2.54, + "top": 2.54, + }, + "template_with_datatable": False, + }, + "user_id": "100321", +}) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `job_id` | *Optional[str]* | :heavy_minus_sign: | Job ID for tracking the status of document generation action | +| `mode` | [Optional[models.Mode]](../../models/mode.md) | :heavy_minus_sign: | Type of mode used for document generation flow:
- partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document.
- full_generation, goes through all the steps for the full generation of final document
| +| `document_generation_v2_request` | [Optional[models.DocumentGenerationV2Request]](../../models/documentgenerationv2request.md) | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[models.DocumentGenerationV2Response](../../models/documentgenerationv2response.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | diff --git a/document/docs/sdks/epilot/README.md b/document/docs/sdks/epilot/README.md new file mode 100644 index 000000000..7760bd114 --- /dev/null +++ b/document/docs/sdks/epilot/README.md @@ -0,0 +1,12 @@ +# Epilot SDK + + +## Overview + +Document API: A document generation API that allows you to generate documents from templates with variables. + +[Feature Documentation](https://docs.epilot.io/docs/files/document-generation) + + +### Available Operations + diff --git a/document/gen.yaml b/document/gen.yaml index 6da6ae8fe..e7d466484 100644 --- a/document/gen.yaml +++ b/document/gen.yaml @@ -1,16 +1,41 @@ -configVersion: 1.0.0 -management: - docChecksum: 8fe5464a1ad4d46ff34f4097ba4129f3 - docVersion: 1.0.0 - speakeasyVersion: 1.19.2 - generationVersion: 2.16.5 +configVersion: 2.0.0 generation: - telemetryEnabled: false sdkClassName: epilot + usageSnippets: + optionalPropertyRendering: withExample + fixes: + nameResolutionDec2023: false + parameterOrderingFeb2024: false + requestResponseComponentNamesFeb2024: false + auth: + oAuth2ClientCredentialsEnabled: false sdkFlattening: true - singleTagPerOp: false + telemetryEnabled: false python: - version: 1.2.2 + version: 1.3.0 + additionalDependencies: + dev: {} + main: {} author: epilot + authors: + - Speakeasy + clientServerStatusCodesAsErrors: true description: Python Client SDK for Epilot + enumFormat: enum + flattenGlobalSecurity: true + flattenRequests: false + imports: + option: openapi + paths: + callbacks: "" + errors: "" + operations: "" + shared: "" + webhooks: "" + inputModelSuffix: input + maxMethodParams: 4 + methodArguments: infer-optional-args + outputModelSuffix: output packageName: epilot-document + responseFormat: flat + templateVersion: v2 diff --git a/document/poetry.toml b/document/poetry.toml new file mode 100644 index 000000000..ab1033bd3 --- /dev/null +++ b/document/poetry.toml @@ -0,0 +1,2 @@ +[virtualenvs] +in-project = true diff --git a/document/py.typed b/document/py.typed new file mode 100644 index 000000000..3e38f1a92 --- /dev/null +++ b/document/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/document/pylintrc b/document/pylintrc old mode 100755 new mode 100644 index 81c63b93f..66e1cfa05 --- a/document/pylintrc +++ b/document/pylintrc @@ -59,10 +59,11 @@ ignore-paths= # Emacs file locks ignore-patterns=^\.# -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. +# List of module names for which member attributes should not be checked and +# will not be imported (useful for modules/projects where namespaces are +# manipulated during runtime and thus existing member attributes cannot be +# deduced by static analysis). It supports qualified module names, as well as +# Unix pattern matching. ignored-modules= # Python code to execute, usually for sys.path manipulation such as @@ -88,11 +89,17 @@ persistent=yes # Minimum Python version to use for version dependent checks. Will default to # the version used to run pylint. -py-version=3.9 +py-version=3.8 # Discover python modules and packages in the file system subtree. recursive=no +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots=src + # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes @@ -116,20 +123,15 @@ argument-naming-style=snake_case #argument-rgx= # Naming style matching correct attribute names. -attr-naming-style=snake_case +#attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. If left empty, attribute names will be checked with the set naming # style. -#attr-rgx= +attr-rgx=[^\W\d][^\W]*|__.*__$ # Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata +bad-names= # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused @@ -184,7 +186,8 @@ good-names=i, k, ex, Run, - _ + _, + e # Good variable names regexes, separated by a comma. If names match any regex, # they will always be accepted @@ -228,6 +231,10 @@ no-docstring-rgx=^_ # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +typealias-rgx=.* + # Regular expression matching correct type variable names. If left empty, type # variable names will be checked with the set naming style. #typevar-rgx= @@ -250,15 +257,12 @@ check-protected-access-in-special-methods=no defining-attr-methods=__init__, __new__, setUp, + asyncSetUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls @@ -421,6 +425,8 @@ disable=raw-checker-failed, suppressed-message, useless-suppression, deprecated-pragma, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero, use-symbolic-message-instead, trailing-whitespace, line-too-long, @@ -433,18 +439,27 @@ disable=raw-checker-failed, broad-exception-raised, too-few-public-methods, too-many-branches, - chained-comparison, duplicate-code, trailing-newlines, too-many-public-methods, too-many-locals, - too-many-lines + too-many-lines, + using-constant-test, + too-many-statements, + cyclic-import, + too-many-nested-blocks, + too-many-boolean-expressions, + no-else-raise, + bare-except, + broad-exception-caught, + fixme, + relative-beyond-top-level # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member +enable= [METHOD_ARGS] @@ -490,8 +505,9 @@ evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor # used to format the message information. See doc for all details. msg-template= -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. #output-format= @@ -525,8 +541,8 @@ min-similarity-lines=4 # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 -# Spelling dictionary name. Available dictionaries: none. To make it work, -# install the 'python-enchant' package. +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. spelling-dict= # List of comma separated words that should be considered directives if they @@ -619,7 +635,7 @@ additional-builtins= allow-global-unused-variables=yes # List of names allowed to shadow builtins -allowed-redefined-builtins= +allowed-redefined-builtins=id,object # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. diff --git a/document/pyproject.toml b/document/pyproject.toml new file mode 100644 index 000000000..33a9dfa0a --- /dev/null +++ b/document/pyproject.toml @@ -0,0 +1,55 @@ +[tool.poetry] +name = "epilot-document" +version = "1.3.0" +description = "Python Client SDK for Epilot" +authors = ["Speakeasy",] +readme = "README.md" +repository = "https://github.com/epilot-dev/sdk-python.git" +packages = [ + { include = "epilot_document", from = "src" } +] +include = ["py.typed", "src/epilot_document/py.typed"] + +[tool.setuptools.package-data] +"*" = ["py.typed", "src/epilot_document/py.typed"] + +[virtualenvs] +in-project = true + +[tool.poetry.dependencies] +python = "^3.8" +httpx = "^0.27.0" +jsonpath-python = "^1.0.6" +pydantic = "~2.8.2" +python-dateutil = "^2.9.0.post0" +typing-inspect = "^0.9.0" + +[tool.poetry.group.dev.dependencies] +mypy = "==1.10.1" +pylint = "==3.2.3" +pyright = "==1.1.374" +types-python-dateutil = "^2.9.0.20240316" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" + +[tool.pytest.ini_options] +pythonpath = ["src"] + +[tool.mypy] +disable_error_code = "misc" + +[[tool.mypy.overrides]] +module = "typing_inspect" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "jsonpath" +ignore_missing_imports = true + +[tool.pyright] +venvPath = "." +venv = ".venv" + + diff --git a/document/scripts/compile.sh b/document/scripts/compile.sh new file mode 100755 index 000000000..aa49772e2 --- /dev/null +++ b/document/scripts/compile.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash + +set -o pipefail # Ensure pipeline failures are propagated + +# Use temporary files to store outputs and exit statuses +declare -A output_files +declare -A status_files + +# Function to run a command with temporary output and status files +run_command() { + local cmd="$1" + local key="$2" + local output_file="$3" + local status_file="$4" + + # Run the command and store output and exit status + { + eval "$cmd" + echo $? > "$status_file" + } &> "$output_file" & +} + +# Create temporary files for outputs and statuses +for cmd in compileall pylint mypy pyright; do + output_files[$cmd]=$(mktemp) + status_files[$cmd]=$(mktemp) +done + +# Collect PIDs for background processes +declare -a pids + +# Run commands in parallel using temporary files +echo "Running python -m compileall" +run_command 'poetry run python -m compileall -q . && echo "Success"' 'compileall' "${output_files[compileall]}" "${status_files[compileall]}" +pids+=($!) + +echo "Running pylint" +run_command 'poetry run pylint src' 'pylint' "${output_files[pylint]}" "${status_files[pylint]}" +pids+=($!) + +echo "Running mypy" +run_command 'poetry run mypy src' 'mypy' "${output_files[mypy]}" "${status_files[mypy]}" +pids+=($!) + +echo "Running pyright (optional)" +run_command 'if command -v pyright > /dev/null 2>&1; then pyright src; else echo "pyright not found, skipping"; fi' 'pyright' "${output_files[pyright]}" "${status_files[pyright]}" +pids+=($!) + +# Wait for all processes to complete +echo "Waiting for processes to complete" +for pid in "${pids[@]}"; do + wait "$pid" +done + +# Print output sequentially and check for failures +failed=false +for key in "${!output_files[@]}"; do + echo "--- Output from Command: $key ---" + echo + cat "${output_files[$key]}" + echo # Empty line for separation + echo "--- End of Output from Command: $key ---" + echo + + exit_status=$(cat "${status_files[$key]}") + if [ "$exit_status" -ne 0 ]; then + echo "Command $key failed with exit status $exit_status" >&2 + failed=true + fi +done + +# Clean up temporary files +for tmp_file in "${output_files[@]}" "${status_files[@]}"; do + rm -f "$tmp_file" +done + +if $failed; then + echo "One or more commands failed." >&2 + exit 1 +else + echo "All commands completed successfully." + exit 0 +fi diff --git a/document/scripts/publish.sh b/document/scripts/publish.sh new file mode 100755 index 000000000..1ee7194cd --- /dev/null +++ b/document/scripts/publish.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +export POETRY_PYPI_TOKEN_PYPI=${PYPI_TOKEN} + +poetry publish --build --skip-existing diff --git a/document/setup.py b/document/setup.py deleted file mode 100755 index 965ca9e0f..000000000 --- a/document/setup.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import setuptools - -try: - with open("README.md", "r") as fh: - long_description = fh.read() -except FileNotFoundError: - long_description = "" - -setuptools.setup( - name="epilot-document", - version="1.2.2", - author="epilot", - description="Python Client SDK for Epilot", - long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages(where="src"), - install_requires=[ - "certifi==2022.12.07", - "charset-normalizer==2.1.1", - "dataclasses-json-speakeasy==0.5.8", - "idna==3.3", - "marshmallow==3.17.1", - "marshmallow-enum==1.5.1", - "mypy-extensions==0.4.3", - "packaging==21.3", - "pyparsing==3.0.9", - "python-dateutil==2.8.2", - "requests==2.28.1", - "six==1.16.0", - "typing-inspect==0.8.0", - "typing_extensions==4.3.0", - "urllib3==1.26.12", - "pylint==2.16.2", - ], - package_dir={'': 'src'}, - python_requires='>=3.9' -) diff --git a/document/src/epilot/__init__.py b/document/src/epilot/__init__.py deleted file mode 100755 index b9e232018..000000000 --- a/document/src/epilot/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .sdk import * diff --git a/document/src/epilot/documents.py b/document/src/epilot/documents.py deleted file mode 100755 index 9ae2c0b45..000000000 --- a/document/src/epilot/documents.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import requests as requests_http -from . import utils -from epilot.models import operations -from typing import Optional - -class Documents: - r"""Document Generation""" - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str - - def __init__(self, client: requests_http.Session, security_client: requests_http.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None: - self._client = client - self._security_client = security_client - self._server_url = server_url - self._language = language - self._sdk_version = sdk_version - self._gen_version = gen_version - - def generate_document(self, request: operations.GenerateDocumentRequestBody) -> operations.GenerateDocumentResponse: - r"""generateDocument - Builds document generated from input document with variables. - - Supported input document types: - - .docx - - Supported output document types: - - .pdf - - Uses [Template Variables API](https://docs.epilot.io/api/template-variables) to replace variables in the document. - - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/documents:generate' - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.GenerateDocumentResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[operations.GenerateDocument200ApplicationJSON]) - res.generate_document_200_application_json_object = out - - return res - - \ No newline at end of file diff --git a/document/src/epilot/models/__init__.py b/document/src/epilot/models/__init__.py deleted file mode 100755 index 889f8adcf..000000000 --- a/document/src/epilot/models/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - diff --git a/document/src/epilot/models/operations/__init__.py b/document/src/epilot/models/operations/__init__.py deleted file mode 100755 index 6e6164cc2..000000000 --- a/document/src/epilot/models/operations/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .generatedocument import * - -__all__ = ["GenerateDocument200ApplicationJSON","GenerateDocument200ApplicationJSONOutputDocument","GenerateDocumentRequestBody","GenerateDocumentRequestBodyTemplateDocument","GenerateDocumentResponse"] diff --git a/document/src/epilot/models/operations/generatedocument.py b/document/src/epilot/models/operations/generatedocument.py deleted file mode 100755 index 903edcef8..000000000 --- a/document/src/epilot/models/operations/generatedocument.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import s3reference as shared_s3reference -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class GenerateDocumentRequestBodyTemplateDocument: - r"""Input template document""" - - filename: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('filename'), 'exclude': lambda f: f is None }}) - r"""Document original filename""" - s3ref: Optional[shared_s3reference.S3Reference] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('s3ref'), 'exclude': lambda f: f is None }}) - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class GenerateDocumentRequestBody: - - template_document: GenerateDocumentRequestBodyTemplateDocument = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_document') }}) - r"""Input template document""" - context_entity_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('context_entity_id'), 'exclude': lambda f: f is None }}) - r"""Entity to use for variable context""" - language: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('language'), 'exclude': lambda f: f is None }}) - r"""Language to use""" - user_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('user_id'), 'exclude': lambda f: f is None }}) - r"""User Id for variable context""" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class GenerateDocument200ApplicationJSONOutputDocument: - - filename: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('filename'), 'exclude': lambda f: f is None }}) - r"""Generated document filename""" - s3ref: Optional[shared_s3reference.S3Reference] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('s3ref'), 'exclude': lambda f: f is None }}) - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class GenerateDocument200ApplicationJSON: - r"""Generated document output""" - - output_document: Optional[GenerateDocument200ApplicationJSONOutputDocument] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('output_document'), 'exclude': lambda f: f is None }}) - preview_url: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('preview_url'), 'exclude': lambda f: f is None }}) - r"""Pre-signed S3 GET URL for preview""" - - -@dataclasses.dataclass -class GenerateDocumentResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - generate_document_200_application_json_object: Optional[GenerateDocument200ApplicationJSON] = dataclasses.field(default=None) - r"""Generated document output""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/document/src/epilot/models/shared/__init__.py b/document/src/epilot/models/shared/__init__.py deleted file mode 100755 index 10b6655df..000000000 --- a/document/src/epilot/models/shared/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .s3reference import * -from .security import * - -__all__ = ["S3Reference","Security"] diff --git a/document/src/epilot/models/shared/s3reference.py b/document/src/epilot/models/shared/s3reference.py deleted file mode 100755 index a6848b7e0..000000000 --- a/document/src/epilot/models/shared/s3reference.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from epilot import utils - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class S3Reference: - - bucket: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('bucket') }}) - key: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('key') }}) - \ No newline at end of file diff --git a/document/src/epilot/models/shared/security.py b/document/src/epilot/models/shared/security.py deleted file mode 100755 index cca0d01c8..000000000 --- a/document/src/epilot/models/shared/security.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses - - -@dataclasses.dataclass -class Security: - - epilot_auth: str = dataclasses.field(metadata={'security': { 'scheme': True, 'type': 'http', 'sub_type': 'bearer', 'field_name': 'Authorization' }}) - \ No newline at end of file diff --git a/document/src/epilot/sdk.py b/document/src/epilot/sdk.py deleted file mode 100755 index 32052cc4b..000000000 --- a/document/src/epilot/sdk.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import requests as requests_http -from . import utils -from .documents import Documents -from epilot.models import shared - -SERVERS = [ - "https://document.sls.epilot.io", -] -"""Contains the list of servers available to the SDK""" - -class Epilot: - r"""Generate documents with epilot data - - [Feature Documentation](https://docs.epilot.io/docs/files/document-generation) - - """ - documents: Documents - r"""Document Generation""" - - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str = SERVERS[0] - _language: str = "python" - _sdk_version: str = "1.2.2" - _gen_version: str = "2.16.5" - - def __init__(self, - security: shared.Security = None, - server_url: str = None, - url_params: dict[str, str] = None, - client: requests_http.Session = None - ) -> None: - """Instantiates the SDK configuring it with the provided parameters. - - :param security: The security details required for authentication - :type security: shared.Security - :param server_url: The server URL to use for all operations - :type server_url: str - :param url_params: Parameters to optionally template the server URL with - :type url_params: dict[str, str] - :param client: The requests.Session HTTP client to use for all operations - :type client: requests_http.Session - """ - self._client = requests_http.Session() - - - if server_url is not None: - if url_params is not None: - self._server_url = utils.template_url(server_url, url_params) - else: - self._server_url = server_url - - if client is not None: - self._client = client - - self._security_client = utils.configure_security_client(self._client, security) - - - self._init_sdks() - - def _init_sdks(self): - self.documents = Documents( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - \ No newline at end of file diff --git a/document/src/epilot/utils/__init__.py b/document/src/epilot/utils/__init__.py deleted file mode 100755 index 94b739857..000000000 --- a/document/src/epilot/utils/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .retries import * -from .utils import * diff --git a/document/src/epilot/utils/retries.py b/document/src/epilot/utils/retries.py deleted file mode 100755 index c6251d948..000000000 --- a/document/src/epilot/utils/retries.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import random -import time - -import requests - - -class BackoffStrategy: - initial_interval: int - max_interval: int - exponent: float - max_elapsed_time: int - - def __init__(self, initial_interval: int, max_interval: int, exponent: float, max_elapsed_time: int): - self.initial_interval = initial_interval - self.max_interval = max_interval - self.exponent = exponent - self.max_elapsed_time = max_elapsed_time - - -class RetryConfig: - strategy: str - backoff: BackoffStrategy - retry_connection_errors: bool - - def __init__(self, strategy: str, retry_connection_errors: bool): - self.strategy = strategy - self.retry_connection_errors = retry_connection_errors - - -class Retries: - config: RetryConfig - status_codes: list[str] - - def __init__(self, config: RetryConfig, status_codes: list[str]): - self.config = config - self.status_codes = status_codes - - -class TemporaryError(Exception): - response: requests.Response - - def __init__(self, response: requests.Response): - self.response = response - - -class PermanentError(Exception): - inner: Exception - - def __init__(self, inner: Exception): - self.inner = inner - - -def retry(func, retries: Retries): - if retries.config.strategy == 'backoff': - def do_request(): - res: requests.Response - try: - res = func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if status_major >= code_range and status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except requests.exceptions.ConnectionError as exception: - if not retries.config.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except requests.exceptions.Timeout as exception: - if not retries.config.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return retry_with_backoff(do_request, retries.config.backoff.initial_interval, retries.config.backoff.max_interval, retries.config.backoff.exponent, retries.config.backoff.max_elapsed_time) - - return func() - - -def retry_with_backoff(func, initial_interval=500, max_interval=60000, exponent=1.5, max_elapsed_time=3600000): - start = round(time.time()*1000) - retries = 0 - - while True: - try: - return func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time()*1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - - raise - sleep = ((initial_interval/1000) * - exponent**retries + random.uniform(0, 1)) - if sleep > max_interval/1000: - sleep = max_interval/1000 - time.sleep(sleep) - retries += 1 diff --git a/document/src/epilot/utils/utils.py b/document/src/epilot/utils/utils.py deleted file mode 100755 index 9d4fba324..000000000 --- a/document/src/epilot/utils/utils.py +++ /dev/null @@ -1,735 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import base64 -import json -import re -from dataclasses import Field, dataclass, fields, is_dataclass, make_dataclass -from datetime import date, datetime -from email.message import Message -from enum import Enum -from typing import Any, Callable, Optional, Tuple, Union, get_args, get_origin -from xmlrpc.client import boolean - -import dateutil.parser -import requests -from dataclasses_json import DataClassJsonMixin - - -class SecurityClient: - client: requests.Session - query_params: dict[str, str] = {} - - def __init__(self, client: requests.Session): - self.client = client - - def request(self, method, url, **kwargs): - params = kwargs.get('params', {}) - kwargs["params"] = self.query_params | params - - return self.client.request(method, url, **kwargs) - - -def configure_security_client(client: requests.Session, security: dataclass): - client = SecurityClient(client) - - if security is None: - return client - - sec_fields: Tuple[Field, ...] = fields(security) - for sec_field in sec_fields: - value = getattr(security, sec_field.name) - if value is None: - continue - - metadata = sec_field.metadata.get('security') - if metadata is None: - continue - if metadata.get('option'): - _parse_security_option(client, value) - return client - if metadata.get('scheme'): - # Special case for basic auth which could be a flattened struct - if metadata.get("sub_type") == "basic" and not is_dataclass(value): - _parse_security_scheme(client, metadata, security) - else: - _parse_security_scheme(client, metadata, value) - - return client - - -def _parse_security_option(client: SecurityClient, option: dataclass): - opt_fields: Tuple[Field, ...] = fields(option) - for opt_field in opt_fields: - metadata = opt_field.metadata.get('security') - if metadata is None or metadata.get('scheme') is None: - continue - _parse_security_scheme( - client, metadata, getattr(option, opt_field.name)) - - -def _parse_security_scheme(client: SecurityClient, scheme_metadata: dict, scheme: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') - - if is_dataclass(scheme): - if scheme_type == 'http' and sub_type == 'basic': - _parse_basic_auth_scheme(client, scheme) - return - - scheme_fields: Tuple[Field, ...] = fields(scheme) - for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: - continue - - value = getattr(scheme, scheme_field.name) - - _parse_security_scheme_value( - client, scheme_metadata, metadata, value) - else: - _parse_security_scheme_value( - client, scheme_metadata, scheme_metadata, scheme) - - -def _parse_security_scheme_value(client: SecurityClient, scheme_metadata: dict, security_metadata: dict, value: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') - - header_name = security_metadata.get('field_name') - - if scheme_type == "apiKey": - if sub_type == 'header': - client.client.headers[header_name] = value - elif sub_type == 'query': - client.query_params[header_name] = value - elif sub_type == 'cookie': - client.client.cookies[header_name] = value - else: - raise Exception('not supported') - elif scheme_type == "openIdConnect": - client.client.headers[header_name] = value - elif scheme_type == 'oauth2': - client.client.headers[header_name] = value - elif scheme_type == 'http': - if sub_type == 'bearer': - client.client.headers[header_name] = value - else: - raise Exception('not supported') - else: - raise Exception('not supported') - - -def _parse_basic_auth_scheme(client: SecurityClient, scheme: dataclass): - username = "" - password = "" - - scheme_fields: Tuple[Field, ...] = fields(scheme) - for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: - continue - - field_name = metadata.get('field_name') - value = getattr(scheme, scheme_field.name) - - if field_name == 'username': - username = value - if field_name == 'password': - password = value - - data = f'{username}:{password}'.encode() - client.client.headers['Authorization'] = f'Basic {base64.b64encode(data).decode()}' - - -def generate_url(clazz: type, server_url: str, path: str, path_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> str: - path_param_fields: Tuple[Field, ...] = fields(clazz) - for field in path_param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: - continue - - param_metadata = field.metadata.get('path_param') - if param_metadata is None: - continue - - if param_metadata.get('style', 'simple') == 'simple': - param = getattr( - path_params, field.name) if path_params is not None else None - param = _populate_from_globals( - field.name, param, 'pathParam', gbls) - - if param is None: - continue - - if isinstance(param, list): - pp_vals: list[str] = [] - for pp_val in param: - if pp_val is None: - continue - pp_vals.append(_val_to_string(pp_val)) - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif isinstance(param, dict): - pp_vals: list[str] = [] - for pp_key in param: - if param[pp_key] is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{pp_key}={_val_to_string(param[pp_key])}") - else: - pp_vals.append( - f"{pp_key},{_val_to_string(param[pp_key])}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif not isinstance(param, (str, int, float, complex, bool)): - pp_vals: list[str] = [] - param_fields: Tuple[Field, ...] = fields(param) - for param_field in param_fields: - param_value_metadata = param_field.metadata.get( - 'path_param') - if not param_value_metadata: - continue - - parm_name = param_value_metadata.get( - 'field_name', field.name) - - param_field_val = getattr(param, param_field.name) - if param_field_val is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{parm_name}={_val_to_string(param_field_val)}") - else: - pp_vals.append( - f"{parm_name},{_val_to_string(param_field_val)}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - else: - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', _val_to_string(param), 1) - - return server_url.removesuffix("/") + path - - -def is_optional(field): - return get_origin(field) is Union and type(None) in get_args(field) - - -def template_url(url_with_params: str, params: dict[str, str]) -> str: - for key, value in params.items(): - url_with_params = url_with_params.replace( - '{' + key + '}', value) - - return url_with_params - - -def get_query_params(clazz: type, query_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - param_fields: Tuple[Field, ...] = fields(clazz) - for field in param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: - continue - - metadata = field.metadata.get('query_param') - if not metadata: - continue - - param_name = field.name - value = getattr( - query_params, param_name) if query_params is not None else None - - value = _populate_from_globals(param_name, value, 'queryParam', gbls) - - f_name = metadata.get("field_name") - serialization = metadata.get('serialization', '') - if serialization != '': - params = params | _get_serialized_query_params( - metadata, f_name, value) - else: - style = metadata.get('style', 'form') - if style == 'deepObject': - params = params | _get_deep_object_query_params( - metadata, f_name, value) - elif style == 'form': - params = params | _get_form_query_params( - metadata, f_name, value) - else: - raise Exception('not yet implemented') - return params - - -def get_headers(headers_params: dataclass) -> dict[str, str]: - if headers_params is None: - return {} - - headers: dict[str, str] = {} - - param_fields: Tuple[Field, ...] = fields(headers_params) - for field in param_fields: - metadata = field.metadata.get('header') - if not metadata: - continue - - value = _serialize_header(metadata.get( - 'explode', False), getattr(headers_params, field.name)) - - if value != '': - headers[metadata.get('field_name', field.name)] = value - - return headers - - -def _get_serialized_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - serialization = metadata.get('serialization', '') - if serialization == 'json': - params[metadata.get("field_name", field_name)] = marshal_json(obj) - - return params - - -def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - if obj is None: - return params - - if is_dataclass(obj): - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('query_param') - if not obj_param_metadata: - continue - - obj_val = getattr(obj, obj_field.name) - if obj_val is None: - continue - - if isinstance(obj_val, list): - for val in obj_val: - if val is None: - continue - - if params.get(f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]') is None: - params[f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - ] - - params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'].append(_val_to_string(val)) - else: - params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - _val_to_string(obj_val)] - elif isinstance(obj, dict): - for key, value in obj.items(): - if value is None: - continue - - if isinstance(value, list): - for val in value: - if val is None: - continue - - if params.get(f'{metadata.get("field_name", field_name)}[{key}]') is None: - params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - ] - - params[ - f'{metadata.get("field_name", field_name)}[{key}]'].append(_val_to_string(val)) - else: - params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - _val_to_string(value)] - return params - - -def _get_query_param_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('query_param') - - if not obj_param_metadata: - return "" - - return obj_param_metadata.get("field_name", obj_field.name) - - -def _get_form_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - return _populate_form(field_name, metadata.get("explode", True), obj, _get_query_param_field_name) - - -SERIALIZATION_METHOD_TO_CONTENT_TYPE = { - 'json': 'application/json', - 'form': 'application/x-www-form-urlencoded', - 'multipart': 'multipart/form-data', - 'raw': 'application/octet-stream', - 'string': 'text/plain', -} - - -def serialize_request_body(request: dataclass, request_field_name: str, serialization_method: str) -> Tuple[str, any, any]: - if request is None: - return None, None, None, None - - if not is_dataclass(request) or not hasattr(request, request_field_name): - return serialize_content_type(request_field_name, SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], request) - - request_val = getattr(request, request_field_name) - - request_fields: Tuple[Field, ...] = fields(request) - request_metadata = None - - for field in request_fields: - if field.name == request_field_name: - request_metadata = field.metadata.get('request') - break - - if request_metadata is None: - raise Exception('invalid request type') - - return serialize_content_type(request_field_name, request_metadata.get('media_type', 'application/octet-stream'), request_val) - - -def serialize_content_type(field_name: str, media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - if re.match(r'(application|text)\/.*?\+*json.*', media_type) is not None: - return media_type, marshal_json(request), None - if re.match(r'multipart\/.*', media_type) is not None: - return serialize_multipart_form(media_type, request) - if re.match(r'application\/x-www-form-urlencoded.*', media_type) is not None: - return media_type, serialize_form_data(field_name, request), None - if isinstance(request, (bytes, bytearray)): - return media_type, request, None - if isinstance(request, str): - return media_type, request, None - - raise Exception( - f"invalid request body type {type(request)} for mediaType {media_type}") - - -def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - form: list[list[any]] = [] - request_fields = fields(request) - - for field in request_fields: - val = getattr(request, field.name) - if val is None: - continue - - field_metadata = field.metadata.get('multipart_form') - if not field_metadata: - continue - - if field_metadata.get("file") is True: - file_fields = fields(val) - - file_name = "" - field_name = "" - content = bytes() - - for file_field in file_fields: - file_metadata = file_field.metadata.get('multipart_form') - if file_metadata is None: - continue - - if file_metadata.get("content") is True: - content = getattr(val, file_field.name) - else: - field_name = file_metadata.get( - "field_name", file_field.name) - file_name = getattr(val, file_field.name) - if field_name == "" or file_name == "" or content == bytes(): - raise Exception('invalid multipart/form-data file') - - form.append([field_name, [file_name, content]]) - elif field_metadata.get("json") is True: - to_append = [field_metadata.get("field_name", field.name), [ - None, marshal_json(val), "application/json"]] - form.append(to_append) - else: - field_name = field_metadata.get( - "field_name", field.name) - if isinstance(val, list): - for value in val: - if value is None: - continue - form.append( - [field_name + "[]", [None, _val_to_string(value)]]) - else: - form.append([field_name, [None, _val_to_string(val)]]) - return media_type, None, form - - -def serialize_dict(original: dict, explode: bool, field_name, existing: Optional[dict[str, list[str]]]) -> dict[ - str, list[str]]: - if existing is None: - existing = [] - - if explode is True: - for key, val in original.items(): - if key not in existing: - existing[key] = [] - existing[key].append(val) - else: - temp = [] - for key, val in original.items(): - temp.append(str(key)) - temp.append(str(val)) - if field_name not in existing: - existing[field_name] = [] - existing[field_name].append(",".join(temp)) - return existing - - -def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: - form: dict[str, list[str]] = {} - - if is_dataclass(data): - for field in fields(data): - val = getattr(data, field.name) - if val is None: - continue - - metadata = field.metadata.get('form') - if metadata is None: - continue - - field_name = metadata.get('field_name', field.name) - - if metadata.get('json'): - form[field_name] = [marshal_json(val)] - else: - if metadata.get('style', 'form') == 'form': - form = form | _populate_form( - field_name, metadata.get('explode', True), val, _get_form_field_name) - else: - raise Exception( - f'Invalid form style for field {field.name}') - elif isinstance(data, dict): - for key, value in data.items(): - form[key] = [_val_to_string(value)] - else: - raise Exception(f'Invalid request body type for field {field_name}') - - return form - - -def _get_form_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('form') - - if not obj_param_metadata: - return "" - - return obj_param_metadata.get("field_name", obj_field.name) - - -def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_func: Callable) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - if obj is None: - return params - - if is_dataclass(obj): - items = [] - - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_field_name = get_field_name_func(obj_field) - if obj_field_name == '': - continue - - val = getattr(obj, obj_field.name) - if val is None: - continue - - if explode: - params[obj_field_name] = [_val_to_string(val)] - else: - items.append( - f'{obj_field_name},{_val_to_string(val)}') - - if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, dict): - items = [] - for key, value in obj.items(): - if value is None: - continue - - if explode: - params[key] = _val_to_string(value) - else: - items.append(f'{key},{_val_to_string(value)}') - - if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, list): - items = [] - - for value in obj: - if value is None: - continue - - if explode: - if not field_name in params: - params[field_name] = [] - params[field_name].append(_val_to_string(value)) - else: - items.append(_val_to_string(value)) - - if len(items) > 0: - params[field_name] = [','.join([str(item) for item in items])] - else: - params[field_name] = [_val_to_string(obj)] - - return params - - -def _serialize_header(explode: bool, obj: any) -> str: - if obj is None: - return '' - - if is_dataclass(obj): - items = [] - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('header') - - if not obj_param_metadata: - continue - - obj_field_name = obj_param_metadata.get( - 'field_name', obj_field.name) - if obj_field_name == '': - continue - - val = getattr(obj, obj_field.name) - if val is None: - continue - - if explode: - items.append( - f'{obj_field_name}={_val_to_string(val)}') - else: - items.append(obj_field_name) - items.append(_val_to_string(val)) - - if len(items) > 0: - return ','.join(items) - elif isinstance(obj, dict): - items = [] - - for key, value in obj.items(): - if value is None: - continue - - if explode: - items.append(f'{key}={_val_to_string(value)}') - else: - items.append(key) - items.append(_val_to_string(value)) - - if len(items) > 0: - return ','.join([str(item) for item in items]) - elif isinstance(obj, list): - items = [] - - for value in obj: - if value is None: - continue - - items.append(_val_to_string(value)) - - if len(items) > 0: - return ','.join(items) - else: - return f'{_val_to_string(obj)}' - - return '' - - -def unmarshal_json(data, typ): - unmarhsal = make_dataclass('Unmarhsal', [('res', typ)], - bases=(DataClassJsonMixin,)) - json_dict = json.loads(data) - out = unmarhsal.from_dict({"res": json_dict}) - return out.res - - -def marshal_json(val): - marshal = make_dataclass('Marshal', [('res', type(val))], - bases=(DataClassJsonMixin,)) - marshaller = marshal(res=val) - json_dict = marshaller.to_dict() - return json.dumps(json_dict["res"]) - - -def match_content_type(content_type: str, pattern: str) -> boolean: - if pattern in (content_type, "*", "*/*"): - return True - - msg = Message() - msg['content-type'] = content_type - media_type = msg.get_content_type() - - if media_type == pattern: - return True - - parts = media_type.split("/") - if len(parts) == 2: - if pattern in (f'{parts[0]}/*', f'*/{parts[1]}'): - return True - - return False - - -def datetimeisoformat(optional: bool): - def isoformatoptional(val): - if optional and val is None: - return None - return _val_to_string(val) - - return isoformatoptional - - -def dateisoformat(optional: bool): - def isoformatoptional(val): - if optional and val is None: - return None - return date.isoformat(val) - - return isoformatoptional - - -def datefromisoformat(date_str: str): - return dateutil.parser.parse(date_str).date() - - -def get_field_name(name): - def override(_, _field_name=name): - return _field_name - - return override - - -def _val_to_string(val): - if isinstance(val, bool): - return str(val).lower() - if isinstance(val, datetime): - return val.isoformat().replace('+00:00', 'Z') - if isinstance(val, Enum): - return val.value - - return str(val) - - -def _populate_from_globals(param_name: str, value: any, param_type: str, gbls: dict[str, dict[str, dict[str, Any]]]): - if value is None and gbls is not None: - if 'parameters' in gbls: - if param_type in gbls['parameters']: - if param_name in gbls['parameters'][param_type]: - global_value = gbls['parameters'][param_type][param_name] - if global_value is not None: - value = global_value - - return value diff --git a/document/src/epilot_document/__init__.py b/document/src/epilot_document/__init__.py new file mode 100644 index 000000000..68138c477 --- /dev/null +++ b/document/src/epilot_document/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdk import * +from .sdkconfiguration import * +from .models import * diff --git a/document/src/epilot_document/_hooks/__init__.py b/document/src/epilot_document/_hooks/__init__.py new file mode 100644 index 000000000..2ee66cdd5 --- /dev/null +++ b/document/src/epilot_document/_hooks/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkhooks import * +from .types import * +from .registration import * diff --git a/document/src/epilot_document/_hooks/registration.py b/document/src/epilot_document/_hooks/registration.py new file mode 100644 index 000000000..1db6a5293 --- /dev/null +++ b/document/src/epilot_document/_hooks/registration.py @@ -0,0 +1,13 @@ +from .types import Hooks + + +# This file is only ever generated once on the first generation and then is free to be modified. +# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them +# in this file or in separate files in the hooks folder. + + +def init_hooks(hooks: Hooks): + # pylint: disable=unused-argument + """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook + with an instance of a hook that implements that specific Hook interface + Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance""" diff --git a/document/src/epilot_document/_hooks/sdkhooks.py b/document/src/epilot_document/_hooks/sdkhooks.py new file mode 100644 index 000000000..32fe81e24 --- /dev/null +++ b/document/src/epilot_document/_hooks/sdkhooks.py @@ -0,0 +1,57 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from .types import SDKInitHook, BeforeRequestContext, BeforeRequestHook, AfterSuccessContext, AfterSuccessHook, AfterErrorContext, AfterErrorHook, Hooks +from .registration import init_hooks +from typing import List, Optional, Tuple +from epilot_document.httpclient import HttpClient + +class SDKHooks(Hooks): + def __init__(self) -> None: + self.sdk_init_hooks: List[SDKInitHook] = [] + self.before_request_hooks: List[BeforeRequestHook] = [] + self.after_success_hooks: List[AfterSuccessHook] = [] + self.after_error_hooks: List[AfterErrorHook] = [] + init_hooks(self) + + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + self.sdk_init_hooks.append(hook) + + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + self.before_request_hooks.append(hook) + + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + self.after_success_hooks.append(hook) + + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + self.after_error_hooks.append(hook) + + def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + for hook in self.sdk_init_hooks: + base_url, client = hook.sdk_init(base_url, client) + return base_url, client + + def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> httpx.Request: + for hook in self.before_request_hooks: + out = hook.before_request(hook_ctx, request) + if isinstance(out, Exception): + raise out + request = out + + return request + + def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> httpx.Response: + for hook in self.after_success_hooks: + out = hook.after_success(hook_ctx, response) + if isinstance(out, Exception): + raise out + response = out + return response + + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Tuple[Optional[httpx.Response], Optional[Exception]]: + for hook in self.after_error_hooks: + result = hook.after_error(hook_ctx, response, error) + if isinstance(result, Exception): + raise result + response, error = result + return response, error diff --git a/document/src/epilot_document/_hooks/types.py b/document/src/epilot_document/_hooks/types.py new file mode 100644 index 000000000..7965d52a5 --- /dev/null +++ b/document/src/epilot_document/_hooks/types.py @@ -0,0 +1,76 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + + +from abc import ABC, abstractmethod +from epilot_document.httpclient import HttpClient +import httpx +from typing import Any, Callable, List, Optional, Tuple, Union + + +class HookContext: + operation_id: str + oauth2_scopes: Optional[List[str]] = None + security_source: Optional[Union[Any, Callable[[], Any]]] = None + + def __init__(self, operation_id: str, oauth2_scopes: Optional[List[str]], security_source: Optional[Union[Any, Callable[[], Any]]]): + self.operation_id = operation_id + self.oauth2_scopes = oauth2_scopes + self.security_source = security_source + + +class BeforeRequestContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class AfterSuccessContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + + +class AfterErrorContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class SDKInitHook(ABC): + @abstractmethod + def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + pass + + +class BeforeRequestHook(ABC): + @abstractmethod + def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> Union[httpx.Request, Exception]: + pass + + +class AfterSuccessHook(ABC): + @abstractmethod + def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> Union[httpx.Response, Exception]: + pass + + +class AfterErrorHook(ABC): + @abstractmethod + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: + pass + + +class Hooks(ABC): + @abstractmethod + def register_sdk_init_hook(self, hook: SDKInitHook): + pass + + @abstractmethod + def register_before_request_hook(self, hook: BeforeRequestHook): + pass + + @abstractmethod + def register_after_success_hook(self, hook: AfterSuccessHook): + pass + + @abstractmethod + def register_after_error_hook(self, hook: AfterErrorHook): + pass diff --git a/document/src/epilot_document/basesdk.py b/document/src/epilot_document/basesdk.py new file mode 100644 index 000000000..cee6776a6 --- /dev/null +++ b/document/src/epilot_document/basesdk.py @@ -0,0 +1,253 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkconfiguration import SDKConfiguration +from epilot_document import models, utils +from epilot_document._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext +from epilot_document.utils import RetryConfig, SerializedRequestBody, get_body_content +import httpx +from typing import Callable, List, Optional, Tuple + +class BaseSDK: + sdk_configuration: SDKConfiguration + + def __init__(self, sdk_config: SDKConfiguration) -> None: + self.sdk_configuration = sdk_config + + def get_url(self, base_url, url_variables): + sdk_url, sdk_variables = self.sdk_configuration.get_server_details() + + if base_url is None: + base_url = sdk_url + + if url_variables is None: + url_variables = sdk_variables + + return utils.template_url(base_url, url_variables) + + def build_request( + self, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals=None, + security=None, + timeout_ms: Optional[int] = None, + get_serialized_body: Optional[ + Callable[[], Optional[SerializedRequestBody]] + ] = None, + url_override: Optional[str] = None, + ) -> httpx.Request: + client = self.sdk_configuration.client + + query_params = {} + + url = url_override + if url is None: + url = utils.generate_url( + self.get_url(base_url, url_variables), + path, + request if request_has_path_params else None, + _globals if request_has_path_params else None, + ) + + query_params = utils.get_query_params( + request if request_has_query_params else None, + _globals if request_has_query_params else None, + ) + + headers = utils.get_headers(request, _globals) + headers["Accept"] = accept_header_value + headers[user_agent_header] = self.sdk_configuration.user_agent + + if security is not None: + if callable(security): + security = security() + + if security is not None: + security_headers, security_query_params = utils.get_security(security) + headers = {**headers, **security_headers} + query_params = {**query_params, **security_query_params} + + serialized_request_body = SerializedRequestBody("application/octet-stream") + if get_serialized_body is not None: + rb = get_serialized_body() + if request_body_required and rb is None: + raise ValueError("request body is required") + + if rb is not None: + serialized_request_body = rb + + if ( + serialized_request_body.media_type is not None + and serialized_request_body.media_type + not in ( + "multipart/form-data", + "multipart/mixed", + ) + ): + headers["content-type"] = serialized_request_body.media_type + + timeout = timeout_ms / 1000 if timeout_ms is not None else None + + return client.build_request( + method, + url, + params=query_params, + content=serialized_request_body.content, + data=serialized_request_body.data, + files=serialized_request_body.files, + headers=headers, + timeout=timeout, + ) + + def do_request( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.client + logger = self.sdk_configuration.debug_logger + + def do(): + http_res = None + try: + req = self.sdk_configuration.get_hooks().before_request( + BeforeRequestContext(hook_ctx), request + ) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req) + ) + http_res = client.send(req, stream=stream) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), None, e + ) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise models.SDKError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise models.SDKError("Unexpected error occurred") + + return http_res + + if retry_config is not None: + http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1])) + else: + http_res = do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = self.sdk_configuration.get_hooks().after_success( + AfterSuccessContext(hook_ctx), http_res + ) + + return http_res + + async def do_request_async( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.async_client + logger = self.sdk_configuration.debug_logger + async def do(): + http_res = None + try: + req = self.sdk_configuration.get_hooks().before_request( + BeforeRequestContext(hook_ctx), request + ) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req) + ) + http_res = await client.send(req, stream=stream) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), None, e + ) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise models.SDKError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise models.SDKError("Unexpected error occurred") + + return http_res + + if retry_config is not None: + http_res = await utils.retry_async( + do, utils.Retries(retry_config[0], retry_config[1]) + ) + else: + http_res = await do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = self.sdk_configuration.get_hooks().after_success( + AfterSuccessContext(hook_ctx), http_res + ) + + return http_res diff --git a/document/src/epilot_document/documents.py b/document/src/epilot_document/documents.py new file mode 100644 index 000000000..e316ede1f --- /dev/null +++ b/document/src/epilot_document/documents.py @@ -0,0 +1,357 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from epilot_document import models, utils +from epilot_document._hooks import HookContext +from epilot_document.types import BaseModel, OptionalNullable, UNSET +from typing import Optional, Union, cast + +class Documents(BaseSDK): + r"""Document Generation""" + + + def convert_document( + self, *, + request: Optional[Union[models.ConvertDocumentRequest, models.ConvertDocumentRequestTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.ConvertDocumentResponse]: + r"""convertDocument + + Converts a document to a different format. + + Supported input document types: + - .docx + + Supported output document types: + - .pdf + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.ConvertDocumentRequest) + request = cast(models.ConvertDocumentRequest, request) + + req = self.build_request( + method="POST", + path="/v2/documents:convert", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.ConvertDocumentRequest]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="convertDocument", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.ConvertDocumentResponse]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def convert_document_async( + self, *, + request: Optional[Union[models.ConvertDocumentRequest, models.ConvertDocumentRequestTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.ConvertDocumentResponse]: + r"""convertDocument + + Converts a document to a different format. + + Supported input document types: + - .docx + + Supported output document types: + - .pdf + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.ConvertDocumentRequest) + request = cast(models.ConvertDocumentRequest, request) + + req = self.build_request( + method="POST", + path="/v2/documents:convert", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.ConvertDocumentRequest]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="convertDocument", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.ConvertDocumentResponse]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def generate_document_v2( + self, *, + job_id: Optional[str] = None, + mode: Optional[models.Mode] = models.Mode.FULL_GENERATION, + document_generation_v2_request: Optional[Union[models.DocumentGenerationV2Request, models.DocumentGenerationV2RequestTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.DocumentGenerationV2Response]: + r"""generateDocumentV2 + + Builds document generated from input document with variables. + + Supported input document types: + - .docx + + Supported output document types: + - .pdf + - .docx but limited to only text based variables + + Uses [Template Variables API](https://docs.epilot.io/api/template-variables) to replace variables in the document. + + + :param job_id: Job ID for tracking the status of document generation action + :param mode: Type of mode used for document generation flow: - partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. - full_generation, goes through all the steps for the full generation of final document + :param document_generation_v2_request: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GenerateDocumentV2Request( + job_id=job_id, + mode=mode, + document_generation_v2_request=utils.get_pydantic_model(document_generation_v2_request, Optional[models.DocumentGenerationV2Request]), + ) + + req = self.build_request( + method="POST", + path="/v2/documents:generate", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request.document_generation_v2_request, False, True, "json", Optional[models.DocumentGenerationV2Request]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="generateDocumentV2", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.DocumentGenerationV2Response]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def generate_document_v2_async( + self, *, + job_id: Optional[str] = None, + mode: Optional[models.Mode] = models.Mode.FULL_GENERATION, + document_generation_v2_request: Optional[Union[models.DocumentGenerationV2Request, models.DocumentGenerationV2RequestTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.DocumentGenerationV2Response]: + r"""generateDocumentV2 + + Builds document generated from input document with variables. + + Supported input document types: + - .docx + + Supported output document types: + - .pdf + - .docx but limited to only text based variables + + Uses [Template Variables API](https://docs.epilot.io/api/template-variables) to replace variables in the document. + + + :param job_id: Job ID for tracking the status of document generation action + :param mode: Type of mode used for document generation flow: - partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. - full_generation, goes through all the steps for the full generation of final document + :param document_generation_v2_request: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GenerateDocumentV2Request( + job_id=job_id, + mode=mode, + document_generation_v2_request=utils.get_pydantic_model(document_generation_v2_request, Optional[models.DocumentGenerationV2Request]), + ) + + req = self.build_request( + method="POST", + path="/v2/documents:generate", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request.document_generation_v2_request, False, True, "json", Optional[models.DocumentGenerationV2Request]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="generateDocumentV2", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.DocumentGenerationV2Response]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + diff --git a/document/src/epilot_document/httpclient.py b/document/src/epilot_document/httpclient.py new file mode 100644 index 000000000..36b642a0e --- /dev/null +++ b/document/src/epilot_document/httpclient.py @@ -0,0 +1,78 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +# pyright: reportReturnType = false +from typing_extensions import Protocol, runtime_checkable +import httpx +from typing import Any, Optional, Union + + +@runtime_checkable +class HttpClient(Protocol): + def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass + + +@runtime_checkable +class AsyncHttpClient(Protocol): + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass diff --git a/document/src/epilot_document/models/__init__.py b/document/src/epilot_document/models/__init__.py new file mode 100644 index 000000000..e26128159 --- /dev/null +++ b/document/src/epilot_document/models/__init__.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .convertdocumentrequest import ConvertDocumentRequest, ConvertDocumentRequestTypedDict, InputDocument, InputDocumentTypedDict, OutputFormat +from .convertdocumentresponse import ConvertDocumentResponse, ConvertDocumentResponseTypedDict, OutputDocument, OutputDocumentTypedDict +from .documentgenerationv2request import DocumentGenerationV2Request, DocumentGenerationV2RequestTypedDict, TemplateDocument, TemplateDocumentTypedDict, VariablePayload, VariablePayloadTypedDict +from .documentgenerationv2response import DocumentGenerationV2Response, DocumentGenerationV2ResponseOutputDocument, DocumentGenerationV2ResponseOutputDocumentTypedDict, DocumentGenerationV2ResponseSchemasOutputDocument, DocumentGenerationV2ResponseSchemasOutputDocumentTypedDict, DocumentGenerationV2ResponseTypedDict, DocumentGenerationV2ResponseVariablePayload, DocumentGenerationV2ResponseVariablePayloadTypedDict, DocxOutput, DocxOutputTypedDict, JobStatus, PdfOutput, PdfOutputTypedDict +from .errorcode import ErrorCode +from .erroroutput import ErrorOutput, ErrorOutputTypedDict +from .generatedocumentv2op import GenerateDocumentV2Request, GenerateDocumentV2RequestTypedDict, Mode +from .invalidcustomvariableerrordetail import Context, ContextTypedDict, InvalidCustomVariableErrorDetail, InvalidCustomVariableErrorDetailTypedDict, InvalidVariables, InvalidVariablesTypedDict +from .s3reference import S3Reference, S3ReferenceTypedDict +from .sdkerror import SDKError +from .security import Security, SecurityTypedDict +from .templatesettings import CustomMargins, CustomMarginsTypedDict, SuggestedMargins, SuggestedMarginsTypedDict, TemplateSettings, TemplateSettingsTypedDict + +__all__ = ["Context", "ContextTypedDict", "ConvertDocumentRequest", "ConvertDocumentRequestTypedDict", "ConvertDocumentResponse", "ConvertDocumentResponseTypedDict", "CustomMargins", "CustomMarginsTypedDict", "DocumentGenerationV2Request", "DocumentGenerationV2RequestTypedDict", "DocumentGenerationV2Response", "DocumentGenerationV2ResponseOutputDocument", "DocumentGenerationV2ResponseOutputDocumentTypedDict", "DocumentGenerationV2ResponseSchemasOutputDocument", "DocumentGenerationV2ResponseSchemasOutputDocumentTypedDict", "DocumentGenerationV2ResponseTypedDict", "DocumentGenerationV2ResponseVariablePayload", "DocumentGenerationV2ResponseVariablePayloadTypedDict", "DocxOutput", "DocxOutputTypedDict", "ErrorCode", "ErrorOutput", "ErrorOutputTypedDict", "GenerateDocumentV2Request", "GenerateDocumentV2RequestTypedDict", "InputDocument", "InputDocumentTypedDict", "InvalidCustomVariableErrorDetail", "InvalidCustomVariableErrorDetailTypedDict", "InvalidVariables", "InvalidVariablesTypedDict", "JobStatus", "Mode", "OutputDocument", "OutputDocumentTypedDict", "OutputFormat", "PdfOutput", "PdfOutputTypedDict", "S3Reference", "S3ReferenceTypedDict", "SDKError", "Security", "SecurityTypedDict", "SuggestedMargins", "SuggestedMarginsTypedDict", "TemplateDocument", "TemplateDocumentTypedDict", "TemplateSettings", "TemplateSettingsTypedDict", "VariablePayload", "VariablePayloadTypedDict"] diff --git a/document/src/epilot_document/models/convertdocumentrequest.py b/document/src/epilot_document/models/convertdocumentrequest.py new file mode 100644 index 000000000..7cc94e39f --- /dev/null +++ b/document/src/epilot_document/models/convertdocumentrequest.py @@ -0,0 +1,43 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .s3reference import S3Reference, S3ReferenceTypedDict +from enum import Enum +from epilot_document.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class InputDocumentTypedDict(TypedDict): + r"""Input document""" + + s3ref: S3ReferenceTypedDict + + +class InputDocument(BaseModel): + r"""Input document""" + + s3ref: S3Reference + + +class OutputFormat(str, Enum): + r"""Output format of the document""" + PDF = "pdf" + +class ConvertDocumentRequestTypedDict(TypedDict): + input_document: InputDocumentTypedDict + r"""Input document""" + output_format: OutputFormat + r"""Output format of the document""" + output_filename: NotRequired[str] + r"""Filename of the output document (optional)""" + + +class ConvertDocumentRequest(BaseModel): + input_document: InputDocument + r"""Input document""" + output_format: OutputFormat + r"""Output format of the document""" + output_filename: Optional[str] = None + r"""Filename of the output document (optional)""" + diff --git a/document/src/epilot_document/models/convertdocumentresponse.py b/document/src/epilot_document/models/convertdocumentresponse.py new file mode 100644 index 000000000..5b83cb33d --- /dev/null +++ b/document/src/epilot_document/models/convertdocumentresponse.py @@ -0,0 +1,28 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .s3reference import S3Reference, S3ReferenceTypedDict +from epilot_document.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class OutputDocumentTypedDict(TypedDict): + preview_url: NotRequired[str] + r"""Pre-signed URL for the converted document""" + s3ref: NotRequired[S3ReferenceTypedDict] + + +class OutputDocument(BaseModel): + preview_url: Optional[str] = None + r"""Pre-signed URL for the converted document""" + s3ref: Optional[S3Reference] = None + + +class ConvertDocumentResponseTypedDict(TypedDict): + output_document: NotRequired[OutputDocumentTypedDict] + + +class ConvertDocumentResponse(BaseModel): + output_document: Optional[OutputDocument] = None + diff --git a/document/src/epilot_document/models/documentgenerationv2request.py b/document/src/epilot_document/models/documentgenerationv2request.py new file mode 100644 index 000000000..75ea8cbac --- /dev/null +++ b/document/src/epilot_document/models/documentgenerationv2request.py @@ -0,0 +1,64 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .s3reference import S3Reference, S3ReferenceTypedDict +from .templatesettings import TemplateSettings, TemplateSettingsTypedDict +from epilot_document.types import BaseModel +import pydantic +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class TemplateDocumentTypedDict(TypedDict): + r"""Input template document""" + + filename: NotRequired[str] + r"""Document original filename""" + s3ref: NotRequired[S3ReferenceTypedDict] + + +class TemplateDocument(BaseModel): + r"""Input template document""" + + filename: Optional[str] = None + r"""Document original filename""" + s3ref: Optional[S3Reference] = None + + +class VariablePayloadTypedDict(TypedDict): + r"""Custom values for variables in the template. Takes the higher precedence than others.""" + + additional_properties: NotRequired[str] + + +class VariablePayload(BaseModel): + r"""Custom values for variables in the template. Takes the higher precedence than others.""" + + additional_properties: Annotated[Optional[str], pydantic.Field(alias="additionalProperties")] = None + + +class DocumentGenerationV2RequestTypedDict(TypedDict): + template_document: TemplateDocumentTypedDict + r"""Input template document""" + context_entity_id: NotRequired[str] + r"""Entity to use for variable context""" + template_settings: NotRequired[TemplateSettingsTypedDict] + r"""Template Settings for document generation""" + user_id: NotRequired[str] + r"""User Id for variable context""" + variable_payload: NotRequired[VariablePayloadTypedDict] + r"""Custom values for variables in the template. Takes the higher precedence than others.""" + + +class DocumentGenerationV2Request(BaseModel): + template_document: TemplateDocument + r"""Input template document""" + context_entity_id: Optional[str] = None + r"""Entity to use for variable context""" + template_settings: Optional[TemplateSettings] = None + r"""Template Settings for document generation""" + user_id: Optional[str] = None + r"""User Id for variable context""" + variable_payload: Optional[VariablePayload] = None + r"""Custom values for variables in the template. Takes the higher precedence than others.""" + diff --git a/document/src/epilot_document/models/documentgenerationv2response.py b/document/src/epilot_document/models/documentgenerationv2response.py new file mode 100644 index 000000000..adecd0cc4 --- /dev/null +++ b/document/src/epilot_document/models/documentgenerationv2response.py @@ -0,0 +1,109 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .erroroutput import ErrorOutput, ErrorOutputTypedDict +from .s3reference import S3Reference, S3ReferenceTypedDict +from .templatesettings import TemplateSettings, TemplateSettingsTypedDict +from enum import Enum +from epilot_document.types import BaseModel +import pydantic +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class DocumentGenerationV2ResponseOutputDocumentTypedDict(TypedDict): + filename: NotRequired[str] + r"""Generated document filename for DOCX""" + s3ref: NotRequired[S3ReferenceTypedDict] + + +class DocumentGenerationV2ResponseOutputDocument(BaseModel): + filename: Optional[str] = None + r"""Generated document filename for DOCX""" + s3ref: Optional[S3Reference] = None + + +class DocxOutputTypedDict(TypedDict): + output_document: NotRequired[DocumentGenerationV2ResponseOutputDocumentTypedDict] + preview_url: NotRequired[str] + r"""Pre-signed S3 GET URL for DOCX preview""" + + +class DocxOutput(BaseModel): + output_document: Optional[DocumentGenerationV2ResponseOutputDocument] = None + preview_url: Optional[str] = None + r"""Pre-signed S3 GET URL for DOCX preview""" + + +class JobStatus(str, Enum): + r"""Status of the job""" + STARTED = "STARTED" + PROCESSING = "PROCESSING" + SUCCESS = "SUCCESS" + FAILED = "FAILED" + +class DocumentGenerationV2ResponseSchemasOutputDocumentTypedDict(TypedDict): + filename: NotRequired[str] + r"""Generated document filename for PDF""" + s3ref: NotRequired[S3ReferenceTypedDict] + + +class DocumentGenerationV2ResponseSchemasOutputDocument(BaseModel): + filename: Optional[str] = None + r"""Generated document filename for PDF""" + s3ref: Optional[S3Reference] = None + + +class PdfOutputTypedDict(TypedDict): + output_document: NotRequired[DocumentGenerationV2ResponseSchemasOutputDocumentTypedDict] + preview_url: NotRequired[str] + r"""Pre-signed S3 GET URL for PDF preview""" + + +class PdfOutput(BaseModel): + output_document: Optional[DocumentGenerationV2ResponseSchemasOutputDocument] = None + preview_url: Optional[str] = None + r"""Pre-signed S3 GET URL for PDF preview""" + + +class DocumentGenerationV2ResponseVariablePayloadTypedDict(TypedDict): + r"""List of variables and its corresponding replaced values from the document template""" + + additional_properties: NotRequired[str] + + +class DocumentGenerationV2ResponseVariablePayload(BaseModel): + r"""List of variables and its corresponding replaced values from the document template""" + + additional_properties: Annotated[Optional[str], pydantic.Field(alias="additionalProperties")] = None + + +class DocumentGenerationV2ResponseTypedDict(TypedDict): + docx_output: NotRequired[DocxOutputTypedDict] + error_output: NotRequired[ErrorOutputTypedDict] + job_id: NotRequired[str] + job_status: NotRequired[JobStatus] + r"""Status of the job""" + message: NotRequired[str] + r"""A message explaining the progress""" + pdf_output: NotRequired[PdfOutputTypedDict] + template_settings: NotRequired[TemplateSettingsTypedDict] + r"""Template Settings for document generation""" + variable_payload: NotRequired[DocumentGenerationV2ResponseVariablePayloadTypedDict] + r"""List of variables and its corresponding replaced values from the document template""" + + +class DocumentGenerationV2Response(BaseModel): + docx_output: Optional[DocxOutput] = None + error_output: Optional[ErrorOutput] = None + job_id: Optional[str] = None + job_status: Optional[JobStatus] = None + r"""Status of the job""" + message: Optional[str] = None + r"""A message explaining the progress""" + pdf_output: Optional[PdfOutput] = None + template_settings: Optional[TemplateSettings] = None + r"""Template Settings for document generation""" + variable_payload: Optional[DocumentGenerationV2ResponseVariablePayload] = None + r"""List of variables and its corresponding replaced values from the document template""" + diff --git a/document/src/epilot_document/models/errorcode.py b/document/src/epilot_document/models/errorcode.py new file mode 100644 index 000000000..8bb972736 --- /dev/null +++ b/document/src/epilot_document/models/errorcode.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from enum import Enum + + +class ErrorCode(str, Enum): + r"""Error codes for document generation: + - PARSE_ERROR - Error while parsing the document. Normally related with a bad template using the wrong DocxTemplater syntax. + - DOC_TO_PDF_CONVERT_ERROR - Error while converting the document to PDF. Normally related with a ConvertAPI failure. + - INTERNAL_ERROR - Internal error. Please contact support. + - INVALID_TEMPLATE_FORMAT - Invalid template format (only .docx is supported). This can happen due to a bad word file or an unsupported file extension. + + """ + PARSE_ERROR = "PARSE_ERROR" + DOC_TO_PDF_CONVERT_ERROR = "DOC_TO_PDF_CONVERT_ERROR" + INTERNAL_ERROR = "INTERNAL_ERROR" + INVALID_TEMPLATE_FORMAT = "INVALID_TEMPLATE_FORMAT" diff --git a/document/src/epilot_document/models/erroroutput.py b/document/src/epilot_document/models/erroroutput.py new file mode 100644 index 000000000..464d97894 --- /dev/null +++ b/document/src/epilot_document/models/erroroutput.py @@ -0,0 +1,37 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .errorcode import ErrorCode +from .invalidcustomvariableerrordetail import InvalidCustomVariableErrorDetail, InvalidCustomVariableErrorDetailTypedDict +from epilot_document.types import BaseModel +from typing import List, Optional, TypedDict +from typing_extensions import NotRequired + + +class ErrorOutputTypedDict(TypedDict): + error_code: NotRequired[ErrorCode] + r"""Error codes for document generation: + - PARSE_ERROR - Error while parsing the document. Normally related with a bad template using the wrong DocxTemplater syntax. + - DOC_TO_PDF_CONVERT_ERROR - Error while converting the document to PDF. Normally related with a ConvertAPI failure. + - INTERNAL_ERROR - Internal error. Please contact support. + - INVALID_TEMPLATE_FORMAT - Invalid template format (only .docx is supported). This can happen due to a bad word file or an unsupported file extension. + + """ + error_details: NotRequired[List[InvalidCustomVariableErrorDetailTypedDict]] + error_message: NotRequired[str] + r"""Error message""" + + +class ErrorOutput(BaseModel): + error_code: Optional[ErrorCode] = None + r"""Error codes for document generation: + - PARSE_ERROR - Error while parsing the document. Normally related with a bad template using the wrong DocxTemplater syntax. + - DOC_TO_PDF_CONVERT_ERROR - Error while converting the document to PDF. Normally related with a ConvertAPI failure. + - INTERNAL_ERROR - Internal error. Please contact support. + - INVALID_TEMPLATE_FORMAT - Invalid template format (only .docx is supported). This can happen due to a bad word file or an unsupported file extension. + + """ + error_details: Optional[List[InvalidCustomVariableErrorDetail]] = None + error_message: Optional[str] = None + r"""Error message""" + diff --git a/document/src/epilot_document/models/generatedocumentv2op.py b/document/src/epilot_document/models/generatedocumentv2op.py new file mode 100644 index 000000000..fa0c83d70 --- /dev/null +++ b/document/src/epilot_document/models/generatedocumentv2op.py @@ -0,0 +1,43 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .documentgenerationv2request import DocumentGenerationV2Request, DocumentGenerationV2RequestTypedDict +from enum import Enum +from epilot_document.types import BaseModel +from epilot_document.utils import FieldMetadata, QueryParamMetadata, RequestMetadata +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class Mode(str, Enum): + r"""Type of mode used for document generation flow: + - partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. + - full_generation, goes through all the steps for the full generation of final document + + """ + PARTIAL_GENERATION = "partial_generation" + FULL_GENERATION = "full_generation" + +class GenerateDocumentV2RequestTypedDict(TypedDict): + document_generation_v2_request: NotRequired[DocumentGenerationV2RequestTypedDict] + job_id: NotRequired[str] + r"""Job ID for tracking the status of document generation action""" + mode: NotRequired[Mode] + r"""Type of mode used for document generation flow: + - partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. + - full_generation, goes through all the steps for the full generation of final document + + """ + + +class GenerateDocumentV2Request(BaseModel): + document_generation_v2_request: Annotated[Optional[DocumentGenerationV2Request], FieldMetadata(request=RequestMetadata(media_type="application/json"))] = None + job_id: Annotated[Optional[str], FieldMetadata(query=QueryParamMetadata(style="form", explode=True))] = None + r"""Job ID for tracking the status of document generation action""" + mode: Annotated[Optional[Mode], FieldMetadata(query=QueryParamMetadata(style="form", explode=True))] = Mode.FULL_GENERATION + r"""Type of mode used for document generation flow: + - partial_generation will have a intermediate step for users to validate and replace the variable values before generating the final document. + - full_generation, goes through all the steps for the full generation of final document + + """ + diff --git a/document/src/epilot_document/models/invalidcustomvariableerrordetail.py b/document/src/epilot_document/models/invalidcustomvariableerrordetail.py new file mode 100644 index 000000000..e764d8c8c --- /dev/null +++ b/document/src/epilot_document/models/invalidcustomvariableerrordetail.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_document.types import BaseModel +import pydantic +from pydantic import ConfigDict +from typing import Any, Dict, List, Optional, TypedDict +from typing_extensions import NotRequired + + +class InvalidVariablesTypedDict(TypedDict): + r"""Invalid variable""" + + error: NotRequired[str] + r"""Explanation for the error""" + variable: NotRequired[str] + r"""Variable name""" + + +class InvalidVariables(BaseModel): + r"""Invalid variable""" + + error: Optional[str] = None + r"""Explanation for the error""" + variable: Optional[str] = None + r"""Variable name""" + + +class ContextTypedDict(TypedDict): + r"""Context for the error""" + + invalid_variables: NotRequired[List[InvalidVariablesTypedDict]] + r"""List of invalid variables""" + + +class Context(BaseModel): + r"""Context for the error""" + + invalid_variables: Optional[List[InvalidVariables]] = None + r"""List of invalid variables""" + + +class InvalidCustomVariableErrorDetailTypedDict(TypedDict): + context: NotRequired[ContextTypedDict] + r"""Context for the error""" + explanation: NotRequired[str] + r"""Explanation for the error""" + + +class InvalidCustomVariableErrorDetail(BaseModel): + model_config = ConfigDict(populate_by_name=True, arbitrary_types_allowed=True, extra="allow") + __pydantic_extra__: Dict[str, Any] = pydantic.Field(init=False) + + context: Optional[Context] = None + r"""Context for the error""" + explanation: Optional[str] = None + r"""Explanation for the error""" + + @property + def additional_properties(self): + return self.__pydantic_extra__ + + @additional_properties.setter + def additional_properties(self, value): + self.__pydantic_extra__ = value # pyright: ignore[reportIncompatibleVariableOverride] + diff --git a/document/src/epilot_document/models/s3reference.py b/document/src/epilot_document/models/s3reference.py new file mode 100644 index 000000000..990d3c054 --- /dev/null +++ b/document/src/epilot_document/models/s3reference.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_document.types import BaseModel +from typing import TypedDict + + +class S3ReferenceTypedDict(TypedDict): + bucket: str + key: str + + +class S3Reference(BaseModel): + bucket: str + key: str + diff --git a/document/src/epilot_document/models/sdkerror.py b/document/src/epilot_document/models/sdkerror.py new file mode 100644 index 000000000..03216cbf5 --- /dev/null +++ b/document/src/epilot_document/models/sdkerror.py @@ -0,0 +1,22 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from dataclasses import dataclass +from typing import Optional +import httpx + + +@dataclass +class SDKError(Exception): + """Represents an error returned by the API.""" + + message: str + status_code: int = -1 + body: str = "" + raw_response: Optional[httpx.Response] = None + + def __str__(self): + body = "" + if len(self.body) > 0: + body = f"\n{self.body}" + + return f"{self.message}: Status {self.status_code}{body}" diff --git a/document/src/epilot_document/models/security.py b/document/src/epilot_document/models/security.py new file mode 100644 index 000000000..a3f326fb8 --- /dev/null +++ b/document/src/epilot_document/models/security.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_document.types import BaseModel +from epilot_document.utils import FieldMetadata, SecurityMetadata +from typing import TypedDict +from typing_extensions import Annotated + + +class SecurityTypedDict(TypedDict): + epilot_auth: str + + +class Security(BaseModel): + epilot_auth: Annotated[str, FieldMetadata(security=SecurityMetadata(scheme=True, scheme_type="http", sub_type="bearer", field_name="Authorization"))] + diff --git a/document/src/epilot_document/models/templatesettings.py b/document/src/epilot_document/models/templatesettings.py new file mode 100644 index 000000000..93028e845 --- /dev/null +++ b/document/src/epilot_document/models/templatesettings.py @@ -0,0 +1,85 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_document.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class CustomMarginsTypedDict(TypedDict): + r"""Custom margins for the document""" + + bottom: NotRequired[float] + r"""Bottom margin in cm""" + top: NotRequired[float] + r"""Top margin in cm""" + + +class CustomMargins(BaseModel): + r"""Custom margins for the document""" + + bottom: Optional[float] = None + r"""Bottom margin in cm""" + top: Optional[float] = None + r"""Top margin in cm""" + + +class SuggestedMarginsTypedDict(TypedDict): + r"""Suggested margins for the document""" + + bottom: NotRequired[float] + r"""Bottom margin in cm""" + top: NotRequired[float] + r"""Top margin in cm""" + + +class SuggestedMargins(BaseModel): + r"""Suggested margins for the document""" + + bottom: Optional[float] = None + r"""Bottom margin in cm""" + top: Optional[float] = None + r"""Top margin in cm""" + + +class TemplateSettingsTypedDict(TypedDict): + r"""Template Settings for document generation""" + + custom_margins: NotRequired[CustomMarginsTypedDict] + r"""Custom margins for the document""" + display_margin_guidelines: NotRequired[bool] + r"""Display margin guidelines (applicable to partial generation only)""" + enable_data_table_margin_autofix: NotRequired[bool] + r"""Enable data table margin autofix""" + enabled_template_settings_persistence: NotRequired[bool] + r"""Enables the persistance of template settings""" + file_entity_id: NotRequired[str] + r"""The file entity id, used when persisting a new template version with updated settings""" + misconfigured_margins: NotRequired[bool] + r"""An indication that the page margins are misconfigured""" + suggested_margins: NotRequired[SuggestedMarginsTypedDict] + r"""Suggested margins for the document""" + template_with_datatable: NotRequired[bool] + r"""A flag that indicates whether the template has 1 or more data tables in it""" + + +class TemplateSettings(BaseModel): + r"""Template Settings for document generation""" + + custom_margins: Optional[CustomMargins] = None + r"""Custom margins for the document""" + display_margin_guidelines: Optional[bool] = None + r"""Display margin guidelines (applicable to partial generation only)""" + enable_data_table_margin_autofix: Optional[bool] = None + r"""Enable data table margin autofix""" + enabled_template_settings_persistence: Optional[bool] = None + r"""Enables the persistance of template settings""" + file_entity_id: Optional[str] = None + r"""The file entity id, used when persisting a new template version with updated settings""" + misconfigured_margins: Optional[bool] = None + r"""An indication that the page margins are misconfigured""" + suggested_margins: Optional[SuggestedMargins] = None + r"""Suggested margins for the document""" + template_with_datatable: Optional[bool] = None + r"""A flag that indicates whether the template has 1 or more data tables in it""" + diff --git a/document/src/epilot_document/py.typed b/document/src/epilot_document/py.typed new file mode 100644 index 000000000..3e38f1a92 --- /dev/null +++ b/document/src/epilot_document/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/document/src/epilot_document/sdk.py b/document/src/epilot_document/sdk.py new file mode 100644 index 000000000..d4798c525 --- /dev/null +++ b/document/src/epilot_document/sdk.py @@ -0,0 +1,100 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from .httpclient import AsyncHttpClient, HttpClient +from .sdkconfiguration import SDKConfiguration +from .utils.logger import Logger, NoOpLogger +from .utils.retries import RetryConfig +from epilot_document import models, utils +from epilot_document._hooks import SDKHooks +from epilot_document.documents import Documents +from epilot_document.types import OptionalNullable, UNSET +import httpx +from typing import Any, Callable, Dict, Optional, Union + +class Epilot(BaseSDK): + r"""Document API: A document generation API that allows you to generate documents from templates with variables. + + [Feature Documentation](https://docs.epilot.io/docs/files/document-generation) + + """ + documents: Documents + r"""Document Generation""" + def __init__( + self, + epilot_auth: Union[str, Callable[[], str]], + server_idx: Optional[int] = None, + server_url: Optional[str] = None, + url_params: Optional[Dict[str, str]] = None, + client: Optional[HttpClient] = None, + async_client: Optional[AsyncHttpClient] = None, + retry_config: OptionalNullable[RetryConfig] = UNSET, + timeout_ms: Optional[int] = None, + debug_logger: Optional[Logger] = None + ) -> None: + r"""Instantiates the SDK configuring it with the provided parameters. + + :param epilot_auth: The epilot_auth required for authentication + :param server_idx: The index of the server to use for all methods + :param server_url: The server URL to use for all methods + :param url_params: Parameters to optionally template the server URL with + :param client: The HTTP client to use for all synchronous methods + :param async_client: The Async HTTP client to use for all asynchronous methods + :param retry_config: The retry configuration to use for all supported methods + :param timeout_ms: Optional request timeout applied to each operation in milliseconds + """ + if client is None: + client = httpx.Client() + + assert issubclass( + type(client), HttpClient + ), "The provided client must implement the HttpClient protocol." + + if async_client is None: + async_client = httpx.AsyncClient() + + if debug_logger is None: + debug_logger = NoOpLogger() + + assert issubclass( + type(async_client), AsyncHttpClient + ), "The provided async_client must implement the AsyncHttpClient protocol." + + security: Any = None + if callable(epilot_auth): + security = lambda: models.Security(epilot_auth = epilot_auth()) # pylint: disable=unnecessary-lambda-assignment + else: + security = models.Security(epilot_auth = epilot_auth) + + if server_url is not None: + if url_params is not None: + server_url = utils.template_url(server_url, url_params) + + + BaseSDK.__init__(self, SDKConfiguration( + client=client, + async_client=async_client, + security=security, + server_url=server_url, + server_idx=server_idx, + retry_config=retry_config, + timeout_ms=timeout_ms, + debug_logger=debug_logger + )) + + hooks = SDKHooks() + + current_server_url, *_ = self.sdk_configuration.get_server_details() + server_url, self.sdk_configuration.client = hooks.sdk_init(current_server_url, self.sdk_configuration.client) + if current_server_url != server_url: + self.sdk_configuration.server_url = server_url + + # pylint: disable=protected-access + self.sdk_configuration.__dict__["_hooks"] = hooks + + self._init_sdks() + + + def _init_sdks(self): + self.documents = Documents(self.sdk_configuration) + diff --git a/document/src/epilot_document/sdkconfiguration.py b/document/src/epilot_document/sdkconfiguration.py new file mode 100644 index 000000000..97a0090ce --- /dev/null +++ b/document/src/epilot_document/sdkconfiguration.py @@ -0,0 +1,48 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + + +from ._hooks import SDKHooks +from .httpclient import AsyncHttpClient, HttpClient +from .utils import Logger, RetryConfig, remove_suffix +from dataclasses import dataclass +from epilot_document import models +from epilot_document.types import OptionalNullable, UNSET +from pydantic import Field +from typing import Callable, Dict, Optional, Tuple, Union + + +SERVERS = [ + "https://document.sls.epilot.io", +] +"""Contains the list of servers available to the SDK""" + +@dataclass +class SDKConfiguration: + client: HttpClient + async_client: AsyncHttpClient + debug_logger: Logger + security: Optional[Union[models.Security,Callable[[], models.Security]]] = None + server_url: Optional[str] = "" + server_idx: Optional[int] = 0 + language: str = "python" + openapi_doc_version: str = "1.0.0" + sdk_version: str = "1.3.0" + gen_version: str = "2.387.0" + user_agent: str = "speakeasy-sdk/python 1.3.0 2.387.0 1.0.0 epilot-document" + retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET) + timeout_ms: Optional[int] = None + + def __post_init__(self): + self._hooks = SDKHooks() + + def get_server_details(self) -> Tuple[str, Dict[str, str]]: + if self.server_url is not None and self.server_url: + return remove_suffix(self.server_url, "/"), {} + if self.server_idx is None: + self.server_idx = 0 + + return SERVERS[self.server_idx], {} + + + def get_hooks(self) -> SDKHooks: + return self._hooks diff --git a/document/src/epilot_document/types/__init__.py b/document/src/epilot_document/types/__init__.py new file mode 100644 index 000000000..fc76fe0c5 --- /dev/null +++ b/document/src/epilot_document/types/__init__.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basemodel import ( + BaseModel, + Nullable, + OptionalNullable, + UnrecognizedInt, + UnrecognizedStr, + UNSET, + UNSET_SENTINEL, +) + +__all__ = [ + "BaseModel", + "Nullable", + "OptionalNullable", + "UnrecognizedInt", + "UnrecognizedStr", + "UNSET", + "UNSET_SENTINEL", +] diff --git a/document/src/epilot_document/types/basemodel.py b/document/src/epilot_document/types/basemodel.py new file mode 100644 index 000000000..a6187efa6 --- /dev/null +++ b/document/src/epilot_document/types/basemodel.py @@ -0,0 +1,39 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from pydantic import ConfigDict, model_serializer +from pydantic import BaseModel as PydanticBaseModel +from typing import TYPE_CHECKING, Literal, Optional, TypeVar, Union, NewType +from typing_extensions import TypeAliasType, TypeAlias + + +class BaseModel(PydanticBaseModel): + model_config = ConfigDict( + populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=() + ) + + +class Unset(BaseModel): + @model_serializer(mode="plain") + def serialize_model(self): + return UNSET_SENTINEL + + def __bool__(self) -> Literal[False]: + return False + + +UNSET = Unset() +UNSET_SENTINEL = "~?~unset~?~sentinel~?~" + + +T = TypeVar("T") +if TYPE_CHECKING: + Nullable: TypeAlias = Union[T, None] + OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset] +else: + Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) + OptionalNullable = TypeAliasType( + "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,) + ) + +UnrecognizedInt = NewType("UnrecognizedInt", int) +UnrecognizedStr = NewType("UnrecognizedStr", str) diff --git a/document/src/epilot_document/utils/__init__.py b/document/src/epilot_document/utils/__init__.py new file mode 100644 index 000000000..95aa1b60c --- /dev/null +++ b/document/src/epilot_document/utils/__init__.py @@ -0,0 +1,84 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .annotations import get_discriminator +from .enums import OpenEnumMeta +from .headers import get_headers, get_response_headers +from .metadata import ( + FieldMetadata, + find_metadata, + FormMetadata, + HeaderMetadata, + MultipartFormMetadata, + PathParamMetadata, + QueryParamMetadata, + RequestMetadata, + SecurityMetadata, +) +from .queryparams import get_query_params +from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig +from .requestbodies import serialize_request_body, SerializedRequestBody +from .security import get_security +from .serializers import ( + get_pydantic_model, + marshal_json, + unmarshal, + unmarshal_json, + serialize_decimal, + serialize_float, + serialize_int, + stream_to_text, + validate_decimal, + validate_float, + validate_int, + validate_open_enum, +) +from .url import generate_url, template_url, remove_suffix +from .values import get_global_from_env, match_content_type, match_status_codes, match_response +from .logger import Logger, get_body_content, NoOpLogger + +__all__ = [ + "BackoffStrategy", + "FieldMetadata", + "find_metadata", + "FormMetadata", + "generate_url", + "get_body_content", + "get_discriminator", + "get_global_from_env", + "get_headers", + "get_pydantic_model", + "get_query_params", + "get_response_headers", + "get_security", + "HeaderMetadata", + "Logger", + "marshal_json", + "match_content_type", + "match_status_codes", + "match_response", + "MultipartFormMetadata", + "NoOpLogger", + "OpenEnumMeta", + "PathParamMetadata", + "QueryParamMetadata", + "remove_suffix", + "Retries", + "retry", + "retry_async", + "RetryConfig", + "RequestMetadata", + "SecurityMetadata", + "serialize_decimal", + "serialize_float", + "serialize_int", + "serialize_request_body", + "SerializedRequestBody", + "stream_to_text", + "template_url", + "unmarshal", + "unmarshal_json", + "validate_decimal", + "validate_float", + "validate_int", + "validate_open_enum", +] diff --git a/document/src/epilot_document/utils/annotations.py b/document/src/epilot_document/utils/annotations.py new file mode 100644 index 000000000..0d17472b3 --- /dev/null +++ b/document/src/epilot_document/utils/annotations.py @@ -0,0 +1,19 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Any + +def get_discriminator(model: Any, fieldname: str, key: str) -> str: + if isinstance(model, dict): + try: + return f'{model.get(key)}' + except AttributeError as e: + raise ValueError(f'Could not find discriminator key {key} in {model}') from e + + if hasattr(model, fieldname): + return f'{getattr(model, fieldname)}' + + fieldname = fieldname.upper() + if hasattr(model, fieldname): + return f'{getattr(model, fieldname)}' + + raise ValueError(f'Could not find discriminator field {fieldname} in {model}') diff --git a/document/src/epilot_document/utils/enums.py b/document/src/epilot_document/utils/enums.py new file mode 100644 index 000000000..c650b10cb --- /dev/null +++ b/document/src/epilot_document/utils/enums.py @@ -0,0 +1,34 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import enum + + +class OpenEnumMeta(enum.EnumMeta): + def __call__( + cls, value, names=None, *, module=None, qualname=None, type=None, start=1 + ): + # The `type` kwarg also happens to be a built-in that pylint flags as + # redeclared. Safe to ignore this lint rule with this scope. + # pylint: disable=redefined-builtin + + if names is not None: + return super().__call__( + value, + names=names, + module=module, + qualname=qualname, + type=type, + start=start, + ) + + try: + return super().__call__( + value, + names=names, # pyright: ignore[reportArgumentType] + module=module, + qualname=qualname, + type=type, + start=start, + ) + except ValueError: + return value diff --git a/document/src/epilot_document/utils/eventstreaming.py b/document/src/epilot_document/utils/eventstreaming.py new file mode 100644 index 000000000..553b386b3 --- /dev/null +++ b/document/src/epilot_document/utils/eventstreaming.py @@ -0,0 +1,178 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import re +import json +from typing import Callable, TypeVar, Optional, Generator, AsyncGenerator, Tuple +import httpx + +T = TypeVar("T") + + +class ServerEvent: + id: Optional[str] = None + event: Optional[str] = None + data: Optional[str] = None + retry: Optional[int] = None + + +MESSAGE_BOUNDARIES = [ + b"\r\n\r\n", + b"\n\n", + b"\r\r", +] + + +async def stream_events_async( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> AsyncGenerator[T, None]: + buffer = bytearray() + position = 0 + discard = False + async for chunk in response.aiter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def stream_events( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> Generator[T, None, None]: + buffer = bytearray() + position = 0 + discard = False + for chunk in response.iter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def _parse_event( + raw: bytearray, decoder: Callable[[str], T], sentinel: Optional[str] = None +) -> Tuple[Optional[T], bool]: + block = raw.decode() + lines = re.split(r"\r?\n|\r", block) + publish = False + event = ServerEvent() + data = "" + for line in lines: + if not line: + continue + + delim = line.find(":") + if delim <= 0: + continue + + field = line[0:delim] + value = line[delim + 1 :] if delim < len(line) - 1 else "" + if len(value) and value[0] == " ": + value = value[1:] + + if field == "event": + event.event = value + publish = True + elif field == "data": + data += value + "\n" + publish = True + elif field == "id": + event.id = value + publish = True + elif field == "retry": + event.retry = int(value) if value.isdigit() else None + publish = True + + if sentinel and data == f"{sentinel}\n": + return None, True + + if data: + data = data[:-1] + event.data = data + + data_is_primitive = ( + data.isnumeric() or data == "true" or data == "false" or data == "null" + ) + data_is_json = ( + data.startswith("{") or data.startswith("[") or data.startswith('"') + ) + + if data_is_primitive or data_is_json: + try: + event.data = json.loads(data) + except Exception: + pass + + out = None + if publish: + out = decoder(json.dumps(event.__dict__)) + + return out, False + + +def _peek_sequence(position: int, buffer: bytearray, sequence: bytes): + if len(sequence) > (len(buffer) - position): + return None + + for i, seq in enumerate(sequence): + if buffer[position + i] != seq: + return None + + return sequence diff --git a/document/src/epilot_document/utils/forms.py b/document/src/epilot_document/utils/forms.py new file mode 100644 index 000000000..07f9b2359 --- /dev/null +++ b/document/src/epilot_document/utils/forms.py @@ -0,0 +1,207 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .serializers import marshal_json + +from .metadata import ( + FormMetadata, + MultipartFormMetadata, + find_field_metadata, +) +from .values import _val_to_string + + +def _populate_form( + field_name: str, + explode: bool, + obj: Any, + delimiter: str, + form: Dict[str, List[str]], +): + if obj is None: + return form + + if isinstance(obj, BaseModel): + items = [] + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_field_name = obj_field.alias if obj_field.alias is not None else name + if obj_field_name == "": + continue + + val = getattr(obj, name) + if val is None: + continue + + if explode: + form[obj_field_name] = [_val_to_string(val)] + else: + items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, Dict): + items = [] + for key, value in obj.items(): + if value is None: + continue + + if explode: + form[key] = [_val_to_string(value)] + else: + items.append(f"{key}{delimiter}{_val_to_string(value)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, List): + items = [] + + for value in obj: + if value is None: + continue + + if explode: + if not field_name in form: + form[field_name] = [] + form[field_name].append(_val_to_string(value)) + else: + items.append(_val_to_string(value)) + + if len(items) > 0: + form[field_name] = [delimiter.join([str(item) for item in items])] + else: + form[field_name] = [_val_to_string(obj)] + + return form + + +def serialize_multipart_form( + media_type: str, request: Any +) -> Tuple[str, Dict[str, Any], Dict[str, Any]]: + form: Dict[str, Any] = {} + files: Dict[str, Any] = {} + + if not isinstance(request, BaseModel): + raise TypeError("invalid request body type") + + request_fields: Dict[str, FieldInfo] = request.__class__.model_fields + request_field_types = get_type_hints(request.__class__) + + for name in request_fields: + field = request_fields[name] + + val = getattr(request, name) + if val is None: + continue + + field_metadata = find_field_metadata(field, MultipartFormMetadata) + if not field_metadata: + continue + + f_name = field.alias if field.alias is not None else name + + if field_metadata.file: + file_fields: Dict[str, FieldInfo] = val.__class__.model_fields + + file_name = "" + field_name = "" + content = None + content_type = None + + for file_field_name in file_fields: + file_field = file_fields[file_field_name] + + file_metadata = find_field_metadata(file_field, MultipartFormMetadata) + if file_metadata is None: + continue + + if file_metadata.content: + content = getattr(val, file_field_name, None) + elif file_field_name == "content_type": + content_type = getattr(val, file_field_name, None) + else: + field_name = ( + file_field.alias + if file_field.alias is not None + else file_field_name + ) + file_name = getattr(val, file_field_name) + + if field_name == "" or file_name == "" or content is None: + raise ValueError("invalid multipart/form-data file") + + if content_type is not None: + files[field_name] = (file_name, content, content_type) + else: + files[field_name] = (file_name, content) + elif field_metadata.json: + files[f_name] = ( + None, + marshal_json(val, request_field_types[name]), + "application/json", + ) + else: + if isinstance(val, List): + values = [] + + for value in val: + if value is None: + continue + values.append(_val_to_string(value)) + + form[f_name + "[]"] = values + else: + form[f_name] = _val_to_string(val) + return media_type, form, files + + +def serialize_form_data(data: Any) -> Dict[str, Any]: + form: Dict[str, List[str]] = {} + + if isinstance(data, BaseModel): + data_fields: Dict[str, FieldInfo] = data.__class__.model_fields + data_field_types = get_type_hints(data.__class__) + for name in data_fields: + field = data_fields[name] + + val = getattr(data, name) + if val is None: + continue + + metadata = find_field_metadata(field, FormMetadata) + if metadata is None: + continue + + f_name = field.alias if field.alias is not None else name + + if metadata.json: + form[f_name] = [marshal_json(val, data_field_types[name])] + else: + if metadata.style == "form": + _populate_form( + f_name, + metadata.explode, + val, + ",", + form, + ) + else: + raise ValueError(f"Invalid form style for field {name}") + elif isinstance(data, Dict): + for key, value in data.items(): + form[key] = [_val_to_string(value)] + else: + raise TypeError(f"Invalid request body type {type(data)} for form data") + + return form diff --git a/document/src/epilot_document/utils/headers.py b/document/src/epilot_document/utils/headers.py new file mode 100644 index 000000000..e14a0f4a8 --- /dev/null +++ b/document/src/epilot_document/utils/headers.py @@ -0,0 +1,136 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + List, + Optional, +) +from httpx import Headers +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + HeaderMetadata, + find_field_metadata, +) + +from .values import _populate_from_globals, _val_to_string + + +def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: + headers: Dict[str, str] = {} + + globals_already_populated = [] + if headers_params is not None: + globals_already_populated = _populate_headers(headers_params, gbls, headers, []) + if gbls is not None: + _populate_headers(gbls, None, headers, globals_already_populated) + + return headers + + +def _populate_headers( + headers_params: Any, + gbls: Any, + header_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(headers_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + f_name = field.alias if field.alias is not None else name + + metadata = find_field_metadata(field, HeaderMetadata) + if metadata is None: + continue + + value, global_found = _populate_from_globals( + name, getattr(headers_params, name), HeaderMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + value = _serialize_header(metadata.explode, value) + + if value != "": + header_values[f_name] = value + + return globals_already_populated + + +def _serialize_header(explode: bool, obj: Any) -> str: + if obj is None: + return "" + + if isinstance(obj, BaseModel): + items = [] + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata) + + if not obj_param_metadata: + continue + + f_name = obj_field.alias if obj_field.alias is not None else name + + val = getattr(obj, name) + if val is None: + continue + + if explode: + items.append(f"{f_name}={_val_to_string(val)}") + else: + items.append(f_name) + items.append(_val_to_string(val)) + + if len(items) > 0: + return ",".join(items) + elif isinstance(obj, Dict): + items = [] + + for key, value in obj.items(): + if value is None: + continue + + if explode: + items.append(f"{key}={_val_to_string(value)}") + else: + items.append(key) + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join([str(item) for item in items]) + elif isinstance(obj, List): + items = [] + + for value in obj: + if value is None: + continue + + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join(items) + else: + return f"{_val_to_string(obj)}" + + return "" + + +def get_response_headers(headers: Headers) -> Dict[str, List[str]]: + res: Dict[str, List[str]] = {} + for k, v in headers.items(): + if not k in res: + res[k] = [] + + res[k].append(v) + return res diff --git a/document/src/epilot_document/utils/logger.py b/document/src/epilot_document/utils/logger.py new file mode 100644 index 000000000..7e4bbeac2 --- /dev/null +++ b/document/src/epilot_document/utils/logger.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from typing import Any, Protocol + +class Logger(Protocol): + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + +class NoOpLogger: + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + +def get_body_content(req: httpx.Request) -> str: + return "" if not hasattr(req, "_content") else str(req.content) + diff --git a/document/src/epilot_document/utils/metadata.py b/document/src/epilot_document/utils/metadata.py new file mode 100644 index 000000000..173b3e5ce --- /dev/null +++ b/document/src/epilot_document/utils/metadata.py @@ -0,0 +1,118 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Optional, Type, TypeVar, Union +from dataclasses import dataclass +from pydantic.fields import FieldInfo + + +T = TypeVar("T") + + +@dataclass +class SecurityMetadata: + option: bool = False + scheme: bool = False + scheme_type: Optional[str] = None + sub_type: Optional[str] = None + field_name: Optional[str] = None + + def get_field_name(self, default: str) -> str: + return self.field_name or default + + +@dataclass +class ParamMetadata: + serialization: Optional[str] = None + style: str = "simple" + explode: bool = False + + +@dataclass +class PathParamMetadata(ParamMetadata): + pass + + +@dataclass +class QueryParamMetadata(ParamMetadata): + style: str = "form" + explode: bool = True + + +@dataclass +class HeaderMetadata(ParamMetadata): + pass + + +@dataclass +class RequestMetadata: + media_type: str = "application/octet-stream" + + +@dataclass +class MultipartFormMetadata: + file: bool = False + content: bool = False + json: bool = False + + +@dataclass +class FormMetadata: + json: bool = False + style: str = "form" + explode: bool = True + + +class FieldMetadata: + security: Optional[SecurityMetadata] = None + path: Optional[PathParamMetadata] = None + query: Optional[QueryParamMetadata] = None + header: Optional[HeaderMetadata] = None + request: Optional[RequestMetadata] = None + form: Optional[FormMetadata] = None + multipart: Optional[MultipartFormMetadata] = None + + def __init__( + self, + security: Optional[SecurityMetadata] = None, + path: Optional[Union[PathParamMetadata, bool]] = None, + query: Optional[Union[QueryParamMetadata, bool]] = None, + header: Optional[Union[HeaderMetadata, bool]] = None, + request: Optional[Union[RequestMetadata, bool]] = None, + form: Optional[Union[FormMetadata, bool]] = None, + multipart: Optional[Union[MultipartFormMetadata, bool]] = None, + ): + self.security = security + self.path = PathParamMetadata() if isinstance(path, bool) else path + self.query = QueryParamMetadata() if isinstance(query, bool) else query + self.header = HeaderMetadata() if isinstance(header, bool) else header + self.request = RequestMetadata() if isinstance(request, bool) else request + self.form = FormMetadata() if isinstance(form, bool) else form + self.multipart = ( + MultipartFormMetadata() if isinstance(multipart, bool) else multipart + ) + + +def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = find_metadata(field_info, FieldMetadata) + if not metadata: + return None + + fields = metadata.__dict__ + + for field in fields: + if isinstance(fields[field], metadata_type): + return fields[field] + + return None + + +def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = field_info.metadata + if not metadata: + return None + + for md in metadata: + if isinstance(md, metadata_type): + return md + + return None diff --git a/document/src/epilot_document/utils/queryparams.py b/document/src/epilot_document/utils/queryparams.py new file mode 100644 index 000000000..1c8c58340 --- /dev/null +++ b/document/src/epilot_document/utils/queryparams.py @@ -0,0 +1,203 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, +) + +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + QueryParamMetadata, + find_field_metadata, +) +from .values import _get_serialized_params, _populate_from_globals, _val_to_string +from .forms import _populate_form + + +def get_query_params( + query_params: Any, + gbls: Optional[Any] = None, +) -> Dict[str, List[str]]: + params: Dict[str, List[str]] = {} + + globals_already_populated = _populate_query_params(query_params, gbls, params, []) + if gbls is not None: + _populate_query_params(gbls, None, params, globals_already_populated) + + return params + + +def _populate_query_params( + query_params: Any, + gbls: Any, + query_param_values: Dict[str, List[str]], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(query_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields + param_field_types = get_type_hints(query_params.__class__) + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + + metadata = find_field_metadata(field, QueryParamMetadata) + if not metadata: + continue + + value = getattr(query_params, name) if query_params is not None else None + + value, global_found = _populate_from_globals( + name, value, QueryParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + f_name = field.alias if field.alias is not None else name + serialization = metadata.serialization + if serialization is not None: + serialized_parms = _get_serialized_params( + metadata, f_name, value, param_field_types[name] + ) + for key, value in serialized_parms.items(): + if key in query_param_values: + query_param_values[key].extend(value) + else: + query_param_values[key] = [value] + else: + style = metadata.style + if style == "deepObject": + _populate_deep_object_query_params(f_name, value, query_param_values) + elif style == "form": + _populate_delimited_query_params( + metadata, f_name, value, ",", query_param_values + ) + elif style == "pipeDelimited": + _populate_delimited_query_params( + metadata, f_name, value, "|", query_param_values + ) + else: + raise NotImplementedError( + f"query param style {style} not yet supported" + ) + + return globals_already_populated + + +def _populate_deep_object_query_params( + field_name: str, + obj: Any, + params: Dict[str, List[str]], +): + if obj is None: + return + + if isinstance(obj, BaseModel): + _populate_deep_object_query_params_basemodel(field_name, obj, params) + elif isinstance(obj, Dict): + _populate_deep_object_query_params_dict(field_name, obj, params) + + +def _populate_deep_object_query_params_basemodel( + prior_params_key: str, + obj: Any, + params: Dict[str, List[str]], +): + if obj is None: + return + + if not isinstance(obj, BaseModel): + return + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + + f_name = obj_field.alias if obj_field.alias is not None else name + + params_key = f"{prior_params_key}[{f_name}]" + + obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata) + if obj_param_metadata is None: + continue + + obj_val = getattr(obj, name) + if obj_val is None: + continue + + if isinstance(obj_val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, obj_val, params) + elif isinstance(obj_val, Dict): + _populate_deep_object_query_params_dict(params_key, obj_val, params) + elif isinstance(obj_val, List): + _populate_deep_object_query_params_list(params_key, obj_val, params) + else: + params[params_key] = [_val_to_string(obj_val)] + + +def _populate_deep_object_query_params_dict( + prior_params_key: str, + value: Dict, + params: Dict[str, List[str]], +): + if value is None: + return + + for key, val in value.items(): + if val is None: + continue + + params_key = f"{prior_params_key}[{key}]" + + if isinstance(val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, val, params) + elif isinstance(val, Dict): + _populate_deep_object_query_params_dict(params_key, val, params) + elif isinstance(val, List): + _populate_deep_object_query_params_list(params_key, val, params) + else: + params[params_key] = [_val_to_string(val)] + + +def _populate_deep_object_query_params_list( + params_key: str, + value: List, + params: Dict[str, List[str]], +): + if value is None: + return + + for val in value: + if val is None: + continue + + if params.get(params_key) is None: + params[params_key] = [] + + params[params_key].append(_val_to_string(val)) + + +def _populate_delimited_query_params( + metadata: QueryParamMetadata, + field_name: str, + obj: Any, + delimiter: str, + query_param_values: Dict[str, List[str]], +): + _populate_form( + field_name, + metadata.explode, + obj, + delimiter, + query_param_values, + ) diff --git a/document/src/epilot_document/utils/requestbodies.py b/document/src/epilot_document/utils/requestbodies.py new file mode 100644 index 000000000..4f586ae79 --- /dev/null +++ b/document/src/epilot_document/utils/requestbodies.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import io +from dataclasses import dataclass +import re +from typing import ( + Any, + Optional, +) + +from .forms import serialize_form_data, serialize_multipart_form + +from .serializers import marshal_json + +SERIALIZATION_METHOD_TO_CONTENT_TYPE = { + "json": "application/json", + "form": "application/x-www-form-urlencoded", + "multipart": "multipart/form-data", + "raw": "application/octet-stream", + "string": "text/plain", +} + + +@dataclass +class SerializedRequestBody: + media_type: str + content: Optional[Any] = None + data: Optional[Any] = None + files: Optional[Any] = None + + +def serialize_request_body( + request_body: Any, + nullable: bool, + optional: bool, + serialization_method: str, + request_body_type, +) -> Optional[SerializedRequestBody]: + if request_body is None: + if not nullable and optional: + return None + + media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method] + + serialized_request_body = SerializedRequestBody(media_type) + + if re.match(r"(application|text)\/.*?\+*json.*", media_type) is not None: + serialized_request_body.content = marshal_json(request_body, request_body_type) + elif re.match(r"multipart\/.*", media_type) is not None: + ( + serialized_request_body.media_type, + serialized_request_body.data, + serialized_request_body.files, + ) = serialize_multipart_form(media_type, request_body) + elif re.match(r"application\/x-www-form-urlencoded.*", media_type) is not None: + serialized_request_body.data = serialize_form_data(request_body) + elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)): + serialized_request_body.content = request_body + elif isinstance(request_body, str): + serialized_request_body.content = request_body + else: + raise TypeError( + f"invalid request body type {type(request_body)} for mediaType {media_type}" + ) + + return serialized_request_body diff --git a/document/src/epilot_document/utils/retries.py b/document/src/epilot_document/utils/retries.py new file mode 100644 index 000000000..a06f92794 --- /dev/null +++ b/document/src/epilot_document/utils/retries.py @@ -0,0 +1,216 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import random +import time +from typing import List + +import httpx + + +class BackoffStrategy: + initial_interval: int + max_interval: int + exponent: float + max_elapsed_time: int + + def __init__( + self, + initial_interval: int, + max_interval: int, + exponent: float, + max_elapsed_time: int, + ): + self.initial_interval = initial_interval + self.max_interval = max_interval + self.exponent = exponent + self.max_elapsed_time = max_elapsed_time + + +class RetryConfig: + strategy: str + backoff: BackoffStrategy + retry_connection_errors: bool + + def __init__( + self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool + ): + self.strategy = strategy + self.backoff = backoff + self.retry_connection_errors = retry_connection_errors + + +class Retries: + config: RetryConfig + status_codes: List[str] + + def __init__(self, config: RetryConfig, status_codes: List[str]): + self.config = config + self.status_codes = status_codes + + +class TemporaryError(Exception): + response: httpx.Response + + def __init__(self, response: httpx.Response): + self.response = response + + +class PermanentError(Exception): + inner: Exception + + def __init__(self, inner: Exception): + self.inner = inner + + +def retry(func, retries: Retries): + if retries.config.strategy == "backoff": + + def do_request() -> httpx.Response: + res: httpx.Response + try: + res = func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return retry_with_backoff( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return func() + + +async def retry_async(func, retries: Retries): + if retries.config.strategy == "backoff": + + async def do_request() -> httpx.Response: + res: httpx.Response + try: + res = await func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return await retry_with_backoff_async( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return await func() + + +def retry_with_backoff( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + time.sleep(sleep) + retries += 1 + + +async def retry_with_backoff_async( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return await func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + time.sleep(sleep) + retries += 1 diff --git a/document/src/epilot_document/utils/security.py b/document/src/epilot_document/utils/security.py new file mode 100644 index 000000000..aab4cb65c --- /dev/null +++ b/document/src/epilot_document/utils/security.py @@ -0,0 +1,168 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import base64 +from typing import ( + Any, + Dict, + List, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + SecurityMetadata, + find_field_metadata, +) + + + +def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, List[str]]]: + headers: Dict[str, str] = {} + query_params: Dict[str, List[str]] = {} + + if security is None: + return headers, query_params + + if not isinstance(security, BaseModel): + raise TypeError("security must be a pydantic model") + + sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields + for name in sec_fields: + sec_field = sec_fields[name] + + value = getattr(security, name) + if value is None: + continue + + metadata = find_field_metadata(sec_field, SecurityMetadata) + if metadata is None: + continue + if metadata.option: + _parse_security_option(headers, query_params, value) + return headers, query_params + if metadata.scheme: + # Special case for basic auth which could be a flattened model + if metadata.sub_type == "basic" and not isinstance(value, BaseModel): + _parse_security_scheme(headers, query_params, metadata, name, security) + else: + _parse_security_scheme(headers, query_params, metadata, name, value) + + return headers, query_params + + +def _parse_security_option( + headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any +): + if not isinstance(option, BaseModel): + raise TypeError("security option must be a pydantic model") + + opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields + for name in opt_fields: + opt_field = opt_fields[name] + + metadata = find_field_metadata(opt_field, SecurityMetadata) + if metadata is None or not metadata.scheme: + continue + _parse_security_scheme( + headers, query_params, metadata, name, getattr(option, name) + ) + + +def _parse_security_scheme( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + field_name: str, + scheme: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + if isinstance(scheme, BaseModel): + if scheme_type == "http" and sub_type == "basic": + _parse_basic_auth_scheme(headers, scheme) + return + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + value = getattr(scheme, name) + + _parse_security_scheme_value( + headers, query_params, scheme_metadata, metadata, name, value + ) + else: + _parse_security_scheme_value( + headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme + ) + + +def _parse_security_scheme_value( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + security_metadata: SecurityMetadata, + field_name: str, + value: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + header_name = security_metadata.get_field_name(field_name) + + if scheme_type == "apiKey": + if sub_type == "header": + headers[header_name] = value + elif sub_type == "query": + query_params[header_name] = [value] + else: + raise ValueError("sub type {sub_type} not supported") + elif scheme_type == "openIdConnect": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "oauth2": + if sub_type != "client_credentials": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "http": + if sub_type == "bearer": + headers[header_name] = _apply_bearer(value) + else: + raise ValueError("sub type {sub_type} not supported") + else: + raise ValueError("scheme type {scheme_type} not supported") + + +def _apply_bearer(token: str) -> str: + return token.lower().startswith("bearer ") and token or f"Bearer {token}" + + +def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): + username = "" + password = "" + + if not isinstance(scheme, BaseModel): + raise TypeError("basic auth scheme must be a pydantic model") + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + field_name = metadata.field_name + value = getattr(scheme, name) + + if field_name == "username": + username = value + if field_name == "password": + password = value + + data = f"{username}:{password}".encode() + headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" diff --git a/document/src/epilot_document/utils/serializers.py b/document/src/epilot_document/utils/serializers.py new file mode 100644 index 000000000..a98998a3f --- /dev/null +++ b/document/src/epilot_document/utils/serializers.py @@ -0,0 +1,181 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +import json +from typing import Any, Dict, List, Union, get_args +import httpx +from typing_extensions import get_origin +from pydantic import ConfigDict, create_model +from pydantic_core import from_json +from typing_inspect import is_optional_type + +from ..types.basemodel import BaseModel, Nullable, OptionalNullable + + +def serialize_decimal(as_str: bool): + def serialize(d): + if is_optional_type(type(d)) and d is None: + return None + + if not isinstance(d, Decimal): + raise ValueError("Expected Decimal object") + + return str(d) if as_str else float(d) + + return serialize + + +def validate_decimal(d): + if d is None: + return None + + if isinstance(d, Decimal): + return d + + if not isinstance(d, (str, int, float)): + raise ValueError("Expected string, int or float") + + return Decimal(str(d)) + + +def serialize_float(as_str: bool): + def serialize(f): + if is_optional_type(type(f)) and f is None: + return None + + if not isinstance(f, float): + raise ValueError("Expected float") + + return str(f) if as_str else f + + return serialize + + +def validate_float(f): + if f is None: + return None + + if isinstance(f, float): + return f + + if not isinstance(f, str): + raise ValueError("Expected string") + + return float(f) + + +def serialize_int(as_str: bool): + def serialize(b): + if is_optional_type(type(b)) and b is None: + return None + + if not isinstance(b, int): + raise ValueError("Expected int") + + return str(b) if as_str else b + + return serialize + + +def validate_int(b): + if b is None: + return None + + if isinstance(b, int): + return b + + if not isinstance(b, str): + raise ValueError("Expected string") + + return int(b) + + +def validate_open_enum(is_int: bool): + def validate(e): + if e is None: + return None + + if is_int: + if not isinstance(e, int): + raise ValueError("Expected int") + else: + if not isinstance(e, str): + raise ValueError("Expected string") + + return e + + return validate + + +def unmarshal_json(raw, typ: Any) -> Any: + return unmarshal(from_json(raw), typ) + + +def unmarshal(val, typ: Any) -> Any: + unmarshaller = create_model( + "Unmarshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = unmarshaller(body=val) + + # pyright: ignore[reportAttributeAccessIssue] + return m.body # type: ignore + + +def marshal_json(val, typ): + if is_nullable(typ) and val is None: + return "null" + + marshaller = create_model( + "Marshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = marshaller(body=val) + + d = m.model_dump(by_alias=True, mode="json", exclude_none=True) + + if len(d) == 0: + return "" + + return json.dumps(d[next(iter(d))], separators=(",", ":"), sort_keys=True) + + +def is_nullable(field): + origin = get_origin(field) + if origin is Nullable or origin is OptionalNullable: + return True + + if not origin is Union or type(None) not in get_args(field): + return False + + for arg in get_args(field): + if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable: + return True + + return False + + +def stream_to_text(stream: httpx.Response) -> str: + return "".join(stream.iter_text()) + + +def get_pydantic_model(data: Any, typ: Any) -> Any: + if not _contains_pydantic_model(data): + return unmarshal(data, typ) + + return data + + +def _contains_pydantic_model(data: Any) -> bool: + if isinstance(data, BaseModel): + return True + if isinstance(data, List): + return any(_contains_pydantic_model(item) for item in data) + if isinstance(data, Dict): + return any(_contains_pydantic_model(value) for value in data.values()) + + return False diff --git a/document/src/epilot_document/utils/url.py b/document/src/epilot_document/utils/url.py new file mode 100644 index 000000000..b201bfa49 --- /dev/null +++ b/document/src/epilot_document/utils/url.py @@ -0,0 +1,150 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, + Union, + get_args, + get_origin, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + PathParamMetadata, + find_field_metadata, +) +from .values import _get_serialized_params, _populate_from_globals, _val_to_string + + +def generate_url( + server_url: str, + path: str, + path_params: Any, + gbls: Optional[Any] = None, +) -> str: + path_param_values: Dict[str, str] = {} + + globals_already_populated = _populate_path_params( + path_params, gbls, path_param_values, [] + ) + if gbls is not None: + _populate_path_params(gbls, None, path_param_values, globals_already_populated) + + for key, value in path_param_values.items(): + path = path.replace("{" + key + "}", value, 1) + + return remove_suffix(server_url, "/") + path + + +def _populate_path_params( + path_params: Any, + gbls: Any, + path_param_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(path_params, BaseModel): + return globals_already_populated + + path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields + path_param_field_types = get_type_hints(path_params.__class__) + for name in path_param_fields: + if name in skip_fields: + continue + + field = path_param_fields[name] + + param_metadata = find_field_metadata(field, PathParamMetadata) + if param_metadata is None: + continue + + param = getattr(path_params, name) if path_params is not None else None + param, global_found = _populate_from_globals( + name, param, PathParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + if param is None: + continue + + f_name = field.alias if field.alias is not None else name + serialization = param_metadata.serialization + if serialization is not None: + serialized_params = _get_serialized_params( + param_metadata, f_name, param, path_param_field_types[name] + ) + for key, value in serialized_params.items(): + path_param_values[key] = value + else: + pp_vals: List[str] = [] + if param_metadata.style == "simple": + if isinstance(param, List): + for pp_val in param: + if pp_val is None: + continue + pp_vals.append(_val_to_string(pp_val)) + path_param_values[f_name] = ",".join(pp_vals) + elif isinstance(param, Dict): + for pp_key in param: + if param[pp_key] is None: + continue + if param_metadata.explode: + pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}") + else: + pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}") + path_param_values[f_name] = ",".join(pp_vals) + elif not isinstance(param, (str, int, float, complex, bool, Decimal)): + param_fields: Dict[str, FieldInfo] = param.__class__.model_fields + for name in param_fields: + param_field = param_fields[name] + + param_value_metadata = find_field_metadata( + param_field, PathParamMetadata + ) + if param_value_metadata is None: + continue + + param_name = ( + param_field.alias if param_field.alias is not None else name + ) + + param_field_val = getattr(param, name) + if param_field_val is None: + continue + if param_metadata.explode: + pp_vals.append( + f"{param_name}={_val_to_string(param_field_val)}" + ) + else: + pp_vals.append( + f"{param_name},{_val_to_string(param_field_val)}" + ) + path_param_values[f_name] = ",".join(pp_vals) + else: + path_param_values[f_name] = _val_to_string(param) + + return globals_already_populated + + +def is_optional(field): + return get_origin(field) is Union and type(None) in get_args(field) + + +def template_url(url_with_params: str, params: Dict[str, str]) -> str: + for key, value in params.items(): + url_with_params = url_with_params.replace("{" + key + "}", value) + + return url_with_params + + +def remove_suffix(input_string, suffix): + if suffix and input_string.endswith(suffix): + return input_string[: -len(suffix)] + return input_string diff --git a/document/src/epilot_document/utils/values.py b/document/src/epilot_document/utils/values.py new file mode 100644 index 000000000..24ccae3d0 --- /dev/null +++ b/document/src/epilot_document/utils/values.py @@ -0,0 +1,128 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from datetime import datetime +from enum import Enum +from email.message import Message +import os +from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union + +from httpx import Response +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .serializers import marshal_json + +from .metadata import ParamMetadata, find_field_metadata + + +def match_content_type(content_type: str, pattern: str) -> bool: + if pattern in (content_type, "*", "*/*"): + return True + + msg = Message() + msg["content-type"] = content_type + media_type = msg.get_content_type() + + if media_type == pattern: + return True + + parts = media_type.split("/") + if len(parts) == 2: + if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"): + return True + + return False + + +def match_status_codes(status_codes: List[str], status_code: int) -> bool: + if "default" in status_codes: + return True + + for code in status_codes: + if code == str(status_code): + return True + + if code.endswith("XX") and code.startswith(str(status_code)[:1]): + return True + return False + + +T = TypeVar("T") + + +def get_global_from_env( + value: Optional[T], env_key: str, type_cast: Callable[[str], T] +) -> Optional[T]: + if value is not None: + return value + env_value = os.getenv(env_key) + if env_value is not None: + try: + return type_cast(env_value) + except ValueError: + pass + return None + + +def match_response( + response: Response, code: Union[str, List[str]], content_type: str +) -> bool: + codes = code if isinstance(code, list) else [code] + return match_status_codes(codes, response.status_code) and match_content_type( + response.headers.get("content-type", "application/octet-stream"), content_type + ) + + +def _populate_from_globals( + param_name: str, value: Any, param_metadata_type: type, gbls: Any +) -> Tuple[Any, bool]: + if gbls is None: + return value, False + + if not isinstance(gbls, BaseModel): + raise TypeError("globals must be a pydantic model") + + global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields + found = False + for name in global_fields: + field = global_fields[name] + if name is not param_name: + continue + + found = True + + if value is not None: + return value, True + + global_value = getattr(gbls, name) + + param_metadata = find_field_metadata(field, param_metadata_type) + if param_metadata is None: + return value, True + + return global_value, True + + return value, found + + +def _val_to_string(val) -> str: + if isinstance(val, bool): + return str(val).lower() + if isinstance(val, datetime): + return str(val.isoformat().replace("+00:00", "Z")) + if isinstance(val, Enum): + return str(val.value) + + return str(val) + + +def _get_serialized_params( + metadata: ParamMetadata, field_name: str, obj: Any, typ: type +) -> Dict[str, str]: + params: Dict[str, str] = {} + + serialization = metadata.serialization + if serialization == "json": + params[field_name] = marshal_json(obj, typ) + + return params