stract-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. stract_api/__init__.py +141 -0
  2. stract_api/api/__init__.py +16 -0
  3. stract_api/api/account_api.py +1098 -0
  4. stract_api/api/account_credit_ledger_api.py +286 -0
  5. stract_api/api/api_key_api.py +286 -0
  6. stract_api/api/catalog_api.py +837 -0
  7. stract_api/api/credits_api.py +534 -0
  8. stract_api/api/document_api.py +2799 -0
  9. stract_api/api/field_api.py +1168 -0
  10. stract_api/api/job_api.py +2857 -0
  11. stract_api/api/job_document_api.py +575 -0
  12. stract_api/api/llm_model_api.py +286 -0
  13. stract_api/api/struct_api.py +837 -0
  14. stract_api/api/user_api.py +572 -0
  15. stract_api/api_client.py +866 -0
  16. stract_api/api_response.py +21 -0
  17. stract_api/configuration.py +655 -0
  18. stract_api/exceptions.py +219 -0
  19. stract_api/models/__init__.py +52 -0
  20. stract_api/models/account.py +130 -0
  21. stract_api/models/account_credit_cache.py +112 -0
  22. stract_api/models/account_credit_ledger.py +125 -0
  23. stract_api/models/account_user.py +104 -0
  24. stract_api/models/account_user_role.py +38 -0
  25. stract_api/models/api_key.py +102 -0
  26. stract_api/models/catalog.py +100 -0
  27. stract_api/models/create_account_user_request.py +97 -0
  28. stract_api/models/create_catalog_request.py +90 -0
  29. stract_api/models/create_field_request.py +102 -0
  30. stract_api/models/create_job_request.py +109 -0
  31. stract_api/models/create_struct_request.py +90 -0
  32. stract_api/models/deleted_document.py +91 -0
  33. stract_api/models/deleted_field.py +91 -0
  34. stract_api/models/document.py +107 -0
  35. stract_api/models/document_link.py +90 -0
  36. stract_api/models/document_processing_status.py +39 -0
  37. stract_api/models/document_text.py +95 -0
  38. stract_api/models/edit_account_request.py +90 -0
  39. stract_api/models/edit_field_request.py +102 -0
  40. stract_api/models/edit_my_user_request.py +92 -0
  41. stract_api/models/field_type.py +42 -0
  42. stract_api/models/job.py +129 -0
  43. stract_api/models/job_document.py +123 -0
  44. stract_api/models/job_output.py +98 -0
  45. stract_api/models/job_output_record.py +103 -0
  46. stract_api/models/job_status.py +41 -0
  47. stract_api/models/llm_model.py +126 -0
  48. stract_api/models/login_request.py +92 -0
  49. stract_api/models/login_response.py +90 -0
  50. stract_api/models/model_field.py +110 -0
  51. stract_api/models/struct.py +100 -0
  52. stract_api/models/sync_text_job_request.py +118 -0
  53. stract_api/models/upload_text_document_request.py +93 -0
  54. stract_api/models/user.py +102 -0
  55. stract_api/py.typed +0 -0
  56. stract_api/rest.py +335 -0
  57. stract_api-0.1.0.dist-info/METADATA +266 -0
  58. stract_api-0.1.0.dist-info/RECORD +61 -0
  59. stract_api-0.1.0.dist-info/WHEEL +5 -0
  60. stract_api-0.1.0.dist-info/licenses/LICENSE +21 -0
  61. stract_api-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,219 @@
