python-documentcloud 4.4.0__tar.gz → 4.5.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 (32) hide show
  1. {python_documentcloud-4.4.0/python_documentcloud.egg-info → python_documentcloud-4.5.0}/PKG-INFO +3 -2
  2. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/documents.py +111 -134
  3. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0/python_documentcloud.egg-info}/PKG-INFO +3 -2
  4. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/setup.py +1 -1
  5. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/LICENSE +0 -0
  6. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/README.md +0 -0
  7. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/__init__.py +0 -0
  8. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/addon.py +0 -0
  9. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/annotations.py +0 -0
  10. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/base.py +0 -0
  11. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/client.py +0 -0
  12. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/constants.py +0 -0
  13. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/exceptions.py +0 -0
  14. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/organizations.py +0 -0
  15. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/projects.py +0 -0
  16. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/sections.py +0 -0
  17. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/toolbox.py +0 -0
  18. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/documentcloud/users.py +0 -0
  19. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/python_documentcloud.egg-info/SOURCES.txt +0 -0
  20. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/python_documentcloud.egg-info/dependency_links.txt +0 -0
  21. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/python_documentcloud.egg-info/requires.txt +0 -0
  22. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/python_documentcloud.egg-info/top_level.txt +0 -0
  23. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/setup.cfg +0 -0
  24. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_annotations.py +0 -0
  25. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_base.py +0 -0
  26. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_client.py +0 -0
  27. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_documents.py +0 -0
  28. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_organizations.py +0 -0
  29. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_projects.py +0 -0
  30. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_sections.py +0 -0
  31. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_toolbox.py +0 -0
  32. {python_documentcloud-4.4.0 → python_documentcloud-4.5.0}/tests/test_users.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: python-documentcloud
3
- Version: 4.4.0
3
+ Version: 4.5.0
4
4
  Summary: A simple Python wrapper for the DocumentCloud API
5
5
  Home-page: https://github.com/muckrock/python-documentcloud
6
6
  Author: Mitchell Kotler
@@ -46,6 +46,7 @@ Dynamic: description
46
46
  Dynamic: description-content-type
47
47
  Dynamic: home-page
48
48
  Dynamic: license
49
+ Dynamic: license-file
49
50
  Dynamic: provides-extra
50
51
  Dynamic: requires-dist
51
52
  Dynamic: summary
@@ -74,8 +74,11 @@ class Document(BaseAPIObject):
74
74
  def __getattr__(self, attr):
75
75
  """Generate methods for fetching resources"""
76
76
  p_image = re.compile(
77
- r"^get_(?P<size>thumbnail|small|normal|large)_image_url(?P<list>_list)?$"
77
+ r"^get_"
78
+ r"(?P<size>thumbnail|small|normal|large|xlarge)_image_url"
79
+ r"(?P<list>_list)?$"
78
80
  )
81
+
79
82
  get = attr.startswith("get_")
80
83
  url = attr.endswith("_url")
81
84
  text = attr.endswith("_text")
@@ -230,9 +233,15 @@ class Document(BaseAPIObject):
230
233
 
231
234
  return all_results
232
235
 
233
- def process(self):
234
- """Reprocess the document"""
235
- self._client.post(f"{self.api_path}/{self.id}/process/")
236
+ def process(self, **kwargs):
237
+ """Process the document, used on upload and for reprocessing"""
238
+ payload = {}
239
+ if "force_ocr" in kwargs:
240
+ payload["force_ocr"] = kwargs["force_ocr"]
241
+ if "ocr_engine" in kwargs:
242
+ payload["ocr_engine"] = kwargs["ocr_engine"]
243
+
244
+ self._client.post(f"{self.api_path}/{self.id}/process/", json=payload)
236
245
 
237
246
 
238
247
  class DocumentClient(BaseAPIClient):
@@ -310,6 +319,7 @@ class DocumentClient(BaseAPIClient):
310
319
  "title",
311
320
  "data",
312
321
  "force_ocr",
322
+ "ocr_engine",
313
323
  "projects",
314
324
  "delayed_index",
315
325
  "revision_control",
