### Install Python Dependencies Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/src/README.md Installs the project's Python dependencies using pip from a requirements file. Ensure you have Python 3.9 and a virtual environment activated. ```bash pip install -r requirements.txt ``` -------------------------------- ### API Request Example for Graph Construction - Text Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md An example request body for the POST /api/pid-digitization/graph-construction/{pid_id} endpoint. This illustrates the required JSON payload for constructing a graph from a P&ID image, including image details, text detection results, and Hough transform parameters. ```text POST /api/pid-digitization/graph-construction/5 Request body: { "image_url": "pid2.png", "image_details": { "format": "png", "width": 1388, "height": 781 }, "all_text_list": [ { "text": "GLR", "topX": 0.5067512555, "topY": 0.72654658, "bottomX": 0.5136717032, "bottomY": 0.7377242533, }, ... ], "symbol_and_text_associated_list": [ { "id": "", "topX": 0.4067512554, "topY": 0.42654657, "bottomX": 0.4136717031, "bottomY": 0.6377242532, "text_associated": "ZLC" }, ... ], "hough_threshold": 2, "hough_min_line_length": 2, "hough_max_line_gap": 2, "hough_rho": 0.1, "hough_theta": 2, "thinning_enabled": false, "bounding_box_inclusive": { "topX": 0.4067512554, "topY": 0.42654657, "bottomX": 0.4136717031, "bottomY": 0.6377242532 }, "propagation_pass_exhaustive_search": false } ``` -------------------------------- ### API Request Example: Get Graph Construction Status (Text) Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md An example of an HTTP GET request to retrieve the status of a graph construction job for a specific P&ID, identified by its ID. ```text GET /api/pid-digitalization/graph-construction/5 ``` -------------------------------- ### Example API Request for Text Detection Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/text-detection-design.md This snippet shows an example POST request to the TextDetection API endpoint. It includes the P&ID image ID as a path variable and a JSON body containing image details and corrected symbol detection results for text association. ```text POST /api/pid-digitalization/text-detection/5 Request body: { "image_url": "pid2.png", "image_details": { "format": "png", "width": 1388, "height": 781 }, "label": [ { "topX": 0.5067512555, "topY": 0.72654658, "bottomX": 0.5136717032, "bottomY": 0.7377242533, "id": 0, "label": "24", "score": 0.9782005548 }, ... ] } ``` -------------------------------- ### GET TextDetection Request Example Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/text-detection-design.md This is an example of a GET request to the TextDetection endpoint. It requires the P&ID image ID as a path variable to retrieve the latest recognized text stored for that image. ```text GET /api/pid-digitalization/text-detection/5 ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/src/README.md Creates a Python virtual environment named 'venv' and activates it. This isolates project dependencies from the global Python installation. The activation command differs between Windows and Unix-like systems. ```bash python -m venv venv source ./venv/Scripts/activate # or ./venv/bin/activate ``` -------------------------------- ### Run FastAPI Application Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/src/README.md Starts the FastAPI application, which provides an API for P&ID digitization. Can be run directly or using gunicorn for a production-like environment. Access the API documentation at /docs. ```bash python -m init_app # or gunicorn init_app:app -k uvicorn.workers.UvicornWorker -b 0.0.0.0 ``` -------------------------------- ### Graph SQL Querying Examples Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/development_graph_db_setup.md This snippet demonstrates how to query graph data in SQL. It includes sample queries to retrieve sheet, belongs, and pnid information, as well as asset connections. These queries are useful for analyzing relationships within the data. ```SQL SELECT * FROM [pnide].[sheet] as sheet, [pnide].[belongs] as belongs, [pnide].[pnid] as pnid WHERE MATCH (sheet-(belongs)->pnid) AND pnid.Id = 'PNID1' ``` ```SQL SELECT * FROM [pnide].[Asset] as asset1, [pnide].[Asset] as asset2, [pnide].[Connected] as connected WHERE MATCH (asset1-(connected)->asset2) AND asset1.Id = 'Asset1' ``` -------------------------------- ### Get Graph Construction Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md Retrieves the constructed graph for a given piping and instrument diagram. ```APIDOC ## GET /api/pid-digitization/graph-construction/{pid_id} ### Description Retrieves the constructed graph representation for a specified piping and instrument diagram. ### Method GET ### Endpoint /api/pid-digitization/graph-construction/{pid_id} ### Parameters #### Path Parameters - **pid_id** (string) - Required - The unique identifier for the PID. ### Response #### Success Response (200) ### GET Graph Construction Output ```json { "graph": {} } ``` #### Error Response - **404** - Not Found: The specified PID or its constructed graph could not be found. - **500** - Internal Server Error: Failed to retrieve the graph construction. ``` -------------------------------- ### Copy Environment Configuration Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/src/README.md Copies the sample environment configuration file '.env.sample' to '.env'. This sets up the necessary environment variables for the application. ```bash cp .env.sample .env ``` -------------------------------- ### Configuration Management with Pydantic - Python Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt Demonstrates application configuration using Pydantic BaseSettings, reading values from environment variables. It accesses settings for Azure services, inference thresholds, and graph construction parameters. Configuration can be provided via a `.env` file. ```python from app.config import config # Access configuration values print(f"Symbol detection API: {config.symbol_detection_api}") print(f"Inference threshold: {config.inference_score_threshold}") print(f"Line detection threshold: {config.line_detection_hough_threshold}") print(f"Detect dotted lines: {config.detect_dotted_lines}") # Configure environment variables in .env file # BLOB_STORAGE_ACCOUNT_URL=https://mystorageaccount.blob.core.windows.net # BLOB_STORAGE_CONTAINER_NAME=inference-results # FORM_RECOGNIZER_ENDPOINT=https://myformrecognizer.cognitiveservices.azure.com/ # SYMBOL_DETECTION_API=https://myendpoint.azureml.net/score # SYMBOL_DETECTION_API_BEARER_TOKEN=your_bearer_token # GRAPH_DB_CONNECTION_STRING=Server=tcp:myserver.database.windows.net... # INFERENCE_SCORE_THRESHOLD=0.5 # LINE_DETECTION_HOUGH_THRESHOLD=5 # DETECT_DOTTED_LINES=false # ENABLE_PREPROCESSING_TEXT_DETECTION=true # ENABLE_THINNING_PREPROCESSING_LINE_DETECTION=true ``` -------------------------------- ### GET /graph-construction-job-status Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/architecture.md Queries the state of the graph construction job related by Unique Id. ```APIDOC ## GET /graph-construction-job-status ### Description Queries the state of the graph construction job related by Unique Id. ### Method GET ### Endpoint /graph-construction-job-status ### Parameters #### Query Parameters - **uniqueId** (string) - Required - A unique identifier for the P&ID. ### Response #### Success Response (200) - **status** (string) - The current status of the job (e.g., "InProgress", "Completed", "Failed"). - **errorMessage** (string) - An error message if the job failed. - **lineDetectionResults** (array) - Array of detected line segments, each containing start and end coordinates. - **graph** (object) - The constructed graph representing symbols and their connections. #### Response Example ```json { "status": "Completed", "lineDetectionResults": [ {"start": {"x": 10, "y": 20}, "end": {"x": 30, "y": 40}} ], "graph": { "terminals": [ {"id": "symbol_1", "type": "Pump", "connections": ["symbol_2"]} ] } } ``` #### Error Response (404) - **message** (string) - HTTP code 404 if the job does not exist. ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/src/README.md Executes all unit tests for the project using the pytest framework. This command verifies the functionality of different components of the application. ```bash pytest # or python -m pytest ``` -------------------------------- ### GET /inference-result-images Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/architecture.md Retrieves the inference debug images related by Unique Id and Inference Type. ```APIDOC ## GET /inference-result-images ### Description Gets the inference debug images related by the Unique Id and Inference Type. ### Method GET ### Endpoint /inference-result-images ### Parameters #### Query Parameters - **uniqueId** (string) - Required - A unique identifier for the P&ID. - **inferenceType** (string) - Required - The type of inference for which to retrieve debug images (e.g., "SymbolDetection", "TextDetection", "LineDetection"). ### Response #### Success Response (200) - **debugImage** (file) - The debug image file. #### Response Example (Returns binary image data) #### Error Response (404) - **message** (string) - HTTP code 404 if the symbol detected output does not exist yet. ``` -------------------------------- ### GET /inference-results Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/architecture.md Retrieves the latest inference output for a given Unique Id and Inference Type. Prioritizes corrected output over original output. ```APIDOC ## GET /inference-results ### Description Gets the latest inference output related by the Unique Id and Inference Type. The API looks first for the corrected output, otherwise the original output. ### Method GET ### Endpoint /inference-results ### Parameters #### Query Parameters - **uniqueId** (string) - Required - A unique identifier for the P&ID. - **inferenceType** (string) - Required - The type of inference to retrieve (e.g., "SymbolDetection", "TextDetection", "LineDetection", "GraphConstruction"). ### Response #### Success Response (200) - **inferenceResults** (object) - The inference results, which can be one of the following types: - Symbol Detection Inference Results [Symbol Bounding Box/Type/Class] - Text Detection Inference Results [Text Bounding Box/Text/Associated symbol, Text Bounding Box/Text] - Line Detection results [Array of start & end lines] - Symbol Terminals with their connections #### Response Example ```json { "inferenceResults": { "symbolDetectionResults": [ {"boundingBox": {"x_min": 110, "y_min": 110, "x_max": 150, "y_max": 150}, "type": "Pump", "class": "Equipment"} ] } } ``` #### Error Response (404) - **message** (string) - HTTP code 404 if the symbol detected output does not exist yet. ``` -------------------------------- ### GET /api/pid-digitization/graph-construction/{pid_id} Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md Retrieves the line detection job status for a given P&ID ID. The job status can be 'Submitted', 'In Progress', 'Failed', or 'Success'. ```APIDOC ## GET /api/pid-digitization/graph-construction/{pid_id} ### Description Retrieves the line detection job status for a given P&ID ID. The job status can be 'Submitted', 'In Progress', 'Failed', or 'Success'. ### Method GET ### Endpoint /api/pid-digitization/graph-construction/{pid_id} ### Parameters #### Path Parameters - **pid_id** (string) - Required - The ID of the P&ID to get the line detection job status. ### Response #### Success Response (200) - **job_status** (string) - The status of the graph construction job. Possible values: 'Submitted', 'In Progress', 'Failed', 'Success'. #### Response Example ```json { "job_status": "Submitted" } ``` ``` -------------------------------- ### P&ID Digitization API Endpoints (Postman) Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/local_development_setup.md Import the provided Postman collection to easily make requests against the inference service. Ensure you also import the necessary environment files for local, dev, or QA deployments. ```APIDOC ## P&ID Digitization API (Postman) ### Description Use the provided Postman collection to interact with the P&ID digitization inference service. Import the collection and relevant environment files to test endpoints and run the inference workflow. ### Method Various (GET, POST, etc. - defined in Postman collection) ### Endpoint Variable (defined by imported Postman environment) ### Parameters - Path, Query, and Request Body parameters are pre-configured within the Postman collection and environments. Users need to update field values as specified in the documentation. ### Request Example (Refer to specific requests within the imported Postman collection) ### Response #### Success Response (200) - Varies based on the specific endpoint being called. #### Response Example (Refer to specific responses within the imported Postman collection) ``` -------------------------------- ### Get Inference Results API Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt Retrieves completed inference results for a specified stage of the P&ID digitization pipeline. ```APIDOC ## GET /api/pid-digitization/{inference_type}/{pid_id} ### Description Retrieves the completed inference results for a specific stage of the P&ID digitization pipeline. This allows access to structured data such as detected symbols, text, lines, or the final graph. ### Method GET ### Endpoint `/api/pid-digitization/{inference_type}/{pid_id}` ### Parameters #### Path Parameters - **inference_type** (string) - Required - The type of inference results to retrieve. Accepted values: 'symbol_detection', 'text_detection', 'line_detection', 'graph_construction'. - **pid_id** (string) - Required - The unique identifier for the PID. ### Response #### Success Response (200) - The structure of the response depends on the `inference_type`. For 'graph_construction', it includes connected symbols and their relationships. #### Response Example (Graph Construction) ```json { "image_url": "pid_12345.png", "image_details": {"height": 2048, "width": 3072}, "connected_symbols": [ { "id": 0, "label": "Equipment/Pump/Centrifugal", "text_associated": "P-101", "connections": [ { "id": 1, "label": "Instrument/Valve/Gate Valve", "text_associated": "V-201" } ] } ] } ``` ``` -------------------------------- ### Run Pytest Unit Tests Locally Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/local_development_setup.md Command to navigate to the 'src/' directory and execute all discovered pytest tests. This is the primary method for running unit tests locally. ```shell cd src/ pytest . ``` -------------------------------- ### GET /graph-construction/{pid_id}/status Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/user-guide.md Queries the status of a previously submitted graph construction job. This endpoint is used to monitor the progress of the asynchronous job and retrieve results once complete. ```APIDOC ## GET /graph-construction/{pid_id}/status ### Description Retrieves the status of a graph construction job. This allows clients to monitor the progress of the asynchronous job and determine when the results are ready. ### Method GET ### Endpoint `/graph-construction/{pid_id}/status` ### Parameters #### Path Parameters - **pid_id** (string) - Required - The unique identifier for the PID image and its associated graph construction job. #### Query Parameters None #### Request Body None ### Request Example ``` GET /graph-construction/pid-image-abc/status ``` ### Response #### Success Response (200 OK) - **status** (string) - The current status of the job (e.g., "Pending", "Processing", "Success", "Failed"). - **results_url** (string, optional) - A URL to the generated graph data if the job status is "Success". #### Response Example (200 OK - Processing) ```json { "status": "Processing" } ``` #### Response Example (200 OK - Success) ```json { "status": "Success", "results_url": "/path/to/graph/results/pid-image-abc.json" } ``` #### Error Response (404 Not Found) - **error** (string) - Indicates that no job with the specified `pid_id` was found. #### Response Example (404 Not Found) ```json { "error": "Job not found for the specified pid_id." } ``` ``` -------------------------------- ### Submit Asynchronous Graph Construction Job using Bash Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt This API endpoint initiates an asynchronous job to detect lines and construct a connectivity graph from P&ID data. It uses Hough transform for line detection and NetworkX/Shapely for graph creation. The job is queued for background processing, and the API returns immediately. ```bash # Example bash command for submitting the graph construction job # Note: This is a conceptual example as the specific curl command details were not provided in the text. # It would typically involve POSTing relevant image data or job parameters. curl -X POST "http://localhost:8000/api/pid-digitization/graph-construction/submit-job" \ -H "Content-Type: application/json" \ -d '{"image_id": "pid_12345", "processing_mode": "async"}' ``` -------------------------------- ### GET TextDetection [/api/pid-digitization/text-detection/{pid_id}] Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/text-detection-design.md Retrieves the latest recognized text stored for a given P&ID image ID. The response format is identical to the POST TextDetection output. ```APIDOC ## GET TextDetection [/api/pid-digitization/text-detection/{pid_id}] ### Description Retrieves the latest recognized text stored for a given P&ID image ID. The response format is identical to the POST TextDetection output. ### Method GET ### Endpoint /api/pid-digitization/text-detection/{pid_id} ### Parameters #### Path Parameters - **pid_id** (string) - Required - The ID of the P&ID image. ### Request Example ```text GET /api/pid-digitalization/text-detection/5 ``` ### Response #### Success Response (200) - **image_url** (string) - URL of the processed image. - **image_details** (object) - Details about the image. - **format** (string) - Image format (e.g., "png"). - **width** (integer) - Image width in pixels. - **height** (integer) - Image height in pixels. - **all_text_list** (array) - List of all text detected on the image. - **text** (string) - The detected text. - **topX** (float) - Top X coordinate of the text bounding box. - **topY** (float) - Top Y coordinate of the text bounding box. - **bottomX** (float) - Bottom X coordinate of the text bounding box. - **bottomY** (float) - Bottom Y coordinate of the text bounding box. - **symbol_and_text_associated_list** (array) - List of symbols with their associated text. - **id** (string) - Unique identifier for the symbol. - **topX** (float) - Top X coordinate of the symbol bounding box. - **topY** (float) - Top Y coordinate of the symbol bounding box. - **bottomX** (float) - Bottom X coordinate of the symbol bounding box. - **bottomY** (float) - Bottom Y coordinate of the symbol bounding box. - **text_associated** (string) - Text associated with the symbol. #### Response Example ```json { "image_url": "pid2.png", "image_details": { "format": "png", "width": 1388, "height": 781 }, "all_text_list": [ { "text": "GLR", "topX": 0.5067512555, "topY": 0.72654658, "bottomX": 0.5136717032, "bottomY": 0.7377242533 } ], "symbol_and_text_associated_list": [ { "id": "", "topX": 0.4067512554, "topY": 0.42654657, "bottomX": 0.4136717031, "bottomY": 0.6377242532, "text_associated": "ZLC" } ] } ``` ``` -------------------------------- ### POST /graph-construction Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/architecture.md Submits a job to perform line detection and graph construction. Returns 202 Accepted if the server accepted the request. Stores corrected text detection output before job execution. ```APIDOC ## POST /graph-construction ### Description Submits a job into a request queue to perform two processings - line detection and graph construction - on a P&ID image related by the Unique Id. Returns 202 http code if the server accepted the request. Before the job execution starts, it stores the corrected text detection output. ### Method POST ### Endpoint /graph-construction ### Parameters #### Request Body - **correctedTextDetectionResults** (array) - Required - The corrected text detection results. - **uniqueId** (string) - Required - A unique identifier for the P&ID. ### Request Example ```json { "uniqueId": "pid_123", "correctedTextDetectionResults": [ { "boundingBox": {"x_min": 120, "y_min": 120, "x_max": 140, "y_max": 130}, "text": "P-101", "associatedSymbol": {"type": "Pump", "class": "Equipment"} } ] } ``` ### Response #### Success Response (202) - **message** (string) - Indicates that the job request was accepted. #### Response Example ```json { "message": "Graph construction job accepted." } ``` #### Error Response (422) - **message** (string) - HTTP code 422 if PID image has never been provided. ``` -------------------------------- ### Get Inference Images API Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt Retrieves annotated debug images showing detection results overlaid on the original P&ID. ```APIDOC ## GET /api/pid-digitization/{inference_type}/{pid_id}/images ### Description Retrieves annotated debug images for a specific inference stage. These images visually represent the detection results, such as bounding boxes and labels, overlaid on the original P&ID, aiding in quality assurance and troubleshooting. ### Method GET ### Endpoint `/api/pid-digitization/{inference_type}/{pid_id}/images` ### Parameters #### Path Parameters - **inference_type** (string) - Required - The type of inference results to visualize. Accepted values: 'symbol_detection', 'line_detection', 'graph_construction'. - **pid_id** (string) - Required - The unique identifier for the PID. ### Response #### Success Response (200) - Returns an image file (e.g., PNG) containing the annotated P&ID for the specified inference type. #### Response Example (Returns a PNG image file) ``` -------------------------------- ### Python sys.path Modification for Local Imports Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/local_development_setup.md Example of modifying the Python system path to allow local imports from the 'app' directory when running tests. This is often required due to the test execution context. ```python import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')) ``` -------------------------------- ### P&ID Digitization API Endpoints (Swagger) Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/local_development_setup.md Access the auto-generated Swagger UI for a comprehensive view of all available API endpoints. This interface allows you to visualize, test, and interact with the inference service directly. ```APIDOC ## P&ID Digitization API ### Description This API provides access to the inference service for digitizing Piping and Instrument Diagrams (P&IDs). The Swagger UI offers an interactive interface to explore and test all available endpoints. ### Method GET ### Endpoint `{base-inference-service-url}/docs` ### Parameters None ### Request Example None ### Response #### Success Response (200) - Swagger UI interface for API exploration. #### Response Example (HTML content of Swagger UI) ``` -------------------------------- ### POST /api/pid-digitization/graph-construction/{pid_id} Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/user-guide.md Initiates the graph construction process for a given PID diagram. This is an asynchronous endpoint and returns a 202 Accepted status upon successful job submission. It takes the results of text detection as input and allows for tuning parameters. ```APIDOC ## POST /api/pid-digitization/graph-construction/{pid_id} ### Description Submits a job for graph construction, which builds an in-memory graph from line and text detection data to identify assets and their connections (downstream or unknown) in a Piping and Instrument Diagram (PID). ### Method POST ### Endpoint `/api/pid-digitization/graph-construction/{pid_id}` ### Parameters #### Path Parameters - **pid_id** (string) - Required - The unique identifier for the PID image processed by the text detection step. #### Query Parameters None #### Request Body - **hough_threshold** (integer) - Optional - Threshold for Hough line detection. - **hough_min_line_length** (integer) - Optional - Minimum length for detected lines. - **hough_max_line_gap** (integer) - Optional - Maximum gap allowed between line segments. - **hough_rho** (float) - Optional - Distance resolution for Hough transform. - **hough_theta** (float) - Optional - Angle resolution for Hough transform. - **thinning_enabled** (boolean) - Optional - Enables or disables line thinning. - **propagation_pass_exhaustive_search** (boolean) - Optional - Enables exhaustive search during flow propagation. ### Request Example ```json { "hough_threshold": 50, "hough_min_line_length": 50, "hough_max_line_gap": 10, "hough_rho": 1, "hough_theta": 0.017453292519943295, "thinning_enabled": true, "propagation_pass_exhaustive_search": false } ``` ### Response #### Success Response (202 Accepted) - **message** (string) - Confirmation that the job has been submitted. - **job_id** (string) - The identifier for the submitted job. #### Response Example (202 Accepted) ```json { "message": "Graph construction job submitted successfully.", "job_id": "graph-construction-job-12345" } ``` #### Error Response (409 Conflict) - **error** (string) - Indicates that a job for this `pid_id` is already in progress. #### Response Example (409 Conflict) ```json { "error": "A graph construction job for this pid_id is already in progress." } ``` ``` -------------------------------- ### Graph Construction API Request Body Parameters Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/user-guide.md These parameters are used to tune the output results of the graph construction process. They control various aspects of line detection, thinning, and propagation search. ```json { "hough_threshold": , "hough_min_line_length": , "hough_max_line_gap": , "hough_rho": , "hough_theta": , "thinning_enabled": , "propagation_pass_exhaustive_search": } ``` -------------------------------- ### Arrow-to-Line Proximity Matching Algorithm Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md This pseudocode outlines a process to match arrow symbols with lines when the arrow's connection point is not at the start or end of the line. It iterates through arrow nodes and calculates the distance between arrow bounding boxes and line polygons, adding an edge if the distance is below a threshold. ```python arrow_nodes = get_arrow_nodes(G) for arrow_node in arrow_nodes: if degree(arrow_node) != 1: continue min_distance = 100000 min_symbol = None for line in lines: if line.id in G[arrow_node.id]: continue arrow_polygon = convert_to_polygon(arrow_node) line_polygon = convert_to_polygon(line) polygon_distance = distance(arrow_polygon, line_polygon) if polygon_distance < SYMBOL_DISTANCE_THRESHOLD and polygon_distance < min_distance: min_distance = distance min_symbol = line.id if min_symbol: add_edge(min_symbol, arrow_node.id) ``` -------------------------------- ### Run Symbol Detection Programmatically Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt This function reads a P&ID image, performs symbol detection using `run_inferencing`, and prints the detected symbols. It requires the image file path and outputs a list of detected symbols with their associated text and confidence scores. ```python async def process_pid_image(): with open('/path/to/diagram.png', 'rb') as f: image_bytes = f.read() bounding_box = BoundingBox(topX=0.05, topY=0.05, bottomX=0.95, bottomY=0.95) results = await run_inferencing( pid_id="pid_12345", bounding_box_inclusive=bounding_box, inference_score_threshold=0.5, image_bytes=image_bytes, output_image_path="/output/pid_12345_symbols.png" ) # Results contain filtered and pruned symbol detections print(f"Detected {len(results.label)} symbols") for symbol in results.label: print(f" {symbol.label}: {symbol.text_associated} (score: {symbol.score})") ``` -------------------------------- ### Graph Construction API Source: https://context7.com/azure-samples/digitization-of-piping-and-instrument-diagrams/llms.txt Submits an asynchronous job to detect lines and construct a connectivity graph from P&ID data. ```APIDOC ## POST /api/pid-digitization/graph-construction/{pid_id} ### Description Submits an asynchronous job to detect lines and construct a connectivity graph from P&ID data. This endpoint combines line detection using Hough transform with graph construction algorithms to create a connected asset graph. The job is queued for background processing and returns immediately. ### Method POST ### Endpoint `/api/pid-digitization/graph-construction/{pid_id}` ### Parameters #### Path Parameters - **pid_id** (string) - Required - The ID of the P&ID diagram. #### Request Body - **image_url** (string) - Required - The URL of the P&ID image. - **image_details** (object) - Required - Details about the image dimensions. - **height** (integer) - Required - The height of the image. - **width** (integer) - Required - The width of the image. - **symbols** (array) - Required - The list of detected symbols with their bounding boxes and labels. - **id** (integer) - Required - The unique identifier for the symbol. - **topX** (float) - Required - The top X coordinate of the symbol bounding box. - **topY** (float) - Required - The top Y coordinate of the symbol bounding box. - **bottomX** (float) - Required - The bottom X coordinate of the symbol bounding box. - **bottomY** (float) - Required - The bottom Y coordinate of the symbol bounding box. - **label** (string) - Required - The detected label for the symbol. - **score** (float) - Required - The confidence score of the detection. - **texts** (array) - Required - A list of detected text elements associated with symbols. - **id** (integer) - Required - The ID of the associated symbol. - **text_associated** (string) - Required - The text associated with the symbol. ### Request Example ```bash curl -X POST "http://localhost:8000/api/pid-digitization/graph-construction/pid_12345" \ -H "Content-Type: application/json" \ -d '{ "image_url": "pid_12345.png", "image_details": {"height": 2048, "width": 3072}, "symbols": [ { "id": 0, "topX": 0.125, "topY": 0.342, "bottomX": 0.178, "bottomY": 0.398, "label": "Equipment/Pump/Centrifugal", "score": 0.95 } ], "texts": [ { "id": 0, "text_associated": "P-101" } ] }' ``` ### Response #### Success Response (202) - **job_id** (string) - The ID of the asynchronous job. - **status_url** (string) - The URL to check the job status. #### Response Example ```json { "job_id": "job_abc123", "status_url": "http://localhost:8000/api/jobs/job_abc123" } ``` ``` -------------------------------- ### Create Graph Edges from Line Connections (Python) Source: https://github.com/azure-samples/digitization-of-piping-and-instrument-diagrams/blob/main/docs/graph-construction-design.md This Python pseudocode processes line connection candidates to create graph edges. It identifies the closest node to a line's start or end point, creates a new line node if the closest object is text, and then adds an edge between the line and its closest element. ```python # line coordinate candidates is a dict # the key contains the coordinates of the line point and whether the point is start or end for key, value in line_coordinate_candidates.items(): line_id, line_position = key.split('_') line_node = G.nodes[line_id] closest_node = get_closest_node(value) if closest_node.type == GraphNodeType.text: closest_nodes = create_line_from_text_node(closest_node) add_edge(line_id, closest_node.id) ```