Skip to content

download

Classes

DownloadMetadata

Bases: BaseModel

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
18
19
20
21
22
23
class DownloadMetadata(BaseModel):
    url: str = Field(description="The url of the download request.")
    response_headers: List[Dict[str, str]] = Field(
        description="The response headers of the download request."
    )
    request_time: str = Field(description="The time the request was made.")

Attributes

url: str = Field(description='The url of the download request.') instance-attribute class-attribute
response_headers: List[Dict[str, str]] = Field(description='The response headers of the download request.') instance-attribute class-attribute
request_time: str = Field(description='The time the request was made.') instance-attribute class-attribute

DownloadBundleMetadata

Bases: DownloadMetadata

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
26
27
28
29
class DownloadBundleMetadata(DownloadMetadata):
    import_config: FolderImportConfig = Field(
        description="The import configuration that was used to import the files from the source bundle."
    )

Attributes

import_config: FolderImportConfig = Field(description='The import configuration that was used to import the files from the source bundle.') instance-attribute class-attribute

Functions

get_onboard_model_cls(onboard_type: Union[str, None]) -> Union[None, Type[OnboardDataModel]] cached

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
32
33
34
35
36
37
38
39
40
41
42
43
44
@lru_cache()
def get_onboard_model_cls(
    onboard_type: Union[str, None]
) -> Union[None, Type[OnboardDataModel]]:

    if not onboard_type:
        return None

    from kiara.registries.models import ModelRegistry

    model_registry = ModelRegistry.instance()
    model_cls = model_registry.get_model_cls(onboard_type, OnboardDataModel)
    return model_cls  # type: ignore

download_file(url: str, target: Union[str, None] = None, file_name: Union[str, None] = None, attach_metadata: bool = True, return_md5_hash: bool = False) -> Union[KiaraFile, Tuple[KiaraFile, str]]

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def download_file(
    url: str,
    target: Union[str, None] = None,
    file_name: Union[str, None] = None,
    attach_metadata: bool = True,
    return_md5_hash: bool = False,
) -> Union[KiaraFile, Tuple[KiaraFile, str]]:

    import hashlib

    import httpx
    import pytz

    if not file_name:
        # TODO: make this smarter, using content-disposition headers if available
        file_name = url.split("/")[-1]

    if not target:
        tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=file_name)

        def rm_tmp_file():
            os.unlink(tmp_file.name)

        atexit.register(rm_tmp_file)

        _target = Path(tmp_file.name)
    else:
        _target = Path(target)
        _target.parent.mkdir(parents=True, exist_ok=True)

    if return_md5_hash:
        hash_md5 = hashlib.md5()  # noqa

    history = []
    datetime.utcnow().replace(tzinfo=pytz.utc)
    with open(_target, "wb") as f:
        with httpx.stream("GET", url, follow_redirects=True) as r:
            if r.status_code < 200 or r.status_code >= 399:
                raise KiaraException(
                    f"Could not download file from {url}: status code {r.status_code}."
                )
            history.append(dict(r.headers))
            for h in r.history:
                history.append(dict(h.headers))
            for data in r.iter_bytes():
                if return_md5_hash:
                    hash_md5.update(data)
                f.write(data)

    result_file = KiaraFile.load_file(_target.as_posix(), file_name)

    if attach_metadata:
        metadata = {
            "url": url,
            "response_headers": history,
            "request_time": datetime.utcnow().replace(tzinfo=pytz.utc).isoformat(),
        }
        _metadata = DownloadMetadata(**metadata)
        result_file.metadata["download_info"] = _metadata.dict()
        result_file.metadata_schemas["download_info"] = DownloadMetadata.schema_json()

    if return_md5_hash:
        return result_file, hash_md5.hexdigest()
    else:
        return result_file