@@ -333,21 +343,55 @@ class DocumentClient(BaseAPIClient):
333
343
 
334
344
  return params
335
345
 
346
+ def _extract_ocr_options(self, kwargs):
347
+ """
348
+ Extract and validate OCR options from kwargs.
349
+
350
+ Returns:
351
+ force_ocr (bool)
352
+ ocr_engine (str)
353
+ """
354
+ force_ocr = kwargs.pop("force_ocr", False)
355
+ ocr_engine = kwargs.pop("ocr_engine", "tess4")
356
+
357
+ if not isinstance(force_ocr, bool):
358
+ raise ValueError("force_ocr must be a boolean")
359
+
360
+ if ocr_engine and ocr_engine not in ("tess4", "textract"):
361
+ raise ValueError(
362
+ "ocr_engine must be either 'tess4' for tesseract or 'textract'"
363
+ )
364
+
365
+ return force_ocr, ocr_engine
366
+
336
367
  def _get_title(self, name):
337
368
  """Get the default title for a document from its path"""
338
369
  return name.split(os.sep)[-1].rsplit(".", 1)[0]
339
370
 
340
371
  def _upload_url(self, file_url, **kwargs):
341
372
  """Upload a document from a publicly accessible URL"""
373
+ # extract process-related args
374
+ force_ocr, ocr_engine = self._extract_ocr_options(kwargs)
375
+
376
+ # create the document
342
377
  params = self._format_upload_parameters(file_url, **kwargs)
343
378
  params["file_url"] = file_url
379
+ if force_ocr:
380
+ params["force_ocr"] = force_ocr
381
+ params["ocr_engine"] = ocr_engine
344
382
  response = self.client.post("documents/", json=params)
345
- return Document(self.client, response.json())
383
+ create_json = response.json()
384
+
385
+ # wrap in Document object
386
+ doc = Document(self.client, create_json)
387
+
388
+ return doc
346
389
 
347
390
  def _upload_file(self, file_, **kwargs):
348
391
  """Upload a document directly"""
349
392
  # create the document
350
- force_ocr = kwargs.pop("force_ocr", False)
393
+ force_ocr, ocr_engine = self._extract_ocr_options(kwargs)
394
+
351
395
  params = self._format_upload_parameters(file_.name, **kwargs)
352
396
  response = self.client.post("documents/", json=params)
353
397
 
@@ -357,12 +401,12 @@ class DocumentClient(BaseAPIClient):
357
401
  response = requests_retry_session().put(presigned_url, data=file_.read())
358
402
 
359
403
  # begin processing the document
360
- doc_id = create_json["id"]
361
- response = self.client.post(
362
- f"documents/{doc_id}/process/", json={"force_ocr": force_ocr}
363
- )
404
+ doc = Document(self.client, create_json)
364
405
 
365
- return Document(self.client, create_json)
406
+ # begin processing
407
+ doc.process(force_ocr=force_ocr, ocr_engine=ocr_engine)
408
+
409
+ return doc
366
410
 
367
411
  def _collect_files(self, path, extensions):
368
412
  """Find the paths to files with specified extensions under a directory"""
@@ -379,165 +423,98 @@ class DocumentClient(BaseAPIClient):
379
423
 
380
424
  def upload_directory(self, path, handle_errors=False, extensions=".pdf", **kwargs):
381
425
  """Upload files with specified extensions in a directory"""
382
- # pylint: disable=too-many-locals, too-many-branches
383
-
384
- # Do not set the same title for all documents
426
+ # pylint:disable=too-many-locals
385
427
  kwargs.pop("title", None)
386
428
 
387
- # If extensions are specified as None, it will check for all supported
388
- # filetypes.
389
429
  if extensions is None:
390
430
  extensions = SUPPORTED_EXTENSIONS
391
-
392
- # Convert single extension to a list if provided
393
431
  if extensions and not isinstance(extensions, list):
394
432
  extensions = [extensions]
395
-
396
- # Checks to see if the extensions are supported, raises an error if not.
397
433
  invalid_extensions = set(extensions) - set(SUPPORTED_EXTENSIONS)
