insira-datafeed-api-client 1.0.1__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Insira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: insira-datafeed-api-client
3
+ Version: 1.0.1
4
+ Summary: A client interface and sample code for Insira's Data Feed-API and the available content sets.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: insira,cortellis,datafeed,api,client
8
+ Author: cortellislabs
9
+ Author-email: cortellislabs@clarivate.com
10
+ Requires-Python: >=3.9,<4.0
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Dist: httpx (>=0.28.0,<0.29.0)
23
+ Requires-Dist: platformdirs (>=3.11.0,<4.0.0)
24
+ Project-URL: Homepage, https://cortellislabs.com/
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Insira's DATA FEED-API
28
+
29
+ A client interface and sample code for Insira's Data Feed-API and the available content sets.
30
+
31
+ ## Description
32
+
33
+ Insira Data Feed API provides consolidated access to bulk-download various Insira content sets from multiple domains.
34
+
35
+ ## Getting Started
36
+
37
+ ### Authorization
38
+
39
+ A valid API KEY issued by Insira is required.
40
+ You can contact your Insira Sales Account Representative or submit a sales inquiry to be contacted and subscribe to one or more content sets ([Sales enquiries](https://insiraglobal.com/#mission)).
41
+
42
+ ### Installation
43
+
44
+ **Requires Python** 3.9.0+
45
+
46
+ ```
47
+ pip install insira-datafeed-api-client
48
+ ```
49
+
50
+ ## Usage
51
+
52
+ ### Import
53
+
54
+ ```
55
+ from insira import datafeedapi
56
+ ```
57
+
58
+ ### Examples
59
+
60
+ - Download a dataset in async mode. (example with all parameters)
61
+
62
+ ```python
63
+ client = datafeedapi.Client('api key','server url')
64
+ response = client.fetch('dataset', 'preset', 'internal change number', 'output format', 'split files', 'extract resources')
65
+ ```
66
+
67
+ - Download a dataset in sync mode. (example with all parameters)
68
+
69
+ ```python
70
+ client = datafeedapi.Client('api key','server url')
71
+ response = client.fetch_sync('dataset', 'preset', 'internal change number', 'output format', 'split files', 'extract resources')
72
+ ```
73
+
74
+ Note 1: 'api key' and 'server url' can be set into the config.py file.
75
+
76
+ Note 2: 'dataset', 'preset', 'internal change number', 'output format', 'split files' and 'extract resources' parameters have default settings.
77
+
78
+ ## Help
79
+
80
+ ### Support
81
+
82
+ - For technical help or questions regarding the repo, you can leave a message into github;
83
+ - You can also contact us at [cortellislabs](cortellislabs@clarivate.com)
84
+ - Our online documentation is available from the dedicated page at [Insira APIs and Data Products online documentation](https://cortellislabs.com/docs/data-feed-api-private-overview/).
85
+
86
+ ### License
87
+
88
+ This project is licensed under the MIT License - see the LICENSE.md file for details.
89
+
@@ -0,0 +1,62 @@
1
+ # Insira's DATA FEED-API
2
+
3
+ A client interface and sample code for Insira's Data Feed-API and the available content sets.
4
+
5
+ ## Description
6
+
7
+ Insira Data Feed API provides consolidated access to bulk-download various Insira content sets from multiple domains.
8
+
9
+ ## Getting Started
10
+
11
+ ### Authorization
12
+
13
+ A valid API KEY issued by Insira is required.
14
+ You can contact your Insira Sales Account Representative or submit a sales inquiry to be contacted and subscribe to one or more content sets ([Sales enquiries](https://insiraglobal.com/#mission)).
15
+
16
+ ### Installation
17
+
18
+ **Requires Python** 3.9.0+
19
+
20
+ ```
21
+ pip install insira-datafeed-api-client
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ### Import
27
+
28
+ ```
29
+ from insira import datafeedapi
30
+ ```
31
+
32
+ ### Examples
33
+
34
+ - Download a dataset in async mode. (example with all parameters)
35
+
36
+ ```python
37
+ client = datafeedapi.Client('api key','server url')
38
+ response = client.fetch('dataset', 'preset', 'internal change number', 'output format', 'split files', 'extract resources')
39
+ ```
40
+
41
+ - Download a dataset in sync mode. (example with all parameters)
42
+
43
+ ```python
44
+ client = datafeedapi.Client('api key','server url')
45
+ response = client.fetch_sync('dataset', 'preset', 'internal change number', 'output format', 'split files', 'extract resources')
46
+ ```
47
+
48
+ Note 1: 'api key' and 'server url' can be set into the config.py file.
49
+
50
+ Note 2: 'dataset', 'preset', 'internal change number', 'output format', 'split files' and 'extract resources' parameters have default settings.
51
+
52
+ ## Help
53
+
54
+ ### Support
55
+
56
+ - For technical help or questions regarding the repo, you can leave a message into github;
57
+ - You can also contact us at [cortellislabs](cortellislabs@clarivate.com)
58
+ - Our online documentation is available from the dedicated page at [Insira APIs and Data Products online documentation](https://cortellislabs.com/docs/data-feed-api-private-overview/).
59
+
60
+ ### License
61
+
62
+ This project is licensed under the MIT License - see the LICENSE.md file for details.
@@ -0,0 +1,50 @@
1
+ [project]
2
+ name = "insira-datafeed-api-client"
3
+ version = "1.0.1"
4
+
5
+ [tool.poetry]
6
+ name = "insira-datafeed-api-client"
7
+ version = "1.0.1"
8
+ description = "A client interface and sample code for Insira's Data Feed-API and the available content sets."
9
+ authors = ["cortellislabs <cortellislabs@clarivate.com>"]
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ homepage = "https://cortellislabs.com/"
13
+ keywords = ["insira", "cortellis", "datafeed", "api", "client"]
14
+ classifiers = [
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Software Development :: Libraries :: Python Modules",
18
+ ]
19
+ packages = [{include = "insira/datafeedapi", from = "src/"}]
20
+
21
+ [tool.poetry.dependencies]
22
+ python = "^3.9"
23
+ httpx = "^0.28.0"
24
+ platformdirs = "^3.11.0"
25
+
26
+ [tool.poetry.group.dev.dependencies]
27
+ pre-commit = "^3.6.2"
28
+
29
+ [build-system]
30
+ requires = ["poetry-core"]
31
+ build-backend = "poetry.core.masonry.api"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src/"]
35
+ include = ["insira.datafeedapi"]
36
+
37
+ [tool.poetry.scripts]
38
+ datafeed-api-client = "insira.datafeedapi.client:main"
39
+
40
+ [tool.isort]
41
+ profile = "black"
42
+
43
+ [tool.black]
44
+ line-length = 100
45
+ exclude = ".git,.hg,.mypy_cache,_build,buck-out,build,dist"
46
+
47
+ [tool.ruff]
48
+ target-version = "py39"
49
+ select = ["E", "F", "W", "B"]
50
+ ignore = ["E501", "E402", "B018"]
@@ -0,0 +1,3 @@
1
+ from .client import Client
2
+
3
+ __all__ = ["Client"]
@@ -0,0 +1,613 @@
1
+ #!/usr/bin/env python
2
+ import argparse
3
+ import asyncio
4
+ import glob
5
+ import json
6
+ import logging
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import time
11
+ import traceback
12
+ from collections.abc import Coroutine
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any, Literal, Optional
16
+ from urllib.parse import urlparse
17
+
18
+ from httpx import AsyncClient, HTTPStatusError, Response, TransportError
19
+ from platformdirs import user_config_dir
20
+
21
+ LOGGER = logging.getLogger("insira.datafeedapi")
22
+
23
+ # When a new variable is added or existing changed to the config file, It should be available to client.py
24
+ # Start
25
+ from insira.datafeedapi import config as app_config
26
+
27
+ # Autovivify our application's private directory
28
+ MODULE_DIR = Path(__file__).parent
29
+ PRIVATE_DIR = Path(user_config_dir("datafeedapi", "insira"))
30
+
31
+ if not PRIVATE_DIR.exists():
32
+ os.makedirs(PRIVATE_DIR)
33
+ else:
34
+ if not PRIVATE_DIR.is_dir():
35
+ sys.stderr.write(f"Error: {PRIVATE_DIR} is a file, but should be a directory!\n")
36
+ sys.exit(1)
37
+ if not (PRIVATE_DIR / "config.py").exists():
38
+ shutil.copy(MODULE_DIR / "config.py", PRIVATE_DIR)
39
+
40
+ # Import user config
41
+ sys.path.insert(0, str(PRIVATE_DIR.absolute()))
42
+ import config
43
+
44
+ app_config_vars = {key: value for key, value in app_config.__dict__.items() if key.isupper()}
45
+ user_config_vars = {key: value for key, value in config.__dict__.items() if key.isupper()}
46
+
47
+ for key, value in app_config_vars.items():
48
+ if key not in user_config_vars:
49
+ config.__dict__[key] = value
50
+
51
+ sys.path = sys.path[1:]
52
+ # End
53
+
54
+
55
+ # Helper classes & helper functions for performing HTTP calls
56
+ class HTTPResponseNotOK(Exception):
57
+ code = 500
58
+ message = ""
59
+
60
+ def __init__(self, code: int, message: str):
61
+ self.code = code
62
+ self.message = message
63
+
64
+ def __str__(self):
65
+ return self.message
66
+
67
+
68
+ def _retry_exception_logic(e: Exception, ttl: int) -> float:
69
+ if ttl >= config.RETRIES:
70
+ LOGGER.error("Out of retries; giving up")
71
+ raise (
72
+ HTTPResponseNotOK(e.response.status_code, e.response.text)
73
+ if isinstance(e, HTTPStatusError)
74
+ else e
75
+ )
76
+
77
+ if isinstance(e, TransportError):
78
+ return config.RETRY_WAIT * 1.5
79
+
80
+ if isinstance(e, HTTPStatusError):
81
+ if 400 <= e.response.status_code < 500:
82
+ # most 4xx messages are genuinely client problems and ought to be fatal
83
+ raise HTTPResponseNotOK(e.response.status_code, e.response.text)
84
+ elif 500 <= e.response.status_code < 600:
85
+ # 5xx errors are mostly transient, but increase delay to avoid overloading remote server
86
+ return config.RETRY_WAIT * 2
87
+ raise e
88
+
89
+
90
+ def _retry_async(func):
91
+ async def wrapper_retry(*args, **kwargs):
92
+ for ttl in range(0, config.RETRIES):
93
+ try:
94
+ return await func(*args, **kwargs)
95
+ except Exception as e:
96
+ LOGGER.error("Request failed with error %s", e)
97
+
98
+ retry_wait = _retry_exception_logic(e, ttl)
99
+ LOGGER.error(
100
+ "Retrying (attempt %s of %s) after %s s...", ttl + 1, config.RETRIES, retry_wait
101
+ )
102
+ await asyncio.sleep(retry_wait)
103
+ LOGGER.error("Retrying")
104
+
105
+ return wrapper_retry
106
+
107
+
108
+ def _async_to_sync(awaitable: Coroutine) -> Any:
109
+ return asyncio.run(awaitable)
110
+
111
+
112
+ async def _pool_tasks(func: Any, param_list: list[tuple[Any, ...]]) -> None:
113
+ tasks = []
114
+
115
+ for item in param_list:
116
+ tasks.append(asyncio.create_task(func(*item)))
117
+
118
+ if len(tasks) >= config.MAX_CONNECT:
119
+ await asyncio.gather(*tasks)
120
+ tasks = []
121
+
122
+ if tasks:
123
+ await asyncio.gather(*tasks)
124
+
125
+
126
+ def get_file_length(file_path: str) -> int:
127
+ """Get the total bytes of the file."""
128
+ if not os.path.exists(file_path):
129
+ return 0
130
+ return os.path.getsize(file_path)
131
+
132
+
133
+ class MissingAuth(Exception):
134
+ def __str__(self):
135
+ return "No API key found! Please specify as the environment variable DATAFEED_API_KEY or pass to Client initializer."
136
+
137
+
138
+ class Client:
139
+ """A client for the Insira DataFeed API"""
140
+
141
+ def __init__(self, api_key: Optional[str] = None, server_url: Optional[str] = None) -> None:
142
+ self.api_key = api_key or config.API_KEY
143
+ self.server_url = (server_url or config.SERVER_URL).rstrip("/") + "/"
144
+ if not self.api_key:
145
+ raise MissingAuth
146
+
147
+ @property
148
+ def _async_client(self) -> AsyncClient:
149
+ # create new client because it is coupled with async event loop
150
+ return AsyncClient(timeout=120)
151
+
152
+ def _setup_headers(
153
+ self, content_type: Literal["binary", "text"], current_chunk_length: int = 0
154
+ ) -> dict[str, str]:
155
+ headers = {"X-ApiKey": self.api_key}
156
+ if content_type == "text":
157
+ headers["Content-Type"] = "application/json"
158
+ if current_chunk_length > 0:
159
+ headers.update({"Range": f"bytes={current_chunk_length}-"})
160
+ return headers
161
+
162
+ def _process_json_response(self, r: Response) -> dict:
163
+ if r.is_success:
164
+ return r.json()
165
+
166
+ r.raise_for_status()
167
+ return {}
168
+
169
+ @_retry_async
170
+ async def _run_call_async(
171
+ self, pg: str, url: str, payload: Optional[dict[str, Any]] = None
172
+ ) -> dict[str, Any]:
173
+ return self._process_json_response(
174
+ await self._async_client.request(
175
+ pg, url, headers=self._setup_headers("text"), json=payload, follow_redirects=True
176
+ )
177
+ )
178
+
179
+ # contentSets info
180
+ def get_content_sets_info_sync(self) -> list[dict[str, str]]:
181
+ return _async_to_sync(self.get_content_sets_info_async())
182
+
183
+ async def get_content_sets_info_async(self) -> list[dict[str, str]]:
184
+ response = await self._run_call_async("GET", f"{self.server_url}info")
185
+ return response["subscriptions"]
186
+
187
+ # requestPackage
188
+ def _build_request_package_payload(
189
+ self,
190
+ content_set_name: str,
191
+ preset_content_set_name: str,
192
+ internal_change_number: int = 0,
193
+ output_format: Literal["json", "parquet"] = "json",
194
+ split_files: bool = False,
195
+ ) -> dict[str, Any]:
196
+ payload_request = {
197
+ "contentSet": content_set_name,
198
+ "format": output_format,
199
+ "preset": preset_content_set_name,
200
+ "splitFiles": split_files,
201
+ }
202
+ if internal_change_number > 0:
203
+ payload_request["filters"] = [
204
+ {"field": "internalChangeNumber", "op": "gt", "value": internal_change_number}
205
+ ]
206
+ return payload_request
207
+
208
+ def request_package_sync(
209
+ self,
210
+ content_set_name: str,
211
+ preset_content_set_name: str,
212
+ internal_change_number: int = 0,
213
+ output_format: Literal["json", "parquet"] = "json",
214
+ split_files: bool = False,
215
+ ) -> str:
216
+ """Request that datafeed begin packaging a contentset for download (sync version)"""
217
+ return _async_to_sync(
218
+ self.request_package_async(
219
+ content_set_name=content_set_name,
220
+ preset_content_set_name=preset_content_set_name,
221
+ internal_change_number=internal_change_number,
222
+ output_format=output_format,
223
+ split_files=split_files,
224
+ )
225
+ )
226
+
227
+ async def request_package_async(
228
+ self,
229
+ content_set_name: str,
230
+ preset_content_set_name: str,
231
+ internal_change_number: int = 0,
232
+ output_format: Literal["json", "parquet"] = "json",
233
+ split_files: bool = False,
234
+ ) -> str:
235
+ """Request that datafeed begin packaging a contentset for download (async version)"""
236
+ LOGGER.info(
237
+ "Requesting content set '%s' preset '%s' ...", content_set_name, preset_content_set_name
238
+ )
239
+ payload = self._build_request_package_payload(
240
+ content_set_name,
241
+ preset_content_set_name,
242
+ internal_change_number,
243
+ output_format,
244
+ split_files,
245
+ )
246
+ response = await self._run_call_async("POST", f"{self.server_url}requestPackage", payload)
247
+
248
+ if "token" not in response or not response["token"]:
249
+ raise ValueError(
250
+ f"Unexpected response {json.dumps(response)} for request {json.dumps(payload)}"
251
+ )
252
+
253
+ token = response["token"]
254
+ LOGGER.info("Request is successful, token is %s", token)
255
+ return token
256
+
257
+ # checkPackageStatus
258
+
259
+ def check_package_status_sync(self, token: str) -> tuple[str, list[dict]]:
260
+ """Poll for package availability, exactly once (sync version)"""
261
+ return _async_to_sync(self.check_package_status_async(token=token))
262
+
263
+ async def check_package_status_async(
264
+ self, token: str
265
+ ) -> tuple[Optional[str], Optional[list[dict]]]:
266
+ """Poll for package availability, exactly once (async version)"""
267
+ LOGGER.info("Checking status of token %s ...", token)
268
+ files = None
269
+ status = None
270
+ response = await self._run_call_async(
271
+ "GET", f"{self.server_url}checkPackageStatus?token={token}"
272
+ )
273
+ if "status" in response:
274
+ status = response["status"]
275
+ if status == "done":
276
+ files = response["files"]
277
+ LOGGER.info("Status is '%s'", status)
278
+ return status, files
279
+
280
+ # downloadPackage
281
+
282
+ def get_files_sync(self, token: str) -> tuple[str, list[dict]]:
283
+ """Poll for package file availability and return a status and file list when perparation is finished (sync version)"""
284
+ return _async_to_sync(self.get_files_async(token=token))
285
+
286
+ async def get_files_async(self, token: str) -> tuple[Optional[str], Optional[list[dict]]]:
287
+ """Poll for package file availability and return a status and file list when perparation is finished (async version)"""
288
+ status, files = await self.check_package_status_async(token)
289
+ while status not in ["done", "done-no-match", "error"]:
290
+ LOGGER.info("Waiting %s s ...", config.POLL_WAIT)
291
+ await asyncio.sleep(config.POLL_WAIT)
292
+ status, files = await self.check_package_status_async(token)
293
+ return status, files
294
+
295
+ def download_package_file_sync(self, file_name: str, token: str) -> None:
296
+ return _async_to_sync(self.download_package_file_async(file_name=file_name, token=token))
297
+
298
+ async def download_package_file_async(self, file_name: str, token: str) -> None:
299
+ await self.download_package_file_stream_async(token, file_name)
300
+
301
+ def download_package_files_sync(self, destination_directory: str, files: list) -> None:
302
+ """Download all content set package files (sync version)"""
303
+ return _async_to_sync(
304
+ self.download_package_files_async(
305
+ destination_directory=destination_directory, files=files
306
+ )
307
+ )
308
+
309
+ async def download_package_files_async(self, destination_directory: str, files: list) -> None:
310
+ """Download all content set package files (async version)"""
311
+ LOGGER.info("Downloading files to %s ...", destination_directory)
312
+
313
+ params = [(Path(destination_directory) / f["fileName"], f["token"]) for f in files]
314
+ await _pool_tasks(self.download_package_file_async, params)
315
+
316
+ # Downloading resource files
317
+
318
+ def download_file_sync(self, url_structure: tuple[str, str]) -> None:
319
+ """Download resource file (sync version)
320
+
321
+ The url_structure parameter is a tuple (resource_directory_path, url)
322
+ """
323
+ (path, url) = url_structure
324
+ return _async_to_sync(self.download_file_async(path=path, url=url))
325
+
326
+ @_retry_async
327
+ async def download_file_async(self, path: str, url: str) -> None:
328
+ LOGGER.info("Downloading file %s ...", url)
329
+ response = await self._async_client.get(url)
330
+ response.raise_for_status()
331
+
332
+ file_path = f"{path}/{os.path.basename(urlparse(url).path)}"
333
+
334
+ with open(file_path, "wb") as f:
335
+ f.write(response.content)
336
+
337
+ LOGGER.info("Done downloading file %s", url)
338
+
339
+ def get_resource_list(self, dest_folder: str) -> list[tuple[str, str]]:
340
+ """Determine the URLs of downloadable resource files, based on already-downloaded package files"""
341
+ arr_urls = []
342
+ # Find *_resources_*.json file
343
+ name_list = glob.glob(f"{dest_folder}/*_resources_*.json")
344
+ if len(name_list) > 0:
345
+ # Create parent resources folder
346
+ os.makedirs(f"{dest_folder}/resources/", exist_ok=True)
347
+
348
+ # Load the resource file - we may have several resources files, one per entity/sub-entity
349
+ for res_file in name_list:
350
+ entity_name = res_file.split("_")[0]
351
+ resource_folder = f"{dest_folder}/resources/{entity_name}"
352
+ os.makedirs(resource_folder, exist_ok=True)
353
+ with open(res_file) as f:
354
+ data = json.load(f)
355
+ for u in data:
356
+ arr_urls.append((resource_folder, u["url"]))
357
+ return arr_urls
358
+
359
+ def extract_resources_sync(self, dest_folder: str) -> None:
360
+ """Download all resource files (sync version)"""
361
+ # download all binaries before expiration
362
+ return _async_to_sync(self.extract_resources_async(dest_folder=dest_folder))
363
+
364
+ async def extract_resources_async(self, dest_folder: str):
365
+ LOGGER.info("Extracting resources to %s ...", dest_folder)
366
+ await _pool_tasks(self.download_file_async, self.get_resource_list(dest_folder))
367
+ LOGGER.info("Done extracting resources")
368
+
369
+ # fetch() and fetch_sync() perform the entire process of fetching a content set to disk
370
+ async def fetch_async(
371
+ self,
372
+ content_set_name: str,
373
+ preset_content_set_name: str,
374
+ internal_change_number: int = 0,
375
+ output_format: Literal["json", "parquet"] = "json",
376
+ split_files: bool = False,
377
+ extract_resources: bool = False,
378
+ token: Optional[str] = None,
379
+ ) -> str:
380
+ # request package
381
+ if not token:
382
+ token = await self.request_package_async(
383
+ content_set_name,
384
+ preset_content_set_name,
385
+ internal_change_number,
386
+ output_format,
387
+ split_files,
388
+ )
389
+
390
+ # create the destination folder
391
+ dest_folder = f"{config.OUT_DIR}/{content_set_name}_{token}"
392
+ os.makedirs(dest_folder, exist_ok=True)
393
+
394
+ # get the list of files to be downloaded
395
+ status, files = await self.get_files_async(token)
396
+
397
+ if files is not None:
398
+ # Step 3.1 - download all the generated files
399
+ await self.download_package_files_async(dest_folder, files)
400
+
401
+ # Step 3.2 - download resources if requested
402
+ if extract_resources:
403
+ await self.extract_resources_async(dest_folder)
404
+ else:
405
+ LOGGER.error("FAILURE: Download packaged files: no file for download found!")
406
+ return dest_folder
407
+
408
+ def fetch_sync(
409
+ self,
410
+ content_set_name: str,
411
+ preset_content_set_name: str,
412
+ internal_change_number: int = 0,
413
+ output_format: Literal["json", "parquet"] = "json",
414
+ split_files: bool = False,
415
+ extract_resources: bool = False,
416
+ token: Optional[str] = None,
417
+ ) -> str:
418
+ """
419
+ Fetch a content set by name, producing files on disc.
420
+
421
+ This is our 'do-everything' function; most users of the
422
+ library will want to use only this function or its async
423
+ equivalent.
424
+ """
425
+ return _async_to_sync(
426
+ self.fetch_async(
427
+ content_set_name=content_set_name,
428
+ preset_content_set_name=preset_content_set_name,
429
+ internal_change_number=internal_change_number,
430
+ output_format=output_format,
431
+ split_files=split_files,
432
+ extract_resources=extract_resources,
433
+ token=token,
434
+ )
435
+ )
436
+
437
+ fetch = fetch_sync
438
+
439
+ @_retry_async
440
+ async def download_package_file_stream_async(self, token: str, file_name: str) -> None:
441
+ """Download the file via stream, and resumed if it is not completed due to some issue.
442
+
443
+ (async version)"""
444
+ LOGGER.info("Downloading file %s ...", file_name)
445
+
446
+ url, headers = self.prepare_request_stream(token, file_name)
447
+ async with self._async_client.stream(
448
+ "GET", url, headers=headers, follow_redirects=True
449
+ ) as response:
450
+ continue_download = self.handle_response_stream(file_name, response)
451
+ if not continue_download:
452
+ return
453
+ with open(file_name, "ab") as file:
454
+ async for chunk in response.aiter_bytes(config.CHUNK_SIZE):
455
+ file.write(chunk)
456
+ LOGGER.info("Done downloading file %s", file_name)
457
+
458
+ def download_package_file_stream_sync(self, token: str, file_name: str) -> None:
459
+ """Download the file via stream, and resumed if it is not completed due to some issue.
460
+
461
+ (sync version)"""
462
+ return _async_to_sync(
463
+ self.download_package_file_stream_async(token=token, file_name=file_name)
464
+ )
465
+
466
+ def handle_response_stream(self, file_name: str, response: Response) -> bool:
467
+ if response.status_code == 206:
468
+ LOGGER.info("Resuming the download for '%s'", file_name)
469
+ return True
470
+
471
+ # If server returns "Range Not Satisfiable",
472
+ # then we can conclude that file has been fully downloaded.
473
+ if response.status_code == 416:
474
+ LOGGER.info("File '%s' is already fully downloaded.", file_name)
475
+ return False
476
+
477
+ if response.status_code not in [200, 206]:
478
+ response.raise_for_status()
479
+ return True
480
+
481
+ def prepare_request_stream(self, token: str, file_name: str) -> tuple[str, dict[str, str]]:
482
+ current_chunk_length = get_file_length(file_name)
483
+ url = f"{self.server_url}downloadPackage?token={token}"
484
+ headers = self._setup_headers("binary", current_chunk_length)
485
+ return url, headers
486
+
487
+
488
+ def _get_description(available_content_sets: list[dict[str, str]]) -> str:
489
+ lines = ["\033[1mAVAILABLE CONTENTSETS\033[0m", " "]
490
+
491
+ for cs in available_content_sets:
492
+ lines.append("NAME: " + cs.get("name", ""))
493
+ lines.append("CONTENTSET:PRESET: " + cs["contentSet"] + ":" + cs["preset"])
494
+ lines.append("DESCRIPTION: " + cs.get("description", ""))
495
+ lines.append(" ")
496
+
497
+ return "\n".join(lines)
498
+
499
+
500
+ def _get_content_set_presets(available_content_sets: list[dict[str, str]]) -> set[str]:
501
+ return {cs["contentSet"] + ":" + cs["preset"] for cs in available_content_sets}
502
+
503
+
504
+ def main():
505
+ logging.basicConfig(
506
+ level=logging.WARNING,
507
+ format="%(asctime)s.%(msecs)03d - %(name)s - %(levelname)s - %(message)s",
508
+ datefmt="%Y-%m-%d %H:%M:%S",
509
+ force=True,
510
+ )
511
+
512
+ client = Client()
513
+ print("Loading available content sets...")
514
+ available_content_sets = client.get_content_sets_info_sync()
515
+
516
+ description = _get_description(available_content_sets)
517
+ cs_presets = _get_content_set_presets(available_content_sets)
518
+ print()
519
+
520
+ parser = argparse.ArgumentParser(
521
+ description="Bulk download IP datasets",
522
+ formatter_class=argparse.RawDescriptionHelpFormatter,
523
+ epilog=description,
524
+ )
525
+ parser.add_argument(
526
+ "--internal-change-number",
527
+ dest="changenumber",
528
+ default=0,
529
+ type=int,
530
+ help="Select only data newer than this internal change number (default: 0)",
531
+ )
532
+ parser.add_argument(
533
+ "--format",
534
+ dest="fmt",
535
+ default="json",
536
+ choices=["json", "parquet"],
537
+ help="Format for the downloaded files, either json or parquet (default: json)",
538
+ )
539
+ parser.add_argument("--split", dest="split", action="store_true", help="Split files")
540
+ parser.add_argument(
541
+ "--extract",
542
+ dest="extract",
543
+ action="store_true",
544
+ help="Download and extract resources (may be slow)",
545
+ )
546
+ parser.add_argument(
547
+ "--verbose",
548
+ "-v",
549
+ dest="verbose",
550
+ action="store_true",
551
+ help="Make the operation more talkative",
552
+ )
553
+ parser.add_argument(
554
+ "--token",
555
+ dest="token",
556
+ default=None,
557
+ type=str,
558
+ help="Proceed with existing token",
559
+ )
560
+ parser.add_argument(
561
+ "contentset",
562
+ metavar="CONTENTSET:PRESET",
563
+ nargs="+",
564
+ help="The name of the contentset and its preset",
565
+ )
566
+ args = parser.parse_args()
567
+
568
+ if args.verbose:
569
+ LOGGER.setLevel(logging.INFO)
570
+
571
+ for csp in args.contentset:
572
+ if csp not in cs_presets:
573
+ sys.stderr.write(
574
+ f"Error: argument CONTENTSET:PRESET: invalid parameter: '{csp}' (please refer to the help)"
575
+ )
576
+ sys.exit(1)
577
+
578
+ cspairs = [x.split(":") for x in args.contentset]
579
+ for cs in cspairs:
580
+ start = time.time()
581
+ print(f"Process started at {datetime.now().isoformat(sep=' ', timespec='milliseconds')}...")
582
+
583
+ try:
584
+ client.fetch(
585
+ content_set_name=cs[0],
586
+ preset_content_set_name=cs[1],
587
+ internal_change_number=args.changenumber,
588
+ output_format=args.fmt,
589
+ split_files=args.split,
590
+ extract_resources=args.extract,
591
+ token=args.token,
592
+ )
593
+ except Exception as e:
594
+ sys.stderr.write("ERROR\n")
595
+ if isinstance(e, MissingAuth):
596
+ sys.stderr.write(f"{e}\n")
597
+ elif isinstance(e, HTTPResponseNotOK):
598
+ sys.stderr.write(f"{e.message}\n")
599
+ else:
600
+ sys.stderr.write(
601
+ "An unexpected error occurred. Please report the details below to your Insira contact.\n\n"
602
+ )
603
+ sys.stderr.write(f"parameters={sys.argv}")
604
+ sys.stderr.write(traceback.format_exc())
605
+ sys.exit(1)
606
+
607
+ elapsed = (time.time() - start) / 60
608
+ time.sleep(1) # for logs to be flushed
609
+ print(f"Process completed! Time taken: {elapsed:.3f} minutes")
610
+
611
+
612
+ if __name__ == "__main__":
613
+ main()
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+
5
+ # Connection and authentication details
6
+ SERVER_URL = "https://api.clarivate.com/ric/download/v1/"
7
+ API_KEY = os.environ.get("DATAFEED_API_KEY", None)
8
+
9
+ # Poll wait time in seconds
10
+ POLL_WAIT = 60
11
+
12
+ # Directory for saving output
13
+ OUT_DIR = "datafeed_packages"
14
+
15
+ # Number of times to retry a download
16
+ RETRIES = 5
17
+
18
+ # Time in seconds between retries
19
+ RETRY_WAIT = 5
20
+
21
+ # Maximimum simultaneous connections
22
+ MAX_CONNECT = 10
23
+
24
+ # Chunk Size to download 64 KB
25
+ CHUNK_SIZE = 65536