unstructured-ingest 0.1.1__py3-none-any.whl → 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of unstructured-ingest might be problematic. Click here for more details.
- test/integration/connectors/conftest.py +13 -0
- test/integration/connectors/databricks_tests/test_volumes_native.py +8 -4
- test/integration/connectors/sql/test_postgres.py +6 -10
- test/integration/connectors/sql/test_singlestore.py +156 -0
- test/integration/connectors/sql/test_snowflake.py +205 -0
- test/integration/connectors/sql/test_sqlite.py +6 -10
- test/integration/connectors/test_delta_table.py +138 -0
- test/integration/connectors/test_s3.py +1 -1
- test/integration/connectors/utils/docker.py +78 -0
- test/integration/connectors/utils/docker_compose.py +23 -8
- test/integration/connectors/utils/validation.py +93 -2
- unstructured_ingest/__version__.py +1 -1
- unstructured_ingest/v2/cli/utils/click.py +32 -1
- unstructured_ingest/v2/cli/utils/model_conversion.py +10 -3
- unstructured_ingest/v2/interfaces/file_data.py +1 -0
- unstructured_ingest/v2/interfaces/indexer.py +4 -1
- unstructured_ingest/v2/pipeline/pipeline.py +10 -2
- unstructured_ingest/v2/pipeline/steps/index.py +18 -1
- unstructured_ingest/v2/processes/connectors/__init__.py +13 -6
- unstructured_ingest/v2/processes/connectors/astradb.py +278 -55
- unstructured_ingest/v2/processes/connectors/databricks/volumes.py +3 -1
- unstructured_ingest/v2/processes/connectors/delta_table.py +185 -0
- unstructured_ingest/v2/processes/connectors/fsspec/fsspec.py +1 -0
- unstructured_ingest/v2/processes/connectors/slack.py +248 -0
- unstructured_ingest/v2/processes/connectors/sql/__init__.py +15 -2
- unstructured_ingest/v2/processes/connectors/sql/postgres.py +33 -56
- unstructured_ingest/v2/processes/connectors/sql/singlestore.py +168 -0
- unstructured_ingest/v2/processes/connectors/sql/snowflake.py +162 -0
- unstructured_ingest/v2/processes/connectors/sql/sql.py +51 -12
- unstructured_ingest/v2/processes/connectors/sql/sqlite.py +31 -32
- unstructured_ingest/v2/unstructured_api.py +1 -1
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/METADATA +19 -17
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/RECORD +37 -31
- unstructured_ingest/v2/processes/connectors/databricks_volumes.py +0 -250
- unstructured_ingest/v2/processes/connectors/singlestore.py +0 -156
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/LICENSE.md +0 -0
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/WHEEL +0 -0
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/entry_points.txt +0 -0
- {unstructured_ingest-0.1.1.dist-info → unstructured_ingest-0.2.1.dist-info}/top_level.txt +0 -0
|
@@ -1,31 +1,50 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import csv
|
|
3
|
+
import hashlib
|
|
1
4
|
import json
|
|
5
|
+
import sys
|
|
2
6
|
from dataclasses import dataclass, field
|
|
3
7
|
from pathlib import Path
|
|
4
|
-
from
|
|
8
|
+
from time import time
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Generator, Optional
|
|
5
10
|
|
|
6
11
|
from pydantic import Field, Secret
|
|
7
12
|
|
|
8
13
|
from unstructured_ingest import __name__ as integration_name
|
|
9
14
|
from unstructured_ingest.__version__ import __version__ as integration_version
|
|
10
|
-
from unstructured_ingest.error import
|
|
15
|
+
from unstructured_ingest.error import (
|
|
16
|
+
DestinationConnectionError,
|
|
17
|
+
SourceConnectionError,
|
|
18
|
+
SourceConnectionNetworkError,
|
|
19
|
+
)
|
|
11
20
|
from unstructured_ingest.utils.data_prep import batch_generator
|
|
12
21
|
from unstructured_ingest.utils.dep_check import requires_dependencies
|
|
13
22
|
from unstructured_ingest.v2.interfaces import (
|
|
14
23
|
AccessConfig,
|
|
15
24
|
ConnectionConfig,
|
|
25
|
+
Downloader,
|
|
26
|
+
DownloaderConfig,
|
|
27
|
+
DownloadResponse,
|
|
16
28
|
FileData,
|
|
29
|
+
FileDataSourceMetadata,
|
|
30
|
+
Indexer,
|
|
31
|
+
IndexerConfig,
|
|
17
32
|
Uploader,
|
|
18
33
|
UploaderConfig,
|
|
19
34
|
UploadStager,
|
|
20
35
|
UploadStagerConfig,
|
|
36
|
+
download_responses,
|
|
21
37
|
)
|
|
22
38
|
from unstructured_ingest.v2.logger import logger
|
|
23
39
|
from unstructured_ingest.v2.processes.connector_registry import (
|
|
24
40
|
DestinationRegistryEntry,
|
|
41
|
+
SourceRegistryEntry,
|
|
25
42
|
)
|
|
26
43
|
|
|
27
44
|
if TYPE_CHECKING:
|
|
45
|
+
from astrapy import AsyncCollection as AstraDBAsyncCollection
|
|
28
46
|
from astrapy import Collection as AstraDBCollection
|
|
47
|
+
from astrapy import DataAPIClient as AstraDBClient
|
|
29
48
|
|
|
30
49
|
|
|
31
50
|
CONNECTOR_TYPE = "astradb"
|
|
@@ -37,14 +56,253 @@ class AstraDBAccessConfig(AccessConfig):
|
|
|
37
56
|
|
|
38
57
|
|
|
39
58
|
class AstraDBConnectionConfig(ConnectionConfig):
|
|
40
|
-
|
|
59
|
+
connector_type: str = Field(default=CONNECTOR_TYPE, init=False)
|
|
41
60
|
access_config: Secret[AstraDBAccessConfig]
|
|
42
61
|
|
|
62
|
+
@requires_dependencies(["astrapy"], extras="astradb")
|
|
63
|
+
def get_client(self) -> "AstraDBClient":
|
|
64
|
+
from astrapy import DataAPIClient as AstraDBClient
|
|
65
|
+
|
|
66
|
+
# Create a client object to interact with the Astra DB
|
|
67
|
+
# caller_name/version for Astra DB tracking
|
|
68
|
+
return AstraDBClient(
|
|
69
|
+
caller_name=integration_name,
|
|
70
|
+
caller_version=integration_version,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_astra_collection(
|
|
75
|
+
connection_config: AstraDBConnectionConfig,
|
|
76
|
+
collection_name: str,
|
|
77
|
+
keyspace: str,
|
|
78
|
+
) -> "AstraDBCollection":
|
|
79
|
+
# Build the Astra DB object.
|
|
80
|
+
access_configs = connection_config.access_config.get_secret_value()
|
|
81
|
+
|
|
82
|
+
# Create a client object to interact with the Astra DB
|
|
83
|
+
# caller_name/version for Astra DB tracking
|
|
84
|
+
client = connection_config.get_client()
|
|
85
|
+
|
|
86
|
+
# Get the database object
|
|
87
|
+
astra_db = client.get_database(
|
|
88
|
+
api_endpoint=access_configs.api_endpoint,
|
|
89
|
+
token=access_configs.token,
|
|
90
|
+
keyspace=keyspace,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Connect to the collection
|
|
94
|
+
astra_db_collection = astra_db.get_collection(name=collection_name)
|
|
95
|
+
return astra_db_collection
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def get_async_astra_collection(
|
|
99
|
+
connection_config: AstraDBConnectionConfig,
|
|
100
|
+
collection_name: str,
|
|
101
|
+
keyspace: str,
|
|
102
|
+
) -> "AstraDBAsyncCollection":
|
|
103
|
+
# Build the Astra DB object.
|
|
104
|
+
access_configs = connection_config.access_config.get_secret_value()
|
|
105
|
+
|
|
106
|
+
# Create a client object to interact with the Astra DB
|
|
107
|
+
client = connection_config.get_client()
|
|
108
|
+
|
|
109
|
+
# Get the async database object
|
|
110
|
+
async_astra_db = client.get_async_database(
|
|
111
|
+
api_endpoint=access_configs.api_endpoint,
|
|
112
|
+
token=access_configs.token,
|
|
113
|
+
keyspace=keyspace,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# Get async collection from AsyncDatabase
|
|
117
|
+
async_astra_db_collection = await async_astra_db.get_collection(name=collection_name)
|
|
118
|
+
return async_astra_db_collection
|
|
119
|
+
|
|
43
120
|
|
|
44
121
|
class AstraDBUploadStagerConfig(UploadStagerConfig):
|
|
45
122
|
pass
|
|
46
123
|
|
|
47
124
|
|
|
125
|
+
class AstraDBIndexerConfig(IndexerConfig):
|
|
126
|
+
collection_name: str = Field(
|
|
127
|
+
description="The name of the Astra DB collection. "
|
|
128
|
+
"Note that the collection name must only include letters, "
|
|
129
|
+
"numbers, and underscores."
|
|
130
|
+
)
|
|
131
|
+
keyspace: Optional[str] = Field(default=None, description="The Astra DB connection keyspace.")
|
|
132
|
+
namespace: Optional[str] = Field(
|
|
133
|
+
default=None,
|
|
134
|
+
description="The Astra DB connection namespace.",
|
|
135
|
+
deprecated="Please use 'keyspace' instead.",
|
|
136
|
+
)
|
|
137
|
+
batch_size: int = Field(default=20, description="Number of records per batch")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class AstraDBDownloaderConfig(DownloaderConfig):
|
|
141
|
+
fields: list[str] = field(default_factory=list)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class AstraDBUploaderConfig(UploaderConfig):
|
|
145
|
+
collection_name: str = Field(
|
|
146
|
+
description="The name of the Astra DB collection. "
|
|
147
|
+
"Note that the collection name must only include letters, "
|
|
148
|
+
"numbers, and underscores."
|
|
149
|
+
)
|
|
150
|
+
embedding_dimension: int = Field(
|
|
151
|
+
default=384, description="The dimensionality of the embeddings"
|
|
152
|
+
)
|
|
153
|
+
keyspace: Optional[str] = Field(default=None, description="The Astra DB connection keyspace.")
|
|
154
|
+
namespace: Optional[str] = Field(
|
|
155
|
+
default=None,
|
|
156
|
+
description="The Astra DB connection namespace.",
|
|
157
|
+
deprecated="Please use 'keyspace' instead.",
|
|
158
|
+
)
|
|
159
|
+
requested_indexing_policy: Optional[dict[str, Any]] = Field(
|
|
160
|
+
default=None,
|
|
161
|
+
description="The indexing policy to use for the collection.",
|
|
162
|
+
examples=['{"deny": ["metadata"]}'],
|
|
163
|
+
)
|
|
164
|
+
batch_size: int = Field(default=20, description="Number of records per batch")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass
|
|
168
|
+
class AstraDBIndexer(Indexer):
|
|
169
|
+
connection_config: AstraDBConnectionConfig
|
|
170
|
+
index_config: AstraDBIndexerConfig
|
|
171
|
+
|
|
172
|
+
def get_collection(self) -> "AstraDBCollection":
|
|
173
|
+
return get_astra_collection(
|
|
174
|
+
connection_config=self.connection_config,
|
|
175
|
+
collection_name=self.index_config.collection_name,
|
|
176
|
+
keyspace=self.index_config.keyspace or self.index_config.namespace,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def precheck(self) -> None:
|
|
180
|
+
try:
|
|
181
|
+
self.get_collection()
|
|
182
|
+
except Exception as e:
|
|
183
|
+
logger.error(f"Failed to validate connection {e}", exc_info=True)
|
|
184
|
+
raise SourceConnectionError(f"failed to validate connection: {e}")
|
|
185
|
+
|
|
186
|
+
def _get_doc_ids(self) -> set[str]:
|
|
187
|
+
"""Fetches all document ids in an index"""
|
|
188
|
+
# Initialize set of ids
|
|
189
|
+
ids = set()
|
|
190
|
+
|
|
191
|
+
# Get the collection
|
|
192
|
+
collection = self.get_collection()
|
|
193
|
+
|
|
194
|
+
# Perform the find operation to get all items
|
|
195
|
+
astra_db_docs_cursor = collection.find({}, projection={"_id": True})
|
|
196
|
+
|
|
197
|
+
# Iterate over the cursor
|
|
198
|
+
astra_db_docs = []
|
|
199
|
+
for result in astra_db_docs_cursor:
|
|
200
|
+
astra_db_docs.append(result)
|
|
201
|
+
|
|
202
|
+
# Create file data for each astra record
|
|
203
|
+
for astra_record in astra_db_docs:
|
|
204
|
+
ids.add(astra_record["_id"])
|
|
205
|
+
|
|
206
|
+
return ids
|
|
207
|
+
|
|
208
|
+
def run(self, **kwargs: Any) -> Generator[FileData, None, None]:
|
|
209
|
+
all_ids = self._get_doc_ids()
|
|
210
|
+
ids = list(all_ids)
|
|
211
|
+
id_batches = batch_generator(ids, self.index_config.batch_size)
|
|
212
|
+
|
|
213
|
+
for batch in id_batches:
|
|
214
|
+
# Make sure the hash is always a positive number to create identified
|
|
215
|
+
identified = str(hash(batch) + sys.maxsize + 1)
|
|
216
|
+
fd = FileData(
|
|
217
|
+
identifier=identified,
|
|
218
|
+
connector_type=CONNECTOR_TYPE,
|
|
219
|
+
doc_type="batch",
|
|
220
|
+
metadata=FileDataSourceMetadata(
|
|
221
|
+
date_processed=str(time()),
|
|
222
|
+
),
|
|
223
|
+
additional_metadata={
|
|
224
|
+
"ids": list(batch),
|
|
225
|
+
"collection_name": self.index_config.collection_name,
|
|
226
|
+
"keyspace": self.index_config.keyspace or self.index_config.namespace,
|
|
227
|
+
},
|
|
228
|
+
)
|
|
229
|
+
yield fd
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass
|
|
233
|
+
class AstraDBDownloader(Downloader):
|
|
234
|
+
connection_config: AstraDBConnectionConfig
|
|
235
|
+
download_config: AstraDBDownloaderConfig
|
|
236
|
+
connector_type: str = CONNECTOR_TYPE
|
|
237
|
+
|
|
238
|
+
def is_async(self) -> bool:
|
|
239
|
+
return True
|
|
240
|
+
|
|
241
|
+
def get_identifier(self, record_id: str) -> str:
|
|
242
|
+
f = f"{record_id}"
|
|
243
|
+
if self.download_config.fields:
|
|
244
|
+
f = "{}-{}".format(
|
|
245
|
+
f,
|
|
246
|
+
hashlib.sha256(",".join(self.download_config.fields).encode()).hexdigest()[:8],
|
|
247
|
+
)
|
|
248
|
+
return f
|
|
249
|
+
|
|
250
|
+
def write_astra_result_to_csv(self, astra_result: dict, download_path: str) -> None:
|
|
251
|
+
with open(download_path, "w", encoding="utf8") as f:
|
|
252
|
+
writer = csv.writer(f)
|
|
253
|
+
writer.writerow(astra_result.keys())
|
|
254
|
+
writer.writerow(astra_result.values())
|
|
255
|
+
|
|
256
|
+
def generate_download_response(self, result: dict, file_data: FileData) -> DownloadResponse:
|
|
257
|
+
record_id = result["_id"]
|
|
258
|
+
filename_id = self.get_identifier(record_id=record_id)
|
|
259
|
+
filename = f"{filename_id}.csv" # csv to preserve column info
|
|
260
|
+
download_path = self.download_dir / Path(filename)
|
|
261
|
+
logger.debug(f"Downloading results from record {record_id} as csv to {download_path}")
|
|
262
|
+
download_path.parent.mkdir(parents=True, exist_ok=True)
|
|
263
|
+
try:
|
|
264
|
+
self.write_astra_result_to_csv(astra_result=result, download_path=download_path)
|
|
265
|
+
except Exception as e:
|
|
266
|
+
logger.error(
|
|
267
|
+
f"failed to download from record {record_id} to {download_path}: {e}",
|
|
268
|
+
exc_info=True,
|
|
269
|
+
)
|
|
270
|
+
raise SourceConnectionNetworkError(f"failed to download file {file_data.identifier}")
|
|
271
|
+
|
|
272
|
+
# modify input file_data for download_response
|
|
273
|
+
copied_file_data = copy.deepcopy(file_data)
|
|
274
|
+
copied_file_data.identifier = filename
|
|
275
|
+
copied_file_data.doc_type = "file"
|
|
276
|
+
copied_file_data.metadata.date_processed = str(time())
|
|
277
|
+
copied_file_data.metadata.record_locator = {"document_id": record_id}
|
|
278
|
+
copied_file_data.additional_metadata.pop("ids", None)
|
|
279
|
+
return super().generate_download_response(
|
|
280
|
+
file_data=copied_file_data, download_path=download_path
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
def run(self, file_data: FileData, **kwargs: Any) -> download_responses:
|
|
284
|
+
raise NotImplementedError("Use astradb run_async instead")
|
|
285
|
+
|
|
286
|
+
async def run_async(self, file_data: FileData, **kwargs: Any) -> download_responses:
|
|
287
|
+
# Get metadata from file_data
|
|
288
|
+
ids: list[str] = file_data.additional_metadata["ids"]
|
|
289
|
+
collection_name: str = file_data.additional_metadata["collection_name"]
|
|
290
|
+
keyspace: str = file_data.additional_metadata["keyspace"]
|
|
291
|
+
|
|
292
|
+
# Retrieve results from async collection
|
|
293
|
+
download_responses = []
|
|
294
|
+
async_astra_collection = await get_async_astra_collection(
|
|
295
|
+
connection_config=self.connection_config,
|
|
296
|
+
collection_name=collection_name,
|
|
297
|
+
keyspace=keyspace,
|
|
298
|
+
)
|
|
299
|
+
async for result in async_astra_collection.find({"_id": {"$in": ids}}):
|
|
300
|
+
download_responses.append(
|
|
301
|
+
self.generate_download_response(result=result, file_data=file_data)
|
|
302
|
+
)
|
|
303
|
+
return download_responses
|
|
304
|
+
|
|
305
|
+
|
|
48
306
|
@dataclass
|
|
49
307
|
class AstraDBUploadStager(UploadStager):
|
|
50
308
|
upload_stager_config: AstraDBUploadStagerConfig = field(
|
|
@@ -77,29 +335,6 @@ class AstraDBUploadStager(UploadStager):
|
|
|
77
335
|
return output_path
|
|
78
336
|
|
|
79
337
|
|
|
80
|
-
class AstraDBUploaderConfig(UploaderConfig):
|
|
81
|
-
collection_name: str = Field(
|
|
82
|
-
description="The name of the Astra DB collection. "
|
|
83
|
-
"Note that the collection name must only include letters, "
|
|
84
|
-
"numbers, and underscores."
|
|
85
|
-
)
|
|
86
|
-
embedding_dimension: int = Field(
|
|
87
|
-
default=384, description="The dimensionality of the embeddings"
|
|
88
|
-
)
|
|
89
|
-
keyspace: Optional[str] = Field(default=None, description="The Astra DB connection keyspace.")
|
|
90
|
-
namespace: Optional[str] = Field(
|
|
91
|
-
default=None,
|
|
92
|
-
description="The Astra DB connection namespace.",
|
|
93
|
-
deprecated="Please use 'keyspace' instead.",
|
|
94
|
-
)
|
|
95
|
-
requested_indexing_policy: Optional[dict[str, Any]] = Field(
|
|
96
|
-
default=None,
|
|
97
|
-
description="The indexing policy to use for the collection.",
|
|
98
|
-
examples=['{"deny": ["metadata"]}'],
|
|
99
|
-
)
|
|
100
|
-
batch_size: int = Field(default=20, description="Number of records per batch")
|
|
101
|
-
|
|
102
|
-
|
|
103
338
|
@dataclass
|
|
104
339
|
class AstraDBUploader(Uploader):
|
|
105
340
|
connection_config: AstraDBConnectionConfig
|
|
@@ -108,43 +343,23 @@ class AstraDBUploader(Uploader):
|
|
|
108
343
|
|
|
109
344
|
def precheck(self) -> None:
|
|
110
345
|
try:
|
|
111
|
-
|
|
346
|
+
get_astra_collection(
|
|
347
|
+
connection_config=self.connection_config,
|
|
348
|
+
collection_name=self.upload_config.collection_name,
|
|
349
|
+
keyspace=self.upload_config.keyspace or self.upload_config.namespace,
|
|
350
|
+
)
|
|
112
351
|
except Exception as e:
|
|
113
352
|
logger.error(f"Failed to validate connection {e}", exc_info=True)
|
|
114
353
|
raise DestinationConnectionError(f"failed to validate connection: {e}")
|
|
115
354
|
|
|
116
355
|
@requires_dependencies(["astrapy"], extras="astradb")
|
|
117
356
|
def get_collection(self) -> "AstraDBCollection":
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
# Get the collection_name
|
|
124
|
-
collection_name = self.upload_config.collection_name
|
|
125
|
-
|
|
126
|
-
# Build the Astra DB object.
|
|
127
|
-
access_configs = self.connection_config.access_config.get_secret_value()
|
|
128
|
-
|
|
129
|
-
# Create a client object to interact with the Astra DB
|
|
130
|
-
# caller_name/version for Astra DB tracking
|
|
131
|
-
my_client = AstraDBClient(
|
|
132
|
-
caller_name=integration_name,
|
|
133
|
-
caller_version=integration_version,
|
|
134
|
-
)
|
|
135
|
-
|
|
136
|
-
# Get the database object
|
|
137
|
-
astra_db = my_client.get_database(
|
|
138
|
-
api_endpoint=access_configs.api_endpoint,
|
|
139
|
-
token=access_configs.token,
|
|
140
|
-
keyspace=keyspace_param,
|
|
357
|
+
return get_astra_collection(
|
|
358
|
+
connection_config=self.connection_config,
|
|
359
|
+
collection_name=self.upload_config.collection_name,
|
|
360
|
+
keyspace=self.upload_config.keyspace or self.upload_config.namespace,
|
|
141
361
|
)
|
|
142
362
|
|
|
143
|
-
# Connect to the newly created collection
|
|
144
|
-
astra_db_collection = astra_db.get_collection(name=collection_name)
|
|
145
|
-
|
|
146
|
-
return astra_db_collection
|
|
147
|
-
|
|
148
363
|
def run(self, path: Path, file_data: FileData, **kwargs: Any) -> None:
|
|
149
364
|
with path.open("r") as file:
|
|
150
365
|
elements_dict = json.load(file)
|
|
@@ -160,6 +375,14 @@ class AstraDBUploader(Uploader):
|
|
|
160
375
|
collection.insert_many(chunk)
|
|
161
376
|
|
|
162
377
|
|
|
378
|
+
astra_db_source_entry = SourceRegistryEntry(
|
|
379
|
+
indexer=AstraDBIndexer,
|
|
380
|
+
indexer_config=AstraDBIndexerConfig,
|
|
381
|
+
downloader=AstraDBDownloader,
|
|
382
|
+
downloader_config=AstraDBDownloaderConfig,
|
|
383
|
+
connection_config=AstraDBConnectionConfig,
|
|
384
|
+
)
|
|
385
|
+
|
|
163
386
|
astra_db_destination_entry = DestinationRegistryEntry(
|
|
164
387
|
connection_config=AstraDBConnectionConfig,
|
|
165
388
|
upload_stager_config=AstraDBUploadStagerConfig,
|
|
@@ -166,7 +166,9 @@ class DatabricksVolumesUploader(Uploader, ABC):
|
|
|
166
166
|
raise DestinationConnectionError(f"failed to validate connection: {e}")
|
|
167
167
|
|
|
168
168
|
def run(self, path: Path, file_data: FileData, **kwargs: Any) -> None:
|
|
169
|
-
output_path = os.path.join(
|
|
169
|
+
output_path = os.path.join(
|
|
170
|
+
self.upload_config.path, f"{file_data.source_identifiers.filename}.json"
|
|
171
|
+
)
|
|
170
172
|
with open(path, "rb") as elements_file:
|
|
171
173
|
self.connection_config.get_client().files.upload(
|
|
172
174
|
file_path=output_path,
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from multiprocessing import Process
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from pydantic import Field, Secret
|
|
10
|
+
|
|
11
|
+
from unstructured_ingest.error import DestinationConnectionError
|
|
12
|
+
from unstructured_ingest.utils.dep_check import requires_dependencies
|
|
13
|
+
from unstructured_ingest.utils.table import convert_to_pandas_dataframe
|
|
14
|
+
from unstructured_ingest.v2.interfaces import (
|
|
15
|
+
AccessConfig,
|
|
16
|
+
ConnectionConfig,
|
|
17
|
+
FileData,
|
|
18
|
+
Uploader,
|
|
19
|
+
UploaderConfig,
|
|
20
|
+
UploadStager,
|
|
21
|
+
UploadStagerConfig,
|
|
22
|
+
)
|
|
23
|
+
from unstructured_ingest.v2.logger import logger
|
|
24
|
+
from unstructured_ingest.v2.processes.connector_registry import DestinationRegistryEntry
|
|
25
|
+
|
|
26
|
+
CONNECTOR_TYPE = "delta_table"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DeltaTableAccessConfig(AccessConfig):
|
|
30
|
+
aws_access_key_id: Optional[str] = Field(default=None, description="AWS Access Key Id")
|
|
31
|
+
aws_secret_access_key: Optional[str] = Field(default=None, description="AWS Secret Access Key")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DeltaTableConnectionConfig(ConnectionConfig):
|
|
35
|
+
access_config: Secret[DeltaTableAccessConfig] = Field(
|
|
36
|
+
default=DeltaTableAccessConfig(), validate_default=True
|
|
37
|
+
)
|
|
38
|
+
aws_region: Optional[str] = Field(default=None, description="AWS Region")
|
|
39
|
+
table_uri: str = Field(
|
|
40
|
+
default=None,
|
|
41
|
+
description=(
|
|
42
|
+
"Local path or path to the target folder in the S3 bucket, "
|
|
43
|
+
"formatted as s3://my-bucket/my-folder/"
|
|
44
|
+
),
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def update_storage_options(self, storage_options: dict) -> None:
|
|
48
|
+
secrets = self.access_config.get_secret_value()
|
|
49
|
+
if self.aws_region and secrets.aws_access_key_id and secrets.aws_secret_access_key:
|
|
50
|
+
storage_options["AWS_REGION"] = self.aws_region
|
|
51
|
+
storage_options["AWS_ACCESS_KEY_ID"] = secrets.aws_access_key_id
|
|
52
|
+
storage_options["AWS_SECRET_ACCESS_KEY"] = secrets.aws_secret_access_key
|
|
53
|
+
# Delta-rs doesn't support concurrent S3 writes without external locks (DynamoDB).
|
|
54
|
+
# This flag allows single-writer uploads to S3 without using locks, according to:
|
|
55
|
+
# https://delta-io.github.io/delta-rs/usage/writing/writing-to-s3-with-locking-provider/
|
|
56
|
+
storage_options["AWS_S3_ALLOW_UNSAFE_RENAME"] = "true"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DeltaTableUploadStagerConfig(UploadStagerConfig):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class DeltaTableUploadStager(UploadStager):
|
|
65
|
+
upload_stager_config: DeltaTableUploadStagerConfig = field(
|
|
66
|
+
default_factory=lambda: DeltaTableUploadStagerConfig()
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def run(
|
|
70
|
+
self,
|
|
71
|
+
elements_filepath: Path,
|
|
72
|
+
output_dir: Path,
|
|
73
|
+
output_filename: str,
|
|
74
|
+
**kwargs: Any,
|
|
75
|
+
) -> Path:
|
|
76
|
+
with open(elements_filepath) as elements_file:
|
|
77
|
+
elements_contents = json.load(elements_file)
|
|
78
|
+
|
|
79
|
+
output_path = Path(output_dir) / Path(f"{output_filename}.parquet")
|
|
80
|
+
|
|
81
|
+
df = convert_to_pandas_dataframe(elements_dict=elements_contents)
|
|
82
|
+
df.to_parquet(output_path)
|
|
83
|
+
|
|
84
|
+
return output_path
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class DeltaTableUploaderConfig(UploaderConfig):
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class DeltaTableUploader(Uploader):
|
|
93
|
+
upload_config: DeltaTableUploaderConfig
|
|
94
|
+
connection_config: DeltaTableConnectionConfig
|
|
95
|
+
connector_type: str = CONNECTOR_TYPE
|
|
96
|
+
|
|
97
|
+
@requires_dependencies(["s3fs", "fsspec"], extras="s3")
|
|
98
|
+
def precheck(self):
|
|
99
|
+
secrets = self.connection_config.access_config.get_secret_value()
|
|
100
|
+
if (
|
|
101
|
+
self.connection_config.aws_region
|
|
102
|
+
and secrets.aws_access_key_id
|
|
103
|
+
and secrets.aws_secret_access_key
|
|
104
|
+
):
|
|
105
|
+
from fsspec import get_filesystem_class
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
fs = get_filesystem_class("s3")(
|
|
109
|
+
key=secrets.aws_access_key_id, secret=secrets.aws_secret_access_key
|
|
110
|
+
)
|
|
111
|
+
fs.write_bytes(path=self.connection_config.table_uri, value=b"")
|
|
112
|
+
|
|
113
|
+
except Exception as e:
|
|
114
|
+
logger.error(f"failed to validate connection: {e}", exc_info=True)
|
|
115
|
+
raise DestinationConnectionError(f"failed to validate connection: {e}")
|
|
116
|
+
|
|
117
|
+
def process_csv(self, csv_paths: list[Path]) -> pd.DataFrame:
|
|
118
|
+
logger.debug(f"uploading content from {len(csv_paths)} csv files")
|
|
119
|
+
df = pd.concat((pd.read_csv(path) for path in csv_paths), ignore_index=True)
|
|
120
|
+
return df
|
|
121
|
+
|
|
122
|
+
def process_json(self, json_paths: list[Path]) -> pd.DataFrame:
|
|
123
|
+
logger.debug(f"uploading content from {len(json_paths)} json files")
|
|
124
|
+
all_records = []
|
|
125
|
+
for p in json_paths:
|
|
126
|
+
with open(p) as json_file:
|
|
127
|
+
all_records.extend(json.load(json_file))
|
|
128
|
+
|
|
129
|
+
return pd.DataFrame(data=all_records)
|
|
130
|
+
|
|
131
|
+
def process_parquet(self, parquet_paths: list[Path]) -> pd.DataFrame:
|
|
132
|
+
logger.debug(f"uploading content from {len(parquet_paths)} parquet files")
|
|
133
|
+
df = pd.concat((pd.read_parquet(path) for path in parquet_paths), ignore_index=True)
|
|
134
|
+
return df
|
|
135
|
+
|
|
136
|
+
def read_dataframe(self, path: Path) -> pd.DataFrame:
|
|
137
|
+
if path.suffix == ".csv":
|
|
138
|
+
return self.process_csv(csv_paths=[path])
|
|
139
|
+
elif path.suffix == ".json":
|
|
140
|
+
return self.process_json(json_paths=[path])
|
|
141
|
+
elif path.suffix == ".parquet":
|
|
142
|
+
return self.process_parquet(parquet_paths=[path])
|
|
143
|
+
else:
|
|
144
|
+
raise ValueError(f"Unsupported file type, must be parquet, json or csv file: {path}")
|
|
145
|
+
|
|
146
|
+
@requires_dependencies(["deltalake"], extras="delta-table")
|
|
147
|
+
def run(self, path: Path, file_data: FileData, **kwargs: Any) -> None:
|
|
148
|
+
from deltalake.writer import write_deltalake
|
|
149
|
+
|
|
150
|
+
df = self.read_dataframe(path)
|
|
151
|
+
updated_upload_path = os.path.join(
|
|
152
|
+
self.connection_config.table_uri, file_data.source_identifiers.relative_path
|
|
153
|
+
)
|
|
154
|
+
logger.info(
|
|
155
|
+
f"writing {len(df)} rows to destination table "
|
|
156
|
+
f"at {updated_upload_path}\ndtypes: {df.dtypes}",
|
|
157
|
+
)
|
|
158
|
+
storage_options = {}
|
|
159
|
+
self.connection_config.update_storage_options(storage_options=storage_options)
|
|
160
|
+
|
|
161
|
+
writer_kwargs = {
|
|
162
|
+
"table_or_uri": updated_upload_path,
|
|
163
|
+
"data": df,
|
|
164
|
+
"mode": "overwrite",
|
|
165
|
+
"storage_options": storage_options,
|
|
166
|
+
}
|
|
167
|
+
# NOTE: deltalake writer on Linux sometimes can finish but still trigger a SIGABRT and cause
|
|
168
|
+
# ingest to fail, even though all tasks are completed normally. Putting the writer into a
|
|
169
|
+
# process mitigates this issue by ensuring python interpreter waits properly for deltalake's
|
|
170
|
+
# rust backend to finish
|
|
171
|
+
writer = Process(
|
|
172
|
+
target=write_deltalake,
|
|
173
|
+
kwargs=writer_kwargs,
|
|
174
|
+
)
|
|
175
|
+
writer.start()
|
|
176
|
+
writer.join()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
delta_table_destination_entry = DestinationRegistryEntry(
|
|
180
|
+
connection_config=DeltaTableConnectionConfig,
|
|
181
|
+
uploader=DeltaTableUploader,
|
|
182
|
+
uploader_config=DeltaTableUploaderConfig,
|
|
183
|
+
upload_stager=DeltaTableUploadStager,
|
|
184
|
+
upload_stager_config=DeltaTableUploadStagerConfig,
|
|
185
|
+
)
|