398
434
  if invalid_extensions:
399
435
  raise ValueError(
400
436
  f"Invalid extensions provided: {', '.join(invalid_extensions)}"
401
437
  )
402
438
 
403
- # Loop through the path and get all the files with matching extensions
404
439
  path_list = self._collect_files(path, extensions)
405
-
406
440
  logger.info(
407
441
  "Upload directory on %s: Found %d files to upload", path, len(path_list)
408
442
  )
409
443
 
410
- # Upload all the files using the bulk API to reduce the number
411
- # of API calls and improve performance
412
444
  obj_list = []
445
+ force_ocr, ocr_engine = self._extract_ocr_options(kwargs)
413
446
  params = self._format_upload_parameters("", **kwargs)
447
+
414
448
  for i, file_paths in enumerate(grouper(path_list, BULK_LIMIT)):
415
- # Grouper will put None's on the end of the last group
416
449
  file_paths = [p for p in file_paths if p is not None]
417
-
418
450
  logger.info("Uploading group %d:\n%s", i + 1, "\n".join(file_paths))
419
451
 
420
- # Create the documents
421
- logger.info("Creating the documents...")
422
- try:
423
- response = self.client.post(
424
- "documents/",
425
- json=[
426
- merge_dicts(
427
- params,
428
- {
429
- "title": self._get_title(p),
430
- "original_extension": os.path.splitext(
431
- os.path.basename(p)
432
- )[1]
433
- .lower()
434
- .lstrip("."),
435
- },
436
- )
437
- for p in file_paths
438
- ],
439
- )
440
- except (APIError, RequestException) as exc:
441
- if handle_errors:
442
- logger.info(
443
- "Error creating the following documents: %s\n%s",
444
- exc,
445
- "\n".join(file_paths),
446
- )
447
- continue
448
- else:
449
- raise
452
+ create_json = self._create_documents(file_paths, params, handle_errors)
453
+ sorted_create_json = sorted(create_json, key=lambda j: j["title"])
454
+ sorted_file_paths = sorted(file_paths, key=self._get_title)
455
+ obj_list.extend(sorted_create_json)
456
+ presigned_urls = [j["presigned_url"] for j in sorted_create_json]
450
457
 
451
- # Upload the files directly to storage
452
- create_json = response.json()
453
- obj_list.extend(create_json)
454
- presigned_urls = [j["presigned_url"] for j in create_json]
455
- for url, file_path in zip(presigned_urls, file_paths):
456
- logger.info("Uploading %s to S3...", file_path)
457
- try:
458
- with open(file_path, "rb") as file:
459
- response = requests_retry_session().put(url, data=file.read())
460
- self.client.raise_for_status(response)
461
- except (APIError, RequestException) as exc:
462
- if handle_errors:
463
- logger.info(
464
- "Error uploading the following document: %s %s",
465
- exc,
466
- file_path,
467
- )
468
- continue
469
- else:
470
- raise
471
-
472
- # Begin processing the documents
473
- logger.info("Processing the documents...")
474
- doc_ids = [j["id"] for j in create_json]
475
- try:
476
- response = self.client.post("documents/process/", json={"ids": doc_ids})
477
- except (APIError, RequestException) as exc:
478
- if handle_errors:
479
- logger.info(
480
- "Error creating the following documents: %s\n%s",
481
- exc,
482
- "\n".join(file_paths),
483
- )
484
- continue
485
- else:
486
- raise
458
+ self._upload_files_to_s3(sorted_file_paths, presigned_urls, handle_errors)
459
+ self._process_documents(create_json, force_ocr, ocr_engine, handle_errors)
487
460
 
488
461
  logger.info("Upload directory complete")
489
-
490
- # Pass back the list of documents
491
462
  return [Document(self.client, d) for d in obj_list]
492
463
 
