parseur-py 1.5.3__tar.gz → 1.7.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.
Files changed (44) hide show
  1. {parseur_py-1.5.3/parseur_py.egg-info → parseur_py-1.7.0}/PKG-INFO +55 -7
  2. {parseur_py-1.5.3 → parseur_py-1.7.0}/README.md +54 -6
  3. parseur_py-1.7.0/parseur/__init__.py +67 -0
  4. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/cli.py +198 -11
  5. parseur_py-1.7.0/parseur/client.py +71 -0
  6. parseur_py-1.7.0/parseur/document.py +427 -0
  7. parseur_py-1.7.0/parseur/export_config.py +171 -0
  8. parseur_py-1.7.0/parseur/mailbox.py +599 -0
  9. parseur_py-1.7.0/parseur/parser_field.py +214 -0
  10. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/schemas/document.py +16 -0
  11. parseur_py-1.7.0/parseur/schemas/export_config.py +61 -0
  12. parseur_py-1.7.0/parseur/schemas/mailbox.py +345 -0
  13. parseur_py-1.7.0/parseur/schemas/paserfield.py +90 -0
  14. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/server.py +1 -1
  15. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/utils.py +19 -0
  16. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/webhook.py +30 -13
  17. {parseur_py-1.5.3 → parseur_py-1.7.0/parseur_py.egg-info}/PKG-INFO +55 -7
  18. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur_py.egg-info/SOURCES.txt +10 -0
  19. {parseur_py-1.5.3 → parseur_py-1.7.0}/pyproject.toml +1 -1
  20. parseur_py-1.7.0/tests/test_api_key_override.py +72 -0
  21. parseur_py-1.7.0/tests/test_cli.py +73 -0
  22. {parseur_py-1.5.3 → parseur_py-1.7.0}/tests/test_document.py +115 -16
  23. parseur_py-1.7.0/tests/test_export_config.py +165 -0
  24. parseur_py-1.7.0/tests/test_mailbox.py +766 -0
  25. parseur_py-1.7.0/tests/test_parser_field.py +210 -0
  26. parseur_py-1.5.3/parseur/__init__.py +0 -31
  27. parseur_py-1.5.3/parseur/client.py +0 -51
  28. parseur_py-1.5.3/parseur/document.py +0 -217
  29. parseur_py-1.5.3/parseur/mailbox.py +0 -77
  30. parseur_py-1.5.3/parseur/schemas/mailbox.py +0 -177
  31. parseur_py-1.5.3/parseur/schemas/paserfield.py +0 -25
  32. parseur_py-1.5.3/tests/test_mailbox.py +0 -198
  33. {parseur_py-1.5.3 → parseur_py-1.7.0}/LICENSE +0 -0
  34. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/config.py +0 -0
  35. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/decorator.py +0 -0
  36. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/event.py +0 -0
  37. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/schemas/__init__.py +0 -0
  38. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur/schemas/webhook.py +0 -0
  39. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur_py.egg-info/dependency_links.txt +0 -0
  40. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur_py.egg-info/entry_points.txt +0 -0
  41. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur_py.egg-info/requires.txt +0 -0
  42. {parseur_py-1.5.3 → parseur_py-1.7.0}/parseur_py.egg-info/top_level.txt +0 -0
  43. {parseur_py-1.5.3 → parseur_py-1.7.0}/setup.cfg +0 -0
  44. {parseur_py-1.5.3 → parseur_py-1.7.0}/tests/test_webhook.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: parseur-py
3
- Version: 1.5.3
3
+ Version: 1.7.0
4
4
  Summary: A Python client for the Parseur.com API to manage mailboxes, documents, uploads, and listen for new parsing events.
5
5
  Author-email: Parseur Team <admin@parseur.com>
6
6
  Project-URL: Homepage, https://github.com/parseur/parseur-py
@@ -41,7 +41,7 @@ Built to help you automate document parsing at scale, parseur-py makes integrati
41
41
  ✅ Reprocess, skip, copy, or delete documents
42
42
  ✅ Manage custom webhooks for real-time events
43
43
  ✅ Listen to events in real time with a temporary webhook & tunnel
44
- ✅ Fully-featured **Command Line Interface (CLI)**
44
+ ✅ Fully-featured **Command Line Interface (CLI)**
45
45
 
