From 605bd9b0787c311f31744ab20d06cadeb2e59a02 Mon Sep 17 00:00:00 2001 From: sebastianMindee Date: Wed, 18 Oct 2023 15:06:54 +0200 Subject: [PATCH] :sparkles: add default non-sdk async sample code --- docs/extras/code_samples/default_async.txt | 45 ++++++++++++++++++++++ tests/test_code_samples.sh | 7 ++++ 2 files changed, 52 insertions(+) create mode 100644 docs/extras/code_samples/default_async.txt diff --git a/docs/extras/code_samples/default_async.txt b/docs/extras/code_samples/default_async.txt new file mode 100644 index 00000000..7c0b42ef --- /dev/null +++ b/docs/extras/code_samples/default_async.txt @@ -0,0 +1,45 @@ +import json +import requests +from time import sleep + +api_key = "my-api-key" +account = "my-account" +endpoint = "my-endpoint" +version = "my-version" + +url_enqueue = f"https://api.mindee.net/v1/products/{account}/{endpoint}/v{version}/predict_async" +headers = {"Authorization": f"Token {api_key}"} + +with open("/path/to/the/file.ext", "rb") as file_handle: + files = {"document": file_handle} + response_enqueue = requests.post(url_enqueue, files=files, headers=headers) + +json_response_enqueue = response_enqueue.json() + +if not response_enqueue.ok: + raise RuntimeError(json_response_enqueue["api_request"]["error"]) + +job_id = json_response_enqueue["job"]["id"] + +url_parse_queued = f"https://api.mindee.net/v1/products/{account}/{endpoint}/v{version}/documents/queue/{job_id}" +sleep(4) +response_parse = requests.get(url_parse_queued, headers=headers) +tries = 1 +while tries < 10: + if not response_parse.ok: + raise RuntimeError(json_response_enqueue["api_request"]["error"]) + + response_parse = requests.get(url_parse_queued, headers=headers) + json_response_parse = response_parse.json() + if json_response_parse["job"]["status"] == "completed": + break + else: + print(json_response_parse["job"]) + + tries += 1 + sleep(2) + +if json_response_parse["job"]["status"] != "completed": + raise RuntimeError(f"Async parsing timed out after {tries} tries") + +print(json.dumps(json_response_parse["document"], indent=2)) diff --git a/tests/test_code_samples.sh b/tests/test_code_samples.sh index ab0504e6..c902a084 100755 --- a/tests/test_code_samples.sh +++ b/tests/test_code_samples.sh @@ -30,5 +30,12 @@ do sed -i "s/my-version/1/" $OUTPUT_FILE fi + if echo "${f}" | grep -q "default_async.txt" + then + sed -i "s/my-account/mindee/" $OUTPUT_FILE + sed -i "s/my-endpoint/invoice_splitter/" $OUTPUT_FILE + sed -i "s/my-version/1/" $OUTPUT_FILE + fi + python $OUTPUT_FILE done