Package: sensibleapi
Sensible Python SDKWelcome! Sensible is a developer-first platform for extracting structured data from documents, for example, business forms in PDF format. use Sensible to build document-automation features into your SaaS products. Sensible is highly configurable: you can get simple datain minutesby leveraging GPT-4 and other large-language models (LLMs), or you can tackle complex and idiosyncratic document formatting with Sensible's powerfullayout-based document primitives.This open-source Sensible SDK offers convenient access to theSensible API. Use this SDK to:Extract: Extract structured data from your custom documents. Configure the extractions for a set of similar documents, ordocument type, in the Sensible app or Sensible API, then run extractions for documents of the type with this SDK.Classify: Classify documents by the types you define, for example, bank statements or tax forms. Use classification to determine which documents to extract prior to calling a Sensible extraction endpoint, or route each document in a system of record.DocumentationFor extraction and classification response schemas, see theSensible API reference.For configuring document extractions, seeSenseML reference.VersionsThe latest version of this SDK is v0.The latest version of the Sensible API is v0.Python supportThis SDK supports all non end-of-life versions of Python.InstallIn an environment with Python installed, open a command prompt and enter the following commands to create a test project:mkdirsensible-testcdsensible-test
touchindex.mjsThen install the SDK:pipinstallsensibleapiInitializeGet an account atsensible.soif you don't have one already.To initialize the SDK, paste the following code into yourindex.pyfile and replaceYOUR_API_KEYwith yourAPI key:sensible=SensibleSDK("YOUR_API_KEY")Note:Ensure you secure your API key in production, for example as a GitHub secret.QuickstartTo extract data from a sample document at a URL:Install the Sensible SDK using the steps in the previous section.Paste the following code into an emptyindex.pyfile:fromsensibleapiimportSensibleSDKsensible=SensibleSDK("YOUR_API_KEY")# replace with your API keyrequest=sensible.extract(url="https://github.com/sensible-hq/sensible-docs/raw/main/readme-sync/assets/v0/pdfs/contract.pdf",document_type="sensible_instruct_basics",environment="development")results=sensible.wait_for(request)# polls every 5 seconds. Optional if you configure a webhookprint(results)ReplaceYOUR_API_KEYwith yourAPI key.In a command prompt in the same directory as yourindex.pyfile, run the code with the following command:pythonindex.pyThe code extracts data from an example document (contract.pdf) using an example document type (sensible_instruct_basics) and an example extraction configuration.ResultsYou should see the following extracted document text in theparsed_documentobject in the logged response:{"purchase_price":{"source":"$400,000","value":400000,"unit":"$","type":"currency"},"street_address":{"value":"1234 ABC COURT City of SALT LAKE CITY County of Salt Lake -\nState of Utah, Zip 84108","type":"address"}}Optional: Understand extractionNavigate to the example in theSenseML editorto see how the extraction you just ran works in the Sensible app. You can add more fields to the left pane to extract more data:Usage: Extract document dataYou can use this SDK to extract data from a document, as specified by the extraction configurations and document types defined in your Sensible account.OverviewSee the following steps for an overview of the SDK's workflow for document data extraction:Instantiate an SDK object withSensibleSDK().Request a document extraction withsensible.extract(). Use the following required parameters:(required)Specify the document from which to extract data using theurl,path, orfileparameter.(required)Specify the user-defined document type or types using thedocument_typeordocument_typesparameter.Wait for the results. Usesensible.wait_for(), or use a webhook.Optionally convert extractions to an Excel file withgenerate_excel().Consume the data.Extraction configurationYou can configure options for document data extraction:request=sensible.extract(path="./1040_john_doe.pdf",document_type="tax_forms",configuration_name="1040_2021",environment="development",document_name="1040_john_doe.pdf",webhook={"url":"YOUR_WEBHOOK_URL","payload":"additional info, for example, a UUID for verification",})See the following table for information about configuration options:keyvaluedescriptionpathstringThe path to the document you want to extract from. For more information about supported file size and types, seeSupported file types.filestringThe non-encoded bytes of the document you want to extract from.urlstringThe URL of the document you want to extract from. URL must:- respond to a GET request with the bytes of the document you want to extract data from- be either publicly accessible, or presigned with a security token as part of the URL path.To check if the URL meets these criteria, open the URL with a web browser. The browser must either render the document as a full-page view with no other data, or download the document, without prompting for authentication.document_typestringType of document to extract from. Create your custom type in the Sensible app (for example,rate_confirmation,certificate_of_insurance, orhome_inspection_report), or use Sensible's library of out-of-the-box supported document types.document_typesarrayTypes of documents to extract from. Use this parameter to extract from multiple documents that are packaged into one file (a "portfolio").  This parameter specifies the document types contained in the portfolio. Sensible then segments the portfolio into documents using the specified document types (for example, 1099, w2, and bank_statement) and then runs extractions for each document. For more information, seeMulti-doc extraction.configuration_namestringSensible uses the specified config to extract data from the document instead of automatically choosing the configuration.If unspecified, Sensible automatically chooses the best-scoring extraction from the configs in the document type.Not applicable for portfolios.document_namestringIf you specify the file name of the document using this parameter, then Sensible returns the file name in the extraction response and populates the file name in the Sensible app's list of recent extractions.environment"production"or"development". default:"production"If you specifydevelopment, Sensible extracts preferentially using config versions published to the development environment in the Sensible app. The extraction runs all configs in the doc type before picking the best fit. For each config, falls back to production version if no development version of the config exists.webhookobjectSpecifies to return extraction results to the specified webhook URL as soon as they're complete, so you don't have to poll for results status. Sensible also calls this webhook on error.The webhook object has the following parameters:url:  string. Webhook destination. Sensible will POST to this URL when the extraction is complete.payload: string, number, boolean, object, or array. Information additional to the API response, for example a UUID for verification.Extraction resultsGet extraction results by using a webhook or calling the Wait For method.For the extraction results schema,  seeExtract data from a documentand expand the 200 responses in the middle pane and the right pane to see the model and an example, respectively.Example: Extract from PDFs in directory and output an Excel fileSee the following code for an example of how to use the SDK for document extraction in your app.The example:Filters a directory to find the PDF files.Extracts data from the PDF files using the extraction configurations in abank_statementsdocument type.Logs the extracted document data JSON to the console.Writes the extractions to an Excel file. The Generate Excel method takes an extraction or an array of extractions, and outputs an Excel file. For more information about the conversion process, seeSenseML to spreadsheet reference.importosimportjsonimportrequestsfromsensibleapiimportSensibleSDKfrompathlibimportPathapi_key=os.environ.get(SENSIBLE_APIKEY)sensible=SensibleSDK(api_key)dir_path=Path("ABSOLUTE_PATH_TO_DOCUMENTS_DIR")pdf_files=[fileforfileindir_path.glob("*.pdf")]extractions=[]forpdf_fileinpdf_files:file_path=dir_path/pdf_fileextraction=sensible.extract(path=str(file_path),document_type="bank_statements")extractions.append(extraction)results=[sensible.wait_for(extraction)forextractioninextractions]print("Extractions:")print(json.dumps(extractions,indent=2))print("\nResults:")print(json.dumps(results,indent=2))excel=sensible.generate_excel(extractions)print("Excel download URL:")print(excel)excel_file=requests.get(excel["url"])output_path=dir_path/"output.xlsx"withopen(output_path,"wb")asf:f.write(excel_file.content)print("Excel file:")print(output_path)Usage: Classify documents by typeYou can use this SDK to classify a document by type, as specified by the document types defined in your Sensible account. For more information, seeClassifying documents by type.OverviewSee the following steps for an overview of the SDK's workflow for document classification:Instantiate an SDK object (new SensibleSDK().Request a document classification (sensible.classify().  Specify the document to classify using thepathorfileparameter.Poll for the result (sensible.wait_for().Consume the data.Classification configurationYou can configure options for document data extraction:fromsensibleapiimportSensibleSDKsensible=SensibleSDK(api_key="YOUR_API_KEY")# Replace with your API keyrequest=sensible.classify(path="./boa_sample.pdf")results=sensible.wait_for(request)print(results)See the following table for information about configuration options:keyvaluedescriptionpathstringThe path to the document you want to classify. For information about supported file size and types, seeSupported file types.filestringThe non-encoded bytes of the document you want to classify.Classification resultsGet results from this method by calling the Wait For method. For the classification results schema , seeClassify document by type (sync)and expand the 200 responses in the middle pane and the right pane to see the model and an example, respectively.