46
46
  ---
47
47
 
@@ -70,7 +70,7 @@ pip install parseur-py
70
70
  With event listener support (Flask + localtunnel)
71
71
 
72
72
  ```bash
73
- pip install parseur-py[listener]
73
+ pip install "parseur-py[listener]"
74
74
  ```
75
75
 
76
76
  ### Install the package from source
@@ -87,6 +87,24 @@ cd docs
87
87
  make html
88
88
  ```
89
89
 
90
+ ### Run the tests
91
+
92
+ Unit tests run fully offline:
93
+
94
+ ```bash
95
+ pytest
96
+ ```
97
+
98
+ Integration tests hit the real Parseur API. They create and delete real
99
+ resources, so they're skipped unless credentials are provided **via the
100
+ environment** (never committed or stored in `~/.parseur.conf`):
101
+
102
+ ```bash
103
+ PARSEUR_API_BASE=https://api.parseur.com \
104
+ PARSEUR_API_KEY=sk_your_key \
105
+ pytest tests/integration -v
106
+ ```
107
+
90
108
  ---
91
109
 
92
110
  ### Initialize your configuration
@@ -119,10 +137,19 @@ List documents in a mailbox:
119
137
  parseur list-documents 12345
120
138
  ```
121
139
 
122
- Upload a file to a mailbox:
140
+ Upload a file to a mailbox (add `--wait` to block until it is parsed, with a live progress bar):
123
141
 
124
142
  ```bash
125
143
  parseur upload-file 12345 ./path/to/document.pdf
144
+ parseur upload-file 12345 ./path/to/document.pdf --wait
145
+ ```
146
+
147
+ Download a mailbox's results as a file (stdout by default, or `--output`):
148
+
149
+ ```bash
150
+ parseur download-mailbox 12345 --format csv -o results.csv # whole mailbox
151
+ parseur list-parser-fields 12345 # find a table field id
152
+ parseur download-field 12345 PF951 --format xlsx -o lines.xlsx # a table field
126
153
  ```
127
154
 
128
155
  Register a custom webhook:
@@ -161,10 +188,14 @@ for a full list of available commands.
161
188
  - **list-mailboxes**: Search and sort mailboxes
162
189
  - **get-mailbox**: Fetch a mailbox by ID
163
190
  - **get-mailbox-schema**: Get the mailbox parsing schema
191
+ - **list-parser-fields**: List the fields extracted by a mailbox
192
+ - **download-mailbox / download-field / download-export**: Download results as a file (csv/json/xlsx)
193
+ - **list-export-configs**: List a mailbox's custom export configurations
164
194
  - **list-documents**: Advanced document search, filtering, sorting
165
- - **get-document**: Fetch document details
166
- - **reprocess-document / skip-document / delete-document**: Document lifecycle operations
167
- - **upload-file / upload-text**: Upload new documents
195
+ - **get-document / get-document-logs**: Fetch document details and processing logs
196
+ - **reprocess-document / skip-document / copy-document / split-document / reverse-split-document / delete-document**: Document lifecycle operations
197
+ - **upload-file / upload-text**: Upload new documents (add `--wait` for synchronous parsing)
198
+ - **upload-folder**: Upload every file matching a glob path
168
199
  - **create-webhook / get-webhook / list-webhooks / delete-webhook**: Create, get, list, and delete custom webhook integrations.
169
200
  - **enable-webhook / pause-webhook**: Activate or pause a webhook for a specific mailbox.
170
201
  - **listen**: Create a temporary webhook and listen to events in real time (with optional redirect & silent mode)
@@ -219,6 +250,12 @@ Your webhook endpoint will receive POST notifications with Parseur payloads, ena
219
250
 
220
251
  ---
221
252
 