1
+ """
2
+ Stract API
3
+
4
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
5
+
6
+ The version of the OpenAPI document: 0.9.4
7
+ Contact: matt@stract-api.com
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """ # noqa: E501
12
+
13
+
14
+ from typing import Any, Optional
15
+ from typing_extensions import Self
16
+
17
+ class OpenApiException(Exception):
18
+ """The base exception class for all OpenAPIExceptions"""
19
+
20
+
21
+ class ApiTypeError(OpenApiException, TypeError):
22
+ def __init__(self, msg, path_to_item=None, valid_classes=None,
23
+ key_type=None) -> None:
24
+ """ Raises an exception for TypeErrors
25
+
26
+ Args:
27
+ msg (str): the exception message
28
+
29
+ Keyword Args:
30
+ path_to_item (list): a list of keys an indices to get to the
31
+ current_item
32
+ None if unset
33
+ valid_classes (tuple): the primitive classes that current item
34
+ should be an instance of
35
+ None if unset
36
+ key_type (bool): False if our value is a value in a dict
37
+ True if it is a key in a dict
38
+ False if our item is an item in a list
39
+ None if unset
40
+ """
41
+ self.path_to_item = path_to_item
42
+ self.valid_classes = valid_classes
43
+ self.key_type = key_type
44
+ full_msg = msg
45
+ if path_to_item:
46
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
47
+ super(ApiTypeError, self).__init__(full_msg)
48
+
49
+
50
+ class ApiValueError(OpenApiException, ValueError):
51
+ def __init__(self, msg, path_to_item=None) -> None:
52
+ """
53
+ Args:
54
+ msg (str): the exception message
55
+
56
+ Keyword Args:
57
+ path_to_item (list) the path to the exception in the
58
+ received_data dict. None if unset
59
+ """
60
+
61
+ self.path_to_item = path_to_item
62
+ full_msg = msg
63
+ if path_to_item:
64
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
65
+ super(ApiValueError, self).__init__(full_msg)
66
+
67
+
68
+ class ApiAttributeError(OpenApiException, AttributeError):
69
+ def __init__(self, msg, path_to_item=None) -> None:
70
+ """
71
+ Raised when an attribute reference or assignment fails.
72
+
73
+ Args:
74
+ msg (str): the exception message
75
+
76
+ Keyword Args:
77
+ path_to_item (None/list) the path to the exception in the
78
+ received_data dict
79
+ """
80
+ self.path_to_item = path_to_item
81
+ full_msg = msg
82
+ if path_to_item:
83
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
84
+ super(ApiAttributeError, self).__init__(full_msg)
85
+
86
+
87
+ class ApiKeyError(OpenApiException, KeyError):
88
+ def __init__(self, msg, path_to_item=None) -> None:
89
+ """
90
+ Args:
91
+ msg (str): the exception message
92
+
93
+ Keyword Args:
94
+ path_to_item (None/list) the path to the exception in the
95
+ received_data dict
96
+ """
97
+ self.path_to_item = path_to_item
98
+ full_msg = msg
99
+ if path_to_item:
100
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
101
+ super(ApiKeyError, self).__init__(full_msg)
102
+
103
+
104
+ class ApiException(OpenApiException):
105
+
106
+ def __init__(
107
+ self,
108
+ status=None,
109
+ reason=None,
110
+ http_resp=None,
111
+ *,
112
+ body: Optional[str] = None,
113
+ data: Optional[Any] = None,
114
+ ) -> None:
115
+ self.status = status
116
+ self.reason = reason
117
+ self.body = body
118
+ self.data = data
119
+ self.headers = None
120
+
121
+ if http_resp:
122
+ if self.status is None:
123
+ self.status = http_resp.status
124
+ if self.reason is None:
125
+ self.reason = http_resp.reason
126
+ if self.body is None:
127
+ try:
128
+ self.body = http_resp.data.decode('utf-8')
129
+ except Exception:
130
+ pass
131
+ self.headers = http_resp.headers
132
+
133
+ @classmethod
134
+ def from_response(
135
+ cls,
136
+ *,
137
+ http_resp,
138
+ body: Optional[str],
139
+ data: Optional[Any],
140
+ ) -> Self:
141
+ if http_resp.status == 400:
142
+ raise BadRequestException(http_resp=http_resp, body=body, data=data)
143
+
144
+ if http_resp.status == 401:
145
+ raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
146
+
147
+ if http_resp.status == 403:
148
+ raise ForbiddenException(http_resp=http_resp, body=body, data=data)
149
+
150
+ if http_resp.status == 404:
151
+ raise NotFoundException(http_resp=http_resp, body=body, data=data)
152
+
153
+ # Added new conditions for 409 and 422
154
+ if http_resp.status == 409:
155
+ raise ConflictException(http_resp=http_resp, body=body, data=data)
156
+
157
+ if http_resp.status == 422:
158
+ raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data)
159
+
160
+ if 500 <= http_resp.status <= 599:
161
+ raise ServiceException(http_resp=http_resp, body=body, data=data)
162
+ raise ApiException(http_resp=http_resp, body=body, data=data)
163
+
164
+ def __str__(self):
165
+ """Custom error messages for exception"""
166
+ error_message = "({0})\n"\
167
+ "Reason: {1}\n".format(self.status, self.reason)
168
+ if self.headers:
169
+ error_message += "HTTP response headers: {0}\n".format(
170
+ self.headers)
171
+
172
+ if self.body:
173
+ error_message += "HTTP response body: {0}\n".format(self.body)
174
+
175
+ if self.data:
176
+ error_message += "HTTP response data: {0}\n".format(self.data)
177
+
178
+ return error_message
179
+
180
+
181
+ class BadRequestException(ApiException):
182
+ pass
183
+
184
+
185
+ class NotFoundException(ApiException):
186
+ pass
187
+
188
+
189
+ class UnauthorizedException(ApiException):
190
+ pass
191
+
192
+
193
+ class ForbiddenException(ApiException):
194
+ pass
195
+
196
+
197
+ class ServiceException(ApiException):
198
+ pass
199
+
200
+
201
+ class ConflictException(ApiException):
202
+ """Exception for HTTP 409 Conflict."""
203
+ pass
204
+
205
+
206
+ class UnprocessableEntityException(ApiException):
207
+ """Exception for HTTP 422 Unprocessable Entity."""
208
+ pass
209
+
210
+
211
+ def render_path(path_to_item):
212
+ """Returns a string representation of a path"""
213
+ result = ""
214
+ for pth in path_to_item:
215
+ if isinstance(pth, int):
216
+ result += "[{0}]".format(pth)
217
+ else:
218
+ result += "['{0}']".format(pth)
219
+ return result
@@ -0,0 +1,52 @@
1
+ # coding: utf-8
2
+
3
+ # flake8: noqa
4
+ """
5
+ Stract API
6
+
7
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
8
+
9
+ The version of the OpenAPI document: 0.9.4
10
+ Contact: matt@stract-api.com
11
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
12
+
13
+ Do not edit the class manually.
14
+ """ # noqa: E501
15
+
16
+ # import models into model package
17
+ from stract_api.models.account import Account
18
+ from stract_api.models.account_credit_cache import AccountCreditCache
19
+ from stract_api.models.account_credit_ledger import AccountCreditLedger
20
+ from stract_api.models.account_user import AccountUser
21
+ from stract_api.models.account_user_role import AccountUserRole
22
+ from stract_api.models.api_key import ApiKey
23
+ from stract_api.models.catalog import Catalog
24
+ from stract_api.models.create_account_user_request import CreateAccountUserRequest
25
+ from stract_api.models.create_catalog_request import CreateCatalogRequest
26
+ from stract_api.models.create_field_request import CreateFieldRequest
27
+ from stract_api.models.create_job_request import CreateJobRequest
28
+ from stract_api.models.create_struct_request import CreateStructRequest
29
+ from stract_api.models.deleted_document import DeletedDocument
30
+ from stract_api.models.deleted_field import DeletedField
31
+ from stract_api.models.document import Document
32
+ from stract_api.models.document_link import DocumentLink
33
+ from stract_api.models.document_processing_status import DocumentProcessingStatus
34
+ from stract_api.models.document_text import DocumentText
35
+ from stract_api.models.edit_account_request import EditAccountRequest
36
+ from stract_api.models.edit_field_request import EditFieldRequest
37
+ from stract_api.models.edit_my_user_request import EditMyUserRequest
38
+ from stract_api.models.field_type import FieldType
39
+ from stract_api.models.job import Job
40
+ from stract_api.models.job_document import JobDocument
41
+ from stract_api.models.job_output import JobOutput
42
+ from stract_api.models.job_output_record import JobOutputRecord
43
+ from stract_api.models.job_status import JobStatus
44
+ from stract_api.models.llm_model import LlmModel
45
+ from stract_api.models.login_request import LoginRequest
46
+ from stract_api.models.login_response import LoginResponse
47
+ from stract_api.models.model_field import ModelField
48
+ from stract_api.models.struct import Struct
49
+ from stract_api.models.sync_text_job_request import SyncTextJobRequest
50
+ from stract_api.models.upload_text_document_request import UploadTextDocumentRequest
51
+ from stract_api.models.user import User
52
+
@@ -0,0 +1,130 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Stract API
5
+
6
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
7
+
8
+ The version of the OpenAPI document: 0.9.4
9
+ Contact: matt@stract-api.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import pprint
18
+ import re # noqa: F401
19
+ import json
20
+
21
+ from datetime import date, datetime
22
+ from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
23
+ from typing import Any, ClassVar, Dict, List, Optional
24
+ from uuid import UUID
25
+ from stract_api.models.account_user_role import AccountUserRole
26
+ from typing import Optional, Set
27
+ from typing_extensions import Self
28
+ from pydantic_core import to_jsonable_python
29
+ from pydantic import field_validator as _coerce_field_validator
30
+
31
+ class Account(BaseModel):
32
+ """
33
+ Account
34
+ """ # noqa: E501
35
+ id: UUID = Field(description="Unique identifier of the account")
36
+ name: StrictStr = Field(description="Name of the account")
37
+ date_created: date = Field(description="Date when the account was created")
38
+ account_user_role: AccountUserRole
39
+ subscription_type: Optional[StrictStr] = Field(description="The account's active subscription type, or null if the account has no active subscription")
40
+ subscription_dt_started: Optional[datetime] = Field(description="Timestamp when the account's active subscription started, or null if the account has no active subscription")
41
+ subscription_billing_period_end: Optional[datetime] = Field(description="Timestamp when the account's current subscription billing period ends, or null if the account has no active subscription")
42
+ __properties: ClassVar[List[str]] = ["id", "name", "date_created", "account_user_role", "subscription_type", "subscription_dt_started", "subscription_billing_period_end"]
43
+
44
+ @field_validator('subscription_type')
45
+ def subscription_type_validate_enum(cls, value):
46
+ """Validates the enum"""
47
+ if value is None:
48
+ return value
49
+
50
+ if value not in set(['team', 'enterprise']):
51
+ raise ValueError("must be one of enum values ('team', 'enterprise')")
52
+ return value
53
+
54
+ model_config = ConfigDict(
55
+ validate_by_name=True,
56
+ validate_by_alias=True,
57
+ validate_assignment=True,
58
+ protected_namespaces=(),
59
+ )
60
+
61
+
62
+ def to_str(self) -> str:
63
+ """Returns the string representation of the model using alias"""
64
+ return pprint.pformat(self.model_dump(by_alias=True))
65
+
66
+ def to_json(self) -> str:
67
+ """Returns the JSON representation of the model using alias"""
68
+ return json.dumps(to_jsonable_python(self.to_dict()))
69
+
70
+ @classmethod
71
+ def from_json(cls, json_str: str) -> Optional[Self]:
72
+ """Create an instance of Account from a JSON string"""
73
+ return cls.from_dict(json.loads(json_str))
74
+
75
+ def to_dict(self) -> Dict[str, Any]:
76
+ """Return the dictionary representation of the model using alias.
77
+
78
+ This has the following differences from calling pydantic's
79
+ `self.model_dump(by_alias=True)`:
80
+
81
+ * `None` is only added to the output dict for nullable fields that
82
+ were set at model initialization. Other fields with value `None`
83
+ are ignored.
84
+ """
85
+ excluded_fields: Set[str] = set([
86
+ ])
87
+
88
+ _dict = self.model_dump(
89
+ by_alias=True,
90
+ exclude=excluded_fields,
91
+ exclude_none=True,
92
+ )
93
+ # set to None if subscription_type (nullable) is None
94
+ # and model_fields_set contains the field
95
+ if self.subscription_type is None and "subscription_type" in self.model_fields_set:
96
+ _dict['subscription_type'] = None
97
+
98
+ # set to None if subscription_dt_started (nullable) is None
99
+ # and model_fields_set contains the field
100
+ if self.subscription_dt_started is None and "subscription_dt_started" in self.model_fields_set:
101
+ _dict['subscription_dt_started'] = None
102
+
103
+ # set to None if subscription_billing_period_end (nullable) is None
104
+ # and model_fields_set contains the field
105
+ if self.subscription_billing_period_end is None and "subscription_billing_period_end" in self.model_fields_set:
106
+ _dict['subscription_billing_period_end'] = None
107
+
108
+ return _dict
109
+
110
+ @classmethod
111
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
112
+ """Create an instance of Account from a dict"""
113
+ if obj is None:
114
+ return None
115
+
116
+ if not isinstance(obj, dict):
117
+ return cls.model_validate(obj)
118
+
119
+ _obj = cls.model_validate({
120
+ "id": obj.get("id"),
121
+ "name": obj.get("name"),
122
+ "date_created": obj.get("date_created"),
123
+ "account_user_role": obj.get("account_user_role"),
124
+ "subscription_type": obj.get("subscription_type"),
125
+ "subscription_dt_started": obj.get("subscription_dt_started"),
126
+ "subscription_billing_period_end": obj.get("subscription_billing_period_end")
127
+ })
128
+ return _obj
129
+
130
+
@@ -0,0 +1,112 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Stract API
5
+
6
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
7
+
8
+ The version of the OpenAPI document: 0.9.4
9
+ Contact: matt@stract-api.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import pprint
18
+ import re # noqa: F401
19
+ import json
20
+
21
+ from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt
22
+ from typing import Any, ClassVar, Dict, List, Optional, Union
23
+ from uuid import UUID
24
+ from typing import Optional, Set
25
+ from typing_extensions import Self
26
+ from pydantic_core import to_jsonable_python
27
+ from pydantic import field_validator as _coerce_field_validator
28
+
29
+ class AccountCreditCache(BaseModel):
30
+ """
31
+ AccountCreditCache
32
+ """ # noqa: E501
33
+ id: UUID = Field(description="Unique identifier of the account credit balance")
34
+ account_id: UUID = Field(description="ID of the account this credit balance belongs to")
35
+ suser_id: Optional[UUID] = Field(description="ID of the user this credit balance belongs to, or null if it is the organization credit balance")
36
+ cached_balance: Union[StrictFloat, StrictInt] = Field(description="Credit balance for the account", json_schema_extra={"examples": [42]})
37
+ __properties: ClassVar[List[str]] = ["id", "account_id", "suser_id", "cached_balance"]
38
+
39
+ @_coerce_field_validator('cached_balance', mode="before")
40
+ def cached_balance_coerce_numeric_string(cls, value):
41
+ """The API sends numbers as strings (e.g. '29532'); convert them before strict validation"""
42
+ if isinstance(value, str):
43
+ try:
44
+ return int(value)
45
+ except ValueError:
46
+ return float(value)
47
+ return value
48
+
49
+ model_config = ConfigDict(
50
+ validate_by_name=True,
51
+ validate_by_alias=True,
52
+ validate_assignment=True,
53
+ protected_namespaces=(),
54
+ )
55
+
56
+
57
+ def to_str(self) -> str:
58
+ """Returns the string representation of the model using alias"""
59
+ return pprint.pformat(self.model_dump(by_alias=True))
60
+
61
+ def to_json(self) -> str:
62
+ """Returns the JSON representation of the model using alias"""
63
+ return json.dumps(to_jsonable_python(self.to_dict()))
64
+
65
+ @classmethod
66
+ def from_json(cls, json_str: str) -> Optional[Self]:
67
+ """Create an instance of AccountCreditCache from a JSON string"""
68
+ return cls.from_dict(json.loads(json_str))
69
+
70
+ def to_dict(self) -> Dict[str, Any]:
71
+ """Return the dictionary representation of the model using alias.
72
+
73
+ This has the following differences from calling pydantic's
74
+ `self.model_dump(by_alias=True)`:
75
+
76
+ * `None` is only added to the output dict for nullable fields that
77
+ were set at model initialization. Other fields with value `None`
78
+ are ignored.
79
+ """
80
+ excluded_fields: Set[str] = set([
81
+ ])
82
+
83
+ _dict = self.model_dump(
84
+ by_alias=True,
85
+ exclude=excluded_fields,
86
+ exclude_none=True,
87
+ )
88
+ # set to None if suser_id (nullable) is None
89
+ # and model_fields_set contains the field
90
+ if self.suser_id is None and "suser_id" in self.model_fields_set:
91
+ _dict['suser_id'] = None
92
+
93
+ return _dict
94
+
95
+ @classmethod
96
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
97
+ """Create an instance of AccountCreditCache from a dict"""
98
+ if obj is None:
99
+ return None
100
+
101
+ if not isinstance(obj, dict):
102
+ return cls.model_validate(obj)
103
+
104
+ _obj = cls.model_validate({
105
+ "id": obj.get("id"),
106
+ "account_id": obj.get("account_id"),
107
+ "suser_id": obj.get("suser_id"),
108
+ "cached_balance": obj.get("cached_balance")
109
+ })
110
+ return _obj
111
+
112
+
@@ -0,0 +1,125 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Stract API
5
+
6
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
7
+
8
+ The version of the OpenAPI document: 0.9.4
9
+ Contact: matt@stract-api.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ from __future__ import annotations
17
+ import pprint
18
+ import re # noqa: F401
19
+ import json
20
+
21
+ from datetime import datetime
22
+ from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
23
+ from typing import Any, ClassVar, Dict, List, Optional, Union
24
+ from uuid import UUID
25
+ from typing import Optional, Set
26
+ from typing_extensions import Self
27
+ from pydantic_core import to_jsonable_python
28
+ from pydantic import field_validator as _coerce_field_validator
29
+
30
+ class AccountCreditLedger(BaseModel):
31
+ """
32
+ AccountCreditLedger
33
+ """ # noqa: E501
34
+ id: UUID = Field(description="Unique identifier of the ledger entry")
35
+ account_id: UUID = Field(description="ID of the account this ledger entry belongs to")
36
+ suser_id: Optional[UUID] = Field(description="ID of the user account that was charged or null if charged to the organization account")
37
+ spending_suser_id: UUID = Field(description="ID of the user who performed the action that created this ledger entry")
38
+ amount: Union[StrictFloat, StrictInt] = Field(description="Change in credits for this entry (negative for credits spent, positive for credits added)", json_schema_extra={"examples": [42]})
39
+ created_at: datetime = Field(description="Timestamp when the ledger entry was created")
40
+ type: StrictStr = Field(description="The kind of activity that produced this ledger entry")
41
+ reference_id: StrictStr = Field(description="ID of the object (found in reference_table) that this ledger entry relates to")
42
+ reference_table: Optional[StrictStr] = Field(default=None, description="Object type where reference_id can be found")
43
+ idempotency_key: StrictStr = Field(description="Unique key used to prevent duplicate ledger entries")
44
+ __properties: ClassVar[List[str]] = ["id", "account_id", "suser_id", "spending_suser_id", "amount", "created_at", "type", "reference_id", "reference_table", "idempotency_key"]
45
+
46
+ @_coerce_field_validator('amount', mode="before")
47
+ def amount_coerce_numeric_string(cls, value):
48
+ """The API sends numbers as strings (e.g. '29532'); convert them before strict validation"""
49
+ if isinstance(value, str):
50
+ try:
51
+ return int(value)
52
+ except ValueError:
53
+ return float(value)
54
+ return value
55
+
56
+ model_config = ConfigDict(
57
+ validate_by_name=True,
58
+ validate_by_alias=True,
59
+ validate_assignment=True,
60
+ protected_namespaces=(),
61
+ )
62
+
63
+
64
+ def to_str(self) -> str:
65
+ """Returns the string representation of the model using alias"""
66
+ return pprint.pformat(self.model_dump(by_alias=True))
67
+
68
+ def to_json(self) -> str:
69
+ """Returns the JSON representation of the model using alias"""
70
+ return json.dumps(to_jsonable_python(self.to_dict()))
71
+
72
+ @classmethod
73
+ def from_json(cls, json_str: str) -> Optional[Self]:
74
+ """Create an instance of AccountCreditLedger from a JSON string"""
75
+ return cls.from_dict(json.loads(json_str))
76
+
77
+ def to_dict(self) -> Dict[str, Any]:
78
+ """Return the dictionary representation of the model using alias.
79
+
80
+ This has the following differences from calling pydantic's
81
+ `self.model_dump(by_alias=True)`:
82
+
83
+ * `None` is only added to the output dict for nullable fields that
84
+ were set at model initialization. Other fields with value `None`
85
+ are ignored.
86
+ """
87
+ excluded_fields: Set[str] = set([
88
+ ])
89
+
90
+ _dict = self.model_dump(
91
+ by_alias=True,
92
+ exclude=excluded_fields,
93
+ exclude_none=True,
94
+ )
95
+ # set to None if suser_id (nullable) is None
96
+ # and model_fields_set contains the field
97
+ if self.suser_id is None and "suser_id" in self.model_fields_set:
98
+ _dict['suser_id'] = None
99
+
100
+ return _dict
101
+
102
+ @classmethod
103
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
104
+ """Create an instance of AccountCreditLedger from a dict"""
105
+ if obj is None:
106
+ return None
107
+
108
+ if not isinstance(obj, dict):
109
+ return cls.model_validate(obj)
110
+
111
+ _obj = cls.model_validate({
112
+ "id": obj.get("id"),
113
+ "account_id": obj.get("account_id"),
114
+ "suser_id": obj.get("suser_id"),
115
+ "spending_suser_id": obj.get("spending_suser_id"),
116
+ "amount": obj.get("amount"),
117
+ "created_at": obj.get("created_at"),
118
+ "type": obj.get("type"),
119
+ "reference_id": obj.get("reference_id"),
120
+ "reference_table": obj.get("reference_table"),
121
+ "idempotency_key": obj.get("idempotency_key")
122
+ })
123
+ return _obj
124
+
125
+