download_file_bundle(url: str, attach_metadata: bool = True, import_config: Union[FolderImportConfig, None] = None) -> KiaraFileBundle

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def download_file_bundle(
    url: str,
    attach_metadata: bool = True,
    import_config: Union[FolderImportConfig, None] = None,
) -> KiaraFileBundle:

    import shutil
    from datetime import datetime
    from urllib.parse import urlparse

    import httpx
    import pytz

    suffix = None
    try:
        parsed_url = urlparse(url)
        _, suffix = os.path.splitext(parsed_url.path)
    except Exception:
        pass
    if not suffix:
        suffix = ""

    tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
    atexit.register(tmp_file.close)

    history = []
    datetime.utcnow().replace(tzinfo=pytz.utc)
    with open(tmp_file.name, "wb") as f:
        with httpx.stream("GET", url, follow_redirects=True) as r:
            history.append(dict(r.headers))
            for h in r.history:
                history.append(dict(h.headers))
            for data in r.iter_bytes():
                f.write(data)

    out_dir = tempfile.mkdtemp()

    def del_out_dir():
        shutil.rmtree(out_dir, ignore_errors=True)

    atexit.register(del_out_dir)

    # error = None
    # try:
    #     shutil.unpack_archive(tmp_file.name, out_dir)
    # except Exception:
    #     # try patool, maybe we're lucky
    #     try:
    #         import patoolib
    #
    #         patoolib.extract_archive(tmp_file.name, outdir=out_dir)
    #     except Exception as e:
    #         error = e
    #
    # if error is not None:
    #     raise KiaraException(msg=f"Could not extract archive: {error}.")

    unpack_archive(tmp_file.name, out_dir)
    bundle = KiaraFileBundle.import_folder(out_dir, import_config=import_config)

    if import_config is None:
        ic_dict = {}
    elif isinstance(import_config, FolderImportConfig):
        ic_dict = import_config.dict()
    else:
        ic_dict = import_config
    if attach_metadata:
        metadata = {
            "url": url,
            "response_headers": history,
            "request_time": datetime.utcnow().replace(tzinfo=pytz.utc).isoformat(),
            "import_config": ic_dict,
        }
        _metadata = DownloadBundleMetadata(**metadata)
        bundle.metadata["download_info"] = _metadata.dict()
        bundle.metadata_schemas["download_info"] = DownloadMetadata.schema_json()

    return bundle

find_matching_onboard_models(uri: str, for_bundle: bool = False) -> Mapping[Type[OnboardDataModel], Tuple[bool, str]]

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def find_matching_onboard_models(
    uri: str, for_bundle: bool = False
) -> Mapping[Type[OnboardDataModel], Tuple[bool, str]]:

    from kiara.registries.models import ModelRegistry

    model_registry = ModelRegistry.instance()
    onboard_models = model_registry.get_models_of_type(
        OnboardDataModel
    ).item_infos.values()

    result = {}
    onboard_model: Type[OnboardDataModel]
    for onboard_model in onboard_models:  # type: ignore

        python_cls: Type[OnboardDataModel] = onboard_model.python_class.get_class()  # type: ignore
        if for_bundle:
            result[python_cls] = python_cls.accepts_bundle_uri(uri)
        else:
            result[python_cls] = python_cls.accepts_uri(uri)

    return result

onboard_file(source: str, file_name: Union[str, None] = None, onboard_type: Union[str, None] = None, attach_metadata: bool = True) -> KiaraFile

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def onboard_file(
    source: str,
    file_name: Union[str, None] = None,
    onboard_type: Union[str, None] = None,
    attach_metadata: bool = True,
) -> KiaraFile:

    if not onboard_type:

        model_clsses = find_matching_onboard_models(source)
        matches = [k for k, v in model_clsses.items() if v[0]]
        if not matches:
            raise KiaraException(
                msg=f"Can't onboard file from '{source}': no onboard models found that accept this source type."
            )
        elif len(matches) > 1:
            msg = "Valid onboarding types for this uri:\n\n"
            for k, v in model_clsses.items():
                if not v[0]:
                    continue
                msg += f"  - {k._kiara_model_id}: {v[1]}\n"
            raise KiaraException(
                msg=f"Can't onboard file from '{source}': multiple onboard models found that accept this source type.\n\n{msg}"
            )

        model_cls: Type[OnboardDataModel] = matches[0]

    else:

        model_cls = get_onboard_model_cls(onboard_type=onboard_type)  # type: ignore
        if not model_cls:
            raise KiaraException(msg=f"Can't onboard file from '{source}' using onboard type '{onboard_type}': no onboard model found with this name.")  # type: ignore

        valid, msg = model_cls.accepts_uri(source)
        if not valid:
            raise KiaraException(msg=f"Can't onboard file from '{source}' using onboard type '{model_cls._kiara_model_id}': {msg}")  # type: ignore

    if not model_cls.get_config_fields():
        model = model_cls()
    else:
        raise NotImplementedError()

    result = model.retrieve(
        uri=source, file_name=file_name, attach_metadata=attach_metadata
    )
    if not result:
        raise KiaraException(msg=f"Can't onboard file from '{source}' using onboard type '{model_cls._kiara_model_id}': no result data retrieved. This is most likely a bug.")  # type: ignore

    if isinstance(result, str):
        data = KiaraFile.load_file(result, file_name=file_name)
    elif not isinstance(result, KiaraFile):
        raise KiaraException(
            "Can't onboard file: onboard model returned data that is not a file. This is most likely a bug."
        )
    else:
        data = result

    return data

