koichi12 commited on
Commit
2cbac61
·
verified ·
1 Parent(s): 1f6807a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__init__.py +40 -0
  2. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-311.pyc +0 -0
  3. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-311.pyc +0 -0
  4. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_async_client.cpython-311.pyc +0 -0
  5. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client.cpython-311.pyc +0 -0
  6. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client_config.cpython-311.pyc +0 -0
  7. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-311.pyc +0 -0
  8. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers.cpython-311.pyc +0 -0
  9. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_async.cpython-311.pyc +0 -0
  10. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_base.cpython-311.pyc +0 -0
  11. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_base_client.py +370 -0
  12. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client.py +378 -0
  13. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__init__.py +39 -0
  14. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/__init__.cpython-311.pyc +0 -0
  15. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/base.cpython-311.pyc +0 -0
  16. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest.cpython-311.pyc +0 -0
  17. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-311.pyc +0 -0
  18. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/base.py +282 -0
  19. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest.py +473 -0
  20. .venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest_asyncio.py +560 -0
  21. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/answer.cpython-311.pyc +0 -0
  22. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/caching.cpython-311.pyc +0 -0
  23. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/embedding.cpython-311.pyc +0 -0
  24. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/operations.cpython-311.pyc +0 -0
  25. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/permission.cpython-311.pyc +0 -0
  26. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/retriever.cpython-311.pyc +0 -0
  27. .venv/lib/python3.11/site-packages/google/generativeai/__pycache__/version.cpython-311.pyc +0 -0
  28. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/__init__.cpython-311.pyc +0 -0
  29. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/argument_parser.cpython-311.pyc +0 -0
  30. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/cmd_line_parser.cpython-311.pyc +0 -0
  31. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/command_utils.cpython-311.pyc +0 -0
  32. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/compile_cmd.cpython-311.pyc +0 -0
  33. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/gspread_client.cpython-311.pyc +0 -0
  34. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/html_utils.cpython-311.pyc +0 -0
  35. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/ipython_env.cpython-311.pyc +0 -0
  36. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/ipython_env_impl.cpython-311.pyc +0 -0
  37. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/magics.cpython-311.pyc +0 -0
  38. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/model_registry.cpython-311.pyc +0 -0
  39. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/output_utils.cpython-311.pyc +0 -0
  40. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/post_process_utils.cpython-311.pyc +0 -0
  41. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/post_process_utils_test_helper.cpython-311.pyc +0 -0
  42. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/py_utils.cpython-311.pyc +0 -0
  43. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/sheets_sanitize_url.cpython-311.pyc +0 -0
  44. .venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/text_model.cpython-311.pyc +0 -0
  45. .venv/lib/python3.11/site-packages/google/generativeai/notebook/argument_parser.py +112 -0
  46. .venv/lib/python3.11/site-packages/google/generativeai/notebook/command_utils.py +164 -0
  47. .venv/lib/python3.11/site-packages/google/generativeai/notebook/ipython_env.py +49 -0
  48. .venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__init__.py +14 -0
  49. .venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__pycache__/__init__.cpython-311.pyc +0 -0
  50. .venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__pycache__/llm_function.cpython-311.pyc +0 -0
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__init__.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Package for interacting with the google.longrunning.operations meta-API."""
16
+
17
+ from google.api_core.operations_v1.abstract_operations_client import AbstractOperationsClient
18
+ from google.api_core.operations_v1.operations_async_client import OperationsAsyncClient
19
+ from google.api_core.operations_v1.operations_client import OperationsClient
20
+ from google.api_core.operations_v1.transports.rest import OperationsRestTransport
21
+
22
+ __all__ = [
23
+ "AbstractOperationsClient",
24
+ "OperationsAsyncClient",
25
+ "OperationsClient",
26
+ "OperationsRestTransport"
27
+ ]
28
+
29
+ try:
30
+ from google.api_core.operations_v1.transports.rest_asyncio import (
31
+ AsyncOperationsRestTransport,
32
+ )
33
+ from google.api_core.operations_v1.operations_rest_client_async import AsyncOperationsRestClient
34
+
35
+ __all__ += ["AsyncOperationsRestClient", "AsyncOperationsRestTransport"]
36
+ except ImportError:
37
+ # This import requires the `async_rest` extra.
38
+ # Don't raise an exception if `AsyncOperationsRestTransport` cannot be imported
39
+ # as other transports are still available.
40
+ pass
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-311.pyc ADDED
Binary file (16.9 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-311.pyc ADDED
Binary file (16.2 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_async_client.cpython-311.pyc ADDED
Binary file (14.9 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client.cpython-311.pyc ADDED
Binary file (15.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_client_config.cpython-311.pyc ADDED
Binary file (1.08 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-311.pyc ADDED
Binary file (14 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers.cpython-311.pyc ADDED
Binary file (3.19 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_async.cpython-311.pyc ADDED
Binary file (3.55 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/__pycache__/pagers_base.cpython-311.pyc ADDED
Binary file (3.16 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/abstract_operations_base_client.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2024 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from collections import OrderedDict
17
+ import os
18
+ import re
19
+ from typing import Dict, Optional, Type, Union
20
+
21
+ from google.api_core import client_options as client_options_lib # type: ignore
22
+ from google.api_core import gapic_v1 # type: ignore
23
+ from google.api_core.operations_v1.transports.base import (
24
+ DEFAULT_CLIENT_INFO,
25
+ OperationsTransport,
26
+ )
27
+ from google.api_core.operations_v1.transports.rest import OperationsRestTransport
28
+
29
+ try:
30
+ from google.api_core.operations_v1.transports.rest_asyncio import (
31
+ AsyncOperationsRestTransport,
32
+ )
33
+
34
+ HAS_ASYNC_REST_DEPENDENCIES = True
35
+ except ImportError as e:
36
+ HAS_ASYNC_REST_DEPENDENCIES = False
37
+ ASYNC_REST_EXCEPTION = e
38
+
39
+ from google.auth import credentials as ga_credentials # type: ignore
40
+ from google.auth.exceptions import MutualTLSChannelError # type: ignore
41
+ from google.auth.transport import mtls # type: ignore
42
+
43
+
44
+ class AbstractOperationsBaseClientMeta(type):
45
+ """Metaclass for the Operations Base client.
46
+
47
+ This provides base class-level methods for building and retrieving
48
+ support objects (e.g. transport) without polluting the client instance
49
+ objects.
50
+ """
51
+
52
+ _transport_registry = OrderedDict() # type: Dict[str, Type[OperationsTransport]]
53
+ _transport_registry["rest"] = OperationsRestTransport
54
+ if HAS_ASYNC_REST_DEPENDENCIES:
55
+ _transport_registry["rest_asyncio"] = AsyncOperationsRestTransport
56
+
57
+ def get_transport_class(
58
+ cls,
59
+ label: Optional[str] = None,
60
+ ) -> Type[OperationsTransport]:
61
+ """Returns an appropriate transport class.
62
+
63
+ Args:
64
+ label: The name of the desired transport. If none is
65
+ provided, then the first transport in the registry is used.
66
+
67
+ Returns:
68
+ The transport class to use.
69
+ """
70
+ # If a specific transport is requested, return that one.
71
+ if (
72
+ label == "rest_asyncio" and not HAS_ASYNC_REST_DEPENDENCIES
73
+ ): # pragma: NO COVER
74
+ raise ASYNC_REST_EXCEPTION
75
+
76
+ if label:
77
+ return cls._transport_registry[label]
78
+
79
+ # No transport is requested; return the default (that is, the first one
80
+ # in the dictionary).
81
+ return next(iter(cls._transport_registry.values()))
82
+
83
+
84
+ class AbstractOperationsBaseClient(metaclass=AbstractOperationsBaseClientMeta):
85
+ """Manages long-running operations with an API service.
86
+
87
+ When an API method normally takes long time to complete, it can be
88
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
89
+ client, and the client can use this interface to receive the real
90
+ response asynchronously by polling the operation resource, or pass
91
+ the operation resource to another API (such as Google Cloud Pub/Sub
92
+ API) to receive the response. Any API service that returns
93
+ long-running operations should implement the ``Operations``
94
+ interface so developers can have a consistent client experience.
95
+ """
96
+
97
+ @staticmethod
98
+ def _get_default_mtls_endpoint(api_endpoint):
99
+ """Converts api endpoint to mTLS endpoint.
100
+
101
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
102
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
103
+ Args:
104
+ api_endpoint (Optional[str]): the api endpoint to convert.
105
+ Returns:
106
+ str: converted mTLS api endpoint.
107
+ """
108
+ if not api_endpoint:
109
+ return api_endpoint
110
+
111
+ mtls_endpoint_re = re.compile(
112
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
113
+ )
114
+
115
+ m = mtls_endpoint_re.match(api_endpoint)
116
+ name, mtls, sandbox, googledomain = m.groups()
117
+ if mtls or not googledomain:
118
+ return api_endpoint
119
+
120
+ if sandbox:
121
+ return api_endpoint.replace(
122
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
123
+ )
124
+
125
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
126
+
127
+ DEFAULT_ENDPOINT = "longrunning.googleapis.com"
128
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
129
+ DEFAULT_ENDPOINT
130
+ )
131
+
132
+ @classmethod
133
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
134
+ """
135
+ This class method should be overridden by the subclasses.
136
+
137
+ Args:
138
+ info (dict): The service account private key info.
139
+ args: Additional arguments to pass to the constructor.
140
+ kwargs: Additional arguments to pass to the constructor.
141
+
142
+ Raises:
143
+ NotImplementedError: If the method is called on the base class.
144
+ """
145
+ raise NotImplementedError("`from_service_account_info` is not implemented.")
146
+
147
+ @classmethod
148
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
149
+ """
150
+ This class method should be overridden by the subclasses.
151
+
152
+ Args:
153
+ filename (str): The path to the service account private key json
154
+ file.
155
+ args: Additional arguments to pass to the constructor.
156
+ kwargs: Additional arguments to pass to the constructor.
157
+
158
+ Raises:
159
+ NotImplementedError: If the method is called on the base class.
160
+ """
161
+ raise NotImplementedError("`from_service_account_file` is not implemented.")
162
+
163
+ from_service_account_json = from_service_account_file
164
+
165
+ @property
166
+ def transport(self) -> OperationsTransport:
167
+ """Returns the transport used by the client instance.
168
+
169
+ Returns:
170
+ OperationsTransport: The transport used by the client
171
+ instance.
172
+ """
173
+ return self._transport
174
+
175
+ @staticmethod
176
+ def common_billing_account_path(
177
+ billing_account: str,
178
+ ) -> str:
179
+ """Returns a fully-qualified billing_account string."""
180
+ return "billingAccounts/{billing_account}".format(
181
+ billing_account=billing_account,
182
+ )
183
+
184
+ @staticmethod
185
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
186
+ """Parse a billing_account path into its component segments."""
187
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
188
+ return m.groupdict() if m else {}
189
+
190
+ @staticmethod
191
+ def common_folder_path(
192
+ folder: str,
193
+ ) -> str:
194
+ """Returns a fully-qualified folder string."""
195
+ return "folders/{folder}".format(
196
+ folder=folder,
197
+ )
198
+
199
+ @staticmethod
200
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
201
+ """Parse a folder path into its component segments."""
202
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
203
+ return m.groupdict() if m else {}
204
+
205
+ @staticmethod
206
+ def common_organization_path(
207
+ organization: str,
208
+ ) -> str:
209
+ """Returns a fully-qualified organization string."""
210
+ return "organizations/{organization}".format(
211
+ organization=organization,
212
+ )
213
+
214
+ @staticmethod
215
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
216
+ """Parse a organization path into its component segments."""
217
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
218
+ return m.groupdict() if m else {}
219
+
220
+ @staticmethod
221
+ def common_project_path(
222
+ project: str,
223
+ ) -> str:
224
+ """Returns a fully-qualified project string."""
225
+ return "projects/{project}".format(
226
+ project=project,
227
+ )
228
+
229
+ @staticmethod
230
+ def parse_common_project_path(path: str) -> Dict[str, str]:
231
+ """Parse a project path into its component segments."""
232
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
233
+ return m.groupdict() if m else {}
234
+
235
+ @staticmethod
236
+ def common_location_path(
237
+ project: str,
238
+ location: str,
239
+ ) -> str:
240
+ """Returns a fully-qualified location string."""
241
+ return "projects/{project}/locations/{location}".format(
242
+ project=project,
243
+ location=location,
244
+ )
245
+
246
+ @staticmethod
247
+ def parse_common_location_path(path: str) -> Dict[str, str]:
248
+ """Parse a location path into its component segments."""
249
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
250
+ return m.groupdict() if m else {}
251
+
252
+ def __init__(
253
+ self,
254
+ *,
255
+ credentials: Optional[ga_credentials.Credentials] = None,
256
+ transport: Union[str, OperationsTransport, None] = None,
257
+ client_options: Optional[client_options_lib.ClientOptions] = None,
258
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
259
+ ) -> None:
260
+ """Instantiates the operations client.
261
+
262
+ Args:
263
+ credentials (Optional[google.auth.credentials.Credentials]): The
264
+ authorization credentials to attach to requests. These
265
+ credentials identify the application to the service; if none
266
+ are specified, the client will attempt to ascertain the
267
+ credentials from the environment.
268
+ transport (Union[str, OperationsTransport]): The
269
+ transport to use. If set to None, a transport is chosen
270
+ automatically.
271
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
272
+ client. It won't take effect if a ``transport`` instance is provided.
273
+ (1) The ``api_endpoint`` property can be used to override the
274
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
275
+ environment variable can also be used to override the endpoint:
276
+ "always" (always use the default mTLS endpoint), "never" (always
277
+ use the default regular endpoint) and "auto" (auto switch to the
278
+ default mTLS endpoint if client certificate is present, this is
279
+ the default value). However, the ``api_endpoint`` property takes
280
+ precedence if provided.
281
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
282
+ is "true", then the ``client_cert_source`` property can be used
283
+ to provide client certificate for mutual TLS transport. If
284
+ not provided, the default SSL client certificate will be used if
285
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
286
+ set, no client certificate will be used.
287
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
288
+ The client info used to send a user-agent string along with
289
+ API requests. If ``None``, then default info will be used.
290
+ Generally, you only need to set this if you're developing
291
+ your own client library.
292
+
293
+ Raises:
294
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
295
+ creation failed for any reason.
296
+ """
297
+ if isinstance(client_options, dict):
298
+ client_options = client_options_lib.from_dict(client_options)
299
+ if client_options is None:
300
+ client_options = client_options_lib.ClientOptions()
301
+
302
+ # Create SSL credentials for mutual TLS if needed.
303
+ use_client_cert = os.getenv(
304
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
305
+ ).lower()
306
+ if use_client_cert not in ("true", "false"):
307
+ raise ValueError(
308
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
309
+ )
310
+ client_cert_source_func = None
311
+ is_mtls = False
312
+ if use_client_cert == "true":
313
+ if client_options.client_cert_source:
314
+ is_mtls = True
315
+ client_cert_source_func = client_options.client_cert_source
316
+ else:
317
+ is_mtls = mtls.has_default_client_cert_source()
318
+ if is_mtls:
319
+ client_cert_source_func = mtls.default_client_cert_source()
320
+ else:
321
+ client_cert_source_func = None
322
+
323
+ # Figure out which api endpoint to use.
324
+ if client_options.api_endpoint is not None:
325
+ api_endpoint = client_options.api_endpoint
326
+ else:
327
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
328
+ if use_mtls_env == "never":
329
+ api_endpoint = self.DEFAULT_ENDPOINT
330
+ elif use_mtls_env == "always":
331
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
332
+ elif use_mtls_env == "auto":
333
+ if is_mtls:
334
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
335
+ else:
336
+ api_endpoint = self.DEFAULT_ENDPOINT
337
+ else:
338
+ raise MutualTLSChannelError(
339
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
340
+ "values: never, auto, always"
341
+ )
342
+
343
+ # Save or instantiate the transport.
344
+ # Ordinarily, we provide the transport, but allowing a custom transport
345
+ # instance provides an extensibility point for unusual situations.
346
+ if isinstance(transport, OperationsTransport):
347
+ # transport is a OperationsTransport instance.
348
+ if credentials or client_options.credentials_file:
349
+ raise ValueError(
350
+ "When providing a transport instance, "
351
+ "provide its credentials directly."
352
+ )
353
+ if client_options.scopes:
354
+ raise ValueError(
355
+ "When providing a transport instance, provide its scopes "
356
+ "directly."
357
+ )
358
+ self._transport = transport
359
+ else:
360
+ Transport = type(self).get_transport_class(transport)
361
+ self._transport = Transport(
362
+ credentials=credentials,
363
+ credentials_file=client_options.credentials_file,
364
+ host=api_endpoint,
365
+ scopes=client_options.scopes,
366
+ client_cert_source_for_mtls=client_cert_source_func,
367
+ quota_project_id=client_options.quota_project_id,
368
+ client_info=client_info,
369
+ always_use_jwt_access=True,
370
+ )
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/operations_client.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """A client for the google.longrunning.operations meta-API.
16
+
17
+ This is a client that deals with long-running operations that follow the
18
+ pattern outlined by the `Google API Style Guide`_.
19
+
20
+ When an API method normally takes long time to complete, it can be designed to
21
+ return ``Operation`` to the client, and the client can use this interface to
22
+ receive the real response asynchronously by polling the operation resource to
23
+ receive the response.
24
+
25
+ It is not a separate service, but rather an interface implemented by a larger
26
+ service. The protocol-level definition is available at
27
+ `google/longrunning/operations.proto`_. Typically, this will be constructed
28
+ automatically by another client class to deal with operations.
29
+
30
+ .. _Google API Style Guide:
31
+ https://cloud.google.com/apis/design/design_pattern
32
+ s#long_running_operations
33
+ .. _google/longrunning/operations.proto:
34
+ https://github.com/googleapis/googleapis/blob/master/google/longrunning
35
+ /operations.proto
36
+ """
37
+
38
+ import functools
39
+
40
+ from google.api_core import exceptions as core_exceptions
41
+ from google.api_core import gapic_v1
42
+ from google.api_core import page_iterator
43
+ from google.api_core import retry as retries
44
+ from google.api_core import timeout as timeouts
45
+ from google.longrunning import operations_pb2
46
+ from grpc import Compression
47
+
48
+
49
+ class OperationsClient(object):
50
+ """Client for interacting with long-running operations within a service.
51
+
52
+ Args:
53
+ channel (grpc.Channel): The gRPC channel associated with the service
54
+ that implements the ``google.longrunning.operations`` interface.
55
+ client_config (dict):
56
+ A dictionary of call options for each method. If not specified
57
+ the default configuration is used.
58
+ """
59
+
60
+ def __init__(self, channel, client_config=None):
61
+ # Create the gRPC client stub.
62
+ self.operations_stub = operations_pb2.OperationsStub(channel)
63
+
64
+ default_retry = retries.Retry(
65
+ initial=0.1, # seconds
66
+ maximum=60.0, # seconds
67
+ multiplier=1.3,
68
+ predicate=retries.if_exception_type(
69
+ core_exceptions.DeadlineExceeded,
70
+ core_exceptions.ServiceUnavailable,
71
+ ),
72
+ timeout=600.0, # seconds
73
+ )
74
+ default_timeout = timeouts.TimeToDeadlineTimeout(timeout=600.0)
75
+
76
+ default_compression = Compression.NoCompression
77
+
78
+ self._get_operation = gapic_v1.method.wrap_method(
79
+ self.operations_stub.GetOperation,
80
+ default_retry=default_retry,
81
+ default_timeout=default_timeout,
82
+ default_compression=default_compression,
83
+ )
84
+
85
+ self._list_operations = gapic_v1.method.wrap_method(
86
+ self.operations_stub.ListOperations,
87
+ default_retry=default_retry,
88
+ default_timeout=default_timeout,
89
+ default_compression=default_compression,
90
+ )
91
+
92
+ self._cancel_operation = gapic_v1.method.wrap_method(
93
+ self.operations_stub.CancelOperation,
94
+ default_retry=default_retry,
95
+ default_timeout=default_timeout,
96
+ default_compression=default_compression,
97
+ )
98
+
99
+ self._delete_operation = gapic_v1.method.wrap_method(
100
+ self.operations_stub.DeleteOperation,
101
+ default_retry=default_retry,
102
+ default_timeout=default_timeout,
103
+ default_compression=default_compression,
104
+ )
105
+
106
+ # Service calls
107
+ def get_operation(
108
+ self,
109
+ name,
110
+ retry=gapic_v1.method.DEFAULT,
111
+ timeout=gapic_v1.method.DEFAULT,
112
+ compression=gapic_v1.method.DEFAULT,
113
+ metadata=None,
114
+ ):
115
+ """Gets the latest state of a long-running operation.
116
+
117
+ Clients can use this method to poll the operation result at intervals
118
+ as recommended by the API service.
119
+
120
+ Example:
121
+ >>> from google.api_core import operations_v1
122
+ >>> api = operations_v1.OperationsClient()
123
+ >>> name = ''
124
+ >>> response = api.get_operation(name)
125
+
126
+ Args:
127
+ name (str): The name of the operation resource.
128
+ retry (google.api_core.retry.Retry): The retry strategy to use
129
+ when invoking the RPC. If unspecified, the default retry from
130
+ the client configuration will be used. If ``None``, then this
131
+ method will not retry the RPC at all.
132
+ timeout (float): The amount of time in seconds to wait for the RPC
133
+ to complete. Note that if ``retry`` is used, this timeout
134
+ applies to each individual attempt and the overall time it
135
+ takes for this method to complete may be longer. If
136
+ unspecified, the the default timeout in the client
137
+ configuration is used. If ``None``, then the RPC method will
138
+ not time out.
139
+ compression (grpc.Compression): An element of grpc.compression
140
+ e.g. grpc.compression.Gzip.
141
+ metadata (Optional[List[Tuple[str, str]]]):
142
+ Additional gRPC metadata.
143
+
144
+ Returns:
145
+ google.longrunning.operations_pb2.Operation: The state of the
146
+ operation.
147
+
148
+ Raises:
149
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
150
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
151
+ subclass will be raised.
152
+ """
153
+ request = operations_pb2.GetOperationRequest(name=name)
154
+
155
+ # Add routing header
156
+ metadata = metadata or []
157
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
158
+
159
+ return self._get_operation(
160
+ request,
161
+ retry=retry,
162
+ timeout=timeout,
163
+ compression=compression,
164
+ metadata=metadata,
165
+ )
166
+
167
+ def list_operations(
168
+ self,
169
+ name,
170
+ filter_,
171
+ retry=gapic_v1.method.DEFAULT,
172
+ timeout=gapic_v1.method.DEFAULT,
173
+ compression=gapic_v1.method.DEFAULT,
174
+ metadata=None,
175
+ ):
176
+ """
177
+ Lists operations that match the specified filter in the request.
178
+
179
+ Example:
180
+ >>> from google.api_core import operations_v1
181
+ >>> api = operations_v1.OperationsClient()
182
+ >>> name = ''
183
+ >>>
184
+ >>> # Iterate over all results
185
+ >>> for operation in api.list_operations(name):
186
+ >>> # process operation
187
+ >>> pass
188
+ >>>
189
+ >>> # Or iterate over results one page at a time
190
+ >>> iter = api.list_operations(name)
191
+ >>> for page in iter.pages:
192
+ >>> for operation in page:
193
+ >>> # process operation
194
+ >>> pass
195
+
196
+ Args:
197
+ name (str): The name of the operation collection.
198
+ filter_ (str): The standard list filter.
199
+ retry (google.api_core.retry.Retry): The retry strategy to use
200
+ when invoking the RPC. If unspecified, the default retry from
201
+ the client configuration will be used. If ``None``, then this
202
+ method will not retry the RPC at all.
203
+ timeout (float): The amount of time in seconds to wait for the RPC
204
+ to complete. Note that if ``retry`` is used, this timeout
205
+ applies to each individual attempt and the overall time it
206
+ takes for this method to complete may be longer. If
207
+ unspecified, the the default timeout in the client
208
+ configuration is used. If ``None``, then the RPC method will
209
+ not time out.
210
+ compression (grpc.Compression): An element of grpc.compression
211
+ e.g. grpc.compression.Gzip.
212
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
213
+ metadata.
214
+
215
+ Returns:
216
+ google.api_core.page_iterator.Iterator: An iterator that yields
217
+ :class:`google.longrunning.operations_pb2.Operation` instances.
218
+
219
+ Raises:
220
+ google.api_core.exceptions.MethodNotImplemented: If the server
221
+ does not support this method. Services are not required to
222
+ implement this method.
223
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
224
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
225
+ subclass will be raised.
226
+ """
227
+ # Create the request object.
228
+ request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
229
+
230
+ # Add routing header
231
+ metadata = metadata or []
232
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
233
+
234
+ # Create the method used to fetch pages
235
+ method = functools.partial(
236
+ self._list_operations,
237
+ retry=retry,
238
+ timeout=timeout,
239
+ compression=compression,
240
+ metadata=metadata,
241
+ )
242
+
243
+ iterator = page_iterator.GRPCIterator(
244
+ client=None,
245
+ method=method,
246
+ request=request,
247
+ items_field="operations",
248
+ request_token_field="page_token",
249
+ response_token_field="next_page_token",
250
+ )
251
+
252
+ return iterator
253
+
254
+ def cancel_operation(
255
+ self,
256
+ name,
257
+ retry=gapic_v1.method.DEFAULT,
258
+ timeout=gapic_v1.method.DEFAULT,
259
+ compression=gapic_v1.method.DEFAULT,
260
+ metadata=None,
261
+ ):
262
+ """Starts asynchronous cancellation on a long-running operation.
263
+
264
+ The server makes a best effort to cancel the operation, but success is
265
+ not guaranteed. Clients can use :meth:`get_operation` or service-
266
+ specific methods to check whether the cancellation succeeded or whether
267
+ the operation completed despite cancellation. On successful
268
+ cancellation, the operation is not deleted; instead, it becomes an
269
+ operation with an ``Operation.error`` value with a
270
+ ``google.rpc.Status.code`` of ``1``, corresponding to
271
+ ``Code.CANCELLED``.
272
+
273
+ Example:
274
+ >>> from google.api_core import operations_v1
275
+ >>> api = operations_v1.OperationsClient()
276
+ >>> name = ''
277
+ >>> api.cancel_operation(name)
278
+
279
+ Args:
280
+ name (str): The name of the operation resource to be cancelled.
281
+ retry (google.api_core.retry.Retry): The retry strategy to use
282
+ when invoking the RPC. If unspecified, the default retry from
283
+ the client configuration will be used. If ``None``, then this
284
+ method will not retry the RPC at all.
285
+ timeout (float): The amount of time in seconds to wait for the RPC
286
+ to complete. Note that if ``retry`` is used, this timeout
287
+ applies to each individual attempt and the overall time it
288
+ takes for this method to complete may be longer. If
289
+ unspecified, the the default timeout in the client
290
+ configuration is used. If ``None``, then the RPC method will
291
+ not time out.
292
+ compression (grpc.Compression): An element of grpc.compression
293
+ e.g. grpc.compression.Gzip.
294
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
295
+ metadata.
296
+
297
+ Raises:
298
+ google.api_core.exceptions.MethodNotImplemented: If the server
299
+ does not support this method. Services are not required to
300
+ implement this method.
301
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
302
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
303
+ subclass will be raised.
304
+ """
305
+ # Create the request object.
306
+ request = operations_pb2.CancelOperationRequest(name=name)
307
+
308
+ # Add routing header
309
+ metadata = metadata or []
310
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
311
+
312
+ self._cancel_operation(
313
+ request,
314
+ retry=retry,
315
+ timeout=timeout,
316
+ compression=compression,
317
+ metadata=metadata,
318
+ )
319
+
320
+ def delete_operation(
321
+ self,
322
+ name,
323
+ retry=gapic_v1.method.DEFAULT,
324
+ timeout=gapic_v1.method.DEFAULT,
325
+ compression=gapic_v1.method.DEFAULT,
326
+ metadata=None,
327
+ ):
328
+ """Deletes a long-running operation.
329
+
330
+ This method indicates that the client is no longer interested in the
331
+ operation result. It does not cancel the operation.
332
+
333
+ Example:
334
+ >>> from google.api_core import operations_v1
335
+ >>> api = operations_v1.OperationsClient()
336
+ >>> name = ''
337
+ >>> api.delete_operation(name)
338
+
339
+ Args:
340
+ name (str): The name of the operation resource to be deleted.
341
+ retry (google.api_core.retry.Retry): The retry strategy to use
342
+ when invoking the RPC. If unspecified, the default retry from
343
+ the client configuration will be used. If ``None``, then this
344
+ method will not retry the RPC at all.
345
+ timeout (float): The amount of time in seconds to wait for the RPC
346
+ to complete. Note that if ``retry`` is used, this timeout
347
+ applies to each individual attempt and the overall time it
348
+ takes for this method to complete may be longer. If
349
+ unspecified, the the default timeout in the client
350
+ configuration is used. If ``None``, then the RPC method will
351
+ not time out.
352
+ compression (grpc.Compression): An element of grpc.compression
353
+ e.g. grpc.compression.Gzip.
354
+ metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
355
+ metadata.
356
+
357
+ Raises:
358
+ google.api_core.exceptions.MethodNotImplemented: If the server
359
+ does not support this method. Services are not required to
360
+ implement this method.
361
+ google.api_core.exceptions.GoogleAPICallError: If an error occurred
362
+ while invoking the RPC, the appropriate ``GoogleAPICallError``
363
+ subclass will be raised.
364
+ """
365
+ # Create the request object.
366
+ request = operations_pb2.DeleteOperationRequest(name=name)
367
+
368
+ # Add routing header
369
+ metadata = metadata or []
370
+ metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
371
+
372
+ self._delete_operation(
373
+ request,
374
+ retry=retry,
375
+ timeout=timeout,
376
+ compression=compression,
377
+ metadata=metadata,
378
+ )
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2020 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ from collections import OrderedDict
17
+ from typing import cast, Dict, Tuple
18
+
19
+ from .base import OperationsTransport
20
+ from .rest import OperationsRestTransport
21
+
22
+ # Compile a registry of transports.
23
+ _transport_registry: Dict[str, OperationsTransport] = OrderedDict()
24
+ _transport_registry["rest"] = cast(OperationsTransport, OperationsRestTransport)
25
+
26
+ __all__: Tuple[str, ...] = ("OperationsTransport", "OperationsRestTransport")
27
+
28
+ try:
29
+ from .rest_asyncio import AsyncOperationsRestTransport
30
+
31
+ __all__ += ("AsyncOperationsRestTransport",)
32
+ _transport_registry["rest_asyncio"] = cast(
33
+ OperationsTransport, AsyncOperationsRestTransport
34
+ )
35
+ except ImportError:
36
+ # This import requires the `async_rest` extra.
37
+ # Don't raise an exception if `AsyncOperationsRestTransport` cannot be imported
38
+ # as other transports are still available.
39
+ pass
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.05 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (10.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest.cpython-311.pyc ADDED
Binary file (18.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-311.pyc ADDED
Binary file (21.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/base.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2020 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ import abc
17
+ import re
18
+ from typing import Awaitable, Callable, Optional, Sequence, Union
19
+
20
+ import google.api_core # type: ignore
21
+ from google.api_core import exceptions as core_exceptions # type: ignore
22
+ from google.api_core import gapic_v1 # type: ignore
23
+ from google.api_core import retry as retries # type: ignore
24
+ from google.api_core import version
25
+ import google.auth # type: ignore
26
+ from google.auth import credentials as ga_credentials # type: ignore
27
+ from google.longrunning import operations_pb2
28
+ from google.oauth2 import service_account # type: ignore
29
+ import google.protobuf
30
+ from google.protobuf import empty_pb2, json_format # type: ignore
31
+ from grpc import Compression
32
+
33
+
34
+ PROTOBUF_VERSION = google.protobuf.__version__
35
+
36
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
37
+ gapic_version=version.__version__,
38
+ )
39
+
40
+
41
+ class OperationsTransport(abc.ABC):
42
+ """Abstract transport class for Operations."""
43
+
44
+ AUTH_SCOPES = ()
45
+
46
+ DEFAULT_HOST: str = "longrunning.googleapis.com"
47
+
48
+ def __init__(
49
+ self,
50
+ *,
51
+ host: str = DEFAULT_HOST,
52
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): update type hint for credentials to include `google.auth.aio.Credentials`.
53
+ credentials: Optional[ga_credentials.Credentials] = None,
54
+ credentials_file: Optional[str] = None,
55
+ scopes: Optional[Sequence[str]] = None,
56
+ quota_project_id: Optional[str] = None,
57
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
58
+ always_use_jwt_access: Optional[bool] = False,
59
+ url_scheme="https",
60
+ **kwargs,
61
+ ) -> None:
62
+ """Instantiate the transport.
63
+
64
+ Args:
65
+ host (Optional[str]):
66
+ The hostname to connect to.
67
+ credentials (Optional[google.auth.credentials.Credentials]): The
68
+ authorization credentials to attach to requests. These
69
+ credentials identify the application to the service; if none
70
+ are specified, the client will attempt to ascertain the
71
+ credentials from the environment.
72
+ credentials_file (Optional[str]): A file with credentials that can
73
+ be loaded with :func:`google.auth.load_credentials_from_file`.
74
+ This argument is mutually exclusive with credentials.
75
+ scopes (Optional[Sequence[str]]): A list of scopes.
76
+ quota_project_id (Optional[str]): An optional project to use for billing
77
+ and quota.
78
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
79
+ The client info used to send a user-agent string along with
80
+ API requests. If ``None``, then default info will be used.
81
+ Generally, you only need to set this if you're developing
82
+ your own client library.
83
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
84
+ be used for service account credentials.
85
+ url_scheme: the protocol scheme for the API endpoint. Normally
86
+ "https", but for testing or local servers,
87
+ "http" can be specified.
88
+ """
89
+ maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
90
+ if maybe_url_match is None:
91
+ raise ValueError(
92
+ f"Unexpected hostname structure: {host}"
93
+ ) # pragma: NO COVER
94
+
95
+ url_match_items = maybe_url_match.groupdict()
96
+
97
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
98
+
99
+ # Save the hostname. Default to port 443 (HTTPS) if none is specified.
100
+ if ":" not in host:
101
+ host += ":443" # pragma: NO COVER
102
+ self._host = host
103
+
104
+ scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
105
+
106
+ # Save the scopes.
107
+ self._scopes = scopes
108
+
109
+ # If no credentials are provided, then determine the appropriate
110
+ # defaults.
111
+ if credentials and credentials_file:
112
+ raise core_exceptions.DuplicateCredentialArgs(
113
+ "'credentials_file' and 'credentials' are mutually exclusive"
114
+ )
115
+
116
+ if credentials_file is not None:
117
+ credentials, _ = google.auth.load_credentials_from_file(
118
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
119
+ )
120
+
121
+ elif credentials is None:
122
+ credentials, _ = google.auth.default(
123
+ **scopes_kwargs, quota_project_id=quota_project_id
124
+ )
125
+
126
+ # If the credentials are service account credentials, then always try to use self signed JWT.
127
+ if (
128
+ always_use_jwt_access
129
+ and isinstance(credentials, service_account.Credentials)
130
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
131
+ ):
132
+ credentials = credentials.with_always_use_jwt_access(True)
133
+
134
+ # Save the credentials.
135
+ self._credentials = credentials
136
+
137
+ def _prep_wrapped_messages(self, client_info):
138
+ # Precompute the wrapped methods.
139
+ self._wrapped_methods = {
140
+ self.list_operations: gapic_v1.method.wrap_method(
141
+ self.list_operations,
142
+ default_retry=retries.Retry(
143
+ initial=0.5,
144
+ maximum=10.0,
145
+ multiplier=2.0,
146
+ predicate=retries.if_exception_type(
147
+ core_exceptions.ServiceUnavailable,
148
+ ),
149
+ deadline=10.0,
150
+ ),
151
+ default_timeout=10.0,
152
+ default_compression=Compression.NoCompression,
153
+ client_info=client_info,
154
+ ),
155
+ self.get_operation: gapic_v1.method.wrap_method(
156
+ self.get_operation,
157
+ default_retry=retries.Retry(
158
+ initial=0.5,
159
+ maximum=10.0,
160
+ multiplier=2.0,
161
+ predicate=retries.if_exception_type(
162
+ core_exceptions.ServiceUnavailable,
163
+ ),
164
+ deadline=10.0,
165
+ ),
166
+ default_timeout=10.0,
167
+ default_compression=Compression.NoCompression,
168
+ client_info=client_info,
169
+ ),
170
+ self.delete_operation: gapic_v1.method.wrap_method(
171
+ self.delete_operation,
172
+ default_retry=retries.Retry(
173
+ initial=0.5,
174
+ maximum=10.0,
175
+ multiplier=2.0,
176
+ predicate=retries.if_exception_type(
177
+ core_exceptions.ServiceUnavailable,
178
+ ),
179
+ deadline=10.0,
180
+ ),
181
+ default_timeout=10.0,
182
+ default_compression=Compression.NoCompression,
183
+ client_info=client_info,
184
+ ),
185
+ self.cancel_operation: gapic_v1.method.wrap_method(
186
+ self.cancel_operation,
187
+ default_retry=retries.Retry(
188
+ initial=0.5,
189
+ maximum=10.0,
190
+ multiplier=2.0,
191
+ predicate=retries.if_exception_type(
192
+ core_exceptions.ServiceUnavailable,
193
+ ),
194
+ deadline=10.0,
195
+ ),
196
+ default_timeout=10.0,
197
+ default_compression=Compression.NoCompression,
198
+ client_info=client_info,
199
+ ),
200
+ }
201
+
202
+ def close(self):
203
+ """Closes resources associated with the transport.
204
+
205
+ .. warning::
206
+ Only call this method if the transport is NOT shared
207
+ with other clients - this may cause errors in other clients!
208
+ """
209
+ raise NotImplementedError()
210
+
211
+ def _convert_protobuf_message_to_dict(
212
+ self, message: google.protobuf.message.Message
213
+ ):
214
+ r"""Converts protobuf message to a dictionary.
215
+
216
+ When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.
217
+
218
+ Args:
219
+ message(google.protobuf.message.Message): The protocol buffers message
220
+ instance to serialize.
221
+
222
+ Returns:
223
+ A dict representation of the protocol buffer message.
224
+ """
225
+ # TODO(https://github.com/googleapis/python-api-core/issues/643): For backwards compatibility
226
+ # with protobuf 3.x 4.x, Remove once support for protobuf 3.x and 4.x is dropped.
227
+ if PROTOBUF_VERSION[0:2] in ["3.", "4."]:
228
+ result = json_format.MessageToDict(
229
+ message,
230
+ preserving_proto_field_name=True,
231
+ including_default_value_fields=True, # type: ignore # backward compatibility
232
+ )
233
+ else:
234
+ result = json_format.MessageToDict(
235
+ message,
236
+ preserving_proto_field_name=True,
237
+ always_print_fields_with_no_presence=True,
238
+ )
239
+
240
+ return result
241
+
242
+ @property
243
+ def list_operations(
244
+ self,
245
+ ) -> Callable[
246
+ [operations_pb2.ListOperationsRequest],
247
+ Union[
248
+ operations_pb2.ListOperationsResponse,
249
+ Awaitable[operations_pb2.ListOperationsResponse],
250
+ ],
251
+ ]:
252
+ raise NotImplementedError()
253
+
254
+ @property
255
+ def get_operation(
256
+ self,
257
+ ) -> Callable[
258
+ [operations_pb2.GetOperationRequest],
259
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
260
+ ]:
261
+ raise NotImplementedError()
262
+
263
+ @property
264
+ def delete_operation(
265
+ self,
266
+ ) -> Callable[
267
+ [operations_pb2.DeleteOperationRequest],
268
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
269
+ ]:
270
+ raise NotImplementedError()
271
+
272
+ @property
273
+ def cancel_operation(
274
+ self,
275
+ ) -> Callable[
276
+ [operations_pb2.CancelOperationRequest],
277
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
278
+ ]:
279
+ raise NotImplementedError()
280
+
281
+
282
+ __all__ = ("OperationsTransport",)
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2020 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ from typing import Callable, Dict, Optional, Sequence, Tuple, Union
18
+
19
+ from requests import __version__ as requests_version
20
+
21
+ from google.api_core import exceptions as core_exceptions # type: ignore
22
+ from google.api_core import gapic_v1 # type: ignore
23
+ from google.api_core import path_template # type: ignore
24
+ from google.api_core import rest_helpers # type: ignore
25
+ from google.api_core import retry as retries # type: ignore
26
+ from google.auth import credentials as ga_credentials # type: ignore
27
+ from google.auth.transport.requests import AuthorizedSession # type: ignore
28
+ from google.longrunning import operations_pb2 # type: ignore
29
+ from google.protobuf import empty_pb2 # type: ignore
30
+ from google.protobuf import json_format # type: ignore
31
+ import google.protobuf
32
+
33
+ import grpc
34
+ from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, OperationsTransport
35
+
36
+ PROTOBUF_VERSION = google.protobuf.__version__
37
+
38
+ OptionalRetry = Union[retries.Retry, object]
39
+
40
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
41
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
42
+ grpc_version=None,
43
+ rest_version=f"requests@{requests_version}",
44
+ )
45
+
46
+
47
+ class OperationsRestTransport(OperationsTransport):
48
+ """REST backend transport for Operations.
49
+
50
+ Manages long-running operations with an API service.
51
+
52
+ When an API method normally takes long time to complete, it can be
53
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
54
+ client, and the client can use this interface to receive the real
55
+ response asynchronously by polling the operation resource, or pass
56
+ the operation resource to another API (such as Google Cloud Pub/Sub
57
+ API) to receive the response. Any API service that returns
58
+ long-running operations should implement the ``Operations``
59
+ interface so developers can have a consistent client experience.
60
+
61
+ This class defines the same methods as the primary client, so the
62
+ primary client can load the underlying transport implementation
63
+ and call it.
64
+
65
+ It sends JSON representations of protocol buffers over HTTP/1.1
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ *,
71
+ host: str = "longrunning.googleapis.com",
72
+ credentials: Optional[ga_credentials.Credentials] = None,
73
+ credentials_file: Optional[str] = None,
74
+ scopes: Optional[Sequence[str]] = None,
75
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
76
+ quota_project_id: Optional[str] = None,
77
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
78
+ always_use_jwt_access: Optional[bool] = False,
79
+ url_scheme: str = "https",
80
+ http_options: Optional[Dict] = None,
81
+ path_prefix: str = "v1",
82
+ ) -> None:
83
+ """Instantiate the transport.
84
+
85
+ Args:
86
+ host (Optional[str]):
87
+ The hostname to connect to.
88
+ credentials (Optional[google.auth.credentials.Credentials]): The
89
+ authorization credentials to attach to requests. These
90
+ credentials identify the application to the service; if none
91
+ are specified, the client will attempt to ascertain the
92
+ credentials from the environment.
93
+
94
+ credentials_file (Optional[str]): A file with credentials that can
95
+ be loaded with :func:`google.auth.load_credentials_from_file`.
96
+ This argument is ignored if ``channel`` is provided.
97
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
98
+ ignored if ``channel`` is provided.
99
+ client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
100
+ certificate to configure mutual TLS HTTP channel. It is ignored
101
+ if ``channel`` is provided.
102
+ quota_project_id (Optional[str]): An optional project to use for billing
103
+ and quota.
104
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
105
+ The client info used to send a user-agent string along with
106
+ API requests. If ``None``, then default info will be used.
107
+ Generally, you only need to set this if you're developing
108
+ your own client library.
109
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
110
+ be used for service account credentials.
111
+ url_scheme: the protocol scheme for the API endpoint. Normally
112
+ "https", but for testing or local servers,
113
+ "http" can be specified.
114
+ http_options: a dictionary of http_options for transcoding, to override
115
+ the defaults from operations.proto. Each method has an entry
116
+ with the corresponding http rules as value.
117
+ path_prefix: path prefix (usually represents API version). Set to
118
+ "v1" by default.
119
+
120
+ """
121
+ # Run the base constructor
122
+ # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
123
+ # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
124
+ # credentials object
125
+ super().__init__(
126
+ host=host,
127
+ credentials=credentials,
128
+ client_info=client_info,
129
+ always_use_jwt_access=always_use_jwt_access,
130
+ )
131
+ self._session = AuthorizedSession(
132
+ self._credentials, default_host=self.DEFAULT_HOST
133
+ )
134
+ if client_cert_source_for_mtls:
135
+ self._session.configure_mtls_channel(client_cert_source_for_mtls)
136
+ # TODO(https://github.com/googleapis/python-api-core/issues/720): Add wrap logic directly to the property methods for callables.
137
+ self._prep_wrapped_messages(client_info)
138
+ self._http_options = http_options or {}
139
+ self._path_prefix = path_prefix
140
+
141
+ def _list_operations(
142
+ self,
143
+ request: operations_pb2.ListOperationsRequest,
144
+ *,
145
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
146
+ # to allow configuring retryable error codes.
147
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
148
+ timeout: Optional[float] = None,
149
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
150
+ metadata: Sequence[Tuple[str, str]] = (),
151
+ ) -> operations_pb2.ListOperationsResponse:
152
+ r"""Call the list operations method over HTTP.
153
+
154
+ Args:
155
+ request (~.operations_pb2.ListOperationsRequest):
156
+ The request object. The request message for
157
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
158
+
159
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
160
+ should be retried.
161
+ timeout (float): The timeout for this request.
162
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
163
+ sent along with the request as metadata.
164
+
165
+ Returns:
166
+ ~.operations_pb2.ListOperationsResponse:
167
+ The response message for
168
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
169
+
170
+ """
171
+
172
+ http_options = [
173
+ {
174
+ "method": "get",
175
+ "uri": "/{}/{{name=**}}/operations".format(self._path_prefix),
176
+ },
177
+ ]
178
+ if "google.longrunning.Operations.ListOperations" in self._http_options:
179
+ http_options = self._http_options[
180
+ "google.longrunning.Operations.ListOperations"
181
+ ]
182
+
183
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
184
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
185
+
186
+ uri = transcoded_request["uri"]
187
+ method = transcoded_request["method"]
188
+
189
+ # Jsonify the query params
190
+ query_params_request = operations_pb2.ListOperationsRequest()
191
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
192
+ query_params = json_format.MessageToDict(
193
+ query_params_request,
194
+ preserving_proto_field_name=False,
195
+ use_integers_for_enums=False,
196
+ )
197
+
198
+ # Send the request
199
+ headers = dict(metadata)
200
+ headers["Content-Type"] = "application/json"
201
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
202
+ response = getattr(self._session, method)(
203
+ "{host}{uri}".format(host=self._host, uri=uri),
204
+ timeout=timeout,
205
+ headers=headers,
206
+ params=rest_helpers.flatten_query_params(query_params),
207
+ )
208
+
209
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
210
+ # subclass.
211
+ if response.status_code >= 400:
212
+ raise core_exceptions.from_http_response(response)
213
+
214
+ # Return the response
215
+ api_response = operations_pb2.ListOperationsResponse()
216
+ json_format.Parse(response.content, api_response, ignore_unknown_fields=False)
217
+ return api_response
218
+
219
+ def _get_operation(
220
+ self,
221
+ request: operations_pb2.GetOperationRequest,
222
+ *,
223
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
224
+ # to allow configuring retryable error codes.
225
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
226
+ timeout: Optional[float] = None,
227
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
228
+ metadata: Sequence[Tuple[str, str]] = (),
229
+ ) -> operations_pb2.Operation:
230
+ r"""Call the get operation method over HTTP.
231
+
232
+ Args:
233
+ request (~.operations_pb2.GetOperationRequest):
234
+ The request object. The request message for
235
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation].
236
+
237
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
238
+ should be retried.
239
+ timeout (float): The timeout for this request.
240
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
241
+ sent along with the request as metadata.
242
+
243
+ Returns:
244
+ ~.operations_pb2.Operation:
245
+ This resource represents a long-
246
+ running operation that is the result of a
247
+ network API call.
248
+
249
+ """
250
+
251
+ http_options = [
252
+ {
253
+ "method": "get",
254
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
255
+ },
256
+ ]
257
+ if "google.longrunning.Operations.GetOperation" in self._http_options:
258
+ http_options = self._http_options[
259
+ "google.longrunning.Operations.GetOperation"
260
+ ]
261
+
262
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
263
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
264
+
265
+ uri = transcoded_request["uri"]
266
+ method = transcoded_request["method"]
267
+
268
+ # Jsonify the query params
269
+ query_params_request = operations_pb2.GetOperationRequest()
270
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
271
+ query_params = json_format.MessageToDict(
272
+ query_params_request,
273
+ preserving_proto_field_name=False,
274
+ use_integers_for_enums=False,
275
+ )
276
+
277
+ # Send the request
278
+ headers = dict(metadata)
279
+ headers["Content-Type"] = "application/json"
280
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
281
+ response = getattr(self._session, method)(
282
+ "{host}{uri}".format(host=self._host, uri=uri),
283
+ timeout=timeout,
284
+ headers=headers,
285
+ params=rest_helpers.flatten_query_params(query_params),
286
+ )
287
+
288
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
289
+ # subclass.
290
+ if response.status_code >= 400:
291
+ raise core_exceptions.from_http_response(response)
292
+
293
+ # Return the response
294
+ api_response = operations_pb2.Operation()
295
+ json_format.Parse(response.content, api_response, ignore_unknown_fields=False)
296
+ return api_response
297
+
298
+ def _delete_operation(
299
+ self,
300
+ request: operations_pb2.DeleteOperationRequest,
301
+ *,
302
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
303
+ # to allow configuring retryable error codes.
304
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
305
+ timeout: Optional[float] = None,
306
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
307
+ metadata: Sequence[Tuple[str, str]] = (),
308
+ ) -> empty_pb2.Empty:
309
+ r"""Call the delete operation method over HTTP.
310
+
311
+ Args:
312
+ request (~.operations_pb2.DeleteOperationRequest):
313
+ The request object. The request message for
314
+ [Operations.DeleteOperation][google.api_core.operations_v1.Operations.DeleteOperation].
315
+
316
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
317
+ should be retried.
318
+ timeout (float): The timeout for this request.
319
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
320
+ sent along with the request as metadata.
321
+ """
322
+
323
+ http_options = [
324
+ {
325
+ "method": "delete",
326
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
327
+ },
328
+ ]
329
+ if "google.longrunning.Operations.DeleteOperation" in self._http_options:
330
+ http_options = self._http_options[
331
+ "google.longrunning.Operations.DeleteOperation"
332
+ ]
333
+
334
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
335
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
336
+
337
+ uri = transcoded_request["uri"]
338
+ method = transcoded_request["method"]
339
+
340
+ # Jsonify the query params
341
+ query_params_request = operations_pb2.DeleteOperationRequest()
342
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
343
+ query_params = json_format.MessageToDict(
344
+ query_params_request,
345
+ preserving_proto_field_name=False,
346
+ use_integers_for_enums=False,
347
+ )
348
+
349
+ # Send the request
350
+ headers = dict(metadata)
351
+ headers["Content-Type"] = "application/json"
352
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
353
+ response = getattr(self._session, method)(
354
+ "{host}{uri}".format(host=self._host, uri=uri),
355
+ timeout=timeout,
356
+ headers=headers,
357
+ params=rest_helpers.flatten_query_params(query_params),
358
+ )
359
+
360
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
361
+ # subclass.
362
+ if response.status_code >= 400:
363
+ raise core_exceptions.from_http_response(response)
364
+
365
+ return empty_pb2.Empty()
366
+
367
+ def _cancel_operation(
368
+ self,
369
+ request: operations_pb2.CancelOperationRequest,
370
+ *,
371
+ # TODO(https://github.com/googleapis/python-api-core/issues/723): Leverage `retry`
372
+ # to allow configuring retryable error codes.
373
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
374
+ timeout: Optional[float] = None,
375
+ compression: Optional[grpc.Compression] = gapic_v1.method.DEFAULT,
376
+ metadata: Sequence[Tuple[str, str]] = (),
377
+ ) -> empty_pb2.Empty:
378
+ r"""Call the cancel operation method over HTTP.
379
+
380
+ Args:
381
+ request (~.operations_pb2.CancelOperationRequest):
382
+ The request object. The request message for
383
+ [Operations.CancelOperation][google.api_core.operations_v1.Operations.CancelOperation].
384
+
385
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
386
+ should be retried.
387
+ timeout (float): The timeout for this request.
388
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
389
+ sent along with the request as metadata.
390
+ """
391
+
392
+ http_options = [
393
+ {
394
+ "method": "post",
395
+ "uri": "/{}/{{name=**/operations/*}}:cancel".format(self._path_prefix),
396
+ "body": "*",
397
+ },
398
+ ]
399
+ if "google.longrunning.Operations.CancelOperation" in self._http_options:
400
+ http_options = self._http_options[
401
+ "google.longrunning.Operations.CancelOperation"
402
+ ]
403
+
404
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
405
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
406
+
407
+ # Jsonify the request body
408
+ body_request = operations_pb2.CancelOperationRequest()
409
+ json_format.ParseDict(transcoded_request["body"], body_request)
410
+ body = json_format.MessageToDict(
411
+ body_request,
412
+ preserving_proto_field_name=False,
413
+ use_integers_for_enums=False,
414
+ )
415
+ uri = transcoded_request["uri"]
416
+ method = transcoded_request["method"]
417
+
418
+ # Jsonify the query params
419
+ query_params_request = operations_pb2.CancelOperationRequest()
420
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
421
+ query_params = json_format.MessageToDict(
422
+ query_params_request,
423
+ preserving_proto_field_name=False,
424
+ use_integers_for_enums=False,
425
+ )
426
+
427
+ # Send the request
428
+ headers = dict(metadata)
429
+ headers["Content-Type"] = "application/json"
430
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
431
+ response = getattr(self._session, method)(
432
+ "{host}{uri}".format(host=self._host, uri=uri),
433
+ timeout=timeout,
434
+ headers=headers,
435
+ params=rest_helpers.flatten_query_params(query_params),
436
+ data=body,
437
+ )
438
+
439
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
440
+ # subclass.
441
+ if response.status_code >= 400:
442
+ raise core_exceptions.from_http_response(response)
443
+
444
+ return empty_pb2.Empty()
445
+
446
+ @property
447
+ def list_operations(
448
+ self,
449
+ ) -> Callable[
450
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
451
+ ]:
452
+ return self._list_operations
453
+
454
+ @property
455
+ def get_operation(
456
+ self,
457
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
458
+ return self._get_operation
459
+
460
+ @property
461
+ def delete_operation(
462
+ self,
463
+ ) -> Callable[[operations_pb2.DeleteOperationRequest], empty_pb2.Empty]:
464
+ return self._delete_operation
465
+
466
+ @property
467
+ def cancel_operation(
468
+ self,
469
+ ) -> Callable[[operations_pb2.CancelOperationRequest], empty_pb2.Empty]:
470
+ return self._cancel_operation
471
+
472
+
473
+ __all__ = ("OperationsRestTransport",)
.venv/lib/python3.11/site-packages/google/api_core/operations_v1/transports/rest_asyncio.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2024 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ import json
18
+ from typing import Any, Callable, Coroutine, Dict, Optional, Sequence, Tuple
19
+
20
+ from google.auth import __version__ as auth_version
21
+
22
+ try:
23
+ from google.auth.aio.transport.sessions import AsyncAuthorizedSession # type: ignore
24
+ except ImportError as e: # pragma: NO COVER
25
+ raise ImportError(
26
+ "The `async_rest` extra of `google-api-core` is required to use long-running operations. Install it by running "
27
+ "`pip install google-api-core[async_rest]`."
28
+ ) from e
29
+
30
+ from google.api_core import exceptions as core_exceptions # type: ignore
31
+ from google.api_core import gapic_v1 # type: ignore
32
+ from google.api_core import path_template # type: ignore
33
+ from google.api_core import rest_helpers # type: ignore
34
+ from google.api_core import retry_async as retries_async # type: ignore
35
+ from google.auth.aio import credentials as ga_credentials_async # type: ignore
36
+ from google.longrunning import operations_pb2 # type: ignore
37
+ from google.protobuf import empty_pb2 # type: ignore
38
+ from google.protobuf import json_format # type: ignore
39
+
40
+ from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO, OperationsTransport
41
+
42
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
43
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
44
+ grpc_version=None,
45
+ rest_version=f"google-auth@{auth_version}",
46
+ )
47
+
48
+
49
+ class AsyncOperationsRestTransport(OperationsTransport):
50
+ """Asynchronous REST backend transport for Operations.
51
+
52
+ Manages async long-running operations with an API service.
53
+
54
+ When an API method normally takes long time to complete, it can be
55
+ designed to return [Operation][google.api_core.operations_v1.Operation] to the
56
+ client, and the client can use this interface to receive the real
57
+ response asynchronously by polling the operation resource, or pass
58
+ the operation resource to another API (such as Google Cloud Pub/Sub
59
+ API) to receive the response. Any API service that returns
60
+ long-running operations should implement the ``Operations``
61
+ interface so developers can have a consistent client experience.
62
+
63
+ This class defines the same methods as the primary client, so the
64
+ primary client can load the underlying transport implementation
65
+ and call it.
66
+
67
+ It sends JSON representations of protocol buffers over HTTP/1.1
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ *,
73
+ host: str = "longrunning.googleapis.com",
74
+ credentials: Optional[ga_credentials_async.Credentials] = None,
75
+ credentials_file: Optional[str] = None,
76
+ scopes: Optional[Sequence[str]] = None,
77
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
78
+ quota_project_id: Optional[str] = None,
79
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
80
+ always_use_jwt_access: Optional[bool] = False,
81
+ url_scheme: str = "https",
82
+ http_options: Optional[Dict] = None,
83
+ path_prefix: str = "v1",
84
+ # TODO(https://github.com/googleapis/python-api-core/issues/715): Add docstring for `credentials_file` to async REST transport.
85
+ # TODO(https://github.com/googleapis/python-api-core/issues/716): Add docstring for `scopes` to async REST transport.
86
+ # TODO(https://github.com/googleapis/python-api-core/issues/717): Add docstring for `quota_project_id` to async REST transport.
87
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add docstring for `client_cert_source` to async REST transport.
88
+ ) -> None:
89
+ """Instantiate the transport.
90
+
91
+ Args:
92
+ host (Optional[str]):
93
+ The hostname to connect to.
94
+ credentials (Optional[google.auth.aio.credentials.Credentials]): The
95
+ authorization credentials to attach to requests. These
96
+ credentials identify the application to the service; if none
97
+ are specified, the client will attempt to ascertain the
98
+ credentials from the environment.
99
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
100
+ The client info used to send a user-agent string along with
101
+ API requests. If ``None``, then default info will be used.
102
+ Generally, you only need to set this if you're developing
103
+ your own client library.
104
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
105
+ be used for service account credentials.
106
+ url_scheme: the protocol scheme for the API endpoint. Normally
107
+ "https", but for testing or local servers,
108
+ "http" can be specified.
109
+ http_options: a dictionary of http_options for transcoding, to override
110
+ the defaults from operations.proto. Each method has an entry
111
+ with the corresponding http rules as value.
112
+ path_prefix: path prefix (usually represents API version). Set to
113
+ "v1" by default.
114
+
115
+ """
116
+ unsupported_params = {
117
+ # TODO(https://github.com/googleapis/python-api-core/issues/715): Add support for `credentials_file` to async REST transport.
118
+ "google.api_core.client_options.ClientOptions.credentials_file": credentials_file,
119
+ # TODO(https://github.com/googleapis/python-api-core/issues/716): Add support for `scopes` to async REST transport.
120
+ "google.api_core.client_options.ClientOptions.scopes": scopes,
121
+ # TODO(https://github.com/googleapis/python-api-core/issues/717): Add support for `quota_project_id` to async REST transport.
122
+ "google.api_core.client_options.ClientOptions.quota_project_id": quota_project_id,
123
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add support for `client_cert_source` to async REST transport.
124
+ "google.api_core.client_options.ClientOptions.client_cert_source": client_cert_source_for_mtls,
125
+ # TODO(https://github.com/googleapis/python-api-core/issues/718): Add support for `client_cert_source` to async REST transport.
126
+ "google.api_core.client_options.ClientOptions.client_cert_source": client_cert_source_for_mtls,
127
+ }
128
+ provided_unsupported_params = [
129
+ name for name, value in unsupported_params.items() if value is not None
130
+ ]
131
+ if provided_unsupported_params:
132
+ raise core_exceptions.AsyncRestUnsupportedParameterError(
133
+ f"The following provided parameters are not supported for `transport=rest_asyncio`: {', '.join(provided_unsupported_params)}"
134
+ )
135
+
136
+ super().__init__(
137
+ host=host,
138
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): Remove `type: ignore` when the linked issue is resolved.
139
+ credentials=credentials, # type: ignore
140
+ client_info=client_info,
141
+ # TODO(https://github.com/googleapis/python-api-core/issues/725): Set always_use_jwt_access token when supported.
142
+ always_use_jwt_access=False,
143
+ )
144
+ # TODO(https://github.com/googleapis/python-api-core/issues/708): add support for
145
+ # `default_host` in AsyncAuthorizedSession for feature parity with the synchronous
146
+ # code.
147
+ # TODO(https://github.com/googleapis/python-api-core/issues/709): Remove `type: ignore` when the linked issue is resolved.
148
+ self._session = AsyncAuthorizedSession(self._credentials) # type: ignore
149
+ # TODO(https://github.com/googleapis/python-api-core/issues/720): Add wrap logic directly to the property methods for callables.
150
+ self._prep_wrapped_messages(client_info)
151
+ self._http_options = http_options or {}
152
+ self._path_prefix = path_prefix
153
+
154
+ def _prep_wrapped_messages(self, client_info):
155
+ # Precompute the wrapped methods.
156
+ self._wrapped_methods = {
157
+ self.list_operations: gapic_v1.method_async.wrap_method(
158
+ self.list_operations,
159
+ default_retry=retries_async.AsyncRetry(
160
+ initial=0.5,
161
+ maximum=10.0,
162
+ multiplier=2.0,
163
+ predicate=retries_async.if_exception_type(
164
+ core_exceptions.ServiceUnavailable,
165
+ ),
166
+ deadline=10.0,
167
+ ),
168
+ default_timeout=10.0,
169
+ client_info=client_info,
170
+ kind="rest_asyncio",
171
+ ),
172
+ self.get_operation: gapic_v1.method_async.wrap_method(
173
+ self.get_operation,
174
+ default_retry=retries_async.AsyncRetry(
175
+ initial=0.5,
176
+ maximum=10.0,
177
+ multiplier=2.0,
178
+ predicate=retries_async.if_exception_type(
179
+ core_exceptions.ServiceUnavailable,
180
+ ),
181
+ deadline=10.0,
182
+ ),
183
+ default_timeout=10.0,
184
+ client_info=client_info,
185
+ kind="rest_asyncio",
186
+ ),
187
+ self.delete_operation: gapic_v1.method_async.wrap_method(
188
+ self.delete_operation,
189
+ default_retry=retries_async.AsyncRetry(
190
+ initial=0.5,
191
+ maximum=10.0,
192
+ multiplier=2.0,
193
+ predicate=retries_async.if_exception_type(
194
+ core_exceptions.ServiceUnavailable,
195
+ ),
196
+ deadline=10.0,
197
+ ),
198
+ default_timeout=10.0,
199
+ client_info=client_info,
200
+ kind="rest_asyncio",
201
+ ),
202
+ self.cancel_operation: gapic_v1.method_async.wrap_method(
203
+ self.cancel_operation,
204
+ default_retry=retries_async.AsyncRetry(
205
+ initial=0.5,
206
+ maximum=10.0,
207
+ multiplier=2.0,
208
+ predicate=retries_async.if_exception_type(
209
+ core_exceptions.ServiceUnavailable,
210
+ ),
211
+ deadline=10.0,
212
+ ),
213
+ default_timeout=10.0,
214
+ client_info=client_info,
215
+ kind="rest_asyncio",
216
+ ),
217
+ }
218
+
219
+ async def _list_operations(
220
+ self,
221
+ request: operations_pb2.ListOperationsRequest,
222
+ *,
223
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
224
+ # to allow configuring retryable error codes.
225
+ retry=gapic_v1.method_async.DEFAULT,
226
+ timeout: Optional[float] = None,
227
+ metadata: Sequence[Tuple[str, str]] = (),
228
+ ) -> operations_pb2.ListOperationsResponse:
229
+ r"""Asynchronously call the list operations method over HTTP.
230
+
231
+ Args:
232
+ request (~.operations_pb2.ListOperationsRequest):
233
+ The request object. The request message for
234
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
235
+ timeout (float): The timeout for this request.
236
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
237
+ sent along with the request as metadata.
238
+
239
+ Returns:
240
+ ~.operations_pb2.ListOperationsResponse:
241
+ The response message for
242
+ [Operations.ListOperations][google.api_core.operations_v1.Operations.ListOperations].
243
+
244
+ """
245
+
246
+ http_options = [
247
+ {
248
+ "method": "get",
249
+ "uri": "/{}/{{name=**}}/operations".format(self._path_prefix),
250
+ },
251
+ ]
252
+ if "google.longrunning.Operations.ListOperations" in self._http_options:
253
+ http_options = self._http_options[
254
+ "google.longrunning.Operations.ListOperations"
255
+ ]
256
+
257
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
258
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
259
+
260
+ uri = transcoded_request["uri"]
261
+ method = transcoded_request["method"]
262
+
263
+ # Jsonify the query params
264
+ query_params_request = operations_pb2.ListOperationsRequest()
265
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
266
+ query_params = json_format.MessageToDict(
267
+ query_params_request,
268
+ preserving_proto_field_name=False,
269
+ use_integers_for_enums=False,
270
+ )
271
+
272
+ # Send the request
273
+ headers = dict(metadata)
274
+ headers["Content-Type"] = "application/json"
275
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
276
+ response = await getattr(self._session, method)(
277
+ "{host}{uri}".format(host=self._host, uri=uri),
278
+ timeout=timeout,
279
+ headers=headers,
280
+ params=rest_helpers.flatten_query_params(query_params),
281
+ )
282
+ content = await response.read()
283
+
284
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
285
+ # subclass.
286
+ if response.status_code >= 400:
287
+ payload = json.loads(content.decode("utf-8"))
288
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
289
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
290
+
291
+ # Return the response
292
+ api_response = operations_pb2.ListOperationsResponse()
293
+ json_format.Parse(content, api_response, ignore_unknown_fields=False)
294
+ return api_response
295
+
296
+ async def _get_operation(
297
+ self,
298
+ request: operations_pb2.GetOperationRequest,
299
+ *,
300
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
301
+ # to allow configuring retryable error codes.
302
+ retry=gapic_v1.method_async.DEFAULT,
303
+ timeout: Optional[float] = None,
304
+ metadata: Sequence[Tuple[str, str]] = (),
305
+ ) -> operations_pb2.Operation:
306
+ r"""Asynchronously call the get operation method over HTTP.
307
+
308
+ Args:
309
+ request (~.operations_pb2.GetOperationRequest):
310
+ The request object. The request message for
311
+ [Operations.GetOperation][google.api_core.operations_v1.Operations.GetOperation].
312
+ timeout (float): The timeout for this request.
313
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
314
+ sent along with the request as metadata.
315
+
316
+ Returns:
317
+ ~.operations_pb2.Operation:
318
+ This resource represents a long-
319
+ running operation that is the result of a
320
+ network API call.
321
+
322
+ """
323
+
324
+ http_options = [
325
+ {
326
+ "method": "get",
327
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
328
+ },
329
+ ]
330
+ if "google.longrunning.Operations.GetOperation" in self._http_options:
331
+ http_options = self._http_options[
332
+ "google.longrunning.Operations.GetOperation"
333
+ ]
334
+
335
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
336
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
337
+
338
+ uri = transcoded_request["uri"]
339
+ method = transcoded_request["method"]
340
+
341
+ # Jsonify the query params
342
+ query_params_request = operations_pb2.GetOperationRequest()
343
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
344
+ query_params = json_format.MessageToDict(
345
+ query_params_request,
346
+ preserving_proto_field_name=False,
347
+ use_integers_for_enums=False,
348
+ )
349
+
350
+ # Send the request
351
+ headers = dict(metadata)
352
+ headers["Content-Type"] = "application/json"
353
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
354
+ response = await getattr(self._session, method)(
355
+ "{host}{uri}".format(host=self._host, uri=uri),
356
+ timeout=timeout,
357
+ headers=headers,
358
+ params=rest_helpers.flatten_query_params(query_params),
359
+ )
360
+ content = await response.read()
361
+
362
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
363
+ # subclass.
364
+ if response.status_code >= 400:
365
+ payload = json.loads(content.decode("utf-8"))
366
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
367
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
368
+
369
+ # Return the response
370
+ api_response = operations_pb2.Operation()
371
+ json_format.Parse(content, api_response, ignore_unknown_fields=False)
372
+ return api_response
373
+
374
+ async def _delete_operation(
375
+ self,
376
+ request: operations_pb2.DeleteOperationRequest,
377
+ *,
378
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
379
+ # to allow configuring retryable error codes.
380
+ retry=gapic_v1.method_async.DEFAULT,
381
+ timeout: Optional[float] = None,
382
+ metadata: Sequence[Tuple[str, str]] = (),
383
+ ) -> empty_pb2.Empty:
384
+ r"""Asynchronously call the delete operation method over HTTP.
385
+
386
+ Args:
387
+ request (~.operations_pb2.DeleteOperationRequest):
388
+ The request object. The request message for
389
+ [Operations.DeleteOperation][google.api_core.operations_v1.Operations.DeleteOperation].
390
+
391
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
392
+ should be retried.
393
+ timeout (float): The timeout for this request.
394
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
395
+ sent along with the request as metadata.
396
+ """
397
+
398
+ http_options = [
399
+ {
400
+ "method": "delete",
401
+ "uri": "/{}/{{name=**/operations/*}}".format(self._path_prefix),
402
+ },
403
+ ]
404
+ if "google.longrunning.Operations.DeleteOperation" in self._http_options:
405
+ http_options = self._http_options[
406
+ "google.longrunning.Operations.DeleteOperation"
407
+ ]
408
+
409
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
410
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
411
+
412
+ uri = transcoded_request["uri"]
413
+ method = transcoded_request["method"]
414
+
415
+ # Jsonify the query params
416
+ query_params_request = operations_pb2.DeleteOperationRequest()
417
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
418
+ query_params = json_format.MessageToDict(
419
+ query_params_request,
420
+ preserving_proto_field_name=False,
421
+ use_integers_for_enums=False,
422
+ )
423
+
424
+ # Send the request
425
+ headers = dict(metadata)
426
+ headers["Content-Type"] = "application/json"
427
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
428
+ response = await getattr(self._session, method)(
429
+ "{host}{uri}".format(host=self._host, uri=uri),
430
+ timeout=timeout,
431
+ headers=headers,
432
+ params=rest_helpers.flatten_query_params(query_params),
433
+ )
434
+
435
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
436
+ # subclass.
437
+ if response.status_code >= 400:
438
+ content = await response.read()
439
+ payload = json.loads(content.decode("utf-8"))
440
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
441
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
442
+
443
+ return empty_pb2.Empty()
444
+
445
+ async def _cancel_operation(
446
+ self,
447
+ request: operations_pb2.CancelOperationRequest,
448
+ *,
449
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Leverage `retry`
450
+ # to allow configuring retryable error codes.
451
+ retry=gapic_v1.method_async.DEFAULT,
452
+ timeout: Optional[float] = None,
453
+ metadata: Sequence[Tuple[str, str]] = (),
454
+ # TODO(https://github.com/googleapis/python-api-core/issues/722): Add `retry` parameter
455
+ # to allow configuring retryable error codes.
456
+ ) -> empty_pb2.Empty:
457
+ r"""Asynchronously call the cancel operation method over HTTP.
458
+
459
+ Args:
460
+ request (~.operations_pb2.CancelOperationRequest):
461
+ The request object. The request message for
462
+ [Operations.CancelOperation][google.api_core.operations_v1.Operations.CancelOperation].
463
+ timeout (float): The timeout for this request.
464
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
465
+ sent along with the request as metadata.
466
+ """
467
+
468
+ http_options = [
469
+ {
470
+ "method": "post",
471
+ "uri": "/{}/{{name=**/operations/*}}:cancel".format(self._path_prefix),
472
+ "body": "*",
473
+ },
474
+ ]
475
+ if "google.longrunning.Operations.CancelOperation" in self._http_options:
476
+ http_options = self._http_options[
477
+ "google.longrunning.Operations.CancelOperation"
478
+ ]
479
+
480
+ request_kwargs = self._convert_protobuf_message_to_dict(request)
481
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
482
+
483
+ # Jsonify the request body
484
+ body_request = operations_pb2.CancelOperationRequest()
485
+ json_format.ParseDict(transcoded_request["body"], body_request)
486
+ body = json_format.MessageToDict(
487
+ body_request,
488
+ preserving_proto_field_name=False,
489
+ use_integers_for_enums=False,
490
+ )
491
+ uri = transcoded_request["uri"]
492
+ method = transcoded_request["method"]
493
+
494
+ # Jsonify the query params
495
+ query_params_request = operations_pb2.CancelOperationRequest()
496
+ json_format.ParseDict(transcoded_request["query_params"], query_params_request)
497
+ query_params = json_format.MessageToDict(
498
+ query_params_request,
499
+ preserving_proto_field_name=False,
500
+ use_integers_for_enums=False,
501
+ )
502
+
503
+ # Send the request
504
+ headers = dict(metadata)
505
+ headers["Content-Type"] = "application/json"
506
+ # TODO(https://github.com/googleapis/python-api-core/issues/721): Update incorrect use of `uri`` variable name.
507
+ response = await getattr(self._session, method)(
508
+ "{host}{uri}".format(host=self._host, uri=uri),
509
+ timeout=timeout,
510
+ headers=headers,
511
+ params=rest_helpers.flatten_query_params(query_params),
512
+ data=body,
513
+ )
514
+
515
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
516
+ # subclass.
517
+ if response.status_code >= 400:
518
+ content = await response.read()
519
+ payload = json.loads(content.decode("utf-8"))
520
+ request_url = "{host}{uri}".format(host=self._host, uri=uri)
521
+ raise core_exceptions.format_http_response_error(response, method, request_url, payload) # type: ignore
522
+
523
+ return empty_pb2.Empty()
524
+
525
+ @property
526
+ def list_operations(
527
+ self,
528
+ ) -> Callable[
529
+ [operations_pb2.ListOperationsRequest],
530
+ Coroutine[Any, Any, operations_pb2.ListOperationsResponse],
531
+ ]:
532
+ return self._list_operations
533
+
534
+ @property
535
+ def get_operation(
536
+ self,
537
+ ) -> Callable[
538
+ [operations_pb2.GetOperationRequest],
539
+ Coroutine[Any, Any, operations_pb2.Operation],
540
+ ]:
541
+ return self._get_operation
542
+
543
+ @property
544
+ def delete_operation(
545
+ self,
546
+ ) -> Callable[
547
+ [operations_pb2.DeleteOperationRequest], Coroutine[Any, Any, empty_pb2.Empty]
548
+ ]:
549
+ return self._delete_operation
550
+
551
+ @property
552
+ def cancel_operation(
553
+ self,
554
+ ) -> Callable[
555
+ [operations_pb2.CancelOperationRequest], Coroutine[Any, Any, empty_pb2.Empty]
556
+ ]:
557
+ return self._cancel_operation
558
+
559
+
560
+ __all__ = ("AsyncOperationsRestTransport",)
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/answer.cpython-311.pyc ADDED
Binary file (14.5 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/caching.cpython-311.pyc ADDED
Binary file (13.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/embedding.cpython-311.pyc ADDED
Binary file (12.1 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/operations.cpython-311.pyc ADDED
Binary file (6.59 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/permission.cpython-311.pyc ADDED
Binary file (6.96 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/retriever.cpython-311.pyc ADDED
Binary file (9.76 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/__pycache__/version.cpython-311.pyc ADDED
Binary file (280 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (914 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/argument_parser.cpython-311.pyc ADDED
Binary file (5.83 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/cmd_line_parser.cpython-311.pyc ADDED
Binary file (22.9 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/command_utils.cpython-311.pyc ADDED
Binary file (7.67 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/compile_cmd.cpython-311.pyc ADDED
Binary file (2.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/gspread_client.cpython-311.pyc ADDED
Binary file (10.7 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/html_utils.cpython-311.pyc ADDED
Binary file (1.32 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/ipython_env.cpython-311.pyc ADDED
Binary file (1.92 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/ipython_env_impl.cpython-311.pyc ADDED
Binary file (1.39 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/magics.cpython-311.pyc ADDED
Binary file (5.78 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/model_registry.cpython-311.pyc ADDED
Binary file (2.27 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/output_utils.cpython-311.pyc ADDED
Binary file (2.71 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/post_process_utils.cpython-311.pyc ADDED
Binary file (8.96 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/post_process_utils_test_helper.cpython-311.pyc ADDED
Binary file (1.14 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/py_utils.cpython-311.pyc ADDED
Binary file (2.89 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/sheets_sanitize_url.cpython-311.pyc ADDED
Binary file (3.81 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/__pycache__/text_model.cpython-311.pyc ADDED
Binary file (3.15 kB). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/argument_parser.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Customized ArgumentParser.
16
+
17
+ The default behvaior of argparse.ArgumentParser's parse_args() method is to
18
+ exit with a SystemExit exception in the following cases:
19
+ 1. When the user requests a help message (with the --help or -h flags), or
20
+ 2. When there's a parsing error (e.g. missing required flags or mistyped flags)
21
+
22
+ To make the errors more user-friendly, this class customizes
23
+ argparse.ArgumentParser and raises either ParserNormalExit for (1) or
24
+ ParserError for (2); this way the caller has control over how to display them
25
+ to the user.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import abc
30
+ import argparse
31
+ from typing import Sequence
32
+ from google.generativeai.notebook import ipython_env
33
+
34
+
35
+ # pylint: disable-next=g-bad-exception-name
36
+ class _ParserBaseException(RuntimeError, metaclass=abc.ABCMeta):
37
+ """Base class for parser exceptions including normal exit."""
38
+
39
+ def __init__(self, msgs: Sequence[str], *args, **kwargs):
40
+ super().__init__("".join(msgs), *args, **kwargs)
41
+ self._msgs = msgs
42
+ self._ipython_env: ipython_env.IPythonEnv | None = None
43
+
44
+ def set_ipython_env(self, env: ipython_env.IPythonEnv) -> None:
45
+ self._ipython_env = env
46
+
47
+ def _ipython_display_(self):
48
+ self.display(self._ipython_env)
49
+
50
+ def msgs(self) -> Sequence[str]:
51
+ return self._msgs
52
+
53
+ @abc.abstractmethod
54
+ def display(self, env: ipython_env.IPythonEnv | None) -> None:
55
+ """Display this exception on an IPython console."""
56
+
57
+
58
+ # ParserNormalExit is not an error: it's a way for ArgumentParser to indicate
59
+ # that the user has entered a special request (e.g. "--help") instead of a
60
+ # runnable command.
61
+ # pylint: disable-next=g-bad-exception-name
62
+ class ParserNormalExit(_ParserBaseException):
63
+ """Exception thrown when the parser exits normally.
64
+
65
+ This is usually thrown when the user requests the help message.
66
+ """
67
+
68
+ def display(self, env: ipython_env.IPythonEnv | None) -> None:
69
+ for msg in self._msgs:
70
+ print(msg)
71
+
72
+
73
+ class ParserError(_ParserBaseException):
74
+ """Exception thrown when there is an error."""
75
+
76
+ def display(self, env: ipython_env.IPythonEnv | None) -> None:
77
+ for msg in self._msgs:
78
+ print(msg)
79
+ if env is not None:
80
+ # Highlight to the user that an error has occurred.
81
+ env.display_html("<b style='font-family:courier new'>ERROR</b>")
82
+
83
+
84
+ class ArgumentParser(argparse.ArgumentParser):
85
+ """Customized ArgumentParser for LLM Magics.
86
+
87
+ This class overrides the parent argparse.ArgumentParser's error-handling
88
+ methods to avoid side-effects like printing to stderr. The messages are
89
+ accumulated and passed into the raised exceptions for the caller to
90
+ handle them.
91
+ """
92
+
93
+ def __init__(self, *args, **kwargs):
94
+ super().__init__(*args, **kwargs)
95
+ self._messages: list[str] = []
96
+
97
+ def _print_message(self, message, file=None):
98
+ """Override ArgumentParser's _print_message() method."""
99
+ del file
100
+ self._messages.append(message)
101
+
102
+ def exit(self, status=0, message=None):
103
+ """Override ArgumentParser's exit() method."""
104
+ if message:
105
+ self._print_message(message)
106
+
107
+ msgs = self._messages
108
+ self._messages = []
109
+ if status == 0:
110
+ raise ParserNormalExit(msgs=msgs)
111
+ else:
112
+ raise ParserError(msgs=msgs)
.venv/lib/python3.11/site-packages/google/generativeai/notebook/command_utils.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Utilities for Commands.
16
+
17
+ Common methods for Commands such as RunCommand and CompileCommand.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from typing import AbstractSet, Any, Callable, Sequence
22
+
23
+ from google.generativeai.notebook import ipython_env
24
+ from google.generativeai.notebook import model_registry
25
+ from google.generativeai.notebook import parsed_args_lib
26
+ from google.generativeai.notebook import post_process_utils
27
+ from google.generativeai.notebook.lib import llm_function
28
+ from google.generativeai.notebook.lib import llmfn_input_utils
29
+ from google.generativeai.notebook.lib import llmfn_output_row
30
+ from google.generativeai.notebook.lib import llmfn_outputs
31
+ from google.generativeai.notebook.lib import unique_fn
32
+
33
+
34
+ class _GroundTruthLLMFunction(llm_function.LLMFunction):
35
+ """LLMFunction that returns pre-generated ground truth data."""
36
+
37
+ def __init__(self, data: Sequence[str]):
38
+ super().__init__(outputs_ipython_display_fn=None)
39
+ self._data = data
40
+
41
+ def get_placeholders(self) -> AbstractSet[str]:
42
+ # Ground truth is fixed and thus has no placeholders.
43
+ return frozenset({})
44
+
45
+ def _call_impl(
46
+ self, inputs: llmfn_input_utils.LLMFunctionInputs | None
47
+ ) -> Sequence[llmfn_outputs.LLMFnOutputEntry]:
48
+ normalized_inputs = llmfn_input_utils.to_normalized_inputs(inputs)
49
+ if len(self._data) != len(normalized_inputs):
50
+ raise RuntimeError(
51
+ "Ground truth should have same number of entries as inputs: {} vs {}".format(
52
+ len(self._data), len(normalized_inputs)
53
+ )
54
+ )
55
+
56
+ outputs: list[llmfn_outputs.LLMFnOutputEntry] = []
57
+ for idx, (value, prompt_vars) in enumerate(zip(self._data, normalized_inputs)):
58
+ output_row = llmfn_output_row.LLMFnOutputRow(
59
+ data={
60
+ llmfn_outputs.ColumnNames.RESULT_NUM: 0,
61
+ llmfn_outputs.ColumnNames.TEXT_RESULT: value,
62
+ },
63
+ result_type=str,
64
+ )
65
+ outputs.append(
66
+ llmfn_outputs.LLMFnOutputEntry(
67
+ prompt_num=0,
68
+ input_num=idx,
69
+ prompt_vars=prompt_vars,
70
+ output_rows=[output_row],
71
+ )
72
+ )
73
+ return outputs
74
+
75
+
76
+ def _get_ipython_display_fn(
77
+ env: ipython_env.IPythonEnv,
78
+ ) -> Callable[[llmfn_outputs.LLMFnOutputs], None]:
79
+ return lambda x: env.display(x.as_pandas_dataframe())
80
+
81
+
82
+ def create_llm_function(
83
+ models: model_registry.ModelRegistry,
84
+ env: ipython_env.IPythonEnv | None,
85
+ parsed_args: parsed_args_lib.ParsedArgs,
86
+ cell_content: str,
87
+ post_processing_fns: Sequence[post_process_utils.ParsedPostProcessExpr],
88
+ ) -> llm_function.LLMFunction:
89
+ """Creates an LLMFunction from Command.execute() arguments."""
90
+ prompts: list[str] = [cell_content]
91
+
92
+ llmfn_outputs_display_fn = _get_ipython_display_fn(env) if env else None
93
+
94
+ llm_fn = llm_function.LLMFunctionImpl(
95
+ model=models.get_model(parsed_args.model_type),
96
+ model_args=parsed_args.model_args,
97
+ prompts=prompts,
98
+ outputs_ipython_display_fn=llmfn_outputs_display_fn,
99
+ )
100
+ if parsed_args.unique:
101
+ llm_fn = llm_fn.add_post_process_reorder_fn(name="unique", fn=unique_fn.unique_fn)
102
+ for fn in post_processing_fns:
103
+ llm_fn = fn.add_to_llm_function(llm_fn)
104
+
105
+ return llm_fn
106
+
107
+
108
+ def _convert_simple_compare_fn(
109
+ name_and_simple_fn: tuple[str, Callable[[str, str], Any]]
110
+ ) -> tuple[str, llm_function.CompareFn]:
111
+ simple_fn = name_and_simple_fn[1]
112
+ new_fn = lambda x, y: simple_fn(x.result_value(), y.result_value())
113
+ return name_and_simple_fn[0], new_fn
114
+
115
+
116
+ def create_llm_compare_function(
117
+ env: ipython_env.IPythonEnv | None,
118
+ parsed_args: parsed_args_lib.ParsedArgs,
119
+ post_processing_fns: Sequence[post_process_utils.ParsedPostProcessExpr],
120
+ ) -> llm_function.LLMFunction:
121
+ """Creates an LLMCompareFunction from Command.execute() arguments."""
122
+ llmfn_outputs_display_fn = _get_ipython_display_fn(env) if env else None
123
+
124
+ llm_cmp_fn = llm_function.LLMCompareFunction(
125
+ lhs_name_and_fn=parsed_args.lhs_name_and_fn,
126
+ rhs_name_and_fn=parsed_args.rhs_name_and_fn,
127
+ compare_name_and_fns=[_convert_simple_compare_fn(x) for x in parsed_args.compare_fn],
128
+ outputs_ipython_display_fn=llmfn_outputs_display_fn,
129
+ )
130
+ for fn in post_processing_fns:
131
+ llm_cmp_fn = fn.add_to_llm_function(llm_cmp_fn)
132
+
133
+ return llm_cmp_fn
134
+
135
+
136
+ def create_llm_eval_function(
137
+ models: model_registry.ModelRegistry,
138
+ env: ipython_env.IPythonEnv | None,
139
+ parsed_args: parsed_args_lib.ParsedArgs,
140
+ cell_content: str,
141
+ post_processing_fns: Sequence[post_process_utils.ParsedPostProcessExpr],
142
+ ) -> llm_function.LLMFunction:
143
+ """Creates an LLMCompareFunction from Command.execute() arguments."""
144
+ llmfn_outputs_display_fn = _get_ipython_display_fn(env) if env else None
145
+
146
+ # First construct a regular LLMFunction from the cell contents.
147
+ llm_fn = create_llm_function(
148
+ models=models,
149
+ env=env,
150
+ parsed_args=parsed_args,
151
+ cell_content=cell_content,
152
+ post_processing_fns=post_processing_fns,
153
+ )
154
+
155
+ # Next create a LLMCompareFunction.
156
+ ground_truth_fn = _GroundTruthLLMFunction(data=parsed_args.ground_truth)
157
+ llm_cmp_fn = llm_function.LLMCompareFunction(
158
+ lhs_name_and_fn=("actual", llm_fn),
159
+ rhs_name_and_fn=("ground_truth", ground_truth_fn),
160
+ compare_name_and_fns=[_convert_simple_compare_fn(x) for x in parsed_args.compare_fn],
161
+ outputs_ipython_display_fn=llmfn_outputs_display_fn,
162
+ )
163
+
164
+ return llm_cmp_fn
.venv/lib/python3.11/site-packages/google/generativeai/notebook/ipython_env.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Abstract IPythonEnv base class.
16
+
17
+ This module provides a layer of abstraction to address the following problems:
18
+ 1. Sometimes the code needs to run in an environment where IPython is not
19
+ available, e.g. inside a unittest.
20
+ 2. We want to limit dependencies on IPython to code that deals directly with
21
+ the notebook environment.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import abc
26
+ from typing import Any
27
+
28
+
29
+ class IPythonEnv(abc.ABC):
30
+ """Abstract base class that provides a wrapper around IPython methods."""
31
+
32
+ @abc.abstractmethod
33
+ def display(self, x: Any) -> None:
34
+ """Wrapper around IPython.core.display.display()."""
35
+
36
+ @abc.abstractmethod
37
+ def display_html(self, x: str) -> None:
38
+ """Wrapper to display HTML.
39
+
40
+ This method is equivalent to calling:
41
+ display.display(display.HTML(x))
42
+
43
+ display() and HTML() are combined into a single method because
44
+ display.HTML() returns an object, which would be complicated to model with
45
+ this abstract interface.
46
+
47
+ Args:
48
+ x: An HTML string to be displayed.
49
+ """
.venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
.venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (205 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/generativeai/notebook/lib/__pycache__/llm_function.cpython-311.pyc ADDED
Binary file (19.9 kB). View file