Build a multimodal data preprocessing pipeline
This topic describes multimodal data preprocessing on AI Search Open Platform.
Use cases
Multimodal data preprocessing handles unstructured documents and images. The full pipeline consists of document parsing, image parsing, document chunking, text embedding, and sparse text embedding, allowing you to experience the complete data processing workflow. These services use AI Search Open Platform APIs and incur fees based on actual calls.
Prerequisites
-
Activate AI Search Open Platform. For details, see Activate the service.
-
Obtain the service endpoint and authentication information. For details, see Obtain a service endpoint,Manage API key.
AI Search Open Platform supports service calls over public and VPC endpoints, including cross-region calls through VPC. Users in Shanghai, Hangzhou, Shenzhen, Beijing, Zhangjiakou, and Qingdao can call AI Search Open Platform services through a VPC endpoint.
Build a multimodal data preprocessing pipeline
For ease of use, AI Search Open Platform provides four types of development frameworks:
-
Java SDK.
-
Python SDK.
-
If your business already uses the LangChain development framework, select LangChain as the development framework.
-
If your business already uses the LlamaIndex development framework, select LlamaIndex as the development framework.
Step 1: Select services and download the code
This procedure uses the Python SDK to build a multimodal data preprocessing pipeline.
-
Log on to the AI Search Open Platform console.
-
Select the China (Shanghai) region, switch to AI Search Open Platform, and then switch to the target workspace.
Note-
AI Search Open Platform is available only in the China (Shanghai) and Germany (Frankfurt) regions.
-
Users in the China (Hangzhou), China (Shenzhen), China (Beijing), China (Zhangjiakou), and China (Qingdao) regions can use a VPC endpoint to call AI Search Open Platform services across regions.
-
-
In the left-side navigation pane, select Scene Center. Find Multimodal Data Preprocessing - Data Parsing and Vectorization and click Enter.
-
Based on the service information and your business requirements, select services from the drop-down list. View service details on the Service Details page.
Note-
Provide a service ID (service_id) when calling an algorithm service in the multimodal preprocessing pipeline through APIs. For example, the document content parsing service ID is ops-document-analyze-001.
-
Selecting a different service in the list updates service_id in the generated code. After downloading the code, you can still change service_id to call another service.
Stage
Description
Document content parsing
Document content parsing (ops-document-analyze-001): A general-purpose parser that extracts logical structures, such as titles and sections, from unstructured documents containing text, tables, and images, and returns structured output.
Image content parsing
-
Image content understanding (ops-image-analyze-vlm-001): Uses a multimodal model to understand images and recognize text. The parsed text can be used for image retrieval and question answering.
-
Image text recognition (ops-image-analyze-ocr-001): Uses OCR to recognize image text. The parsed text can be used for image retrieval and question answering.
Document chunking
Document chunking (ops-document-split-001): A general-purpose text chunking service that splits structured HTML, Markdown, and txt data based on document paragraphs, semantics, or specified rules. It also extracts code, images, and tables as rich text.
Text embedding
-
OpenSearch text embedding 001 (ops-text-embedding-001): Supports more than 40 languages. Maximum input text length: 300. Output vector dimension: 1536.
-
OpenSearch general-purpose text embedding 002 (ops-text-embedding-002): Supports more than 100 languages. Maximum input text length: 8192. Output vector dimension: 1024.
-
OpenSearch Chinese text embedding 001 (ops-text-embedding-zh-001): Embeds Chinese text. Maximum input text length: 1024. Output vector dimension: 768.
-
OpenSearch English text embedding 001 (ops-text-embedding-en-001): Embeds English text. Maximum input text length: 512. Output vector dimension: 768.
Sparse text embedding
Converts text into sparse vector representations. Sparse vectors require less storage and capture keywords and term frequencies. Combine them with dense vectors for hybrid search to improve retrieval.
OpenSearch sparse text embedding (ops-text-sparse-embedding-001): Supports more than 100 languages. Maximum input text length: 8192.
-
After selecting the services, click After the configuration is completed, enter the code query to view and download the code. The following table describes the runtime flow of the data preprocessing pipeline.
|
Function |
Description |
|
Handles document processing, including document/image parsing, document chunking, and text embedding. |
The main function document_pipeline_execute performs the following process. You can provide the document as a URL or a Base64-encoded file.
|
Under Code Query, select Document Parsing and Vectorization. Click Copy Code or Download File to save the code locally.
Step 2: Configure environment and test pipeline
Configure the following parameters after downloading the code.
|
Category |
Parameter |
Description |
|
AI Search Open Platform |
api_key |
The API key for authentication. Manage API keys. |
|
aisearch_endpoint |
The API endpoint. Obtain a service endpoint. Note
Remove the http:// prefix. You can call the API over the Internet or through a VPC. |
|
|
workspace_name |
The name of your workspace in AI Search Open Platform. |
|
|
service_id |
The service ID. For convenience, configure the services and their IDs with service_id_config.
|
Run the code in Python 3.8.1 or later to verify the results.
Sample output from preprocessing the Introduction to AI Search Open Platform document:
C:\Users\issuser\PycharmProjects\pythonProject630Demo\.venv\Scripts\python.exe C:\Users\issuser\PycharmProjects\pythonProject3\.venv\Lib\site-packages\alibabacloud_searchplat2...
document_analyze task_id:f6dd92de-01e4-46a2-96c4-b80e7b120239
document_analyze done
document-split done, chunks count: 6 rich text count:9
image analyze :https://img.alicdn.com/imgextra/i2/O1CN01bYc1m81RrcSAyOjMu_!!6000000002165-54-tps-60-60.apng
https://img.alicdn.com/imgextra/i2/O1CN01bYc1m81RrcSAyOjMu_!!6000000002165-54-tps-60-60.apng is unanalysable.
image analyze :https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/3873436171/p802381.png
image analyze :https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/0517992271/p821030.png
image analyze ://gw.alicdn.com/tfs/TB16xwdSXXXXXa.aXXXXXXXXXXX-65-70.gif
https://gw.alicdn.com/tfs/TB16xwdSXXXXXa.aXXXXXXXXXXX-65-70.gif is unanalysable.
image analyze ://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png
image analyze :https://img.alicdn.com/tfs/TB1UdKEM6TpK1RjSZKPXXa3UpXa-256-256.png
image analyze :https://img.alicdn.com/tfs/TB1A0dINW6qK1RjSZFmXXX0PFXa-258-258.jpg
image analyze ://gw.alicdn.com/tfs/TB16xwdSXXXXXa.aXXXXXXXXXXX-65-70.gif
https://gw.alicdn.com/tfs/TB16xwdSXXXXXa.aXXXXXXXXXXX-65-70.gif is unanalysable.
image analyze ://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png
text-embedding done.
Process finished with exit code 0
Complete pipeline code:
# Multimodal data processing pipeline
# Environment requirements:
# Python version: 3.7 or later
# Package requirements:
# pip install alibabacloud_searchplat20240529
# AI Search Open Platform settings
aisearch_endpoint = "xxx.platform-cn-shanghai.opensearch.aliyuncs.com"
api_key = "OS-xxx"
workspace_name = "default"
service_id_config = {"document_analyze": "ops-document-analyze-001",
"split": "ops-document-split-001",
"text_embedding": "ops-text-embedding-001",
"text_sparse_embedding": "ops-text-sparse-embedding-001",
"image_analyze": "ops-image-analyze-ocr-001"}
# Input document URL. This example uses the OpenSearch product description document.
document_url = "https://help.aliyun.com/zh/open-search/search-platform/product-overview/introduction-to-search-platform?spm=a2c4g.11186623.0.0.7ab93526WDzQ8z"
import asyncio
from operator import attrgetter
from typing import List
from Tea.exceptions import TeaException, RetryError
from alibabacloud_tea_openapi.models import Config
from alibabacloud_searchplat20240529.client import Client
from alibabacloud_searchplat20240529.models import GetDocumentSplitRequest, CreateDocumentAnalyzeTaskRequest, \
CreateDocumentAnalyzeTaskRequestDocument, GetDocumentAnalyzeTaskStatusRequest, \
GetDocumentSplitRequestDocument, GetTextEmbeddingRequest, GetTextEmbeddingResponseBodyResultEmbeddings, \
GetTextSparseEmbeddingRequest, GetTextSparseEmbeddingResponseBodyResultSparseEmbeddings, \
GetImageAnalyzeTaskStatusResponse, CreateImageAnalyzeTaskRequest, GetImageAnalyzeTaskStatusRequest, \
CreateImageAnalyzeTaskRequestDocument, CreateImageAnalyzeTaskResponse
async def poll_doc_analyze_task_result(ops_client, task_id, service_id, interval=5):
while True:
request = GetDocumentAnalyzeTaskStatusRequest(task_id=task_id)
response = await ops_client.get_document_analyze_task_status_async(workspace_name, service_id, request)
status = response.body.result.status
if status == "PENDING":
await asyncio.sleep(interval)
elif status == "SUCCESS":
return response
else:
print("error: " + response.body.result.error)
raise Exception("document analyze task failed")
def is_analyzable_url(url:str):
if not url:
return False
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'}
return url.lower().endswith(tuple(image_extensions))
async def image_analyze(ops_client, url):
try:
print("image analyze :" + url)
if url.startswith("//"):
url = "https:" + url
if not is_analyzable_url(url):
print(url + " is unanalysable.")
return url
image_analyze_service_id = service_id_config["image_analyze"]
document = CreateImageAnalyzeTaskRequestDocument(
url=url,
)
request = CreateImageAnalyzeTaskRequest(document=document)
response: CreateImageAnalyzeTaskResponse = ops_client.create_image_analyze_task(workspace_name, image_analyze_service_id, request)
task_id = response.body.result.task_id
while True:
request = GetImageAnalyzeTaskStatusRequest(task_id=task_id)
response: GetImageAnalyzeTaskStatusResponse = ops_client.get_image_analyze_task_status(workspace_name, image_analyze_service_id, request)
status = response.body.result.status
if status == "PENDING":
await asyncio.sleep(5)
elif status == "SUCCESS":
return url + response.body.result.data.content
else:
print("image analyze error: " + response.body.result.error)
return url
except Exception as e:
print(f"image analyze Exception : {e}")
def chunk_list(lst, chunk_size):
for i in range(0, len(lst), chunk_size):
yield lst[i:i + chunk_size]
async def document_pipeline_execute(document_url: str = None, document_base64: str = None, file_name: str = None):
# Create an OpenSearch platform client
config = Config(bearer_token=api_key,endpoint=aisearch_endpoint,protocol="http")
ops_client = Client(config=config)
# Step 1: Document/image parsing
document_analyze_request = CreateDocumentAnalyzeTaskRequest(document=CreateDocumentAnalyzeTaskRequestDocument(url=document_url, content=document_base64,file_name=file_name, file_type='html'))
document_analyze_response = await ops_client.create_document_analyze_task_async(workspace_name=workspace_name,service_id=service_id_config["document_analyze"],request=document_analyze_request)
print("document_analyze task_id:" + document_analyze_response.body.result.task_id)
extraction_result = await poll_doc_analyze_task_result(ops_client, document_analyze_response.body.result.task_id, service_id_config["document_analyze"])
print("document_analyze done")
document_content = extraction_result.body.result.data.content
content_type = extraction_result.body.result.data.content_type
# Step 2: Document chunking
document_split_request = GetDocumentSplitRequest(
GetDocumentSplitRequestDocument(content=document_content, content_type=content_type))
document_split_result = await ops_client.get_document_split_async(workspace_name, service_id_config["split"],
document_split_request)
print("document-split done, chunks count: " + str(len(document_split_result.body.result.chunks))
+ " rich text count:" + str(len(document_split_result.body.result.rich_texts)))
# Step 3: Text embedding
# Extract the chunks. Text is extracted from image chunks by the image parsing service.
doc_list = ([{"id": chunk.meta.get("id"), "content": chunk.content} for chunk in document_split_result.body.result.chunks]
+ [{"id": chunk.meta.get("id"), "content": chunk.content} for chunk in document_split_result.body.result.rich_texts if chunk.meta.get("type") != "image"]
+ [{"id": chunk.meta.get("id"), "content": await image_analyze(ops_client,chunk.content)} for chunk in document_split_result.body.result.rich_texts if chunk.meta.get("type") == "image"]
)
chunk_size = 32 # A maximum of 32 embeddings per call
all_text_embeddings: List[GetTextEmbeddingResponseBodyResultEmbeddings] = []
for chunk in chunk_list([text["content"] for text in doc_list], chunk_size):
response = await ops_client.get_text_embedding_async(workspace_name,service_id_config["text_embedding"],GetTextEmbeddingRequest(chunk))
all_text_embeddings.extend(response.body.result.embeddings)
all_text_sparse_embeddings: List[GetTextSparseEmbeddingResponseBodyResultSparseEmbeddings] = []
for chunk in chunk_list([text["content"] for text in doc_list], chunk_size):
response = await ops_client.get_text_sparse_embedding_async(workspace_name,service_id_config["text_sparse_embedding"],GetTextSparseEmbeddingRequest(chunk,input_type="document",return_token=True))
all_text_sparse_embeddings.extend(response.body.result.sparse_embeddings)
for i in range(len(doc_list)):
doc_list[i]["embedding"] = all_text_embeddings[i].embedding
doc_list[i]["sparse_embedding"] = all_text_sparse_embeddings[i].embedding
print("text-embedding done.")
if __name__ == "__main__":
# Run the asynchronous task
# import nest_asyncio # Uncomment these two lines when running in a Jupyter notebook
# nest_asyncio.apply() # Uncomment these two lines when running in a Jupyter notebook
asyncio.run(document_pipeline_execute(document_url))
# asyncio.run(document_pipeline_execute(document_base64="eHh4eHh4eHg...", file_name="attention.pdf")) #Alternative call