opynrefine 0.1.0__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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: opynrefine
3
+ Version: 0.1.0
4
+ Summary: Python client and CLI for the OpenRefine API
5
+ Author: Spencer Norris
6
+ Project-URL: Homepage, https://github.com/SpencerNorris/opynrefine
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: requests>=2.31
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest>=7; extra == "test"
13
+ Dynamic: license-file
14
+
15
+ # opynrefine
16
+
17
+ Python 3.x client and CLI for working with the [OpenRefine API](https://openrefine.org/docs/technical-reference/openrefine-api).
18
+
19
+ ## Getting Started
20
+
21
+ ```bash
22
+ python -m venv .venv
23
+ source .venv/bin/activate
24
+ pip install -e .[test]
25
+ ```
26
+
27
+ ### CLI usage
28
+
29
+ ```bash
30
+ opynrefine --base-url http://127.0.0.1:3333 list-projects
31
+ opynrefine call core/get-models --params '{"project":"123"}'
32
+ opynrefine create-project "New dataset" data.csv --format-hint text/line-based/*sv --options '{"separator":","}'
33
+ opynrefine apply-operations 123 operations.json
34
+ ```
35
+
36
+ ## Tests
37
+
38
+ Pytest-based tests include unit coverage and an integration test that exercises a running OpenRefine instance on `http://127.0.0.1:3333`. If OpenRefine is not running locally the integration test is skipped automatically.
39
+
40
+ ```bash
41
+ pytest
42
+ ```
@@ -0,0 +1,28 @@
1
+ # opynrefine
2
+
3
+ Python 3.x client and CLI for working with the [OpenRefine API](https://openrefine.org/docs/technical-reference/openrefine-api).
4
+
5
+ ## Getting Started
6
+
7
+ ```bash
8
+ python -m venv .venv
9
+ source .venv/bin/activate
10
+ pip install -e .[test]
11
+ ```
12
+
13
+ ### CLI usage
14
+
15
+ ```bash
16
+ opynrefine --base-url http://127.0.0.1:3333 list-projects
17
+ opynrefine call core/get-models --params '{"project":"123"}'
18
+ opynrefine create-project "New dataset" data.csv --format-hint text/line-based/*sv --options '{"separator":","}'
19
+ opynrefine apply-operations 123 operations.json
20
+ ```
21
+
22
+ ## Tests
23
+
24
+ Pytest-based tests include unit coverage and an integration test that exercises a running OpenRefine instance on `http://127.0.0.1:3333`. If OpenRefine is not running locally the integration test is skipped automatically.
25
+
26
+ ```bash
27
+ pytest
28
+ ```
@@ -0,0 +1,9 @@
1
+ """Public export surface for opynrefine."""
2
+ from .client import OpenRefineClient, OpenRefineResponse, build_cli_parser, main
3
+
4
+ __all__ = [
5
+ "OpenRefineClient",
6
+ "OpenRefineResponse",
7
+ "build_cli_parser",
8
+ "main",
9
+ ]
@@ -0,0 +1,476 @@
1
+ """
2
+ OpenRefine API client and CLI entry point.
3
+ Documentation for OpenRefine API: https://openrefine.org/docs/technical-reference/openrefine-api
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ import logging
10
+ import os
11
+ import signal
12
+ import sys
13
+ import threading
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, Iterable, Optional
16
+ from urllib.parse import parse_qs, urlparse
17
+
18
+ import requests
19
+
20
+
21
+ LOGGER = logging.getLogger(__name__)
22
+
23
+
24
+ def configure_logging(level: int = logging.INFO) -> None:
25
+ """Configure a sane default logging setup if the app has not done so."""
26
+ if not logging.getLogger().handlers:
27
+ logging.basicConfig(
28
+ level=level,
29
+ format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
30
+ )
31
+ LOGGER.setLevel(level)
32
+
33
+
34
+ @dataclass
35
+ class OpenRefineResponse:
36
+ """Simple wrapper that exposes the low-level :class:`requests.Response`."""
37
+
38
+ response: requests.Response
39
+
40
+ def json(self) -> Any:
41
+ return self.response.json()
42
+
43
+ @property
44
+ def text(self) -> str:
45
+ return self.response.text
46
+
47
+ @property
48
+ def content(self) -> bytes:
49
+ return self.response.content
50
+
51
+
52
+ class CommandProxy:
53
+ """Fluent builder for OpenRefine command paths."""
54
+
55
+ def __init__(self, client: "OpenRefineClient", parts: Optional[Iterable[str]] = None):
56
+ self._client = client
57
+ self._parts = list(parts or [])
58
+
59
+ def __getattr__(self, attr: str) -> "CommandProxy":
60
+ if attr.startswith("_"):
61
+ raise AttributeError(attr)
62
+ return CommandProxy(self._client, self._parts + [attr.replace("_", "-")])
63
+
64
+ def __call__(
65
+ self,
66
+ *,
67
+ method: str = "GET",
68
+ expect_json: bool = True,
69
+ params: Optional[Dict[str, Any]] = None,
70
+ data: Optional[Any] = None,
71
+ json_body: Optional[Any] = None,
72
+ files: Optional[Dict[str, Any]] = None,
73
+ headers: Optional[Dict[str, str]] = None,
74
+ timeout: Optional[int] = None,
75
+ ) -> Any:
76
+ path = "/".join(self._parts)
77
+ return self._client._request(
78
+ path,
79
+ method=method,
80
+ expect_json=expect_json,
81
+ params=params,
82
+ data=data,
83
+ json_body=json_body,
84
+ files=files,
85
+ headers=headers,
86
+ timeout=timeout,
87
+ )
88
+
89
+
90
+ class OpenRefineClient:
91
+ """Object-oriented wrapper for the OpenRefine HTTP API."""
92
+
93
+ def __init__(
94
+ self,
95
+ base_url: str = "http://127.0.0.1:3333",
96
+ *,
97
+ session: Optional[requests.Session] = None,
98
+ timeout: int = 60,
99
+ logger: Optional[logging.Logger] = None,
100
+ auto_register_signals: bool = True,
101
+ ) -> None:
102
+ self.base_url = self._normalize_base_url(base_url)
103
+ self.session = session or requests.Session()
104
+ self.timeout = timeout
105
+ self.logger = logger or LOGGER
106
+ self._stop_event = threading.Event()
107
+ self._signal_handlers: Dict[int, Any] = {}
108
+ self._csrf_token: Optional[str] = None
109
+ if auto_register_signals:
110
+ self.register_signal_handlers(signal.SIGINT, signal.SIGTERM)
111
+
112
+ @property
113
+ def command(self) -> CommandProxy:
114
+ return CommandProxy(self)
115
+
116
+ def register_signal_handlers(self, *signals_to_handle: signal.Signals) -> None:
117
+ for sig in signals_to_handle:
118
+ try:
119
+ self._signal_handlers[sig] = signal.signal(sig, self._handle_signal) # type: ignore[assignment]
120
+ except (ValueError, OSError): # pragma: no cover - not hit on Windows CI typically
121
+ self.logger.debug("Unable to register handler for %s", sig)
122
+
123
+ def unregister_signal_handlers(self) -> None:
124
+ for sig, handler in self._signal_handlers.items():
125
+ try:
126
+ signal.signal(sig, handler)
127
+ except (ValueError, OSError): # pragma: no cover - best effort only
128
+ self.logger.debug("Unable to restore original handler for %s", sig)
129
+ self._signal_handlers.clear()
130
+
131
+ def close(self) -> None:
132
+ self.unregister_signal_handlers()
133
+ self.session.close()
134
+
135
+ # Public helper methods -------------------------------------------------
136
+ def list_projects(self) -> Dict[str, Any]:
137
+ """Return metadata for all projects."""
138
+ return self.command.core.get_all_project_metadata()
139
+
140
+ def delete_project(self, project_id: str) -> Dict[str, Any]:
141
+ return self.command.core.delete_project(params={"project": project_id})
142
+
143
+ def get_models(self, project_id: str) -> Dict[str, Any]:
144
+ return self.command.core.get_models(params={"project": project_id})
145
+
146
+ def get_rows(self, project_id: str, **options: Any) -> Dict[str, Any]:
147
+ params = {"project": project_id, **options}
148
+ return self.command.core.get_rows(params=params)
149
+
150
+ def export_rows(self, project_id: str, export_format: str = "tsv", **options: Any) -> str:
151
+ params = {"project": project_id, "format": export_format, **options}
152
+ return self.command.core.export_rows(params=params, expect_json=False).text
153
+
154
+ def apply_operations(self, project_id: str, operations: Any) -> Dict[str, Any]:
155
+ payload = json.dumps(operations)
156
+ return self.command.core.apply_operations(
157
+ method="POST",
158
+ data={"project": project_id, "operations": payload},
159
+ )
160
+
161
+ def compute_facets(self, project_id: str, facets: Any) -> Dict[str, Any]:
162
+ payload = json.dumps(facets)
163
+ return self.command.core.compute_facets(
164
+ method="POST",
165
+ data={"project": project_id, "engine": payload},
166
+ )
167
+
168
+ def create_project_from_url(self, project_name: str, data_url: str, format_options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
169
+ data = {
170
+ "projectName": project_name,
171
+ "format": (format_options or {}).get("format"),
172
+ "options": json.dumps(format_options or {}),
173
+ "url": data_url,
174
+ }
175
+ return self.command.core.create_project_from_url(method="POST", data=data)
176
+
177
+ def create_project_from_upload(
178
+ self,
179
+ project_name: str,
180
+ file_path: str,
181
+ *,
182
+ format_hint: Optional[str] = None,
183
+ format_options: Optional[Dict[str, Any]] = None,
184
+ ) -> Dict[str, Any]:
185
+ options_payload = json.dumps(format_options or {}) if format_options else None
186
+ filename = os.path.basename(file_path)
187
+ with open(file_path, "rb") as handle:
188
+ files = {"project-file": (filename, handle)}
189
+ data: Dict[str, Any] = {"project-name": project_name}
190
+ if format_hint:
191
+ data["format"] = format_hint
192
+ if options_payload:
193
+ data["options"] = options_payload
194
+ response = self.command.core.create_project_from_upload(
195
+ method="POST",
196
+ data=data,
197
+ files=files,
198
+ expect_json=False,
199
+ )
200
+ project_id = self._extract_project_id(response.response.url)
201
+ return {
202
+ "project_id": project_id,
203
+ "project_url": response.response.url,
204
+ "html": response.text,
205
+ }
206
+
207
+ def execute_command(
208
+ self,
209
+ command_path: str,
210
+ *,
211
+ method: str = "GET",
212
+ expect_json: bool = True,
213
+ **kwargs: Any,
214
+ ) -> Any:
215
+ """Execute an arbitrary command path."""
216
+ return self._request(command_path, method=method, expect_json=expect_json, **kwargs)
217
+
218
+ # Internal helpers ------------------------------------------------------
219
+ def _handle_signal(self, signum: int, frame: Any) -> None:
220
+ try:
221
+ name = signal.Signals(signum).name
222
+ except ValueError: # pragma: no cover - defensive
223
+ name = str(signum)
224
+ self.logger.warning("Received %s signal; aborting new requests", name)
225
+ self._stop_event.set()
226
+
227
+ def _build_url(self, command: str) -> str:
228
+ command = command.lstrip("/")
229
+ if not command.startswith("command/"):
230
+ command = f"command/{command}"
231
+ return f"{self.base_url}/{command}"
232
+
233
+ @staticmethod
234
+ def _normalize_base_url(value: str) -> str:
235
+ value = value.rstrip("/")
236
+ if not value.startswith(("http://", "https://")):
237
+ value = f"http://{value}"
238
+ return value
239
+
240
+ def _ensure_not_interrupted(self) -> None:
241
+ if self._stop_event.is_set():
242
+ raise RuntimeError("OpenRefine client interrupted by signal")
243
+
244
+ def _request(
245
+ self,
246
+ command: str,
247
+ *,
248
+ method: str = "GET",
249
+ expect_json: bool = True,
250
+ params: Optional[Dict[str, Any]] = None,
251
+ data: Optional[Any] = None,
252
+ json_body: Optional[Any] = None,
253
+ files: Optional[Dict[str, Any]] = None,
254
+ headers: Optional[Dict[str, str]] = None,
255
+ timeout: Optional[int] = None,
256
+ ) -> Any:
257
+ self._ensure_not_interrupted()
258
+ url = self._build_url(command)
259
+ self.logger.debug("%s %s params=%s", method.upper(), url, params)
260
+ method_upper = method.upper()
261
+ params = self._maybe_inject_csrf_token_query(params, method_upper)
262
+ data = self._maybe_inject_csrf_token_form(data, method_upper)
263
+ json_body = self._maybe_inject_csrf_token_json(json_body, method_upper)
264
+ response = self.session.request(
265
+ method=method,
266
+ url=url,
267
+ params=params,
268
+ data=data,
269
+ json=json_body,
270
+ files=files,
271
+ headers=headers,
272
+ timeout=timeout or self.timeout,
273
+ )
274
+ self.logger.info("%s %s -> %s", method.upper(), url, response.status_code)
275
+ response.raise_for_status()
276
+ if expect_json:
277
+ try:
278
+ return response.json()
279
+ except ValueError:
280
+ self.logger.debug("Response did not contain JSON, returning raw text")
281
+ return response.text
282
+ return OpenRefineResponse(response)
283
+
284
+ @staticmethod
285
+ def _extract_project_id(url: str) -> Optional[str]:
286
+ try:
287
+ parsed = urlparse(url)
288
+ except ValueError:
289
+ return None
290
+ project_param = parse_qs(parsed.query).get("project")
291
+ if not project_param:
292
+ return None
293
+ return project_param[0]
294
+
295
+ def _ensure_csrf_token(self) -> str:
296
+ if not self._csrf_token:
297
+ self._csrf_token = self._fetch_csrf_token()
298
+ return self._csrf_token
299
+
300
+ def _fetch_csrf_token(self) -> str:
301
+ url = f"{self.base_url}/command/core/get-csrf-token"
302
+ response = self.session.get(url, timeout=self.timeout)
303
+ response.raise_for_status()
304
+ payload = response.json()
305
+ token = payload.get("token")
306
+ if not token:
307
+ raise RuntimeError("Failed to obtain CSRF token from OpenRefine")
308
+ return token
309
+
310
+ def _maybe_inject_csrf_token_form(self, data: Optional[Any], method: str) -> Optional[Any]:
311
+ if method in {"GET", "HEAD"}:
312
+ return data
313
+ token = self._ensure_csrf_token()
314
+ if data is None:
315
+ return {"csrf_token": token}
316
+ if isinstance(data, dict):
317
+ if "csrf_token" not in data:
318
+ data = dict(data)
319
+ data["csrf_token"] = token
320
+ return data
321
+ if isinstance(data, list):
322
+ if not any(k == "csrf_token" for k, _ in data):
323
+ data = list(data)
324
+ data.append(("csrf_token", token))
325
+ return data
326
+ return data
327
+
328
+ def _maybe_inject_csrf_token_json(self, json_body: Optional[Any], method: str) -> Optional[Any]:
329
+ if method in {"GET", "HEAD"} or json_body is None:
330
+ return json_body
331
+ token = self._ensure_csrf_token()
332
+ if isinstance(json_body, dict) and "csrf_token" not in json_body:
333
+ json_body = dict(json_body)
334
+ json_body["csrf_token"] = token
335
+ return json_body
336
+
337
+ def _maybe_inject_csrf_token_query(self, params: Optional[Dict[str, Any]], method: str) -> Optional[Dict[str, Any]]:
338
+ if method in {"GET", "HEAD"}:
339
+ return params
340
+ token = self._ensure_csrf_token()
341
+ if not params:
342
+ return {"csrf_token": token}
343
+ if "csrf_token" not in params:
344
+ params = dict(params)
345
+ params["csrf_token"] = token
346
+ return params
347
+
348
+
349
+ def _parse_kv_json(value: Optional[str]) -> Optional[Dict[str, Any]]:
350
+ if not value:
351
+ return None
352
+ try:
353
+ parsed = json.loads(value)
354
+ if not isinstance(parsed, dict):
355
+ raise ValueError("Expected a JSON object")
356
+ return parsed
357
+ except json.JSONDecodeError as exc: # pragma: no cover - CLI-only path
358
+ raise SystemExit(f"Invalid JSON payload provided: {exc}") from exc
359
+
360
+
361
+ def _load_json_file(path: str) -> Any:
362
+ try:
363
+ with open(path, "r", encoding="utf-8") as handle:
364
+ return json.load(handle)
365
+ except FileNotFoundError as exc: # pragma: no cover - CLI path
366
+ raise SystemExit(f"Operations file not found: {path}") from exc
367
+ except json.JSONDecodeError as exc: # pragma: no cover
368
+ raise SystemExit(f"Invalid JSON in {path}: {exc}") from exc
369
+
370
+
371
+ def build_cli_parser() -> argparse.ArgumentParser:
372
+ parser = argparse.ArgumentParser(description="Minimal CLI for the OpenRefine API client")
373
+ parser.add_argument("--base-url", default="http://127.0.0.1:3333", help="OpenRefine server base URL")
374
+ parser.add_argument("--timeout", type=int, default=60, help="Request timeout in seconds")
375
+ parser.add_argument("--log-level", default="INFO", help="Python logging level (default: INFO)")
376
+
377
+ subparsers = parser.add_subparsers(dest="action", required=True)
378
+
379
+ list_parser = subparsers.add_parser("list-projects", help="List available projects")
380
+ list_parser.set_defaults(func=_cli_list_projects)
381
+
382
+ delete_parser = subparsers.add_parser("delete-project", help="Delete a project by id")
383
+ delete_parser.add_argument("project_id")
384
+ delete_parser.set_defaults(func=_cli_delete_project)
385
+
386
+ call_parser = subparsers.add_parser("call", help="Execute an arbitrary OpenRefine command")
387
+ call_parser.add_argument("command_path", help="Path following the /command/ prefix, e.g. core/get-models")
388
+ call_parser.add_argument("--method", default="GET", help="HTTP method to use")
389
+ call_parser.add_argument("--params", help="JSON object of query params")
390
+ call_parser.add_argument("--data", help="JSON object of form data to send")
391
+ call_parser.add_argument("--expect-json", action="store_true", help="Expect JSON in response (default true)")
392
+ call_parser.add_argument(
393
+ "--no-expect-json",
394
+ dest="expect_json",
395
+ action="store_false",
396
+ help="Return raw response wrapper",
397
+ )
398
+ call_parser.set_defaults(expect_json=True, func=_cli_call)
399
+
400
+ create_parser = subparsers.add_parser("create-project", help="Create a new project from a file upload")
401
+ create_parser.add_argument("project_name", help="Name for the new project")
402
+ create_parser.add_argument("file_path", help="Path to the data file to upload")
403
+ create_parser.add_argument("--format-hint", help="Optional MIME hint like text/line-based/*sv")
404
+ create_parser.add_argument("--options", help="JSON string of format-specific options")
405
+ create_parser.set_defaults(func=_cli_create_project)
406
+
407
+ apply_parser = subparsers.add_parser("apply-operations", help="Apply a JSON operations file to a project")
408
+ apply_parser.add_argument("project_id", help="Target project id")
409
+ apply_parser.add_argument("operations_file", help="Path to the operations JSON file")
410
+ apply_parser.set_defaults(func=_cli_apply_operations)
411
+
412
+ return parser
413
+
414
+
415
+ def _cli_list_projects(client: OpenRefineClient, _: argparse.Namespace) -> None:
416
+ projects = client.list_projects()
417
+ json.dump(projects, sys.stdout, indent=2)
418
+ sys.stdout.write("\n")
419
+
420
+
421
+ def _cli_delete_project(client: OpenRefineClient, args: argparse.Namespace) -> None:
422
+ result = client.delete_project(args.project_id)
423
+ json.dump(result, sys.stdout, indent=2)
424
+ sys.stdout.write("\n")
425
+
426
+
427
+ def _cli_call(client: OpenRefineClient, args: argparse.Namespace) -> None:
428
+ params = _parse_kv_json(args.params)
429
+ data = _parse_kv_json(args.data)
430
+ result = client.execute_command(
431
+ args.command_path,
432
+ method=args.method,
433
+ params=params,
434
+ data=data,
435
+ expect_json=args.expect_json,
436
+ )
437
+ if isinstance(result, OpenRefineResponse):
438
+ sys.stdout.write(result.text)
439
+ else:
440
+ json.dump(result, sys.stdout, indent=2)
441
+ sys.stdout.write("\n")
442
+
443
+
444
+ def _cli_create_project(client: OpenRefineClient, args: argparse.Namespace) -> None:
445
+ options = _parse_kv_json(args.options)
446
+ result = client.create_project_from_upload(
447
+ args.project_name,
448
+ args.file_path,
449
+ format_hint=args.format_hint,
450
+ format_options=options,
451
+ )
452
+ json.dump(result, sys.stdout, indent=2)
453
+ sys.stdout.write("\n")
454
+
455
+
456
+ def _cli_apply_operations(client: OpenRefineClient, args: argparse.Namespace) -> None:
457
+ operations = _load_json_file(args.operations_file)
458
+ result = client.apply_operations(args.project_id, operations)
459
+ json.dump(result, sys.stdout, indent=2)
460
+ sys.stdout.write("\n")
461
+
462
+
463
+ def main(argv: Optional[Iterable[str]] = None) -> int:
464
+ parser = build_cli_parser()
465
+ args = parser.parse_args(argv)
466
+ configure_logging(getattr(logging, args.log_level.upper(), logging.INFO))
467
+ client = OpenRefineClient(base_url=args.base_url, timeout=args.timeout)
468
+ try:
469
+ args.func(client, args)
470
+ finally:
471
+ client.close()
472
+ return 0
473
+
474
+
475
+ if __name__ == "__main__":
476
+ raise SystemExit(main())
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: opynrefine
3
+ Version: 0.1.0
4
+ Summary: Python client and CLI for the OpenRefine API
5
+ Author: Spencer Norris
6
+ Project-URL: Homepage, https://github.com/SpencerNorris/opynrefine
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: requests>=2.31
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest>=7; extra == "test"
13
+ Dynamic: license-file
14
+
15
+ # opynrefine
16
+
17
+ Python 3.x client and CLI for working with the [OpenRefine API](https://openrefine.org/docs/technical-reference/openrefine-api).
18
+
19
+ ## Getting Started
20
+
21
+ ```bash
22
+ python -m venv .venv
23
+ source .venv/bin/activate
24
+ pip install -e .[test]
25
+ ```
26
+
27
+ ### CLI usage
28
+
29
+ ```bash
30
+ opynrefine --base-url http://127.0.0.1:3333 list-projects
31
+ opynrefine call core/get-models --params '{"project":"123"}'
32
+ opynrefine create-project "New dataset" data.csv --format-hint text/line-based/*sv --options '{"separator":","}'
33
+ opynrefine apply-operations 123 operations.json
34
+ ```
35
+
36
+ ## Tests
37
+
38
+ Pytest-based tests include unit coverage and an integration test that exercises a running OpenRefine instance on `http://127.0.0.1:3333`. If OpenRefine is not running locally the integration test is skipped automatically.
39
+
40
+ ```bash
41
+ pytest
42
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ opynrefine/__init__.py
5
+ opynrefine/client.py
6
+ opynrefine.egg-info/PKG-INFO
7
+ opynrefine.egg-info/SOURCES.txt
8
+ opynrefine.egg-info/dependency_links.txt
9
+ opynrefine.egg-info/entry_points.txt
10
+ opynrefine.egg-info/requires.txt
11
+ opynrefine.egg-info/top_level.txt
12
+ tests/test_client.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ opynrefine = opynrefine.client:main
@@ -0,0 +1,4 @@
1
+ requests>=2.31
2
+
3
+ [test]
4
+ pytest>=7
@@ -0,0 +1 @@
1
+ opynrefine
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=67", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "opynrefine"
7
+ version = "0.1.0"
8
+ description = "Python client and CLI for the OpenRefine API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ authors = [
12
+ { name = "Spencer Norris" }
13
+ ]
14
+ dependencies = [
15
+ "requests>=2.31",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ test = [
20
+ "pytest>=7",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/SpencerNorris/opynrefine"
25
+
26
+ [project.scripts]
27
+ opynrefine = "opynrefine.client:main"
28
+
29
+ [tool.pytest.ini_options]
30
+ markers = [
31
+ "integration: tests that require a running OpenRefine server on http://127.0.0.1:3333",
32
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,125 @@
1
+ import json
2
+ import signal
3
+
4
+ import pytest
5
+ import requests
6
+
7
+ from opynrefine.client import OpenRefineClient, OpenRefineResponse
8
+
9
+
10
+ class DummyResponse:
11
+ def __init__(self, data=None, *, text="", status_code=200, url="http://example/command"):
12
+ self._data = data
13
+ self.text = text or (json.dumps(data) if data is not None else "")
14
+ self.status_code = status_code
15
+ self.url = url
16
+ self.content = self.text.encode() # mimic requests API
17
+
18
+ def json(self):
19
+ if self._data is None:
20
+ raise ValueError("No JSON available")
21
+ return self._data
22
+
23
+ def raise_for_status(self):
24
+ if self.status_code >= 400:
25
+ raise requests.HTTPError(response=self)
26
+
27
+
28
+ class DummySession:
29
+ def __init__(self, response, csrf_response=None):
30
+ self._response = response
31
+ self._csrf_response = csrf_response or DummyResponse({"token": "csrf"})
32
+ self.last_request = None
33
+ self.last_get = None
34
+
35
+ def request(self, method, url, **kwargs):
36
+ self.last_request = (method, url, kwargs)
37
+ return self._response
38
+
39
+ def get(self, url, **kwargs):
40
+ self.last_get = (url, kwargs)
41
+ return self._csrf_response
42
+
43
+ def close(self):
44
+ return None
45
+
46
+
47
+ def test_command_proxy_executes_normalized_path():
48
+ response = DummyResponse({"ok": True})
49
+ session = DummySession(response)
50
+ client = OpenRefineClient("http://example", session=session, auto_register_signals=False)
51
+
52
+ result = client.command.core.get_all_project_metadata(params={"foo": "bar"})
53
+
54
+ assert result == {"ok": True}
55
+ method, url, kwargs = session.last_request
56
+ assert method == "GET"
57
+ assert url == "http://example/command/core/get-all-project-metadata"
58
+ assert kwargs["params"] == {"foo": "bar"}
59
+
60
+
61
+ def test_signal_interrupt_blocks_requests():
62
+ response = DummyResponse({"ok": True})
63
+ session = DummySession(response)
64
+ client = OpenRefineClient("http://example", session=session, auto_register_signals=False)
65
+
66
+ client._handle_signal(signal.SIGINT, None)
67
+
68
+ with pytest.raises(RuntimeError):
69
+ client.command.core.get_models()
70
+
71
+
72
+ def test_raw_response_wrapper_returned_when_requested():
73
+ response = DummyResponse(text="plain text")
74
+ session = DummySession(response)
75
+ client = OpenRefineClient("http://example", session=session, auto_register_signals=False)
76
+
77
+ result = client.command.core.export_rows(expect_json=False)
78
+
79
+ assert isinstance(result, OpenRefineResponse)
80
+ assert result.text == "plain text"
81
+
82
+
83
+ def test_create_project_from_upload_returns_metadata(tmp_path):
84
+ project_file = tmp_path / "test.csv"
85
+ project_file.write_text("foo,bar\n1,2\n", encoding="utf-8")
86
+ response = DummyResponse(text="<html />", url="http://example/project?project=123")
87
+ session = DummySession(response, csrf_response=DummyResponse({"token": "abc"}))
88
+ client = OpenRefineClient("http://example", session=session, auto_register_signals=False)
89
+
90
+ result = client.create_project_from_upload(
91
+ "Example Project",
92
+ str(project_file),
93
+ format_hint="text/line-based/*sv",
94
+ format_options={"separator": ","},
95
+ )
96
+
97
+ assert result["project_id"] == "123"
98
+ assert session.last_get[0] == "http://example/command/core/get-csrf-token"
99
+ method, url, kwargs = session.last_request
100
+ assert method == "POST"
101
+ assert url == "http://example/command/core/create-project-from-upload"
102
+ assert kwargs["data"]["project-name"] == "Example Project"
103
+ assert kwargs["data"]["format"] == "text/line-based/*sv"
104
+ assert json.loads(kwargs["data"]["options"]) == {"separator": ","}
105
+ assert kwargs["data"]["csrf_token"] == "abc"
106
+ assert kwargs["params"]["csrf_token"] == "abc"
107
+ assert kwargs["files"]["project-file"][0] == "test.csv"
108
+
109
+
110
+ def test_base_url_without_scheme_is_normalized():
111
+ client = OpenRefineClient("127.0.0.1:3333", session=DummySession(DummyResponse({})), auto_register_signals=False)
112
+ assert client.base_url == "http://127.0.0.1:3333"
113
+
114
+
115
+ @pytest.mark.integration
116
+ def test_list_projects_against_local_instance():
117
+ client = OpenRefineClient()
118
+ try:
119
+ projects = client.list_projects()
120
+ except requests.exceptions.RequestException as exc:
121
+ pytest.skip(f"OpenRefine not running: {exc}")
122
+ finally:
123
+ client.close()
124
+
125
+ assert isinstance(projects, dict)