493
- def upload_urls(self, url_list, handle_errors=False, **kwargs):
494
- """Upload documents from a list of URLs"""
495
-
496
- # Do not set the same title for all documents
497
- kwargs.pop("title", None)
498
-
499
- obj_list = []
500
- params = self._format_upload_parameters("", **kwargs)
501
- for i, url_group in enumerate(grouper(url_list, BULK_LIMIT)):
502
- # Grouper will put None's on the end of the last group
503
- url_group = [url for url in url_group if url is not None]
504
-
505
- logger.info("Uploading group %d: %s", i + 1, "\n".join(url_group))
506
-
507
- # Create the documents
508
- logger.info("Creating the documents...")
509
- try:
510
- response = self.client.post(
511
- "documents/",
512
- json=[
513
- merge_dicts(
514
- params,
515
- {
516
- "title": self._get_title(url),
517
- "file_url": url,
518
- },
519
- )
520
- for url in url_group
521
- ],
464
+ def _create_documents(self, file_paths, params, handle_errors):
465
+ body = [
466
+ merge_dicts(
467
+ params,
468
+ {
469
+ "title": self._get_title(p),
470
+ "original_extension": os.path.splitext(os.path.basename(p))[1]
471
+ .lower()
472
+ .lstrip("."),
473
+ },
474
+ )
475
+ for p in sorted(file_paths)
476
+ ]
477
+ try:
478
+ response = self.client.post("documents/", json=body)
479
+ except (APIError, RequestException) as exc:
480
+ if handle_errors:
481
+ logger.info(
482
+ "Error creating the following documents: %s\n%s",
483
+ exc,
484
+ "\n".join(file_paths),
522
485
  )
486
+ return []
487
+ else:
488
+ raise
489
+ return response.json()
490
+
491
+ def _upload_files_to_s3(self, file_paths, presigned_urls, handle_errors):
492
+ for url, file_path in zip(presigned_urls, file_paths):
493
+ logger.info("Uploading %s to S3...", file_path)
494
+ try:
495
+ with open(file_path, "rb") as f:
496
+ response = requests_retry_session().put(url, data=f.read())
497
+ self.client.raise_for_status(response)
523
498
  except (APIError, RequestException) as exc:
524
499
  if handle_errors:
525
500
  logger.info(
526
- "Error creating the following documents: %s\n%s",
527
- str(exc),
528
- "\n".join(url_group),
501
+ "Error uploading the following document: %s %s", exc, file_path
529
502
  )
530
- continue
531
503
  else:
532
504
  raise
533
505
 
534
- create_json = response.json()
535
- obj_list.extend(create_json)
536
-
537
- logger.info("Upload URLs complete")
538
-
539
- # Pass back the list of documents
540
- return [Document(self.client, d) for d in obj_list]
506
+ def _process_documents(self, create_json, force_ocr, ocr_engine, handle_errors):
507
+ payload = [
508
+ {"id": j["id"], "force_ocr": force_ocr, "ocr_engine": ocr_engine}
509
+ for j in create_json
510
+ ]
511
+ try:
512
+ self.client.post("documents/process/", json=payload)
513
+ except (APIError, RequestException) as exc:
514
+ if handle_errors:
515
+ logger.info("Error processing documents: %s", exc)
516
+ else:
517
+ raise
541
518
 
542
519
 
543
520
  class Mention:
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: python-documentcloud
3
- Version: 4.4.0
3
+ Version: 4.5.0
4
4
  Summary: A simple Python wrapper for the DocumentCloud API
5
5
  Home-page: https://github.com/muckrock/python-documentcloud
6
6
  Author: Mitchell Kotler
@@ -46,6 +46,7 @@ Dynamic: description
46
46
  Dynamic: description-content-type
47
47
  Dynamic: home-page
48
48
  Dynamic: license
49
+ Dynamic: license-file
49
50
  Dynamic: provides-extra
50
51
  Dynamic: requires-dist
51
52
  Dynamic: summary
@@ -7,7 +7,7 @@ with open("README.md", "r") as fh:
7
7
 
8
8
  setup(
9
9
  name="python-documentcloud",
10
- version="4.4.0",
10
+ version="4.5.0",
11
11
  description="A simple Python wrapper for the DocumentCloud API",
12
12
  author="Mitchell Kotler",
13
13
  author_email="mitch@muckrock.com",