onboard_file_bundle(source: str, import_config: Union[FolderImportConfig, None], onboard_type: Union[str, None] = None, attach_metadata: bool = True) -> KiaraFileBundle

Source code in /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/kiara_plugin/onboarding/utils/download.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def onboard_file_bundle(
    source: str,
    import_config: Union[FolderImportConfig, None],
    onboard_type: Union[str, None] = None,
    attach_metadata: bool = True,
) -> KiaraFileBundle:

    if not onboard_type:

        model_clsses = find_matching_onboard_models(uri=source, for_bundle=True)
        matches = [k for k, v in model_clsses.items() if v[0]]
        if not matches:
            raise KiaraException(
                msg=f"Can't onboard file from '{source}': no onboard models found that accept this source type."
            )
        elif len(matches) > 1:
            msg = "Valid onboarding types for this uri:\n\n"
            for k, v in model_clsses.items():
                if not v[0]:
                    continue
                msg += f"  - {k._kiara_model_id}: {v[1]}\n"
            raise KiaraException(
                msg=f"Can't onboard file from '{source}': multiple onboard models found that accept this source type.\n\n{msg}"
            )

        model_cls: Type[OnboardDataModel] = matches[0]

    else:
        model_cls = get_onboard_model_cls(onboard_type=onboard_type)  # type: ignore
        if not model_cls:
            raise KiaraException(msg=f"Can't onboard file from '{source}' using onboard type '{onboard_type}': no onboard model found with this name.")  # type: ignore
        valid, msg = model_cls.accepts_bundle_uri(source)
        if not valid:
            raise KiaraException(msg=f"Can't onboard file from '{source}' using onboard type '{model_cls._kiara_model_id}': {msg}")  # type: ignore

    if not model_cls.get_config_fields():
        model = model_cls()
    else:
        raise NotImplementedError()

    if not import_config:
        import_config = FolderImportConfig()

    try:
        result: Union[None, KiaraFileBundle] = model.retrieve_bundle(
            uri=source, import_config=import_config, attach_metadata=attach_metadata
        )

        if not result:
            raise KiaraException(msg=f"Can't onboard file bundle from '{source}' using onboard type '{model_cls._kiara_model_id}': no result data retrieved. This is most likely a bug.")  # type: ignore

        if isinstance(result, str):
            result = KiaraFileBundle.import_folder(source=result)

    except NotImplementedError:
        result = None

    if not result:
        result_file = model.retrieve(
            uri=source, file_name=None, attach_metadata=attach_metadata
        )
        if not result_file:
            raise KiaraException(msg=f"Can't onboard file bundle from '{source}' using onboard type '{model_cls._kiara_model_id}': no result data retrieved. This is most likely a bug.")  # type: ignore

        if isinstance(result, str):
            imported_bundle_file = KiaraFile.load_file(result_file)  # type: ignore
        elif not isinstance(result_file, KiaraFile):
            raise KiaraException(
                "Can't onboard file: onboard model returned data that is not a file. This is most likely a bug."
            )
        else:
            imported_bundle_file = result_file

        imported_bundle = KiaraFileBundle.from_archive_file(
            imported_bundle_file, import_config=import_config
        )
    else:
        imported_bundle = result

    return imported_bundle