feat: Make OCR and task concurrency configurable

This commit is contained in:
begoniezhao
2026-01-15 10:42:48 +08:00
parent 928d1c3d44
commit 1abdaa5d5c
5 changed files with 49 additions and 35 deletions
+7
View File
@@ -82,6 +82,13 @@ JWT_SECRET=weknora-jwt-secret
# Embedding并发数,出现429错误时,可调小此参数 # Embedding并发数,出现429错误时,可调小此参数
CONCURRENCY_POOL_SIZE=5 CONCURRENCY_POOL_SIZE=5
# Docreader 并发任务数(图片OCR/Caption等异步任务),默认 1
# 默认使用的 paddleocr 在高并发场景下,会出现异常,请谨慎设置
# IMAGE_MAX_CONCURRENT=1
# Docreader OCR后端(no_ocr, paddle, nanonets)
# OCR_BACKEND=paddle
# 如果使用ElasticSearch作为向量存储,需要配置以下参数 # 如果使用ElasticSearch作为向量存储,需要配置以下参数
# ElasticSearch地址,例如 http://localhost:9200 # ElasticSearch地址,例如 http://localhost:9200
# ELASTICSEARCH_ADDR=your_elasticsearch_addr # ELASTICSEARCH_ADDR=your_elasticsearch_addr
+2
View File
@@ -120,6 +120,8 @@ services:
- WEB_PROXY=${WEB_PROXY:-} - WEB_PROXY=${WEB_PROXY:-}
# File size limit (in MB) # File size limit (in MB)
- MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50} - MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50}
- IMAGE_MAX_CONCURRENT=${IMAGE_MAX_CONCURRENT:-1}
- OCR_BACKEND=${OCR_BACKEND:-paddle}
healthcheck: healthcheck:
test: ["CMD", "grpc_health_probe", "-addr=:50051"] test: ["CMD", "grpc_health_probe", "-addr=:50051"]
interval: 30s interval: 30s
+2
View File
@@ -148,6 +148,8 @@ services:
- MINERU_ENDPOINT=${MINERU_ENDPOINT:-} - MINERU_ENDPOINT=${MINERU_ENDPOINT:-}
# File size limit (in MB) # File size limit (in MB)
- MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50} - MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50}
- IMAGE_MAX_CONCURRENT=${IMAGE_MAX_CONCURRENT:-1}
- OCR_BACKEND=${OCR_BACKEND:-paddle}
healthcheck: healthcheck:
test: ["CMD", "grpc_health_probe", "-addr=:50051"] test: ["CMD", "grpc_health_probe", "-addr=:50051"]
interval: 30s interval: 30s
+25 -25
View File
@@ -46,7 +46,7 @@ class BaseParser(ABC):
parsed_url = urlparse(url) parsed_url = urlparse(url)
# Only allow http and https schemes # Only allow http and https schemes
if parsed_url.scheme not in ['http', 'https']: if parsed_url.scheme not in ["http", "https"]:
logger.warning(f"Rejected URL with invalid scheme: {parsed_url.scheme}") logger.warning(f"Rejected URL with invalid scheme: {parsed_url.scheme}")
return False return False
@@ -60,9 +60,13 @@ class BaseParser(ABC):
try: try:
ip = ipaddress.ip_address(hostname) ip = ipaddress.ip_address(hostname)
# Reject private, loopback, link-local, multicast addresses # Reject private, loopback, link-local, multicast addresses
if (ip.is_private or ip.is_loopback or if (
ip.is_link_local or ip.is_multicast or ip.is_private
ip.is_reserved): or ip.is_loopback
or ip.is_link_local
or ip.is_multicast
or ip.is_reserved
):
logger.warning(f"Rejected URL with restricted IP: {ip}") logger.warning(f"Rejected URL with restricted IP: {ip}")
return False return False
except ValueError: except ValueError:
@@ -70,14 +74,16 @@ class BaseParser(ABC):
# Reject localhost and common internal hostnames # Reject localhost and common internal hostnames
hostname_lower = hostname.lower() hostname_lower = hostname.lower()
restricted_hostnames = [ restricted_hostnames = [
'localhost', "localhost",
'127.0.0.1', "127.0.0.1",
'::1', "::1",
'metadata.google.internal', "metadata.google.internal",
'metadata.tencentyun.com', "metadata.tencentyun.com",
'169.254.169.254', # AWS metadata endpoint "169.254.169.254", # AWS metadata endpoint
] ]
if hostname_lower in restricted_hostnames or hostname_lower.endswith('.local'): if hostname_lower in restricted_hostnames or hostname_lower.endswith(
".local"
):
logger.warning(f"Rejected URL with restricted hostname: {hostname}") logger.warning(f"Rejected URL with restricted hostname: {hostname}")
return False return False
@@ -121,7 +127,7 @@ class BaseParser(ABC):
chunk_size: int = 1000, chunk_size: int = 1000,
chunk_overlap: int = 200, chunk_overlap: int = 200,
separators: list[str] = ["\n\n", "\n", "。"], separators: list[str] = ["\n\n", "\n", "。"],
ocr_backend: str = "paddle", ocr_backend: str = "no_ocr",
ocr_config: dict = {}, ocr_config: dict = {},
max_image_size: int = 1920, # Maximum image size max_image_size: int = 1920, # Maximum image size
max_concurrent_tasks: int = 5, # Max concurrent tasks max_concurrent_tasks: int = 5, # Max concurrent tasks
@@ -151,7 +157,7 @@ class BaseParser(ABC):
self.chunk_size = chunk_size self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap self.chunk_overlap = chunk_overlap
self.separators = separators self.separators = separators
self.ocr_backend = os.getenv("OCR_BACKEND", ocr_backend) self.ocr_backend = ocr_backend
self.ocr_config = ocr_config self.ocr_config = ocr_config
self.max_image_size = max_image_size self.max_image_size = max_image_size
self.max_concurrent_tasks = max_concurrent_tasks self.max_concurrent_tasks = max_concurrent_tasks
@@ -161,13 +167,14 @@ class BaseParser(ABC):
self.chunking_config.storage_config if self.chunking_config else None self.chunking_config.storage_config if self.chunking_config else None
) )
logger.info(f"Initializing parser for file: {file_name}, type: {file_type}")
logger.info( logger.info(
f"Parser config: chunk_size={chunk_size}, " f"Initializing parser for file={file_name}, type={file_type}, "
f"parser config: chunk_size={chunk_size}, "
f"overlap={chunk_overlap}, " f"overlap={chunk_overlap}, "
f"multimodal={enable_multimodal}, " f"multimodal={enable_multimodal}, "
f"max_chunks={max_chunks}, "
f"ocr_backend={ocr_backend}, " f"ocr_backend={ocr_backend}, "
f"max_chunks={max_chunks}" f"max_concurrent_tasks={max_concurrent_tasks}"
) )
# Only initialize Caption service if multimodal is enabled # Only initialize Caption service if multimodal is enabled
vlm_config = self.chunking_config.vlm_config if self.chunking_config else None vlm_config = self.chunking_config.vlm_config if self.chunking_config else None
@@ -305,13 +312,8 @@ class BaseParser(ABC):
logger.warning("No image data to process") logger.warning("No image data to process")
return [] return []
# Set max concurrency, reduce concurrency to avoid resource contention
max_concurrency = min(
self.max_concurrent_tasks, 1
) # Reduce concurrency to prevent excessive memory usage
# Use semaphore to limit concurrency # Use semaphore to limit concurrency
semaphore = asyncio.Semaphore(max_concurrency) semaphore = asyncio.Semaphore(self.max_concurrent_tasks)
# Store results to avoid overall failure due to task failure # Store results to avoid overall failure due to task failure
results = [] results = []
@@ -952,10 +954,8 @@ class BaseParser(ABC):
# Create and run all Chunk concurrent processing tasks # Create and run all Chunk concurrent processing tasks
async def process_all_chunks(): async def process_all_chunks():
# Set max concurrency, reduce concurrency to avoid resource contention
max_concurrency = min(self.max_concurrent_tasks, 1) # Reduce concurrency
# Use semaphore to limit concurrency # Use semaphore to limit concurrency
semaphore = asyncio.Semaphore(max_concurrency) semaphore = asyncio.Semaphore(self.max_concurrent_tasks)
async def process_with_limit(chunk, idx, total): async def process_with_limit(chunk, idx, total):
"""Use semaphore to control concurrent processing of Chunks""" """Use semaphore to control concurrent processing of Chunks"""
+5 -2
View File
@@ -1,4 +1,5 @@
import logging import logging
import os
from typing import Dict, Type from typing import Dict, Type
from docreader.models.document import Document from docreader.models.document import Document
@@ -109,8 +110,9 @@ class Parser:
separators=config.separators, # Text separators for chunking separators=config.separators, # Text separators for chunking
enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing
max_image_size=1920, # Limit image size to 1920px for performance max_image_size=1920, # Limit image size to 1920px for performance
max_concurrent_tasks=5, # Limit concurrent tasks to 5 to avoid resource exhaustion
chunking_config=config, # Pass the entire chunking config for advanced options chunking_config=config, # Pass the entire chunking config for advanced options
max_concurrent_tasks=int(os.getenv("IMAGE_MAX_CONCURRENT", "1")),
ocr_backend=os.getenv("OCR_BACKEND", "paddle"),
) )
logger.info(f"Starting to parse file content, size: {len(content)} bytes") logger.info(f"Starting to parse file content, size: {len(content)} bytes")
@@ -155,8 +157,9 @@ class Parser:
separators=config.separators, # Text separators for chunking separators=config.separators, # Text separators for chunking
enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing enable_multimodal=config.enable_multimodal, # Enable image/multimodal processing
max_image_size=1920, # Limit image size to 1920px for performance max_image_size=1920, # Limit image size to 1920px for performance
max_concurrent_tasks=5, # Limit concurrent tasks to avoid resource exhaustion
chunking_config=config, # Pass the entire chunking config chunking_config=config, # Pass the entire chunking config
max_concurrent_tasks=int(os.getenv("IMAGE_MAX_CONCURRENT", "1")),
ocr_backend=os.getenv("OCR_BACKEND", "paddle"),
) )
logger.info("Starting to parse URL content") logger.info("Starting to parse URL content")