orcli 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.
- orcli-0.1.0/LICENSE.md +121 -0
- orcli-0.1.0/PKG-INFO +252 -0
- orcli-0.1.0/README.md +240 -0
- orcli-0.1.0/pyproject.toml +23 -0
- orcli-0.1.0/setup.cfg +4 -0
- orcli-0.1.0/src/orcli/__init__.py +4 -0
- orcli-0.1.0/src/orcli/client.py +267 -0
- orcli-0.1.0/src/orcli.egg-info/PKG-INFO +252 -0
- orcli-0.1.0/src/orcli.egg-info/SOURCES.txt +10 -0
- orcli-0.1.0/src/orcli.egg-info/dependency_links.txt +1 -0
- orcli-0.1.0/src/orcli.egg-info/requires.txt +4 -0
- orcli-0.1.0/src/orcli.egg-info/top_level.txt +1 -0
orcli-0.1.0/LICENSE.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Creative Commons Legal Code
|
|
2
|
+
|
|
3
|
+
CC0 1.0 Universal
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
orcli-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: orcli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python client for interacting with OpenRefine
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE.md
|
|
8
|
+
Requires-Dist: requests>=2.28.0
|
|
9
|
+
Provides-Extra: test
|
|
10
|
+
Requires-Dist: pytest; extra == "test"
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# refine-client
|
|
15
|
+
|
|
16
|
+
A Python client library for interacting with [OpenRefine](https://openrefine.org/) via its REST API.
|
|
17
|
+
|
|
18
|
+
For simple project creation, data transformation, metadata management and export operations.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Create and delete projects from local files.
|
|
23
|
+
- Retrieve and manage project metadata.
|
|
24
|
+
- Apply OpenRefine operations individually or in batches.
|
|
25
|
+
- Load operations from JSON files.
|
|
26
|
+
- Export data in multiple formats (TSV, CSV, JSON).
|
|
27
|
+
- Retrieve column information and project models, convert and manipulate row data.
|
|
28
|
+
- Error handling with detailed response logging.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
### Requirements
|
|
33
|
+
|
|
34
|
+
Requires Python 3.10+ and a running OpenRefine server instance.
|
|
35
|
+
|
|
36
|
+
### Quick Start
|
|
37
|
+
|
|
38
|
+
1. Clone the repository:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git clone https://github.com/rkraasch/refine-client.git
|
|
42
|
+
cd refine-client
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
2. Install dependencies:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
python -m venv .venv
|
|
49
|
+
source [.venv/bin/activate](.venv/bin/activate) # Linux and Mac.
|
|
50
|
+
# .venv\Scripts\activate # Windows.
|
|
51
|
+
pip install -r requirements.txt
|
|
52
|
+
python -m pip list
|
|
53
|
+
deactivate
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
3. Optionally run tests:
|
|
57
|
+
|
|
58
|
+
[Download](https://openrefine.org/download) and run OpenRefine, then run the tests as shown below.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
python -m pytest tests/ -v
|
|
62
|
+
```
|
|
63
|
+
This creates temporary test projects in OpenRefine which should be cleaned up automatically.
|
|
64
|
+
If a project prefixed `pytest_refine-client-integration_` remains visible in the Open project tab (under [#open-project](http://127.0.0.1:3333/#open-project)), something went wrong.
|
|
65
|
+
|
|
66
|
+
4. Basic Usage:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from refine_client import Refine
|
|
70
|
+
|
|
71
|
+
# Initialize the client
|
|
72
|
+
refine = Refine(base_url="http://127.0.0.1:3333")
|
|
73
|
+
|
|
74
|
+
# Create a project
|
|
75
|
+
project_id = refine.create_project("input_file.csv", "My Project")
|
|
76
|
+
|
|
77
|
+
# Get column names
|
|
78
|
+
columns = refine.get_column_names(project_id)
|
|
79
|
+
print(f"Columns: {columns}")
|
|
80
|
+
|
|
81
|
+
# Apply an operation
|
|
82
|
+
operation = {
|
|
83
|
+
"op": "core/column-removal",
|
|
84
|
+
"columnName": "unwanted_column",
|
|
85
|
+
"description": "Remove column"
|
|
86
|
+
}
|
|
87
|
+
refine.apply_operation(operation, project_id)
|
|
88
|
+
|
|
89
|
+
# Export data
|
|
90
|
+
refine.export_data("output_file.tsv", fmt="tsv", project_id=project_id)
|
|
91
|
+
|
|
92
|
+
# Clean up
|
|
93
|
+
refine.delete_project(project_id)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
5. Access Project Metadata:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
# Set metadata
|
|
100
|
+
refine.set_project_metadata("name", "Project Name", project_id)
|
|
101
|
+
|
|
102
|
+
# Get all projects
|
|
103
|
+
projects = refine.get_all_projects_metadata()
|
|
104
|
+
for pid, metadata in projects.items():
|
|
105
|
+
print(f"{metadata['name']} (ID: {pid})")
|
|
106
|
+
|
|
107
|
+
# Find by name
|
|
108
|
+
project_id = refine.get_project_id_by_name("Project Name")
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
6. Do Batch Operations:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# Apply multiple operations
|
|
115
|
+
operations = [
|
|
116
|
+
{"op": "core/column-removal", "columnName": "col1"},
|
|
117
|
+
{"op": "core/column-removal", "columnName": "col2"}
|
|
118
|
+
]
|
|
119
|
+
refine.apply_operations(operations, project_id)
|
|
120
|
+
|
|
121
|
+
# Load from file
|
|
122
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Examples
|
|
126
|
+
|
|
127
|
+
### Example 1: Data Pipeline
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from refine_client import Refine
|
|
131
|
+
|
|
132
|
+
refine = Refine(verbose=True)
|
|
133
|
+
|
|
134
|
+
# Create project
|
|
135
|
+
project_id = refine.create_project("raw_data.csv", "Processing")
|
|
136
|
+
|
|
137
|
+
# Transform data
|
|
138
|
+
operations = [
|
|
139
|
+
{"op": "core/column-removal", "columnName": "temp_field"},
|
|
140
|
+
{"op": "core/text-transform", "columnName": "email",
|
|
141
|
+
"expression": "value.toLowerCase()"}
|
|
142
|
+
]
|
|
143
|
+
refine.apply_operations(operations, project_id, wait=True)
|
|
144
|
+
|
|
145
|
+
# Export
|
|
146
|
+
refine.export_data("processed_data.csv", fmt="csv", project_id=project_id)
|
|
147
|
+
|
|
148
|
+
# Cleanup
|
|
149
|
+
refine.delete_project(project_id)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Example 2: Batch Processing
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
import os
|
|
156
|
+
from refine_client import Refine
|
|
157
|
+
|
|
158
|
+
refine = Refine()
|
|
159
|
+
|
|
160
|
+
for filename in os.listdir("input_dir/"):
|
|
161
|
+
if filename.endswith(".csv"):
|
|
162
|
+
project_id = refine.create_project(f"input_dir/{filename}", filename)
|
|
163
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
164
|
+
refine.export_data(f"output_dir/{filename}", fmt="csv", project_id=project_id)
|
|
165
|
+
refine.delete_project(project_id)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## API Reference
|
|
169
|
+
|
|
170
|
+
### Initialization
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
Refine(base_url=None, verbose=False, silent=False)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Parameters:
|
|
177
|
+
- base_url: OpenRefine server URL (default: http://127.0.0.1:3333)
|
|
178
|
+
- verbose: Enable verbose logging
|
|
179
|
+
- silent: Suppress logging
|
|
180
|
+
|
|
181
|
+
### Methods
|
|
182
|
+
|
|
183
|
+
| Method | Description |
|
|
184
|
+
|--------|-------------|
|
|
185
|
+
| create_project(file, name) | Create project |
|
|
186
|
+
| delete_project(project_id) | Delete project |
|
|
187
|
+
| get_all_projects_metadata() | Get all projects |
|
|
188
|
+
| get_project_id_by_name(name) | Find project by name |
|
|
189
|
+
| set_project_metadata(field, value, id) | Update metadata |
|
|
190
|
+
| apply_operation(op, id, wait) | Apply operation |
|
|
191
|
+
| apply_operations(ops, id, wait) | Apply multiple |
|
|
192
|
+
| apply_operations_from_file(file, id, wait) | Load from file |
|
|
193
|
+
| get_models(id) | Get models |
|
|
194
|
+
| get_column_names(id) | Get columns |
|
|
195
|
+
| export_data(file, fmt, id) | Export data |
|
|
196
|
+
| rows_as_list(data) | Convert rows |
|
|
197
|
+
| wait_until_idle(id, delay) | Wait for completion |
|
|
198
|
+
|
|
199
|
+
## Configuration
|
|
200
|
+
|
|
201
|
+
### Logging
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
# Verbose mode
|
|
205
|
+
refine = Refine(verbose=True)
|
|
206
|
+
|
|
207
|
+
# Silent mode
|
|
208
|
+
refine = Refine(silent=True)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Custom Server
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
refine = Refine(base_url="http://example.com:3333")
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Troubleshooting
|
|
218
|
+
|
|
219
|
+
- **ConnectionError:** Ensure OpenRefine is running, verify the server URL and check network connectivity.
|
|
220
|
+
- **CSRF token errors:** Check server status and logs.
|
|
221
|
+
- **FileNotFoundError:** Use absolute paths, verify the file exists and check permissions.
|
|
222
|
+
|
|
223
|
+
## Support and Contribute
|
|
224
|
+
|
|
225
|
+
Open an issue on the project's [issues tab](https://github.com/rkraasch/refine-client/issues) on Github.
|
|
226
|
+
|
|
227
|
+
Or contribute via Github:
|
|
228
|
+
|
|
229
|
+
- fork the repository,
|
|
230
|
+
- create a feature branch,
|
|
231
|
+
- commit changes,
|
|
232
|
+
- push to branch,
|
|
233
|
+
- open Pull Request.
|
|
234
|
+
|
|
235
|
+
## References
|
|
236
|
+
|
|
237
|
+
References:
|
|
238
|
+
|
|
239
|
+
- [OpenRefine Documentation](https://docs.openrefine.org/)
|
|
240
|
+
- [OpenRefine REST API](https://docs.openrefine.org/manual/running)
|
|
241
|
+
|
|
242
|
+
Similar Projects:
|
|
243
|
+
|
|
244
|
+
- [paulmakepeace/refine-client-py](https://github.com/paulmakepeace/refine-client-py): OpenRefine Python 2 Client (last update 11 years ago).
|
|
245
|
+
- [opencultureconsulting/openrefine-client](https://github.com/opencultureconsulting/openrefine-client): OpenRefine Python Client (archived 2024).
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
This project is released under [CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/).
|
|
250
|
+
|
|
251
|
+
For a plain text version see this project's [LICENSE file](./LICENSE.md) or visit [creativecommons.org](https://creativecommons.org/2011/04/15/plaintext-versions-of-creative-commons-licenses-and-cc0/).
|
|
252
|
+
|
orcli-0.1.0/README.md
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
|
|
2
|
+
# refine-client
|
|
3
|
+
|
|
4
|
+
A Python client library for interacting with [OpenRefine](https://openrefine.org/) via its REST API.
|
|
5
|
+
|
|
6
|
+
For simple project creation, data transformation, metadata management and export operations.
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- Create and delete projects from local files.
|
|
11
|
+
- Retrieve and manage project metadata.
|
|
12
|
+
- Apply OpenRefine operations individually or in batches.
|
|
13
|
+
- Load operations from JSON files.
|
|
14
|
+
- Export data in multiple formats (TSV, CSV, JSON).
|
|
15
|
+
- Retrieve column information and project models, convert and manipulate row data.
|
|
16
|
+
- Error handling with detailed response logging.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
### Requirements
|
|
21
|
+
|
|
22
|
+
Requires Python 3.10+ and a running OpenRefine server instance.
|
|
23
|
+
|
|
24
|
+
### Quick Start
|
|
25
|
+
|
|
26
|
+
1. Clone the repository:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
git clone https://github.com/rkraasch/refine-client.git
|
|
30
|
+
cd refine-client
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
2. Install dependencies:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
python -m venv .venv
|
|
37
|
+
source [.venv/bin/activate](.venv/bin/activate) # Linux and Mac.
|
|
38
|
+
# .venv\Scripts\activate # Windows.
|
|
39
|
+
pip install -r requirements.txt
|
|
40
|
+
python -m pip list
|
|
41
|
+
deactivate
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
3. Optionally run tests:
|
|
45
|
+
|
|
46
|
+
[Download](https://openrefine.org/download) and run OpenRefine, then run the tests as shown below.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
python -m pytest tests/ -v
|
|
50
|
+
```
|
|
51
|
+
This creates temporary test projects in OpenRefine which should be cleaned up automatically.
|
|
52
|
+
If a project prefixed `pytest_refine-client-integration_` remains visible in the Open project tab (under [#open-project](http://127.0.0.1:3333/#open-project)), something went wrong.
|
|
53
|
+
|
|
54
|
+
4. Basic Usage:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from refine_client import Refine
|
|
58
|
+
|
|
59
|
+
# Initialize the client
|
|
60
|
+
refine = Refine(base_url="http://127.0.0.1:3333")
|
|
61
|
+
|
|
62
|
+
# Create a project
|
|
63
|
+
project_id = refine.create_project("input_file.csv", "My Project")
|
|
64
|
+
|
|
65
|
+
# Get column names
|
|
66
|
+
columns = refine.get_column_names(project_id)
|
|
67
|
+
print(f"Columns: {columns}")
|
|
68
|
+
|
|
69
|
+
# Apply an operation
|
|
70
|
+
operation = {
|
|
71
|
+
"op": "core/column-removal",
|
|
72
|
+
"columnName": "unwanted_column",
|
|
73
|
+
"description": "Remove column"
|
|
74
|
+
}
|
|
75
|
+
refine.apply_operation(operation, project_id)
|
|
76
|
+
|
|
77
|
+
# Export data
|
|
78
|
+
refine.export_data("output_file.tsv", fmt="tsv", project_id=project_id)
|
|
79
|
+
|
|
80
|
+
# Clean up
|
|
81
|
+
refine.delete_project(project_id)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
5. Access Project Metadata:
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
# Set metadata
|
|
88
|
+
refine.set_project_metadata("name", "Project Name", project_id)
|
|
89
|
+
|
|
90
|
+
# Get all projects
|
|
91
|
+
projects = refine.get_all_projects_metadata()
|
|
92
|
+
for pid, metadata in projects.items():
|
|
93
|
+
print(f"{metadata['name']} (ID: {pid})")
|
|
94
|
+
|
|
95
|
+
# Find by name
|
|
96
|
+
project_id = refine.get_project_id_by_name("Project Name")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
6. Do Batch Operations:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
# Apply multiple operations
|
|
103
|
+
operations = [
|
|
104
|
+
{"op": "core/column-removal", "columnName": "col1"},
|
|
105
|
+
{"op": "core/column-removal", "columnName": "col2"}
|
|
106
|
+
]
|
|
107
|
+
refine.apply_operations(operations, project_id)
|
|
108
|
+
|
|
109
|
+
# Load from file
|
|
110
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Examples
|
|
114
|
+
|
|
115
|
+
### Example 1: Data Pipeline
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from refine_client import Refine
|
|
119
|
+
|
|
120
|
+
refine = Refine(verbose=True)
|
|
121
|
+
|
|
122
|
+
# Create project
|
|
123
|
+
project_id = refine.create_project("raw_data.csv", "Processing")
|
|
124
|
+
|
|
125
|
+
# Transform data
|
|
126
|
+
operations = [
|
|
127
|
+
{"op": "core/column-removal", "columnName": "temp_field"},
|
|
128
|
+
{"op": "core/text-transform", "columnName": "email",
|
|
129
|
+
"expression": "value.toLowerCase()"}
|
|
130
|
+
]
|
|
131
|
+
refine.apply_operations(operations, project_id, wait=True)
|
|
132
|
+
|
|
133
|
+
# Export
|
|
134
|
+
refine.export_data("processed_data.csv", fmt="csv", project_id=project_id)
|
|
135
|
+
|
|
136
|
+
# Cleanup
|
|
137
|
+
refine.delete_project(project_id)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Example 2: Batch Processing
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
import os
|
|
144
|
+
from refine_client import Refine
|
|
145
|
+
|
|
146
|
+
refine = Refine()
|
|
147
|
+
|
|
148
|
+
for filename in os.listdir("input_dir/"):
|
|
149
|
+
if filename.endswith(".csv"):
|
|
150
|
+
project_id = refine.create_project(f"input_dir/{filename}", filename)
|
|
151
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
152
|
+
refine.export_data(f"output_dir/{filename}", fmt="csv", project_id=project_id)
|
|
153
|
+
refine.delete_project(project_id)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## API Reference
|
|
157
|
+
|
|
158
|
+
### Initialization
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
Refine(base_url=None, verbose=False, silent=False)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Parameters:
|
|
165
|
+
- base_url: OpenRefine server URL (default: http://127.0.0.1:3333)
|
|
166
|
+
- verbose: Enable verbose logging
|
|
167
|
+
- silent: Suppress logging
|
|
168
|
+
|
|
169
|
+
### Methods
|
|
170
|
+
|
|
171
|
+
| Method | Description |
|
|
172
|
+
|--------|-------------|
|
|
173
|
+
| create_project(file, name) | Create project |
|
|
174
|
+
| delete_project(project_id) | Delete project |
|
|
175
|
+
| get_all_projects_metadata() | Get all projects |
|
|
176
|
+
| get_project_id_by_name(name) | Find project by name |
|
|
177
|
+
| set_project_metadata(field, value, id) | Update metadata |
|
|
178
|
+
| apply_operation(op, id, wait) | Apply operation |
|
|
179
|
+
| apply_operations(ops, id, wait) | Apply multiple |
|
|
180
|
+
| apply_operations_from_file(file, id, wait) | Load from file |
|
|
181
|
+
| get_models(id) | Get models |
|
|
182
|
+
| get_column_names(id) | Get columns |
|
|
183
|
+
| export_data(file, fmt, id) | Export data |
|
|
184
|
+
| rows_as_list(data) | Convert rows |
|
|
185
|
+
| wait_until_idle(id, delay) | Wait for completion |
|
|
186
|
+
|
|
187
|
+
## Configuration
|
|
188
|
+
|
|
189
|
+
### Logging
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
# Verbose mode
|
|
193
|
+
refine = Refine(verbose=True)
|
|
194
|
+
|
|
195
|
+
# Silent mode
|
|
196
|
+
refine = Refine(silent=True)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Custom Server
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
refine = Refine(base_url="http://example.com:3333")
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Troubleshooting
|
|
206
|
+
|
|
207
|
+
- **ConnectionError:** Ensure OpenRefine is running, verify the server URL and check network connectivity.
|
|
208
|
+
- **CSRF token errors:** Check server status and logs.
|
|
209
|
+
- **FileNotFoundError:** Use absolute paths, verify the file exists and check permissions.
|
|
210
|
+
|
|
211
|
+
## Support and Contribute
|
|
212
|
+
|
|
213
|
+
Open an issue on the project's [issues tab](https://github.com/rkraasch/refine-client/issues) on Github.
|
|
214
|
+
|
|
215
|
+
Or contribute via Github:
|
|
216
|
+
|
|
217
|
+
- fork the repository,
|
|
218
|
+
- create a feature branch,
|
|
219
|
+
- commit changes,
|
|
220
|
+
- push to branch,
|
|
221
|
+
- open Pull Request.
|
|
222
|
+
|
|
223
|
+
## References
|
|
224
|
+
|
|
225
|
+
References:
|
|
226
|
+
|
|
227
|
+
- [OpenRefine Documentation](https://docs.openrefine.org/)
|
|
228
|
+
- [OpenRefine REST API](https://docs.openrefine.org/manual/running)
|
|
229
|
+
|
|
230
|
+
Similar Projects:
|
|
231
|
+
|
|
232
|
+
- [paulmakepeace/refine-client-py](https://github.com/paulmakepeace/refine-client-py): OpenRefine Python 2 Client (last update 11 years ago).
|
|
233
|
+
- [opencultureconsulting/openrefine-client](https://github.com/opencultureconsulting/openrefine-client): OpenRefine Python Client (archived 2024).
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
This project is released under [CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/).
|
|
238
|
+
|
|
239
|
+
For a plain text version see this project's [LICENSE file](./LICENSE.md) or visit [creativecommons.org](https://creativecommons.org/2011/04/15/plaintext-versions-of-creative-commons-licenses-and-cc0/).
|
|
240
|
+
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
|
|
2
|
+
[build-system]
|
|
3
|
+
requires = ["setuptools>=61"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
name = "orcli"
|
|
8
|
+
version = "0.1.0"
|
|
9
|
+
description = "A Python client for interacting with OpenRefine"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"requests>=2.28.0",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
test = [
|
|
18
|
+
"pytest",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
23
|
+
|
orcli-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# client.py
|
|
3
|
+
# (c) 2025 RK, Lic. CC-0
|
|
4
|
+
|
|
5
|
+
import json, time, logging, requests
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.parse import urlparse, parse_qs
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
# Library logger setup – no default handlers, safe for reuse
|
|
11
|
+
if not logger.hasHandlers():
|
|
12
|
+
null_handler = logging.NullHandler()
|
|
13
|
+
logger.addHandler(null_handler)
|
|
14
|
+
|
|
15
|
+
class Refine:
|
|
16
|
+
"""Client interface for interacting with an OpenRefine server through its REST API."""
|
|
17
|
+
|
|
18
|
+
DEFAULT_BASE_URL = "http://127.0.0.1:3333"
|
|
19
|
+
|
|
20
|
+
def __init__(self, base_url: str | None = None, verbose: bool = False, silent: bool = False) -> None:
|
|
21
|
+
self.base_url: str = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
|
|
22
|
+
self.session = requests.Session()
|
|
23
|
+
self.csrf_token: str = ""
|
|
24
|
+
self.project_id: str | None = None
|
|
25
|
+
self.silent: bool = silent
|
|
26
|
+
self.verbose: bool = verbose
|
|
27
|
+
logger.setLevel(logging.INFO)
|
|
28
|
+
if silent:
|
|
29
|
+
logger.setLevel(logging.ERROR)
|
|
30
|
+
elif verbose:
|
|
31
|
+
logger.setLevel(logging.DEBUG)
|
|
32
|
+
logger.debug("Verbose logging enabled.")
|
|
33
|
+
stream_handler = logging.StreamHandler()
|
|
34
|
+
stream_handler.setLevel(logging.DEBUG)
|
|
35
|
+
formatter = logging.Formatter(
|
|
36
|
+
"%(asctime)s - %(levelname)s - %(name)s - %(message)s"
|
|
37
|
+
)
|
|
38
|
+
stream_handler.setFormatter(formatter)
|
|
39
|
+
logger.addHandler(stream_handler)
|
|
40
|
+
try:
|
|
41
|
+
response = self.session.get(f"{self.base_url}")
|
|
42
|
+
response.raise_for_status()
|
|
43
|
+
logger.info(f"Connected to OpenRefine server at {self.base_url}")
|
|
44
|
+
except Exception as e:
|
|
45
|
+
logger.error(f"Failed to connect to OpenRefine server at {self.base_url}: {e}")
|
|
46
|
+
raise ConnectionError(f"Could not connect to OpenRefine server at {self.base_url}") from e
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get_csrf_token(self) -> str:
|
|
50
|
+
"""Fetch CSRF token from server and cache it."""
|
|
51
|
+
if not self.csrf_token:
|
|
52
|
+
response = self.session.get(f"{self.base_url}/command/core/get-csrf-token")
|
|
53
|
+
response.raise_for_status()
|
|
54
|
+
token = response.json().get("token")
|
|
55
|
+
if not token:
|
|
56
|
+
logger.error("Failed to acquire CSRF token.")
|
|
57
|
+
raise ValueError("CSRF token retrieval failed.")
|
|
58
|
+
self.csrf_token = token
|
|
59
|
+
logger.debug("CSRF token retrieved successfully.")
|
|
60
|
+
return self.csrf_token
|
|
61
|
+
|
|
62
|
+
def _get_id(self, project_id: str | None) -> str:
|
|
63
|
+
"""Resolve a project ID or use the currently loaded one."""
|
|
64
|
+
if project_id:
|
|
65
|
+
return project_id
|
|
66
|
+
if not self.project_id:
|
|
67
|
+
raise ValueError("No project ID specified or loaded.")
|
|
68
|
+
return self.project_id
|
|
69
|
+
|
|
70
|
+
def create_project(self, project_file: str, project_name: str) -> str:
|
|
71
|
+
"""Create a new project from a local file."""
|
|
72
|
+
self._get_csrf_token()
|
|
73
|
+
file_path = Path(project_file)
|
|
74
|
+
if not file_path.is_file():
|
|
75
|
+
logger.error(f"File not found: {project_file}")
|
|
76
|
+
raise FileNotFoundError(project_file)
|
|
77
|
+
|
|
78
|
+
logger.info(f"Creating OpenRefine project: {project_name}")
|
|
79
|
+
with open(file_path, "rb") as f:
|
|
80
|
+
files = {"project-file": (file_path.name, f)}
|
|
81
|
+
params = {"project-name": project_name, "csrf_token": self.csrf_token}
|
|
82
|
+
response = self.session.post(
|
|
83
|
+
f"{self.base_url}/command/core/create-project-from-upload",
|
|
84
|
+
params=params,
|
|
85
|
+
files=files,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if response.status_code != 200:
|
|
89
|
+
self._save_error_response(response, "Project creation failed.")
|
|
90
|
+
raise RuntimeError(f"Failed to create project: {response.status_code}")
|
|
91
|
+
|
|
92
|
+
parsed_url = urlparse(response.url)
|
|
93
|
+
self.project_id = parse_qs(parsed_url.query).get("project", [None])[0]
|
|
94
|
+
if not self.project_id:
|
|
95
|
+
logger.error("Failed to parse project ID from server response.")
|
|
96
|
+
raise ValueError("Project ID not found in response.")
|
|
97
|
+
logger.info(f"Project created successfully: {self.project_id}")
|
|
98
|
+
return self.project_id
|
|
99
|
+
|
|
100
|
+
def apply_operations_from_file(self, operations_file: str, project_id: str | None = None, wait: bool = False):
|
|
101
|
+
"""Apply JSON operations from a given file."""
|
|
102
|
+
file_path = Path(operations_file)
|
|
103
|
+
if not file_path.is_file():
|
|
104
|
+
raise FileNotFoundError(operations_file)
|
|
105
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
106
|
+
operations = json.load(f)
|
|
107
|
+
return self.apply_operations(operations, project_id, wait)
|
|
108
|
+
|
|
109
|
+
def apply_operations(self, operations: list, project_id: str | None = None, wait: bool = False):
|
|
110
|
+
"""Apply a list of OpenRefine operations."""
|
|
111
|
+
results = []
|
|
112
|
+
for op in operations:
|
|
113
|
+
results.append(self.apply_operation(op, project_id, wait))
|
|
114
|
+
return results
|
|
115
|
+
|
|
116
|
+
def apply_operation(self, operation: dict, project_id: str | None = None, wait: bool = False):
|
|
117
|
+
"""Apply a single operation to a project."""
|
|
118
|
+
project = self._get_id(project_id)
|
|
119
|
+
self._get_csrf_token()
|
|
120
|
+
payload = {"operations": json.dumps([operation]), "csrf_token": self.csrf_token}
|
|
121
|
+
response = self.session.post(
|
|
122
|
+
f"{self.base_url}/command/core/apply-operations",
|
|
123
|
+
params={"project": project},
|
|
124
|
+
data=payload,
|
|
125
|
+
)
|
|
126
|
+
if response.status_code == 200:
|
|
127
|
+
if self.verbose:
|
|
128
|
+
desc = operation.get("description", "Unnamed operation")
|
|
129
|
+
logger.info(f"Applied operation: {desc}")
|
|
130
|
+
else:
|
|
131
|
+
self._save_error_response(response, "Operation failed.")
|
|
132
|
+
raise RuntimeError(f"Operation failed: {response.status_code}")
|
|
133
|
+
if wait:
|
|
134
|
+
self.wait_until_idle(project)
|
|
135
|
+
return response.json()
|
|
136
|
+
|
|
137
|
+
def export_data(self, output_file: str = "exported_data.tsv", fmt: str = "tsv", project_id: str | None = None):
|
|
138
|
+
"""Export project data to file in specified format."""
|
|
139
|
+
project = self._get_id(project_id)
|
|
140
|
+
self._get_csrf_token()
|
|
141
|
+
params = {"project": project, "format": fmt, "csrf_token": self.csrf_token}
|
|
142
|
+
response = self.session.post(f"{self.base_url}/command/core/export-rows", params=params)
|
|
143
|
+
if response.status_code != 200:
|
|
144
|
+
self._save_error_response(response, "Export failed.")
|
|
145
|
+
raise RuntimeError(f"Export failed: {response.status_code}")
|
|
146
|
+
|
|
147
|
+
with open(output_file, "wb") as f:
|
|
148
|
+
f.write(response.content)
|
|
149
|
+
logger.info(f"Exported data to {output_file}")
|
|
150
|
+
|
|
151
|
+
def get_models(self,project_id: str|None = None):
|
|
152
|
+
"""Get project models."""
|
|
153
|
+
project = self._get_id(project_id)
|
|
154
|
+
self._get_csrf_token()
|
|
155
|
+
|
|
156
|
+
response = self.session.get(f'{self.base_url}/command/core/get-models',
|
|
157
|
+
params={'project': project, 'csrf_token': self.csrf_token})
|
|
158
|
+
if response.status_code == 200:
|
|
159
|
+
logger.info(f"Get models {project}")
|
|
160
|
+
data = response.json()
|
|
161
|
+
return data
|
|
162
|
+
else:
|
|
163
|
+
self._save_error_response(response, 'Get models failed.')
|
|
164
|
+
raise Exception(f'Get models failed: {response.status_code}')
|
|
165
|
+
|
|
166
|
+
def get_column_names(self,project_id: str|None = None):
|
|
167
|
+
"""Get column names from project models."""
|
|
168
|
+
project = self._get_id(project_id)
|
|
169
|
+
self._get_csrf_token()
|
|
170
|
+
|
|
171
|
+
response = self.session.get(f'{self.base_url}/command/core/get-models',
|
|
172
|
+
params={'project': project, 'csrf_token': self.csrf_token})
|
|
173
|
+
if response.status_code == 200:
|
|
174
|
+
logger.info(f"Get column names {project}")
|
|
175
|
+
data = response.json()["columnModel"]
|
|
176
|
+
data = [col["name"] for col in data["columns"]]
|
|
177
|
+
return data
|
|
178
|
+
else:
|
|
179
|
+
self._save_error_response(response, 'Get column names failed.')
|
|
180
|
+
raise Exception(f'Get column names failed: {response.status_code}')
|
|
181
|
+
|
|
182
|
+
def delete_project(self, project_id: str | None = None):
|
|
183
|
+
"""Delete a specific project."""
|
|
184
|
+
project = self._get_id(project_id)
|
|
185
|
+
self._get_csrf_token()
|
|
186
|
+
response = self.session.post(
|
|
187
|
+
f"{self.base_url}/command/core/delete-project",
|
|
188
|
+
data={"project": project, "csrf_token": self.csrf_token},
|
|
189
|
+
)
|
|
190
|
+
if response.status_code == 200:
|
|
191
|
+
logger.info(f"Deleted project {project}")
|
|
192
|
+
else:
|
|
193
|
+
self._save_error_response(response, "Project deletion failed.")
|
|
194
|
+
raise RuntimeError(f"Deletion failed: {response.status_code}")
|
|
195
|
+
|
|
196
|
+
def _save_error_response(self, response, message: str):
|
|
197
|
+
"""Save HTML error responses for debugging."""
|
|
198
|
+
filename = "response.html"
|
|
199
|
+
logger.error(f"{message}. Status: {response.status_code}")
|
|
200
|
+
with open(filename, "w", encoding="utf-8") as f:
|
|
201
|
+
f.write(response.text)
|
|
202
|
+
logger.debug(f"Saved error details to {filename}")
|
|
203
|
+
|
|
204
|
+
def get_all_projects_metadata(self) -> dict:
|
|
205
|
+
"""Retrieve metadata for all OpenRefine projects."""
|
|
206
|
+
response = self.session.get(f"{self.base_url}/command/core/get-all-project-metadata")
|
|
207
|
+
if response.status_code != 200:
|
|
208
|
+
self._save_error_response(response, "Metadata retrieval failed.")
|
|
209
|
+
raise RuntimeError("Failed to retrieve metadata.")
|
|
210
|
+
logger.info("Retrieved all project metadata.")
|
|
211
|
+
return response.json().get("projects", {})
|
|
212
|
+
|
|
213
|
+
def get_project_id_by_name(self, name: str = "") -> str | None :
|
|
214
|
+
"""Get project id by project name"""
|
|
215
|
+
projects = self.get_all_projects_metadata()
|
|
216
|
+
for pid, metadata in projects.items():
|
|
217
|
+
if metadata["name"] == name:
|
|
218
|
+
logger.info("Retrieved project id.")
|
|
219
|
+
return pid
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
def set_project_metadata(self, field_name: str, value: str, id: str | None = None) -> None:
|
|
223
|
+
project = self._get_id(id)
|
|
224
|
+
self._get_csrf_token()
|
|
225
|
+
data = {
|
|
226
|
+
'project': project,
|
|
227
|
+
'name': field_name,
|
|
228
|
+
'value': value,
|
|
229
|
+
'csrf_token': self.csrf_token
|
|
230
|
+
}
|
|
231
|
+
response = self.session.post(f'{self.base_url}/command/core/set-project-metadata', data=data)
|
|
232
|
+
if response.status_code == 200:
|
|
233
|
+
if self.verbose:
|
|
234
|
+
logger.info(f"Project metadata '{field_name}' updated to '{value}'.")
|
|
235
|
+
else:
|
|
236
|
+
self._save_error_response(response, "Failed to update project metadata")
|
|
237
|
+
raise Exception(f"Failed to update project metadata: {response.status_code}")
|
|
238
|
+
|
|
239
|
+
def wait_until_idle(self, project_id: str | None = None, delay: float = 0.5):
|
|
240
|
+
"""Wait until OpenRefine finishes processing all jobs."""
|
|
241
|
+
project = self._get_id(project_id)
|
|
242
|
+
while True:
|
|
243
|
+
response = self.session.get(f"{self.base_url}/command/core/get-processes", params={"project": project})
|
|
244
|
+
processes = response.json().get("processes", [])
|
|
245
|
+
if processes:
|
|
246
|
+
time.sleep(delay)
|
|
247
|
+
else:
|
|
248
|
+
logger.debug("OpenRefine is idle.")
|
|
249
|
+
break
|
|
250
|
+
|
|
251
|
+
def rows_as_list(self, data:dict)->list:
|
|
252
|
+
"""Return rows as list"""
|
|
253
|
+
if 'rows' in data:
|
|
254
|
+
rows_list = [
|
|
255
|
+
[cell.get("v", None) for cell in row["cells"]]
|
|
256
|
+
for row in data["rows"]
|
|
257
|
+
]
|
|
258
|
+
return rows_list
|
|
259
|
+
else:
|
|
260
|
+
return []
|
|
261
|
+
|
|
262
|
+
if __name__ == "__main__":
|
|
263
|
+
refine = Refine(verbose=True)
|
|
264
|
+
# Example usage:
|
|
265
|
+
# project_id = refine.create_project("data.csv", "My Project")
|
|
266
|
+
# refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
267
|
+
# refine.export_data("output.tsv", "tsv", project_id)
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: orcli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python client for interacting with OpenRefine
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE.md
|
|
8
|
+
Requires-Dist: requests>=2.28.0
|
|
9
|
+
Provides-Extra: test
|
|
10
|
+
Requires-Dist: pytest; extra == "test"
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# refine-client
|
|
15
|
+
|
|
16
|
+
A Python client library for interacting with [OpenRefine](https://openrefine.org/) via its REST API.
|
|
17
|
+
|
|
18
|
+
For simple project creation, data transformation, metadata management and export operations.
|
|
19
|
+
|
|
20
|
+
## Features
|
|
21
|
+
|
|
22
|
+
- Create and delete projects from local files.
|
|
23
|
+
- Retrieve and manage project metadata.
|
|
24
|
+
- Apply OpenRefine operations individually or in batches.
|
|
25
|
+
- Load operations from JSON files.
|
|
26
|
+
- Export data in multiple formats (TSV, CSV, JSON).
|
|
27
|
+
- Retrieve column information and project models, convert and manipulate row data.
|
|
28
|
+
- Error handling with detailed response logging.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
### Requirements
|
|
33
|
+
|
|
34
|
+
Requires Python 3.10+ and a running OpenRefine server instance.
|
|
35
|
+
|
|
36
|
+
### Quick Start
|
|
37
|
+
|
|
38
|
+
1. Clone the repository:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git clone https://github.com/rkraasch/refine-client.git
|
|
42
|
+
cd refine-client
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
2. Install dependencies:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
python -m venv .venv
|
|
49
|
+
source [.venv/bin/activate](.venv/bin/activate) # Linux and Mac.
|
|
50
|
+
# .venv\Scripts\activate # Windows.
|
|
51
|
+
pip install -r requirements.txt
|
|
52
|
+
python -m pip list
|
|
53
|
+
deactivate
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
3. Optionally run tests:
|
|
57
|
+
|
|
58
|
+
[Download](https://openrefine.org/download) and run OpenRefine, then run the tests as shown below.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
python -m pytest tests/ -v
|
|
62
|
+
```
|
|
63
|
+
This creates temporary test projects in OpenRefine which should be cleaned up automatically.
|
|
64
|
+
If a project prefixed `pytest_refine-client-integration_` remains visible in the Open project tab (under [#open-project](http://127.0.0.1:3333/#open-project)), something went wrong.
|
|
65
|
+
|
|
66
|
+
4. Basic Usage:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from refine_client import Refine
|
|
70
|
+
|
|
71
|
+
# Initialize the client
|
|
72
|
+
refine = Refine(base_url="http://127.0.0.1:3333")
|
|
73
|
+
|
|
74
|
+
# Create a project
|
|
75
|
+
project_id = refine.create_project("input_file.csv", "My Project")
|
|
76
|
+
|
|
77
|
+
# Get column names
|
|
78
|
+
columns = refine.get_column_names(project_id)
|
|
79
|
+
print(f"Columns: {columns}")
|
|
80
|
+
|
|
81
|
+
# Apply an operation
|
|
82
|
+
operation = {
|
|
83
|
+
"op": "core/column-removal",
|
|
84
|
+
"columnName": "unwanted_column",
|
|
85
|
+
"description": "Remove column"
|
|
86
|
+
}
|
|
87
|
+
refine.apply_operation(operation, project_id)
|
|
88
|
+
|
|
89
|
+
# Export data
|
|
90
|
+
refine.export_data("output_file.tsv", fmt="tsv", project_id=project_id)
|
|
91
|
+
|
|
92
|
+
# Clean up
|
|
93
|
+
refine.delete_project(project_id)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
5. Access Project Metadata:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
# Set metadata
|
|
100
|
+
refine.set_project_metadata("name", "Project Name", project_id)
|
|
101
|
+
|
|
102
|
+
# Get all projects
|
|
103
|
+
projects = refine.get_all_projects_metadata()
|
|
104
|
+
for pid, metadata in projects.items():
|
|
105
|
+
print(f"{metadata['name']} (ID: {pid})")
|
|
106
|
+
|
|
107
|
+
# Find by name
|
|
108
|
+
project_id = refine.get_project_id_by_name("Project Name")
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
6. Do Batch Operations:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
# Apply multiple operations
|
|
115
|
+
operations = [
|
|
116
|
+
{"op": "core/column-removal", "columnName": "col1"},
|
|
117
|
+
{"op": "core/column-removal", "columnName": "col2"}
|
|
118
|
+
]
|
|
119
|
+
refine.apply_operations(operations, project_id)
|
|
120
|
+
|
|
121
|
+
# Load from file
|
|
122
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Examples
|
|
126
|
+
|
|
127
|
+
### Example 1: Data Pipeline
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from refine_client import Refine
|
|
131
|
+
|
|
132
|
+
refine = Refine(verbose=True)
|
|
133
|
+
|
|
134
|
+
# Create project
|
|
135
|
+
project_id = refine.create_project("raw_data.csv", "Processing")
|
|
136
|
+
|
|
137
|
+
# Transform data
|
|
138
|
+
operations = [
|
|
139
|
+
{"op": "core/column-removal", "columnName": "temp_field"},
|
|
140
|
+
{"op": "core/text-transform", "columnName": "email",
|
|
141
|
+
"expression": "value.toLowerCase()"}
|
|
142
|
+
]
|
|
143
|
+
refine.apply_operations(operations, project_id, wait=True)
|
|
144
|
+
|
|
145
|
+
# Export
|
|
146
|
+
refine.export_data("processed_data.csv", fmt="csv", project_id=project_id)
|
|
147
|
+
|
|
148
|
+
# Cleanup
|
|
149
|
+
refine.delete_project(project_id)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Example 2: Batch Processing
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
import os
|
|
156
|
+
from refine_client import Refine
|
|
157
|
+
|
|
158
|
+
refine = Refine()
|
|
159
|
+
|
|
160
|
+
for filename in os.listdir("input_dir/"):
|
|
161
|
+
if filename.endswith(".csv"):
|
|
162
|
+
project_id = refine.create_project(f"input_dir/{filename}", filename)
|
|
163
|
+
refine.apply_operations_from_file("operations.json", project_id, wait=True)
|
|
164
|
+
refine.export_data(f"output_dir/{filename}", fmt="csv", project_id=project_id)
|
|
165
|
+
refine.delete_project(project_id)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## API Reference
|
|
169
|
+
|
|
170
|
+
### Initialization
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
Refine(base_url=None, verbose=False, silent=False)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Parameters:
|
|
177
|
+
- base_url: OpenRefine server URL (default: http://127.0.0.1:3333)
|
|
178
|
+
- verbose: Enable verbose logging
|
|
179
|
+
- silent: Suppress logging
|
|
180
|
+
|
|
181
|
+
### Methods
|
|
182
|
+
|
|
183
|
+
| Method | Description |
|
|
184
|
+
|--------|-------------|
|
|
185
|
+
| create_project(file, name) | Create project |
|
|
186
|
+
| delete_project(project_id) | Delete project |
|
|
187
|
+
| get_all_projects_metadata() | Get all projects |
|
|
188
|
+
| get_project_id_by_name(name) | Find project by name |
|
|
189
|
+
| set_project_metadata(field, value, id) | Update metadata |
|
|
190
|
+
| apply_operation(op, id, wait) | Apply operation |
|
|
191
|
+
| apply_operations(ops, id, wait) | Apply multiple |
|
|
192
|
+
| apply_operations_from_file(file, id, wait) | Load from file |
|
|
193
|
+
| get_models(id) | Get models |
|
|
194
|
+
| get_column_names(id) | Get columns |
|
|
195
|
+
| export_data(file, fmt, id) | Export data |
|
|
196
|
+
| rows_as_list(data) | Convert rows |
|
|
197
|
+
| wait_until_idle(id, delay) | Wait for completion |
|
|
198
|
+
|
|
199
|
+
## Configuration
|
|
200
|
+
|
|
201
|
+
### Logging
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
# Verbose mode
|
|
205
|
+
refine = Refine(verbose=True)
|
|
206
|
+
|
|
207
|
+
# Silent mode
|
|
208
|
+
refine = Refine(silent=True)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Custom Server
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
refine = Refine(base_url="http://example.com:3333")
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Troubleshooting
|
|
218
|
+
|
|
219
|
+
- **ConnectionError:** Ensure OpenRefine is running, verify the server URL and check network connectivity.
|
|
220
|
+
- **CSRF token errors:** Check server status and logs.
|
|
221
|
+
- **FileNotFoundError:** Use absolute paths, verify the file exists and check permissions.
|
|
222
|
+
|
|
223
|
+
## Support and Contribute
|
|
224
|
+
|
|
225
|
+
Open an issue on the project's [issues tab](https://github.com/rkraasch/refine-client/issues) on Github.
|
|
226
|
+
|
|
227
|
+
Or contribute via Github:
|
|
228
|
+
|
|
229
|
+
- fork the repository,
|
|
230
|
+
- create a feature branch,
|
|
231
|
+
- commit changes,
|
|
232
|
+
- push to branch,
|
|
233
|
+
- open Pull Request.
|
|
234
|
+
|
|
235
|
+
## References
|
|
236
|
+
|
|
237
|
+
References:
|
|
238
|
+
|
|
239
|
+
- [OpenRefine Documentation](https://docs.openrefine.org/)
|
|
240
|
+
- [OpenRefine REST API](https://docs.openrefine.org/manual/running)
|
|
241
|
+
|
|
242
|
+
Similar Projects:
|
|
243
|
+
|
|
244
|
+
- [paulmakepeace/refine-client-py](https://github.com/paulmakepeace/refine-client-py): OpenRefine Python 2 Client (last update 11 years ago).
|
|
245
|
+
- [opencultureconsulting/openrefine-client](https://github.com/opencultureconsulting/openrefine-client): OpenRefine Python Client (archived 2024).
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
This project is released under [CC0 1.0 Universal License](https://creativecommons.org/publicdomain/zero/1.0/).
|
|
250
|
+
|
|
251
|
+
For a plain text version see this project's [LICENSE file](./LICENSE.md) or visit [creativecommons.org](https://creativecommons.org/2011/04/15/plaintext-versions-of-creative-commons-licenses-and-cc0/).
|
|
252
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
orcli
|