253
+ ## 🤖 MCP Server (AI assistants)
254
+
255
+ Parseur hosts an [MCP](https://modelcontextprotocol.io) server at `https://api.parseur.com/mcp`. Add this URL to any MCP-compatible AI assistant (Claude, Codex, Cursor, …) to drive Parseur from it. No local install is needed.
256
+
257
+ ---
258
+
222
259
  ## 🛠️ Configuration
223
260
 
224
261
  Your API token and settings are stored in a simple INI file:
@@ -246,6 +283,17 @@ for mailbox in parseur.Mailbox.list():
246
283
  print(mailbox.name)
247
284
  ```
248
285
 
286
+ ### Per-call API key override
287
+
288
+ Every method accepts an optional `api_key` argument that **takes priority over
289
+ the global `parseur.api_key`** for that single call — useful for multi-account
290
+ or multi-tenant code:
291
+
292
+ ```python
293
+ parseur.Mailbox.list(api_key="sk_account_a")
294
+ parseur.Document.upload_file(123, "invoice.pdf", api_key="sk_account_b")
295
+ ```
296
+
249
297
  ---
250
298
 
251
299
  ## 📖 Documentation
@@ -23,7 +23,7 @@ Built to help you automate document parsing at scale, parseur-py makes integrati
23
23
  ✅ Reprocess, skip, copy, or delete documents
24
24
  ✅ Manage custom webhooks for real-time events
25
25
  ✅ Listen to events in real time with a temporary webhook & tunnel
26
- ✅ Fully-featured **Command Line Interface (CLI)**
26
+ ✅ Fully-featured **Command Line Interface (CLI)**
27
27
 
28
28
  ---
29
29
 
@@ -52,7 +52,7 @@ pip install parseur-py
52
52
  With event listener support (Flask + localtunnel)
53
53
 
54
54
  ```bash
55
- pip install parseur-py[listener]
55
+ pip install "parseur-py[listener]"
56
56
  ```
57
57
 
58
58
  ### Install the package from source
@@ -69,6 +69,24 @@ cd docs
69
69
  make html
70
70
  ```
71
71
 
72
+ ### Run the tests
73
+
74
+ Unit tests run fully offline:
75
+
76
+ ```bash
77
+ pytest
78
+ ```
79
+
80
+ Integration tests hit the real Parseur API. They create and delete real
81
+ resources, so they're skipped unless credentials are provided **via the
82
+ environment** (never committed or stored in `~/.parseur.conf`):
83
+
84
+ ```bash
85
+ PARSEUR_API_BASE=https://api.parseur.com \
86
+ PARSEUR_API_KEY=sk_your_key \
87
+ pytest tests/integration -v
88
+ ```
89
+
72
90
  ---
73
91
 
74
92
  ### Initialize your configuration
@@ -101,10 +119,19 @@ List documents in a mailbox:
101
119
  parseur list-documents 12345
102
120
  ```
103
121
 
104
- Upload a file to a mailbox:
122
+ Upload a file to a mailbox (add `--wait` to block until it is parsed, with a live progress bar):
105
123
 
106
124
  ```bash
107
125
  parseur upload-file 12345 ./path/to/document.pdf
126
+ parseur upload-file 12345 ./path/to/document.pdf --wait
127
+ ```
128
+
129
+ Download a mailbox's results as a file (stdout by default, or `--output`):
130
+
131
+ ```bash
132
+ parseur download-mailbox 12345 --format csv -o results.csv # whole mailbox
133
+ parseur list-parser-fields 12345 # find a table field id
134
+ parseur download-field 12345 PF951 --format xlsx -o lines.xlsx # a table field
108
135
  ```
109
136
 
110
137
  Register a custom webhook:
@@ -143,10 +170,14 @@ for a full list of available commands.
143
170
  - **list-mailboxes**: Search and sort mailboxes
144
171
  - **get-mailbox**: Fetch a mailbox by ID
145
172
  - **get-mailbox-schema**: Get the mailbox parsing schema
173
+ - **list-parser-fields**: List the fields extracted by a mailbox
174
+ - **download-mailbox / download-field / download-export**: Download results as a file (csv/json/xlsx)
175
+ - **list-export-configs**: List a mailbox's custom export configurations
146
176
  - **list-documents**: Advanced document search, filtering, sorting
147
- - **get-document**: Fetch document details
148
- - **reprocess-document / skip-document / delete-document**: Document lifecycle operations
149
- - **upload-file / upload-text**: Upload new documents
177
+ - **get-document / get-document-logs**: Fetch document details and processing logs
178
+ - **reprocess-document / skip-document / copy-document / split-document / reverse-split-document / delete-document**: Document lifecycle operations
179
+ - **upload-file / upload-text**: Upload new documents (add `--wait` for synchronous parsing)
180
+ - **upload-folder**: Upload every file matching a glob path
150
181
  - **create-webhook / get-webhook / list-webhooks / delete-webhook**: Create, get, list, and delete custom webhook integrations.
151
182
  - **enable-webhook / pause-webhook**: Activate or pause a webhook for a specific mailbox.
152
183
  - **listen**: Create a temporary webhook and listen to events in real time (with optional redirect & silent mode)
@@ -201,6 +232,12 @@ Your webhook endpoint will receive POST notifications with Parseur payloads, ena
201
232
 
202
233
  ---
203
234
 
235
+ ## 🤖 MCP Server (AI assistants)
236
+
237
+ Parseur hosts an [MCP](https://modelcontextprotocol.io) server at `https://api.parseur.com/mcp`. Add this URL to any MCP-compatible AI assistant (Claude, Codex, Cursor, …) to drive Parseur from it. No local install is needed.
238
+
239
+ ---
240
+
204
241
  ## 🛠️ Configuration
205
242
 
206
243
  Your API token and settings are stored in a simple INI file:
@@ -228,6 +265,17 @@ for mailbox in parseur.Mailbox.list():
228
265
  print(mailbox.name)
229
266
  ```
230
267
 
268
+ ### Per-call API key override
269
+
270
+ Every method accepts an optional `api_key` argument that **takes priority over
271
+ the global `parseur.api_key`** for that single call — useful for multi-account
272
+ or multi-tenant code:
273
+
274
+ ```python
275
+ parseur.Mailbox.list(api_key="sk_account_a")
276
+ parseur.Document.upload_file(123, "invoice.pdf", api_key="sk_account_b")
277
+ ```
278
+
231
279
  ---
232
280
 
233
281
  ## 📖 Documentation
@@ -0,0 +1,67 @@
1
+ from pathlib import Path
2
+
3
+ from parseur.config import Config
4
+ from parseur.document import (
5
+ Document,
6
+ DocumentOrderKey,
7
+ FAILED_STATUSES,
8
+ FINAL_STATUSES,
9
+ PENDING_STATUSES,
10
+ )
11
+ from parseur.event import ParseurEvent
12
+ from parseur.export_config import ExportConfig
13
+ from parseur.mailbox import (
14
+ EmailProcessing,
15
+ Mailbox,
16
+ MailboxOrderKey,
17
+ Metadata,
18
+ SenderFilter,
19
+ )
20
+ from parseur.parser_field import ParserField
21
+ from parseur.schemas.document import DocumentStatus
22
+ from parseur.schemas.export_config import ExportType
23
+ from parseur.schemas.mailbox import (
24
+ AIEngine,
25
+ DateFormat,
26
+ DecimalSeparator,
27
+ SUPPORTED_FILE_EXTENSIONS,
28
+ )
29
+ from parseur.schemas.paserfield import FieldFormat
30
+ from parseur.utils import to_json
31
+ from parseur.webhook import Webhook
32
+
33
+ __all__ = [
34
+ "AIEngine",
35
+ "Config",
36
+ "DateFormat",
37
+ "DecimalSeparator",
38
+ "Document",
39
+ "DocumentOrderKey",
40
+ "DocumentStatus",
41
+ "EmailProcessing",
42
+ "ExportConfig",
43
+ "ExportType",
44
+ "FAILED_STATUSES",
45
+ "FINAL_STATUSES",
46
+ "FieldFormat",
47
+ "Mailbox",
48
+ "MailboxOrderKey",
49
+ "Metadata",
50
+ "PENDING_STATUSES",
51
+ "ParseurEvent",
52
+ "ParserField",
53
+ "SUPPORTED_FILE_EXTENSIONS",
54
+ "SenderFilter",
55
+ "Webhook",
56
+ "to_json",
57
+ ]
58
+
59
+
60
+ CONFIG_PATH = Path.home() / ".parseur.conf"
61
+ config = Config(CONFIG_PATH)
62
+ config.load()
63
+
64
+ DEFAULT_API_BASE = "https://api.parseur.com"
65
+
66
+ api_key = config.api_key
67
+ api_base = config.api_base or DEFAULT_API_BASE
@@ -5,6 +5,55 @@ import click
5
5
 
6
6
  import parseur
7
7
 
8
+ WAIT_OPTION = click.option(
9
+ "--wait",
10
+ is_flag=True,
11
+ default=False,
12
+ help=(
13
+ "Block until the document reaches a final status "
14
+ "(polls every 5s, up to 10 min), showing live progress."
15
+ ),
16
+ )
17
+
18
+
19
+ def progress_printer():
20
+ """Return an ``on_poll(elapsed, status)`` callback rendering a progress bar.
21
+
22
+ Progress is written to stderr so stdout stays a clean JSON document.
23
+ """
24
+
25
+ def on_poll(elapsed, status):
26
+ remaining = max(0, parseur.document.MAX_WAIT - elapsed)
27
+ width = 24
28
+ fraction = min(1.0, elapsed / parseur.document.MAX_WAIT)
29
+ filled = int(fraction * width)
30
+ bar = "█" * filled + "░" * (width - filled)
31
+ click.echo(
32
+ f"\r⏳ [{bar}] {status:<9} elapsed {elapsed:4.0f}s · ETA ≤ {remaining:4.0f}s",
33
+ nl=False,
34
+ err=True,
35
+ )
36
+
37
+ return on_poll
38
+
39
+
40
+ DOWNLOAD_FORMATS = ["csv", "json", "xlsx"]
41
+ EXPORT_FORMATS = ["csv", "xlsx"]
42
+
43
+
44
+ def write_download(content, output):
45
+ """Write downloaded bytes to ``output`` if given, otherwise to stdout.
46
+
47
+ Binary formats (xlsx) are written through the raw stdout buffer so they
48
+ survive redirection, e.g. ``parseur download-mailbox 123 > results.csv``.
49
+ """
50
+ if output:
51
+ with open(output, "wb") as fh:
52
+ fh.write(content)
53
+ click.echo(f"✅ Saved {len(content)} bytes to {output}", err=True)
54
+ else:
55
+ click.get_binary_stream("stdout").write(content)
56
+
8
57
 
9
58
  def headers_to_dict(headers):
10
59
  headers_dict = {}
@@ -100,6 +149,97 @@ def get_mailbox_schema(mailbox_id):
100
149
  click.echo(parseur.to_json(result))
101
150
 
102
151
 
152
+ @cli.command("download-mailbox")
153
+ @click.argument("mailbox_id", type=int)
154
+ @click.option(
155
+ "--format",
156
+ "fmt",
157
+ type=click.Choice(DOWNLOAD_FORMATS),
158
+ default="csv",
159
+ help="Export file format (default: csv).",
160
+ )
161
+ @click.option(
162
+ "--output",
163
+ "-o",
164
+ type=click.Path(),
165
+ help="Write to this file instead of stdout.",
166
+ )
167
+ def download_mailbox(mailbox_id, fmt, output):
168
+ """Download all parsed results of a mailbox (one row per document)."""
169
+ content = parseur.Mailbox.download(mailbox_id, fmt)
170
+ write_download(content, output)
171
+
172
+
173
+ # ------------------------
174
+ # Parser field commands
175
+ # ------------------------
176
+
177
+
178
+ @cli.command("list-parser-fields")
179
+ @click.argument("mailbox_id", type=int)
180
+ def list_parser_fields(mailbox_id):
181
+ """List the parser fields configured on a mailbox."""
182
+ fields = parseur.ParserField.list(mailbox_id)
183
+ click.echo(parseur.to_json(fields))
184
+
185
+
186
+ @cli.command("download-field")
187
+ @click.argument("mailbox_id", type=int)
188
+ @click.argument("field_id", type=str)
189
+ @click.option(
190
+ "--format",
191
+ "fmt",
192
+ type=click.Choice(DOWNLOAD_FORMATS),
193
+ default="csv",
194
+ help="Export file format (default: csv).",
195
+ )
196
+ @click.option(
197
+ "--output",
198
+ "-o",
199
+ type=click.Path(),
200
+ help="Write to this file instead of stdout.",
201
+ )
202
+ def download_field(mailbox_id, field_id, fmt, output):
203
+ """Download a table field's rows (one row per line item)."""
204
+ content = parseur.ParserField.download(mailbox_id, field_id, fmt)
205
+ write_download(content, output)
206
+
207
+
208
+ # ------------------------
209
+ # Export commands
210
+ # ------------------------
211
+
212
+
213
+ @cli.command("list-export-configs")
214
+ @click.argument("mailbox_id", type=int)
215
+ def list_export_configs(mailbox_id):
216
+ """List the export configurations of a mailbox."""
217
+ configs = parseur.ExportConfig.list(mailbox_id)
218
+ click.echo(parseur.to_json(configs))
219
+
220
+
221
+ @cli.command("download-export")
222
+ @click.argument("mailbox_id", type=int)
223
+ @click.argument("export_config_id", type=int)
224
+ @click.option(
225
+ "--format",
226
+ "fmt",
227
+ type=click.Choice(EXPORT_FORMATS),
228
+ default="csv",
229
+ help="Export file format (default: csv).",
230
+ )
231
+ @click.option(
232
+ "--output",
233
+ "-o",
234
+ type=click.Path(),
235
+ help="Write to this file instead of stdout.",
236
+ )
237
+ def download_export(mailbox_id, export_config_id, fmt, output):
238
+ """Download a custom export configuration's file."""
239
+ content = parseur.ExportConfig.download(mailbox_id, export_config_id, fmt)
240
+ write_download(content, output)
241
+
242
+
103
243
  # ------------------------
104
244
  # Document commands
105
245
  # ------------------------
@@ -200,6 +340,22 @@ def copy_document(document_id, target_mailbox_id):
200
340
  click.echo(parseur.to_json(result))
201
341
 
202
342
 
343
+ @cli.command("split-document")
344
+ @click.argument("document_id", type=str)
345
+ def split_document(document_id):
346
+ """Split a multi-page document per the mailbox's split settings."""
347
+ result = parseur.Document.split(document_id)
348
+ click.echo(parseur.to_json(result))
349
+
350
+
351
+ @cli.command("reverse-split-document")
352
+ @click.argument("document_id", type=str)
353
+ def reverse_split_document(document_id):
354
+ """Undo a previous split of a document."""
355
+ result = parseur.Document.reverse_split(document_id)
356
+ click.echo(parseur.to_json(result))
357
+
358
+
203
359
  @cli.command("get-document-logs")
204
360
  @click.argument("document_id", type=str)
205
361
  def get_document_logs(document_id):
@@ -219,9 +375,21 @@ def delete_document(document_id):
219
375
  @cli.command("upload-file")
220
376
  @click.argument("mailbox_id", type=int)
221
377
  @click.argument("file_path", type=click.Path(exists=True))
222
- def upload_file(mailbox_id, file_path):
223
- """Upload a document file to a mailbox."""
224
- result = parseur.Document.upload_file(mailbox_id, file_path)
378
+ @WAIT_OPTION
379
+ def upload_file(mailbox_id, file_path, wait):
380
+ """Upload a document file to a mailbox (optionally wait for processing)."""
381
+ if not wait:
382
+ result = parseur.Document.upload_file(mailbox_id, file_path)
383
+ click.echo(parseur.to_json(result))
384
+ return
385
+ try:
386
+ result = parseur.Document.upload_file_and_wait(
387
+ mailbox_id, file_path, on_poll=progress_printer()
388
+ )
389
+ except TimeoutError as e:
390
+ click.echo("", err=True)
391
+ raise click.ClickException(str(e))
392
+ click.echo("", err=True) # end the progress line
225
393
  click.echo(parseur.to_json(result))
226
394
 
227
395
 
@@ -240,11 +408,28 @@ def upload_folder(mailbox_id, folder_path):
240
408
  @click.option("--sender", default=None, help="Sender email (optional)")
241
409
  @click.option("--body-html", default=None, help="HTML text content")
242
410
  @click.option("--body-plain", default=None, help="Plain text content")
243
- def upload_text(recipient, subject, sender, body_html, body_plain):
244
- """Upload text content to a mailbox by email address."""
245
- result = parseur.Document.upload_text(
246
- recipient, subject, sender, body_html, body_plain
247
- )
411
+ @WAIT_OPTION
412
+ def upload_text(recipient, subject, sender, body_html, body_plain, wait):
413
+ """Upload text content to a mailbox (optionally wait for processing)."""
414
+ if not wait:
415
+ result = parseur.Document.upload_text(
416
+ recipient, subject, sender, body_html, body_plain
417
+ )
418
+ click.echo(parseur.to_json(result))
419
+ return
420
+ try:
421
+ result = parseur.Document.upload_text_and_wait(
422
+ recipient,
423
+ subject,
424
+ sender,
425
+ body_html,
426
+ body_plain,
427
+ on_poll=progress_printer(),
428
+ )
429
+ except TimeoutError as e:
430
+ click.echo("", err=True)
431
+ raise click.ClickException(str(e))
432
+ click.echo("", err=True) # end the progress line
248
433
  click.echo(parseur.to_json(result))
249
434
 
250
435
 
@@ -412,9 +597,11 @@ def listen(
412
597
  ):
413
598
  """
414
599
  Listen to a Parseur event in real time with a temporary webhook.
415
- Example:
416
- parseur listen --event document.parsed_ok --mailbox-id 12345
417
- parseur listen --event document.processed --mailbox-id 12345 --redirect-url http://localhost --redirect-port 8000
600
+
601
+ Example::
602
+
603
+ parseur listen --event document.processed --mailbox-id 12345
604
+ parseur listen --event document.processed --mailbox-id 12345 --redirect-url http://localhost --redirect-port 8000
418
605
  """
419
606
  from . import server
420
607
 
@@ -0,0 +1,71 @@
1
+ import logging
2
+ from typing import Any, Dict, Generator, Optional
3
+ from urllib.parse import urljoin
4
+
5
+ import requests
6
+
7
+ import parseur
8
+
9
+
10
+ class Client:
11
+ @classmethod
12
+ def auth_headers(cls, json=True, api_key: Optional[str] = None) -> Dict[str, str]:
13
+ # An explicitly provided api_key takes priority over the global one.
14
+ key = api_key or parseur.api_key
15
+ if not key:
16
+ raise ValueError("API token is required. Run 'parseur init' first.")
17
+ headers = {"Authorization": f"Token {key}"}
18
+ if json:
19
+ headers["Content-Type"] = "application/json"
20
+ return headers
21
+
22
+ @classmethod
23
+ def request(
24
+ cls, method: str, endpoint: str, *, api_key: Optional[str] = None, **kwargs
25
+ ) -> Any:
26
+ url = urljoin(parseur.api_base, endpoint)
27
+ logging.debug(f"Request: {method} {url}")
28
+ headers = cls.auth_headers(json="json" in kwargs, api_key=api_key)
29
+ response = requests.request(method, url, headers=headers, **kwargs)
30
+ response.raise_for_status()
31
+ # Some endpoints (e.g. DELETE /webhook) reply with an empty body.
32
+ if response.status_code == 204 or not response.content:
33
+ return None
34
+ return response.json()
35
+
36
+ @classmethod
37
+ def download(cls, url: str, *, api_key: Optional[str] = None) -> bytes:
38
+ """GET a (possibly relative) URL with auth and return the raw bytes."""
39
+ full_url = url if url.startswith("http") else urljoin(parseur.api_base, url)
40
+ headers = cls.auth_headers(json=False, api_key=api_key)
41
+ response = requests.get(full_url, headers=headers)
42
+ response.raise_for_status()
43
+ return response.content
44
+
45
+ @classmethod
46
+ def paginate(
47
+ cls,
48
+ endpoint: str,
49
+ params: Optional[Dict[str, Any]] = None,
50
+ *,
51
+ api_key: Optional[str] = None,
52
+ ) -> Generator[Dict, None, None]:
53
+ url = urljoin(parseur.api_base, endpoint)
54
+ headers = cls.auth_headers(api_key=api_key)
55
+ params = params.copy() if params else {}
56
+ page = 1
57
+
58
+ while True:
59
+ params["page"] = page
60
+ logging.debug(f"Paginate request: {url} (page {page})")
61
+ response = requests.get(url, headers=headers, params=params)
62
+ response.raise_for_status()
63
+ data = response.json()
64
+
65
+ for item in data["results"]:
66
+ yield item
67
+
68
+ if data["current"] >= data["total"]:
69
+ break
70
+
71
+ page += 1