### Cursor Manual Setup Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/README.md Manual setup instructions for Cursor, requiring the skill folder to be copied into the project and a rule to be added in .cursor/rules/dbr.mdc. ```markdown --- description: Use when writing Python code with Dynamsoft Barcode Reader SDK globs: **/*.py --- When generating code that uses dynamsoft_barcode_reader_bundle, follow the skill definition in `skills/dbr-python-sample-creator/SKILL.md`. Read the relevant reference files from `skills/dbr-python-sample-creator/references/` for API details. ``` -------------------------------- ### Windsurf Manual Setup Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/README.md Manual setup instructions for Windsurf, requiring the skill folder to be copied into the project and a rule to be added in .windsurfrules. ```text When writing Python code that uses dynamsoft_barcode_reader_bundle or Dynamsoft Barcode Reader SDK, follow the skill defined in skills/dbr-python-sample-creator/SKILL.md and read API references from skills/dbr-python-sample-creator/references/ as needed. ``` -------------------------------- ### Production Server Setup with Gunicorn Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Use Gunicorn for production deployment. Ensure it's installed via pip. This command starts 4 worker processes on port 8000. ```bash # Production setup with Gunicorn # pip install gunicorn # Run with Gunicorn (4 workers, port 8000) gunicorn -w 4 -b 0.0.0.0:8000 server_side_barcode_decoder:app ``` -------------------------------- ### Install DBR Python Sample Creator Skill Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/README.md Installs the DBR Python Sample Creator AI coding skill using the 'skills' CLI. This can be done from a local repository or directly from GitHub. ```bash npx skills add . ``` ```bash npx skills add Dynamsoft/barcode-reader-python-samples ``` -------------------------------- ### Claude Code Manual Setup Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/README.md Manual setup instructions for Claude Code, requiring the skill folder to be copied into the project and a reference added to CLAUDE.md. ```markdown ## Coding Skills When writing Python code that uses the Dynamsoft Barcode Reader SDK, read and follow the skill defined in `skills/dbr-python-sample-creator/SKILL.md` and its `references/` directory. ``` -------------------------------- ### Asynchronous Capture Setup Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/README.md Prepare for streaming barcode capture. Set the image source, add a result receiver, and start capturing with a template name. ```python cvr.set_input(image_source) cvr.add_result_receiver(receiver) cvr.start_capturing(template_name, wait_for_ready) ``` -------------------------------- ### Install DBR Python Sample Creator Skill for Specific Agents Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/README.md Installs the DBR Python Sample Creator AI coding skill for specific AI agents like Claude or Cursor using the 'skills' CLI. ```bash npx skills add . -a claude-code ``` ```bash npx skills add . -a cursor -a windsurf ``` -------------------------------- ### Example: Enable QR Code and PDF417 detection Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/types.md This snippet demonstrates how to enable detection for specific barcode formats using bitwise OR. ```python # Enable QR Code and PDF417 detection settings.barcode_settings.barcode_format_ids = EnumBarcodeFormat.BF_QR_CODE | EnumBarcodeFormat.BF_PDF417 ``` -------------------------------- ### Install AI Coding Skill Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/README.md Install the AI coding skill for your AI agent from the repository root. This command automatically detects and sets up the skill for compatible agents. ```bash npx skills add . ``` -------------------------------- ### Install Dynamsoft Barcode Reader Bundle Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/README.md Install the Dynamsoft Barcode Reader Python package using pip. ```bash pip install dynamsoft-barcode-reader-bundle ``` ```bash pip3 install dynamsoft-barcode-reader-bundle ``` -------------------------------- ### Continuous Capture Setup Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/SKILL.md Set up continuous or streaming capture using `ImageSourceAdapter`, `CapturedResultReceiver`, and `ImageSourceStateListener`. This is suitable for video or batch directory processing. ```python # Set up image source fetcher = DirectoryFetcher() # or custom ImageSourceAdapter subclass fetcher.set_directory("path/to/images") cvr_instance.set_input(fetcher) # Set up result receiver receiver = MyCapturedResultReceiver() # subclass of CapturedResultReceiver cvr_instance.add_result_receiver(receiver) # Set up state listener (to know when processing is done) listener = MyImageSourceStateListener(cvr_instance) cvr_instance.add_image_source_state_listener(listener) # Start processing cvr_instance.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, True) ``` -------------------------------- ### Main Application Flow with License Initialization Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/sample-patterns.md Sets up the main application flow, including initializing the Dynamsoft license and starting the interactive parameter tuning loop. It handles user choices for continuing or exiting the application. ```python def main(): print("Welcome to ParameterTuner!\n") # Initialize license. # The string "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTEwNTI2NzQwMSJ9" here is a free public trial license. Note that network connection is required for this license to work. # You can also request a 30-day trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=python error_code, error_string = LicenseManager.init_license("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTEwNTI2NzQwMSJ9") if error_code != EnumErrorCode.EC_OK and error_code != EnumErrorCode.EC_LICENSE_WARNING: print("License initialization failed: ErrorCode:", str(error_code) + ", ErrorString:", error_string) loop_info = LoopInfo(CaptureVisionRouter()) loop_inner(loop_info) while True: print("What would you like to do next?") print("[1] Try a different template") print("[2] Load another image") print("[3] Exit") choice = input("Enter your choice:\n> ").strip() if choice == "1": loop_inner(loop_info, get_image=False, get_template=True) elif choice == "2": loop_inner(loop_info, get_image=True, get_template=False) elif choice == "3": print("Thank you for using ParameterTuner!") break else: print("Invalid input. Returning to main menu.") if __name__ == "__main__": main() ``` -------------------------------- ### Error Response Example 1 (HTTP 400 or 500) Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Example of an error response with specific error details. ```json { "error_string": "Invalid barcode format", "error_code": 23 } ``` -------------------------------- ### Success Response Example (HTTP 200) Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Example of a successful response containing a JSON array of decoded barcode strings. ```json [ "https://www.dynamsoft.com", "1234567890", "QR-CODE-SAMPLE" ] ``` -------------------------------- ### Raw Binary Request Body Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Illustrates sending raw image bytes directly in the request body. ```http Content-Type: image/png [binary image data] ``` -------------------------------- ### Multipart Form Data Request Body Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Demonstrates how to send an image file as form data in a multipart/form-data request. ```http Content-Type: multipart/form-data; boundary=----FormBoundary ------FormBoundary Content-Disposition: form-data; name="file"; filename="barcode.png" Content-Type: image/png [binary image data] ------FormBoundary-- ``` -------------------------------- ### Error Response Example 2 (HTTP 400 or 500) Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Alternative error response format indicating a missing file in multipart data. ```json { "error": "File not found in multipart data" } ``` -------------------------------- ### Start Asynchronous Capture Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Initiates asynchronous image capture. Results are delivered via registered callbacks. Use when continuous image processing is required. ```python receiver = MyResultReceiver() cvr.add_result_receiver(receiver) err_code, err_msg = cvr.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, False) if err_code == EnumErrorCode.EC_OK: print("Capturing started") ``` -------------------------------- ### cURL Barcode Decoding Examples Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Illustrates how to call the Barcode Reader API using cURL for file upload, Base64 encoded JSON, and raw binary data. ```bash # File upload curl -X POST -F "file=@barcode.png" http://localhost:8000/decode_barcode # Base64 JSON curl -X POST -H "Content-Type: application/json" \ -d '{"data":"'$(base64 -w0 barcode.png)'"}' \ http://localhost:8000/decode_barcode # Raw binary curl -X POST --data-binary @barcode.png http://localhost:8000/decode_barcode ``` -------------------------------- ### Decode Multiple Images from Directory Asynchronously Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/code-examples.md This example demonstrates how to process all images within a specified directory asynchronously using callbacks for results and state changes. It requires custom receiver and listener classes to handle the asynchronous operations. ```python from dynamsoft_barcode_reader_bundle import * from dynamsoft_utility import DirectoryFetcher # Custom receiver for results class MyResultReceiver(CapturedResultReceiver): def on_decoded_barcodes_received(self, result: DecodedBarcodesResult): if result.get_error_code() != EnumErrorCode.EC_OK: print(f"Error: {result.get_error_string()}") return tag = result.get_original_image_tag() file_path = tag.get_file_path() if isinstance(tag, FileImageTag) else "unknown" items = result.get_items() print(f"File: {file_path} - Found {len(items)} barcodes") for item in items: print(f" {item.get_format_string()}: {item.get_text()}") # Listener for end-of-source notification class MyImageSourceStateListener(ImageSourceStateListener): def __init__(self, cvr): super().__init__() self.cvr = cvr def on_image_source_state_received(self, state): if state == EnumImageSourceState.ISS_EXHAUSTED: self.cvr.stop_capturing() print("Processing complete") # Initialize LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") cvr = CaptureVisionRouter() # Configure image source fetcher = DirectoryFetcher() fetcher.set_directory("./images", "*.png;*.jpg;*.jpeg") cvr.set_input(fetcher) # Register receivers cvr.add_result_receiver(MyResultReceiver()) cvr.add_image_source_state_listener(MyImageSourceStateListener(cvr)) # Start processing error_code, error_msg = cvr.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, True) if error_code != EnumErrorCode.EC_OK: print(f"Start error: {error_msg}") # Keep running until source is exhausted input("Processing... Press Enter to stop\n") cvr.stop_capturing() ``` -------------------------------- ### Video Streaming Capture Pattern Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/sample-patterns.md Set up a video streaming capture process by subclassing ImageSourceAdapter and adding a result receiver. Start, feed frames, and stop capturing. ```python # 1. Subclass ImageSourceAdapter class MyFetcher(ImageSourceAdapter): def has_next_image_to_fetch(self): return True # 2. Set input source cvr.set_input(fetcher) # 3. Add result receiver (CapturedResultReceiver subclass) cvr.add_result_receiver(receiver) # 4. Optionally add cross filter filter = MultiFrameResultCrossFilter() filter.enable_result_cross_verification(CRIT_BARCODE, True) filter.enable_result_deduplication(CRIT_BARCODE, True) cvr.add_result_filter(filter) # 5. Start non-blocking capture cvr.start_capturing(template, False) # 6. Feed frames in loop image = ImageData(bytes, w, h, stride, pixel_format, orientation, tag) fetcher.add_image_to_buffer(image) # 7. Stop when done cvr.stop_capturing(False, True) ``` -------------------------------- ### Nginx Load Balancing Configuration Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md This Nginx configuration example sets up upstream servers for load balancing requests to multiple barcode decoding server instances running on different ports. ```nginx # Nginx configuration example upstream barcode_server { server localhost:8000; server localhost:8001; server localhost:8002; } server { listen 80; location /decode_barcode { proxy_pass http://barcode_server; } } ``` -------------------------------- ### Decode Single Image File Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/INDEX.txt Example of decoding a single image file using the SDK. This is a common starting point for basic barcode detection. ```python from dynamsoft import dbr # Initialize license dbr.LicenseManager.init_license("YOUR_LICENSE_KEY") # Create a barcode reader instance reader = dbr.BarcodeReader() # Decode barcodes from an image file results = reader.decode_file("image.png") # Print results for result in results: print(f"Format: {result.barcode_format_string}, Value: {result.barcode_text}") ``` -------------------------------- ### Initialize Settings from File Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/sample-patterns.md Load barcode reading settings from a JSON file. Use an empty string for default settings. ```python errorCode, errorMsg = cvr_instance.init_settings_from_file(json_file_path) # Then use the template Name from the JSON: result = cvr_instance.capture(image, "TemplateName") # Or empty string for default: result = cvr_instance.capture_multi_pages(image, "") ``` -------------------------------- ### Initialize License Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/README.md Crucial step before any barcode operations. Replace 'YOUR-LICENSE-KEY' with your actual license key. ```python LicenseManager.init_license("YOUR-LICENSE-KEY") ``` -------------------------------- ### Raw Binary cURL Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Example using cURL to send raw image bytes directly to the /decode_barcode endpoint. ```bash curl -X POST --data-binary @barcode.png http://localhost:8000/decode_barcode ``` -------------------------------- ### Initialize License Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Initializes the SDK with a license key. This must be called before using CaptureVisionRouter. Handles success, warnings for nearing expiration, and other error codes. ```python from dynamsoft_license import LicenseManager err_code, err_msg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") if err_code != 0 and err_code != 2: # EC_OK or EC_LICENSE_WARNING print(f"License error: {err_msg}") ``` -------------------------------- ### Multipart Form Data cURL Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Example using cURL to send an image file via multipart/form-data to the /decode_barcode endpoint. ```bash curl -X POST -F "file=@barcode.png" http://localhost:8000/decode_barcode ``` -------------------------------- ### CaptureVisionRouter.init_settings_from_file Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Loads barcode reader settings from a JSON configuration file stored on disk. ```APIDOC ## CaptureVisionRouter.init_settings_from_file ### Description Loads settings from a JSON template file on disk. This method is used to apply pre-configured settings from an external file. ### Method `init_settings_from_file` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **settings_file** (str) - Required - Path to the JSON settings file. ### Request Example ```python err_code, err_msg = cvr.init_settings_from_file("CustomTemplates/ReadDPM.json") if err_code != EnumErrorCode.EC_OK: print(f"Failed to load settings: {err_msg}") ``` ### Response #### Success Response - **Tuple[int, str]** - A tuple containing the error code and error message indicating the success or failure of loading the settings. #### Response Example (See Request Example for usage) ### Error Handling Returns error codes and messages to indicate success or failure, such as file not found or invalid JSON format. ``` -------------------------------- ### JSON with Base64 cURL Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Example using cURL to send Base64 encoded image data in a JSON request to the /decode_barcode endpoint. ```bash curl -X POST -H "Content-Type: application/json" \ -d '{"data": "iVBORw0KGgoAAAANSUhEUgAAAAUA..."}' \ http://localhost:8000/decode_barcode ``` -------------------------------- ### Set Environment Variables for Server Configuration Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/configuration.md Configure server settings, license, image sources, and logging by exporting environment variables before application startup. ```bash # License (if using environment variable instead of hardcoding) export DYNAMSOFT_LICENSE_KEY="YOUR-LICENSE-KEY" # Image source directory (for DirectoryFetcher) export IMAGE_SOURCE_DIR="../Images" # Server binding (for Flask) export FLASK_HOST="0.0.0.0" export FLASK_PORT="8000" export FLASK_ENV="production" # Threading export OMP_NUM_THREADS=8 # Logging export DYNAMSOFT_LOG_LEVEL="INFO" ``` -------------------------------- ### start_capturing Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Begins asynchronous image capture from a configured image source adapter. Results are delivered via registered CapturedResultReceiver callbacks. ```APIDOC ## start_capturing ### Description Begins asynchronous image capture from a configured image source adapter. Results are delivered via registered `CapturedResultReceiver` callbacks. ### Method `CaptureVisionRouter.start_capturing` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **template_name** (str) - Required - Template name for processing - **wait_for_ready** (bool) - Optional - Block until pipeline is ready for processing (Default: False) ### Returns - **Tuple[int, str]** - (error_code, error_message) ### Request Example ```python receiver = MyResultReceiver() cvr.add_result_receiver(receiver) err_code, err_msg = cvr.start_capturing(EnumPresetTemplate.PT_READ_BARCODES, False) if err_code == EnumErrorCode.EC_OK: print("Capturing started") ``` ``` -------------------------------- ### Install AI Coding Skill for Specific Agent Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/README.md Install the AI coding skill for a specific AI agent like Claude or Cursor. You can target one or multiple agents. ```bash npx skills add . -a claude-code ``` ```bash npx skills add . -a cursor -a windsurf ``` -------------------------------- ### Configure LicenseManager Settings Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/configuration.md Manage license tracking and activation. Set a friendly device name, limit concurrent instances, specify a license cache directory for offline use, and initialize the license with your key. Call set_license_cache_path before init_license. ```python from dynamsoft_license import LicenseManager # Set device name for licensing tracking err_code, err_msg = LicenseManager.set_device_friendly_name("My-Server-01") # Limit concurrent instances on this device err_code, err_msg = LicenseManager.set_max_concurrent_instance_count(5) # Get device UUID for hardware-based licensing err_code, err_msg, uuid = LicenseManager.get_device_uuid(2) # 2 = hardware-based # Set license cache directory (call before init_license) err_code, err_msg = LicenseManager.set_license_cache_path("/var/cache/dbr") # Initialize license err_code, err_msg = LicenseManager.init_license("YOUR-LICENSE-KEY") ``` -------------------------------- ### Initialize License and Decode Video Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/sample-patterns.md Initializes the Dynamsoft License Manager and then proceeds to decode barcodes from a video source (camera or file) based on user input. Requires network connection for the provided trial license. ```python import os from dynamsoft import LicenseManager, EnumErrorCode def get_mode_and_path(): use_video_file = False video_file_path = "" while True: try: mode = int( input( ">> Choose a Mode Number:\n" "1. Decode video from camera.\n" "2. Decode video from file.\n" ">> 1 or 2:\n" )) if mode == 1 or mode == 2: if mode == 1: use_video_file = False break use_video_file = True while True: video_file_path = input(">> Input your video full path:\n").strip(' \'"') if not os.path.exists(video_file_path): print("Error:File not found.\n") continue break break else: raise ValueError except ValueError: print("Error:Wrong input.\n") continue return use_video_file, video_file_path if __name__ == "__main__": # silence_opencv() # Assuming silence_opencv is defined elsewhere print("-------------------start------------------------") try: # Initialize license. # The string "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTEwNTI2NzQwMSJ9" here is a free public trial license. Note that network connection is required for this license to work. # You can also request a 30-day trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=python errorCode, errorMsg = LicenseManager.init_license("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTEwNTI2NzQwMSJ9") if errorCode != EnumErrorCode.EC_OK and errorCode != EnumErrorCode.EC_LICENSE_WARNING: print("License initialization failed: ErrorCode:", errorCode, ", ErrorString:", errorMsg) else: # Decode video from file or camera use_video_file, video_file_path = get_mode_and_path() # decode_video(use_video_file, video_file_path) # Assuming decode_video is defined elsewhere except Exception as e: print(e) print("-------------------over------------------------") ``` -------------------------------- ### Get Module Version Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-license.md Retrieves the version string of the dynamsoft_license module. This is a static method. ```python from dynamsoft_license import LicenseModule version = LicenseModule.get_version() print(f"License module version: {version}") ``` -------------------------------- ### Initialize License and Handle Errors Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/errors.md Initialize the license key and check for success or specific error codes like warnings or invalid keys. Exit the application on critical license errors. ```python from dynamsoft_barcode_reader_bundle import LicenseManager, EnumErrorCode error_code, error_msg = LicenseManager.init_license("YOUR_LICENSE_KEY") if error_code == EnumErrorCode.EC_OK: print("License initialized successfully") elif error_code == EnumErrorCode.EC_LICENSE_WARNING: print(f"License warning (near expiration): {error_msg}") elif error_code == EnumErrorCode.EC_LICENSE_EXPIRED: print("ERROR: License has expired") exit(1) elif error_code == EnumErrorCode.EC_LICENSE_INVALID: print("ERROR: Invalid license key") exit(1) else: print(f"ERROR {error_code}: {error_msg}") exit(1) ``` -------------------------------- ### Initialize CaptureVisionRouter with JSON Template Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/SKILL.md Load custom settings and configurations from a JSON template file into the CaptureVisionRouter instance. Check for initialization errors. ```python error_code, error_msg = cvr_instance.init_settings_from_file("path/to/template.json") if error_code != EnumErrorCode.EC_OK: print("Init template failed:", error_msg) ``` -------------------------------- ### TextureDetectionResultUnit Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-core.md Represents the result of texture stripe spacing detection. Provides methods to get and set the X and Y spacing values. ```APIDOC ## TextureDetectionResultUnit(IntermediateResultUnit) Texture stripe spacing detection result. ### Methods - `get_x_spacing() -> int` / `set_x_spacing(x_spacing: int) -> None` - `get_y_spacing() -> int` / `set_y_spacing(y_spacing: int) -> None` ``` -------------------------------- ### Initialize CaptureVisionRouter Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/configuration.md Instantiate the CaptureVisionRouter without any parameters. All configuration is applied later using update_settings() or init_settings_from_file(). ```python from dynamsoft_barcode_reader_bundle import CaptureVisionRouter # No parameters required cvr = CaptureVisionRouter() ``` -------------------------------- ### LicenseManager.init_license Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Initializes the SDK with a license key. This method must be called before using any barcode reading functionalities. ```APIDOC ## LicenseManager.init_license ### Description Initializes the SDK with a license key. Must be called before using CaptureVisionRouter. ### Method `static` ### Signature `LicenseManager.init_license(license_key: str) -> Tuple[int, str]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **license_key** (str) - Required - License key string from Dynamsoft ### Request Example ```python from dynamsoft_license import LicenseManager err_code, err_msg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") if err_code != 0 and err_code != 2: # EC_OK or EC_LICENSE_WARNING print(f"License error: {err_msg}") ``` ### Response #### Success Response (0) Returns `EC_OK` for success. #### Warning Response (2) Returns `EC_LICENSE_WARNING` if license is valid but nearing expiration. #### Error Response Other error codes indicate license failure. #### Response Example `Tuple[int, str]` — (error_code, error_message) ``` -------------------------------- ### JSON with Base64 Request Body Example Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Shows the format for sending Base64 encoded image data within a JSON payload. ```json { "data": "iVBORw0KGgoAAAANSUhEUgAAAAUA..." } ``` -------------------------------- ### PredetectedRegionsUnit Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-core.md Manages a collection of pre-detected regions. Supports getting, adding, setting, and removing individual regions, as well as clearing all regions. ```APIDOC **PredetectedRegionsUnit(IntermediateResultUnit)** - `get_count() -> int` - `get_predetected_region(index: int) -> PredetectedRegionElement` - `add_predetected_region(element, matrix_to_original_image=IDENTITY_MATRIX) -> int` - `set_predetected_region(index, element, matrix_to_original_image=IDENTITY_MATRIX) -> int` - `remove_predetected_region(index) -> int` / `remove_all_predetected_regions() -> None` ``` -------------------------------- ### Configure DirectoryFetcher Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/configuration.md Set up DirectoryFetcher to scan images from a specified directory. Configure the path, file filter, and whether to scan recursively. ```python from dynamsoft_utility import DirectoryFetcher fetcher = DirectoryFetcher() # Set directory to scan err_code, err_msg = fetcher.set_directory( path="../Images", filter="*.png;*.jpg;*.jpeg", recursive=False ) ``` -------------------------------- ### Validate Configuration Parameter Ranges Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/errors.md Ensure that configuration parameter values are within their valid ranges. For example, `expected_barcodes_count` should be between 0-999 and `min_result_confidence` between 0-100. ```python # Check valid ranges before setting # expected_barcodes_count: 0-999 # min_result_confidence: 0-100 settings.barcode_settings.expected_barcodes_count = min(10, 999) settings.barcode_settings.min_result_confidence = min(50, 100) ``` -------------------------------- ### Initialize License Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-license.md Call `init_license` before using any Dynamsoft Core Value (DCV) functionality. It returns an error code and message. ```python from dynamsoft_license import LicenseManager error_code, error_msg = LicenseManager.init_license("YOUR-LICENSE-KEY") if error_code != 0: print(f"License error: {error_msg}") ``` -------------------------------- ### Load Settings from JSON File Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Initialize barcode reader settings by loading a configuration from a specified JSON file. Check the returned error code to ensure the settings were loaded successfully. ```python err_code, err_msg = cvr.init_settings_from_file("CustomTemplates/ReadDPM.json") if err_code != EnumErrorCode.EC_OK: print(f"Failed to load settings: {err_msg}") ``` -------------------------------- ### Get Device UUID Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Retrieves or generates a unique device identifier for licensing. Supports both random UUID generation and hardware-based UUID generation. ```python err_code, err_msg, uuid_string = LicenseManager.get_device_uuid(1) # 1 for random UUID ``` -------------------------------- ### Handle License Manager Errors Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/api-reference.md Initialize the license using a provided key and check the returned error code. This snippet demonstrates handling successful initialization and specific warning conditions. ```python error_code, error_message = LicenseManager.init_license("key") if error_code == EnumErrorCode.EC_OK: print("Success") elif error_code == EnumErrorCode.EC_LICENSE_WARNING: print("License warning (still valid)") else: print(f"Error {error_code}: {error_message}") ``` -------------------------------- ### CandidateBarcodeZone Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/types.md Represents a single candidate region for a barcode. It includes methods to get and set the zone's location and possible barcode formats. ```APIDOC ## CandidateBarcodeZone Single candidate region. ### Methods - `get_location()`: Returns `Quadrilateral`. Zone boundaries. - `set_location(loc)`: Updates the zone boundaries. Returns `int`. - `get_possible_formats()`: Returns `int`. Suspected formats. - `set_possible_formats(formats)`: Overrides the suspected formats. Returns `int`. ``` -------------------------------- ### License Initialization in Flask Server Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md This Python code snippet shows how to initialize the Dynamsoft License Manager using an environment variable for the license key. It includes error handling for license initialization. ```python if __name__ == '__main__': import os license_key = os.environ.get('DBR_LICENSE_KEY', 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9') error_code, error_string = LicenseManager.init_license(license_key) if error_code != 0 and error_code != 2: # EC_OK or EC_LICENSE_WARNING print(f"License error: {error_string}") exit(1) app.run(host='0.0.0.0', port=8000, debug=False) ``` -------------------------------- ### Decode Single Image File Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/code-examples.md This snippet shows the most basic way to initialize the license, create a router, and decode barcodes from a single image file. Ensure you have a valid license key and the image file is accessible. ```python from dynamsoft_barcode_reader_bundle import * # 1. Initialize license error_code, error_msg = LicenseManager.init_license("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9") if error_code != EnumErrorCode.EC_OK and error_code != EnumErrorCode.EC_LICENSE_WARNING: print(f"License error: {error_msg}") exit(1) # 2. Create router instance cvr = CaptureVisionRouter() # 3. Decode image result = cvr.capture("barcode.png", EnumPresetTemplate.PT_READ_BARCODES) # 4. Extract and print results if result.get_error_code() != EnumErrorCode.EC_OK: print(f"Error: {result.get_error_string()}") else: barcode_result = result.get_decoded_barcodes_result() if barcode_result: for item in barcode_result.get_items(): print(f"Format: {item.get_format_string()}") print(f"Text: {item.get_text()}") ``` -------------------------------- ### ShortLinesUnit Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-core.md Manages a collection of short lines, following a similar pattern to `LineSegmentsUnit` for getting, adding, setting, and removing short line elements. ```APIDOC **ShortLinesUnit(IntermediateResultUnit)** — Same pattern as LineSegmentsUnit but with `short_line` methods. ``` -------------------------------- ### LineSegmentsUnit Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-core.md Manages a collection of line segments. Supports operations to get, add, set, and remove individual line segments, and to remove all segments. ```APIDOC **LineSegmentsUnit(IntermediateResultUnit)** - `get_count() -> int` - `get_line_segment(index: int) -> LineSegment` - `add_line_segment(line, matrix=IDENTITY_MATRIX) -> int` - `set_line_segment(index, line, matrix=IDENTITY_MATRIX) -> int` - `remove_line_segment(index) -> int` / `remove_all_line_segments() -> None` ``` -------------------------------- ### Parameter Tuner Sample - Initialization Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/sample-patterns.md Initializes the CaptureVisionRouter and defines a class to hold loop information for image and template testing. This is part of an interactive sample for tuning barcode reading parameters. ```python import time import os import dynamsoft_barcode_reader_bundle from pathlib import Path from dynamsoft_barcode_reader_bundle import * BASE_DIR = Path(__file__).resolve().parent PKG_DIR = Path(dynamsoft_barcode_reader_bundle.__file__).resolve().parent class LoopInfo(): def __init__(self,cvr_instance : CaptureVisionRouter, image_path: str = None,matched_template: str = None, description: str = None, template_path: str = None): self.cvr_instance = cvr_instance self.image_path = image_path self.template_path = template_path self.matched_template = matched_template self.description = description sample_images = { "1": ("Images/blurry.png", "ReadBlurry1DBarcode.json", "Suitable for blurred 1D barcode"), "2": ("Images/GeneralBarcodes.png", "ReadMultipleBarcode.json", "Suitable for multiple barcodes"), "3": ("Images/inverted-barcode.png", "ReadInvertedBarcode.json", "Suitable for colour inverted barcode"), "4": ("Images/DPM.png", "ReadDPM.json", "Suitable for Direct Part Marking barcode"), "5": ("Images/EAN-13.jpg", "ReadOneDRetail.json", "Suitable for retail 1D barcode such as EAN13, UPC-A"), "6": ("Images/OneDIndustrial.jpg", "ReadOneDIndustrial.json", "Suitable for industrial 1D barcode such as Code128, Code39"), } def select_image(): print("Available Sample Scenarios:") print("[1] Blurry 1D barcode") print("[2] Multiple barcodes") print("[3] Colour Inverted Barcode") print("[4] Direct Part Marking (DPM)") print("[5] Retail 1D barcode") print("[6] Industrial 1D barcode") print("[7] Custom Image") while True: choice = input("\nEnter the number of the image to test, or provide a full path to your own image:\n> ").strip(' \'"') image_path, matched_template, description = None, None, None if choice in sample_images: image_path, matched_template, description = sample_images[choice] image_path = str(BASE_DIR.parent / image_path) elif choice == "7": image_path = input("Enter full path to your custom image:\n> ").strip(' \'"') if not os.path.isfile(image_path): print("Invalid path input, please try again.") continue else: image_path = choice if not os.path.isfile(image_path): print("Invalid path input, please try again.") continue image_path = os.path.abspath(image_path) return image_path, matched_template, description def select_template(matched_template, description): print("\nSelect template for this image:") options = [] if matched_template: options.append((matched_template, description)) options.append(("ReadBarcodes_Default.json", "General purpose settings")) options.append(("Custom template", "Use your own template")) for idx, (path, desc) in enumerate(options, start=1): print(f"[{idx}] {path} ({desc})") print("\nEnter the number of the template to test, or provide a full path to your own template:") ``` -------------------------------- ### Image-type Intermediate Units Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/references/api-core.md Classes representing image-based intermediate results, all inheriting from `IntermediateResultUnit`. They share an interface for getting and setting image data. ```APIDOC ## Image-type Intermediate Units All inherit from `IntermediateResultUnit` and share the same interface: ### Methods - `get_image_data() -> ImageData` - `set_image_data(img_data: ImageData) -> int` | Class | IRUT Type | |-------|-----------| | `ColourImageUnit` | IRUT_COLOUR_IMAGE | | `ScaledColourImageUnit` | IRUT_SCALED_COLOUR_IMAGE | | `GrayscaleImageUnit` | IRUT_GRAYSCALE_IMAGE | | `TransformedGrayscaleImageUnit` | IRUT_TRANSFORMED_GRAYSCALE_IMAGE | | `EnhancedGrayscaleImageUnit` | IRUT_ENHANCED_GRAYSCALE_IMAGE | | `BinaryImageUnit` | IRUT_BINARY_IMAGE | | `TextureRemovedGrayscaleImageUnit` | IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE | | `TextureRemovedBinaryImageUnit` | IRUT_TEXTURE_REMOVED_BINARY_IMAGE | | `TextRemovedBinaryImageUnit` | IRUT_TEXT_REMOVED_BINARY_IMAGE | ``` -------------------------------- ### Load Custom Template from JSON Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/INDEX.txt Initializes barcode reader settings from a JSON configuration file. This allows for complex and reusable configurations. ```python from dynamsoft import dbr # Initialize license dbr.LicenseManager.init_license("YOUR_LICENSE_KEY") # Create a barcode reader instance reader = dbr.BarcodeReader() # Initialize settings from a JSON file # The JSON file should contain the configuration parameters. reader.init_settings_from_file("custom_settings.json") # Decode an image using the loaded settings results = reader.decode_file("image_to_decode.png") # Print results for result in results: print(f"Format: {result.barcode_format_string}, Value: {result.barcode_text}") ``` -------------------------------- ### Get and Update Barcode Reader Settings Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/configuration.md Retrieve current barcode reading settings and then modify them programmatically. Apply the updated settings to the CaptureVisionRouter. ```python from dynamsoft_barcode_reader_bundle import CaptureVisionRouter, EnumPresetTemplate cvr = CaptureVisionRouter() # Retrieve current settings err_code, err_msg, settings = cvr.get_simplified_settings(EnumPresetTemplate.PT_READ_BARCODES) # Modify settings settings.barcode_settings.expected_barcodes_count = 10 # Apply settings err_code, err_msg = cvr.update_settings(EnumPresetTemplate.PT_READ_BARCODES, settings) ``` -------------------------------- ### Create CaptureVisionRouter Instance Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/skills/dbr-python-sample-creator/SKILL.md Instantiate the central orchestrator for image processing. No arguments are required for basic initialization. ```python cvr_instance = CaptureVisionRouter() ``` -------------------------------- ### Update Barcode Reader Settings Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/errors.md Retrieve current settings, modify them, and then update them. Handle errors that may occur during the get or update operations. ```python from dynamsoft_barcode_reader_bundle import CaptureVisionRouter, EnumErrorCode, EnumPresetTemplate cvr = CaptureVisionRouter() # Get current settings err_code, err_msg, settings = cvr.get_simplified_settings(EnumPresetTemplate.PT_READ_BARCODES) if err_code != EnumErrorCode.EC_OK: print(f"Failed to get settings: {err_msg}") else: # Modify settings settings.barcode_settings.expected_barcodes_count = 5 # Update settings err_code, err_msg = cvr.update_settings(EnumPresetTemplate.PT_READ_BARCODES, settings) if err_code != EnumErrorCode.EC_OK: print(f"Failed to update settings: {err_msg}") ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/endpoints.md Builds a Docker image for the barcode reader server and runs it. Use cURL to send a barcode image for decoding. ```dockerfile FROM python:3.11-slim WORKDIR /app COPY Samples/server_side_barcode_decoder.py . RUN pip install dynamsoft-barcode-reader-bundle flask EXPOSE 8000 CMD ["python", "server_side_barcode_decoder.py"] ``` ```bash docker build -t dbr-server . docker run -p 8000:8000 dbr-server ``` ```bash curl -F "file=@barcode.png" http://localhost:8000/decode_barcode ``` -------------------------------- ### ECISegment Source: https://github.com/dynamsoft/barcode-reader-python-samples/blob/master/_autodocs/types.md Information about character encoding segments within barcode text, including ECI value, charset encoding, start index, and length. ```APIDOC ## ECISegment Character encoding information for barcode text. **Attributes:** | Attribute | Type | Description | |-----------|------|-------------| | `eci_value` | `int` | ECI assignment number (ISO/IEC 15424) | | `charset_encoding` | `str` | Charset name (e.g., "UTF-8", "ISO-8859-1") | | `start_index` | `int` | Start position in decoded bytes | | `length` | `int` | Length in bytes | **Example:** ```python for eci in item.get_eci_segments(): print(f"ECI {eci.eci_value}: {eci.charset_encoding}") ``` ```