Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat: support minio storage

wizardchen8b4393188655
diff --git a/.env.example b/.env.example
index 6879932d9..a321117ae 100644
--- a/.env.example
+++ b/.env.example
@@ -7,8 +7,7 @@
# 可选值: debug(开发模式,有详细日志), release(生产模式)
GIN_MODE=debug
-# ollama
-# Ollama 服务的基准 URL,用于连接本地运行的 Ollama LLM 服务
+# Ollama 服务的基准 URL,用于连接本地/其他服务器上运行的 Ollama 服务
OLLAMA_BASE_URL=http://host.docker.internal:11435
# 存储配置
@@ -25,9 +24,6 @@ STORAGE_TYPE=local
STREAM_MANAGER_TYPE=redis
# 主数据库配置
-# 数据库地址,可以是主机名或IP地址
-DB_HOST=postgres
-
# 数据库端口,默认为5432
DB_PORT=5432
@@ -41,9 +37,6 @@ DB_PASSWORD=postgres123!@#
DB_NAME=WeKnora
# 如果使用 redis 作为流处理后端,需要配置以下参数
-# Redis地址,可以是主机名或IP地址
-REDIS_HOST=redis
-
# Redis端口,默认为6379
REDIS_PORT=6379
@@ -64,6 +57,10 @@ TENANT_AES_KEY=weknorarag-api-key-secret-secret
# 是否开启知识图谱构建和检索(构建阶段需调用大模型,耗时较长)
ENABLE_GRAPH_RAG=false
+MINIO_PORT=9000
+
+MINIO_CONSOLE_PORT=9001
+
# 如果使用ElasticSearch作为向量存储,需要配置以下参数
# ElasticSearch地址,例如 http://localhost:9200
# ELASTICSEARCH_ADDR=your_elasticsearch_addr
@@ -78,9 +75,6 @@ ENABLE_GRAPH_RAG=false
# ELASTICSEARCH_INDEX=WeKnora
# 如果使用MinIO作为文件存储,需要配置以下参数
-# MinIO服务器地址,例如 minio:9000
-# MINIO_ENDPOINT=minio:9000
-
# MinIO访问密钥
# MINIO_ACCESS_KEY_ID=your_minio_access_key
diff --git a/Makefile b/Makefile
index 3ddc72463..609f8d678 100644
--- a/Makefile
+++ b/Makefile
@@ -90,5 +90,11 @@ clean-db:
@if [ $$(docker volume ls -q -f name=weknora_postgres-data) ]; then \
docker volume rm weknora_postgres-data; \
fi
+ @if [ $$(docker volume ls -q -f name=weknora_minio_data) ]; then \
+ docker volume rm weknora_minio_data; \
+ fi
+ @if [ $$(docker volume ls -q -f name=weknora_redis_data) ]; then \
+ docker volume rm weknora_redis_data; \
+ fi
diff --git a/docker-compose.yml b/docker-compose.yml
index 420582bc8..8edce0d61 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,5 +1,3 @@
-version: "3.8"
-
services:
app:
build:
@@ -13,9 +11,9 @@ services:
- ./config:/app/config
environment:
- GIN_MODE=${GIN_MODE}
- - DB_DRIVER=${DB_DRIVER}
- - DB_HOST=${DB_HOST}
- - DB_PORT=${DB_PORT}
+ - DB_DRIVER=postgres
+ - DB_HOST=postgres
+ - DB_PORT=5432
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
- DB_NAME=${DB_NAME}
@@ -34,13 +32,13 @@ services:
- DOCREADER_ADDR=docreader:50051
- STORAGE_TYPE=${STORAGE_TYPE}
- LOCAL_STORAGE_BASE_DIR=${LOCAL_STORAGE_BASE_DIR}
- - MINIO_ENDPOINT=${MINIO_ENDPOINT}
- - MINIO_ACCESS_KEY_ID=${MINIO_ACCESS_KEY_ID}
- - MINIO_SECRET_ACCESS_KEY=${MINIO_SECRET_ACCESS_KEY}
+ - MINIO_ENDPOINT=minio:9000
+ - MINIO_ACCESS_KEY_ID=${MINIO_ACCESS_KEY_ID:-minioadmin}
+ - MINIO_SECRET_ACCESS_KEY=${MINIO_SECRET_ACCESS_KEY:-minioadmin}
- MINIO_BUCKET_NAME=${MINIO_BUCKET_NAME}
- - OLLAMA_BASE_URL=${OLLAMA_BASE_URL}
+ - OLLAMA_BASE_URL=${OLLAMA_BASE_URL:-http://host.docker.internal:11434}
- STREAM_MANAGER_TYPE=${STREAM_MANAGER_TYPE}
- - REDIS_ADDR=${REDIS_HOST}:${REDIS_PORT}
+ - REDIS_ADDR=redis:6379
- REDIS_PASSWORD=${REDIS_PASSWORD}
- REDIS_DB=${REDIS_DB}
- REDIS_PREFIX=${REDIS_PREFIX}
@@ -57,19 +55,39 @@ services:
- INIT_RERANK_MODEL_NAME=${INIT_RERANK_MODEL_NAME}
- INIT_RERANK_MODEL_BASE_URL=${INIT_RERANK_MODEL_BASE_URL}
- INIT_RERANK_MODEL_API_KEY=${INIT_RERANK_MODEL_API_KEY}
- - INIT_TEST_TENANT_ID=${INIT_TEST_TENANT_ID}
- - INIT_TEST_KNOWLEDGE_BASE_ID=${INIT_TEST_KNOWLEDGE_BASE_ID}
depends_on:
redis:
condition: service_started
postgres:
condition: service_healthy
+ minio:
+ condition: service_started
networks:
- WeKnora-network
restart: unless-stopped
extra_hosts:
- "host.docker.internal:host-gateway"
+ minio:
+ image: minio/minio:latest
+ container_name: WeKnora-minio
+ ports:
+ - "${MINIO_PORT:-9000}:9000"
+ - "${MINIO_CONSOLE_PORT:-9001}:9001"
+ environment:
+ - MINIO_ROOT_USER=${MINIO_ACCESS_KEY_ID:-minioadmin}
+ - MINIO_ROOT_PASSWORD=${MINIO_SECRET_ACCESS_KEY:-minioadmin}
+ command: server --console-address ":9001" /data
+ volumes:
+ - minio_data:/data
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
+ interval: 30s
+ timeout: 20s
+ retries: 3
+ networks:
+ - WeKnora-network
+
frontend:
build:
context: ./frontend
@@ -103,6 +121,13 @@ services:
- VLM_MODEL_BASE_URL=${VLM_MODEL_BASE_URL}
- VLM_MODEL_NAME=${VLM_MODEL_NAME}
- VLM_MODEL_API_KEY=${VLM_MODEL_API_KEY}
+ - STORAGE_TYPE=${STORAGE_TYPE}
+ - MINIO_PUBLIC_ENDPOINT=http://localhost:${MINIO_PORT:-9000}
+ - MINIO_ENDPOINT=minio:9000
+ - MINIO_ACCESS_KEY_ID=${MINIO_ACCESS_KEY_ID:-minioadmin}
+ - MINIO_SECRET_ACCESS_KEY=${MINIO_SECRET_ACCESS_KEY:-minioadmin}
+ - MINIO_BUCKET_NAME=${MINIO_BUCKET_NAME}
+ - MINIO_USE_SSL=${MINIO_USE_SSL}
networks:
- WeKnora-network
restart: unless-stopped
@@ -175,3 +200,4 @@ volumes:
data-files:
jaeger_data:
redis_data:
+ minio_data:
diff --git a/docker/Dockerfile.docreader b/docker/Dockerfile.docreader
index cbe79e898..5330b3662 100644
--- a/docker/Dockerfile.docreader
+++ b/docker/Dockerfile.docreader
@@ -99,8 +99,8 @@ RUN mkdir -p /tmp/libreoffice && \
cd LibreOffice_25.2.4*_Linux_x86-64_deb/DEBS && \
dpkg -i *.deb; \
elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then \
- wget -q https://mirrors.tuna.tsinghua.edu.cn/libreoffice/libreoffice/testing/25.8.0/deb/aarch64/LibreOffice_25.8.0.2_Linux_aarch64_deb.tar.gz && \
- tar -xzf LibreOffice_25.8.0.2_Linux_aarch64_deb.tar.gz && \
+ wget -q https://mirrors.aliyun.com/libreoffice/testing/25.8.0/deb/aarch64/LibreOffice_25.8.0.3_Linux_aarch64_deb.tar.gz && \
+ tar -xzf LibreOffice_25.8.0.3_Linux_aarch64_deb.tar.gz && \
cd LibreOffice_25.8.0*_Linux_aarch64_deb/DEBS && \
dpkg -i *.deb; \
else \
diff --git a/frontend/src/api/initialization/index.ts b/frontend/src/api/initialization/index.ts
index 875179be3..ee0d7a5ac 100644
--- a/frontend/src/api/initialization/index.ts
+++ b/frontend/src/api/initialization/index.ts
@@ -22,6 +22,7 @@ export interface InitializationConfig {
};
multimodal: {
enabled: boolean;
+ storageType: 'cos' | 'minio';
vlm?: {
modelName: string;
baseUrl: string;
@@ -36,12 +37,18 @@ export interface InitializationConfig {
appId: string;
pathPrefix?: string;
};
+ minio?: {
+ bucketName: string;
+ pathPrefix?: string;
+ };
};
documentSplitting: {
chunkSize: number;
chunkOverlap: number;
separators: string[];
};
+ // Frontend-only hint for storage selection UI
+ storageType?: 'cos' | 'minio';
}
// 下载任务状态类型
@@ -88,7 +95,7 @@ export function initializeSystem(config: InitializationConfig): Promise<any> {
}
// 检查Ollama服务状态
-export function checkOllamaStatus(): Promise<{ available: boolean; version?: string; error?: string }> {
+export function checkOllamaStatus(): Promise<{ available: boolean; version?: string; error?: string; baseUrl?: string }> {
return new Promise((resolve, reject) => {
get('/api/v1/initialization/ollama/status')
.then((response: any) => {
@@ -101,6 +108,20 @@ export function checkOllamaStatus(): Promise<{ available: boolean; version?: str
});
}
+// 列出已安装的 Ollama 模型
+export function listOllamaModels(): Promise<string[]> {
+ return new Promise((resolve, reject) => {
+ get('/api/v1/initialization/ollama/models')
+ .then((response: any) => {
+ resolve((response.data && response.data.models) || []);
+ })
+ .catch((error: any) => {
+ console.error('获取 Ollama 模型列表失败:', error);
+ resolve([]);
+ });
+ });
+}
+
// 检查Ollama模型状态
export function checkOllamaModels(models: string[]): Promise<{ models: Record<string, boolean> }> {
return new Promise((resolve, reject) => {
@@ -218,12 +239,17 @@ export function testMultimodalFunction(testData: {
vlm_base_url: string;
vlm_api_key?: string;
vlm_interface_type?: string;
- cos_secret_id: string;
- cos_secret_key: string;
- cos_region: string;
- cos_bucket_name: string;
- cos_app_id: string;
+ storage_type?: 'cos'|'minio';
+ // COS optional fields (required only when storage_type === 'cos')
+ cos_secret_id?: string;
+ cos_secret_key?: string;
+ cos_region?: string;
+ cos_bucket_name?: string;
+ cos_app_id?: string;
cos_path_prefix?: string;
+ // MinIO optional fields
+ minio_bucket_name?: string;
+ minio_path_prefix?: string;
chunk_size: number;
chunk_overlap: number;
separators: string[];
@@ -245,14 +271,21 @@ export function testMultimodalFunction(testData: {
if (testData.vlm_interface_type) {
formData.append('vlm_interface_type', testData.vlm_interface_type);
}
- formData.append('cos_secret_id', testData.cos_secret_id);
- formData.append('cos_secret_key', testData.cos_secret_key);
- formData.append('cos_region', testData.cos_region);
- formData.append('cos_bucket_name', testData.cos_bucket_name);
- formData.append('cos_app_id', testData.cos_app_id);
- if (testData.cos_path_prefix) {
- formData.append('cos_path_prefix', testData.cos_path_prefix);
+ if (testData.storage_type) {
+ formData.append('storage_type', testData.storage_type);
+ }
+ // Append COS fields only when storage_type is COS
+ if (testData.storage_type === 'cos') {
+ if (testData.cos_secret_id) formData.append('cos_secret_id', testData.cos_secret_id);
+ if (testData.cos_secret_key) formData.append('cos_secret_key', testData.cos_secret_key);
+ if (testData.cos_region) formData.append('cos_region', testData.cos_region);
+ if (testData.cos_bucket_name) formData.append('cos_bucket_name', testData.cos_bucket_name);
+ if (testData.cos_app_id) formData.append('cos_app_id', testData.cos_app_id);
+ if (testData.cos_path_prefix) formData.append('cos_path_prefix', testData.cos_path_prefix);
}
+ // MinIO fields
+ if (testData.minio_bucket_name) formData.append('minio_bucket_name', testData.minio_bucket_name);
+ if (testData.minio_path_prefix) formData.append('minio_path_prefix', testData.minio_path_prefix);
formData.append('chunk_size', testData.chunk_size.toString());
formData.append('chunk_overlap', testData.chunk_overlap.toString());
formData.append('separators', JSON.stringify(testData.separators));
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index 54badc88f..e2b71750f 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -158,7 +158,7 @@ function splitMarkdownByImages(markdown) {
function isLink(str) {
const trimmedStr = str.trim();
// 正则表达式匹配常见链接格式
- const urlPattern = /^(https?:\/\/|ftp:\/\/|www\.)[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/i;
+ const urlPattern = /^(https?:\/\/|ftp:\/\/|www\.)(?:(?:[\w-]+(?:\.[\w-]+)*)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:\[[a-fA-F0-9:]+\]))(?::\d{1,5})?(?:[\/\w.,@?^=%&:~+#-]*[\w@?^=%&\/~+#-])?/i;
return urlPattern.test(trimmedStr);
}
diff --git a/frontend/src/views/initialization/InitializationConfig.vue b/frontend/src/views/initialization/InitializationConfig.vue
index 4a2a71ee5..097021cfb 100644
--- a/frontend/src/views/initialization/InitializationConfig.vue
+++ b/frontend/src/views/initialization/InitializationConfig.vue
@@ -1,13 +1,57 @@
<template>
<div class="initialization-container">
+ <!-- 页面标题区域 -->
<div class="initialization-header">
<h1>WeKnora 系统初始化配置</h1>
<p>首次使用需要配置模型和服务信息,完成后即可开始使用系统</p>
</div>
+ <!-- 页面主体两栏布局:左侧导航 + 右侧内容 -->
+ <div class="init-layout">
+ <!-- 左侧导航 -->
+ <aside class="sidebar">
+ <div class="sidebar-card">
+ <div class="nav-title">配置导航</div>
+ <ul class="nav-list">
+ <li v-for="s in sections" :key="s.id" :class="['nav-item', { active: activeSectionId === s.id }]" @click="goToSection(s.id)">
+ <span class="dot" />{{ s.label }}
+ </li>
+ </ul>
+ </div>
+ </aside>
+ <div class="init-main">
+ <!-- 顶部公共区域:Ollama 服务状态与已安装模型 -->
+ <div class="ollama-summary-card" id="section-ollama">
+ <div class="summary-header">
+ <span class="title"><t-icon name="server" />Ollama 服务状态</span>
+ <t-tag :theme="ollamaStatus.available ? 'success' : 'danger'" size="small" class="state">
+ {{ ollamaStatus.available ? `正常 (${ollamaStatus.version||'v?'} )` : (ollamaStatus.error || '未运行') }}
+ </t-tag>
+ <t-tooltip content="刷新状态">
+ <t-icon name="refresh" class="refresh-icon" :class="{ spinning: summaryRefreshing }" @click="refreshOllamaSummary" />
+ </t-tooltip>
+ </div>
+ <div class="summary-body">
+ <div class="models">
+ <span class="label">Ollama 服务地址</span>
+ <div class="model-list">
+ <t-tag size="small" theme="default" class="model-pill">{{ ollamaStatus.baseUrl || '未配置' }}</t-tag>
+ </div>
+ </div>
+ <div class="models">
+ <span class="label">已安装模型</span>
+ <div class="model-list">
+ <t-tag v-for="m in installedModels" :key="m" size="small" theme="default" class="model-pill">{{ m }}</t-tag>
+ <span v-if="installedModels.length===0" class="empty">暂无</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 主配置表单 -->
<t-form ref="form" :data="formData" :rules="rules" @submit.prevent layout="vertical">
- <!-- LLM 模型配置 -->
- <div class="config-section">
+ <!-- LLM 大语言模型配置区域 -->
+ <div class="config-section" id="section-llm">
<h3><t-icon name="chat" class="section-icon" />LLM 大语言模型配置</h3>
<div class="form-row">
<t-form-item label="模型来源" name="llm.source">
@@ -20,63 +64,91 @@
<div class="form-row">
<t-form-item label="模型名称" name="llm.modelName">
- <t-input v-model="formData.llm.modelName" placeholder="例如: qwen3:0.6b"
- @blur="onModelNameChange('llm')"
- @input="onModelNameInput('llm')"
- @keyup.enter="onModelNameChange('llm')" />
- </t-form-item>
- </div>
-
- <!-- Ollama模型状态检查 -->
- <div v-if="formData.llm.source === 'local'" class="ollama-status">
- <div class="status-item">
- <div class="status-header">
- <span class="status-label">Ollama服务状态:</span>
- <t-tag v-if="ollamaStatus.checked" :theme="ollamaStatus.available ? 'success' : 'danger'">
- {{ ollamaStatus.available ? `运行中 (${ollamaStatus.version})` : '未运行' }}
- </t-tag>
- <t-tag v-else theme="default">检查中...</t-tag>
- <t-button v-if="!ollamaStatus.available && ollamaStatus.checked"
- theme="primary" variant="text" size="small" @click="checkOllama">
- 重新检查
- </t-button>
- </div>
- </div>
-
- <div v-if="formData.llm.modelName" class="status-item">
- <div class="status-header">
- <span class="status-label">LLM模型状态:</span>
- <t-tag v-if="modelStatus.llm.checked" :theme="modelStatus.llm.available ? 'success' : 'warning'">
- {{ modelStatus.llm.available ? '已安装' : '未安装' }}
- </t-tag>
- <t-tag v-else theme="default">检查中...</t-tag>
+ <div class="model-input-with-status">
+ <t-input v-model="formData.llm.modelName" placeholder="例如: qwen3:0.6b"
+ @blur="onModelNameChange('llm')"
+ @input="onModelNameInput('llm')"
+ @keyup.enter="onModelNameChange('llm')" />
+ <div class="model-status-icon">
+ <t-icon
+ v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.checked"
+ :name="modelStatus.llm.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.llm.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.llm.available ? '已安装' : '未安装'"
+ />
+ <t-icon
+ v-else-if="formData.llm.source === 'local' && formData.llm.modelName && !modelStatus.llm.checked"
+ name="help-circle"
+ class="status-icon unknown"
+ title="未检查"
+ />
+ <t-icon
+ v-else-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.downloading"
+ name="loading"
+ class="status-icon downloading spinning"
+ title="下载中"
+ />
+ </div>
+ <!-- 下载按钮:未安装时显示 -->
+ <div v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.checked && !modelStatus.llm.available && !modelStatus.llm.downloading" class="download-action">
+ <t-tooltip content="下载模型">
+ <t-button
+ size="small"
+ theme="primary"
+ @click="downloadModel('llm', formData.llm.modelName)"
+ class="download-btn"
+ :disabled="modelStatus.llm.downloading"
+ >
+ <t-icon name="download" />
+ </t-button>
+ </t-tooltip>
+ </div>
- <t-button v-if="!modelStatus.llm.available && modelStatus.llm.checked && ollamaStatus.available && !modelStatus.llm.downloading"
- theme="primary" size="small"
- @click="downloadModel('llm', formData.llm.modelName)">
- 下载模型
- </t-button>
</div>
-
- <!-- 下载进度显示 -->
- <div v-if="modelStatus.llm.downloading" class="download-progress">
- <t-progress
- :percentage="modelStatus.llm.progress"
- :label="false"
- size="small"
- status="active">
- </t-progress>
- <span class="progress-text">{{ modelStatus.llm.message }} ({{ modelStatus.llm.progress.toFixed(1) }}%)</span>
+ </t-form-item>
+
+ <!-- 下载进度:下载中时显示 -->
+ <div v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.downloading" class="download-progress">
+ <div class="progress-info">
+ <t-icon name="loading" class="loading-icon spinning" />
+ <span class="progress-text">下载中</span>
</div>
+ <t-progress :percentage="Number(modelStatus.llm.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
+ <div class="progress-message">{{ modelStatus.llm.message }}</div>
</div>
</div>
+ <!-- 远程 API 配置区域 -->
<div v-if="formData.llm.source === 'remote'" class="remote-config">
<div class="form-row">
<t-form-item label="Base URL" name="llm.baseUrl">
- <t-input v-model="formData.llm.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/chat/completions路径后的URL的前面部分"
- @blur="onRemoteConfigChange('llm')"
- @input="onRemoteConfigInput('llm')" />
+ <div class="url-input-with-check">
+ <t-input v-model="formData.llm.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/chat/completions路径后的URL的前面部分"
+ @blur="onRemoteConfigChange('llm')"
+ @input="onRemoteConfigInput('llm')" />
+ <div v-if="formData.llm.modelName && formData.llm.baseUrl" class="check-action">
+ <t-tooltip v-if="!modelStatus.llm.available && modelStatus.llm.checked" content="重新检查连接">
+ <t-icon
+ name="refresh"
+ class="refresh-icon"
+ :class="{ spinning: modelStatus.llm.checking }"
+ @click="checkRemoteModelStatus('llm')"
+ />
+ </t-tooltip>
+ <t-icon
+ v-else-if="modelStatus.llm.checked"
+ :name="modelStatus.llm.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.llm.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.llm.available ? '连接正常' : '连接失败'"
+ />
+ <t-icon
+ v-else
+ name="loading"
+ class="status-icon checking spinning"
+ title="检查连接中"
+ />
+ </div>
+ </div>
</t-form-item>
</div>
<div class="form-row">
@@ -87,37 +159,21 @@
</t-form-item>
</div>
- <!-- Remote API模型状态检查 -->
- <div v-if="formData.llm.modelName && formData.llm.baseUrl" class="remote-status">
- <t-tag v-if="modelStatus.llm.checked" :theme="modelStatus.llm.available ? 'success' : 'danger'" size="small">
- <t-icon :name="modelStatus.llm.available ? 'check-circle' : 'close-circle'" />
- {{ modelStatus.llm.available ? '连接正常' : '连接失败' }}
- </t-tag>
- <t-tag v-else theme="default" size="small">
- <t-icon name="loading" />
- 检查连接中...
- </t-tag>
-
- <t-button v-if="!modelStatus.llm.available && modelStatus.llm.checked"
- theme="primary" variant="text" size="small"
- @click="checkRemoteModelStatus('llm')">
- 重新检查
- </t-button>
-
- <div v-if="modelStatus.llm.checked && !modelStatus.llm.available && modelStatus.llm.message"
- class="error-message">
- <t-icon name="error-circle" />
- {{ modelStatus.llm.message }}
- </div>
+ <!-- 错误信息显示 -->
+ <div v-if="modelStatus.llm.checked && !modelStatus.llm.available && modelStatus.llm.message" class="error-message">
+ <t-icon name="error-circle" />
+ <span>{{ modelStatus.llm.message }}</span>
</div>
+
+
</div>
</div>
- <!-- Embedding 模型配置 -->
- <div class="config-section">
+ <!-- Embedding 嵌入模型配置区域 -->
+ <div class="config-section" id="section-embedding">
<h3><t-icon name="layers" class="section-icon" />Embedding 嵌入模型配置</h3>
- <!-- 禁用提示 -->
+ <!-- 已有文件时的禁用提示 -->
<div v-if="hasFiles" class="embedding-warning">
<t-alert theme="warning" message="知识库中已有文件,无法修改Embedding模型配置" />
</div>
@@ -133,45 +189,53 @@
<div class="form-row">
<t-form-item label="模型名称" name="embedding.modelName">
- <t-input v-model="formData.embedding.modelName" placeholder="例如: nomic-embed-text:latest"
- @blur="onModelNameChange('embedding')"
- @input="onModelNameInput('embedding')"
- @keyup.enter="onModelNameChange('embedding')"
- :disabled="hasFiles" />
- </t-form-item>
- </div>
-
- <!-- Ollama模型状态检查 -->
- <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName" class="ollama-status">
- <div class="status-item">
- <div class="status-header">
- <span class="status-label">Embedding模型状态:</span>
- <t-tag v-if="modelStatus.embedding.checked" :theme="modelStatus.embedding.available ? 'success' : 'warning'">
- {{ modelStatus.embedding.available ? '已安装' : '未安装' }}
- </t-tag>
- <t-tag v-else theme="default">检查中...</t-tag>
+ <div class="model-input-with-status">
+ <t-input v-model="formData.embedding.modelName" placeholder="例如: nomic-embed-text:latest"
+ @blur="onModelNameChange('embedding')"
+ @input="onModelNameInput('embedding')"
+ @keyup.enter="onModelNameChange('embedding')"
+ :disabled="hasFiles" />
+ <div class="model-status-icon">
+ <t-icon
+ v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.checked"
+ :name="modelStatus.embedding.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.embedding.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.embedding.available ? '已安装' : '未安装'"
+ />
+ <t-icon
+ v-else-if="formData.embedding.source === 'local' && formData.embedding.modelName && !modelStatus.embedding.checked"
+ name="help-circle"
+ class="status-icon unknown"
+ title="未检查"
+ />
+ <t-icon
+ v-else-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.downloading"
+ name="loading"
+ class="status-icon downloading spinning"
+ title="下载中"
+ />
+ </div>
+ <!-- 下载按钮:未安装时显示 -->
+ <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.checked && !modelStatus.embedding.available && !modelStatus.embedding.downloading" class="download-action">
+ <t-tooltip content="下载模型">
+ <t-button
+ size="small"
+ theme="primary"
+ @click="downloadModel('embedding', formData.embedding.modelName)"
+ class="download-btn"
+ :disabled="modelStatus.embedding.downloading"
+ >
+ <t-icon name="download" />
+ </t-button>
+ </t-tooltip>
+ </div>
- <t-button v-if="!modelStatus.embedding.available && modelStatus.embedding.checked && ollamaStatus.available && !modelStatus.embedding.downloading"
- theme="primary" size="small"
- @click="downloadModel('embedding', formData.embedding.modelName)">
- 下载模型
- </t-button>
- </div>
-
- <!-- 下载进度显示 -->
- <div v-if="modelStatus.embedding.downloading" class="download-progress">
- <t-progress
- :percentage="modelStatus.embedding.progress"
- :label="false"
- size="small"
- status="active">
- </t-progress>
- <span class="progress-text">{{ modelStatus.embedding.message }} ({{ modelStatus.embedding.progress.toFixed(1) }}%)</span>
</div>
- </div>
+ </t-form-item>
+
</div>
- <!-- 维度设置 -->
+ <!-- 向量维度设置 -->
<div class="form-row">
<t-form-item label="维度" name="embedding.dimension">
<t-input v-model="formData.embedding.dimension"
@@ -180,14 +244,49 @@
style="width: 100px;"
@input="onDimensionInput" />
</t-form-item>
+
+ <!-- 下载进度:下载中时显示 -->
+ <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.downloading" class="download-progress">
+ <div class="progress-info">
+ <t-icon name="loading" class="loading-icon spinning" />
+ <span class="progress-text">下载中 {{ modelStatus.embedding.progress.toFixed(1) }}%</span>
+ </div>
+ <t-progress :percentage="Number(modelStatus.embedding.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
+ <div class="progress-message">{{ modelStatus.embedding.message }}</div>
+ </div>
</div>
+ <!-- 远程 Embedding API 配置 -->
<div v-if="formData.embedding.source === 'remote'" class="remote-config">
<div class="form-row">
<t-form-item label="Base URL" name="embedding.baseUrl">
- <t-input v-model="formData.embedding.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/embeddings路径后的URL的前面部分"
- :disabled="hasFiles" @blur="onRemoteConfigChange('embedding')"
- @input="onRemoteConfigInput('embedding')" />
+ <div class="url-input-with-check">
+ <t-input v-model="formData.embedding.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/embeddings路径后的URL的前面部分"
+ :disabled="hasFiles" @blur="onRemoteConfigChange('embedding')"
+ @input="onRemoteConfigInput('embedding')" />
+ <div v-if="formData.embedding.modelName && formData.embedding.baseUrl && !hasFiles" class="check-action">
+ <t-tooltip v-if="!modelStatus.embedding.available && modelStatus.embedding.checked" content="重新检查连接">
+ <t-icon
+ name="refresh"
+ class="refresh-icon"
+ :class="{ spinning: modelStatus.embedding.checking }"
+ @click="checkRemoteModelStatus('embedding')"
+ />
+ </t-tooltip>
+ <t-icon
+ v-else-if="modelStatus.embedding.checked"
+ :name="modelStatus.embedding.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.embedding.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.embedding.available ? '连接正常' : '连接失败'"
+ />
+ <t-icon
+ v-else
+ name="loading"
+ class="input-icon checking spinning"
+ title="检查连接中"
+ />
+ </div>
+ </div>
</t-form-item>
</div>
<div class="form-row">
@@ -198,34 +297,18 @@
</t-form-item>
</div>
- <!-- Remote API模型状态检查 -->
- <div v-if="formData.embedding.modelName && formData.embedding.baseUrl && !hasFiles" class="remote-status">
- <t-tag v-if="modelStatus.embedding.checked" :theme="modelStatus.embedding.available ? 'success' : 'danger'" size="small">
- <t-icon :name="modelStatus.embedding.available ? 'check-circle' : 'close-circle'" />
- {{ modelStatus.embedding.available ? '连接正常' : '连接失败' }}
- </t-tag>
- <t-tag v-else theme="default" size="small">
- <t-icon name="loading" />
- 检查连接中...
- </t-tag>
-
- <t-button v-if="!modelStatus.embedding.available && modelStatus.embedding.checked"
- theme="primary" variant="text" size="small"
- @click="checkRemoteModelStatus('embedding')">
- 重新检查
- </t-button>
-
- <div v-if="modelStatus.embedding.checked && !modelStatus.embedding.available && modelStatus.embedding.message"
- class="error-message">
- <t-icon name="error-circle" />
- {{ modelStatus.embedding.message }}
- </div>
+ <!-- 错误信息显示 -->
+ <div v-if="modelStatus.embedding.checked && !modelStatus.embedding.available && modelStatus.embedding.message" class="error-message">
+ <t-icon name="error-circle" />
+ <span>{{ modelStatus.embedding.message }}</span>
</div>
+
+
</div>
</div>
- <!-- Rerank 模型配置 -->
- <div class="config-section">
+ <!-- Rerank 重排模型配置区域 -->
+ <div class="config-section" id="section-rerank">
<h3><t-icon name="swap" class="section-icon" />Rerank 重排模型配置</h3>
<div class="form-row">
@@ -237,20 +320,61 @@
</t-form-item>
</div>
+ <!-- Rerank 详细配置 -->
<div v-if="formData.rerank.enabled" class="rerank-config">
<div class="form-row">
<t-form-item label="模型名称" name="rerank.modelName">
- <t-input v-model="formData.rerank.modelName" placeholder="例如: bge-reranker-v2-m3"
- @blur="onRerankConfigChange"
- @input="onRerankConfigInput" />
+ <div class="model-input-with-status">
+ <t-input v-model="formData.rerank.modelName" placeholder="例如: bge-reranker-v2-m3"
+ @blur="onRerankConfigChange"
+ @input="onRerankConfigInput" />
+ <div class="model-status-icon">
+ <t-icon
+ v-if="formData.rerank.modelName && modelStatus.rerank.checked"
+ :name="modelStatus.rerank.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.rerank.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.rerank.available ? '连接正常' : '连接失败'"
+ />
+ <t-icon
+ v-else-if="formData.rerank.modelName && !modelStatus.rerank.checked"
+ name="help-circle"
+ class="status-icon unknown"
+ title="未检查"
+ />
+ </div>
+ </div>
</t-form-item>
</div>
<div class="form-row">
<t-form-item label="Base URL" name="rerank.baseUrl">
- <t-input v-model="formData.rerank.baseUrl" placeholder="例如: http://localhost:11434, 去除末尾/rerank路径后的URL的前面部分"
- @blur="onRerankConfigChange"
- @input="onRerankConfigInput" />
+ <div class="url-input-with-check">
+ <t-input v-model="formData.rerank.baseUrl" placeholder="例如: http://localhost:11434, 去除末尾/rerank路径后的URL的前面部分"
+ @blur="onRerankConfigChange"
+ @input="onRerankConfigInput" />
+ <div v-if="formData.rerank.modelName && formData.rerank.baseUrl" class="check-action">
+ <t-tooltip v-if="!modelStatus.rerank.available && modelStatus.rerank.checked" content="重新检查连接">
+ <t-icon
+ name="refresh"
+ class="refresh-icon"
+ :class="{ spinning: modelStatus.rerank.checking }"
+ @click="checkRerankModelStatus"
+ />
+ </t-tooltip>
+ <t-icon
+ v-else-if="modelStatus.rerank.checked"
+ :name="modelStatus.rerank.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.rerank.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.rerank.available ? '连接正常' : '连接失败'"
+ />
+ <t-icon
+ v-else
+ name="loading"
+ class="input-icon checking spinning"
+ title="检查连接中"
+ />
+ </div>
+ </div>
</t-form-item>
</div>
@@ -262,34 +386,18 @@
</t-form-item>
</div>
- <!-- Rerank模型状态检查 -->
- <div v-if="formData.rerank.modelName && formData.rerank.baseUrl" class="remote-status">
- <t-tag v-if="modelStatus.rerank.checked" :theme="modelStatus.rerank.available ? 'success' : 'danger'" size="small">
- <t-icon :name="modelStatus.rerank.available ? 'check-circle' : 'close-circle'" />
- {{ modelStatus.rerank.available ? '连接正常' : '连接失败' }}
- </t-tag>
- <t-tag v-else theme="default" size="small">
- <t-icon name="loading" />
- 检查连接中...
- </t-tag>
-
- <t-button v-if="!modelStatus.rerank.available && modelStatus.rerank.checked"
- theme="primary" variant="text" size="small"
- @click="checkRerankModelStatus">
- 重新检查
- </t-button>
-
- <div v-if="modelStatus.rerank.checked && !modelStatus.rerank.available && modelStatus.rerank.message"
- class="error-message">
- <t-icon name="error-circle" />
- {{ modelStatus.rerank.message }}
- </div>
+ <!-- 错误信息显示 -->
+ <div v-if="modelStatus.rerank.checked && !modelStatus.rerank.available && modelStatus.rerank.message" class="error-message">
+ <t-icon name="error-circle" />
+ <span>{{ modelStatus.rerank.message }}</span>
</div>
+
+
</div>
</div>
- <!-- 多模态配置 -->
- <div class="config-section">
+ <!-- 多模态配置区域 -->
+ <div class="config-section" id="section-multimodal">
<h3><t-icon name="image" class="section-icon" />多模态配置</h3>
<div class="form-row">
<t-form-item name="multimodal.enabled">
@@ -300,19 +408,67 @@
</t-form-item>
</div>
+ <!-- 多模态详细配置 -->
<div v-if="formData.multimodal.enabled" class="multimodal-config">
- <!-- VLM 模型配置 -->
+ <!-- VLM 视觉语言模型配置 -->
<h4>视觉语言模型配置</h4>
- <div class="form-row">
- <t-form-item label="VLM 模型名称" name="multimodal.vlm.modelName">
+ <div class="form-row">
+ <t-form-item label="模型名称" name="multimodal.vlm.modelName">
+ <div class="model-input-with-status">
<t-input v-model="formData.multimodal.vlm.modelName" placeholder="例如: llava:13b"
@blur="onModelNameChange('vlm')"
@input="onModelNameInput('vlm')"
@keyup.enter="onModelNameChange('vlm')" />
- </t-form-item>
+ <div class="model-status-icon">
+ <t-icon
+ v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.checked"
+ :name="modelStatus.vlm.available ? 'check-circle-filled' : 'close-circle-filled'"
+ :class="['status-icon', modelStatus.vlm.available ? 'installed' : 'not-installed']"
+ :title="modelStatus.vlm.available ? '已安装' : '未安装'"
+ />
+ <t-icon
+ v-else-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && !modelStatus.vlm.checked"
+ name="help-circle"
+ class="status-icon unknown"
+ title="未检查"
+ />
+ <t-icon
+ v-else-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.downloading"
+ name="loading"
+ class="status-icon downloading spinning"
+ title="下载中"
+ />
+ </div>
+ <!-- 下载按钮:未安装时显示 -->
+ <div v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.checked && !modelStatus.vlm.available && !modelStatus.vlm.downloading" class="download-action">
+ <t-tooltip content="下载模型">
+ <t-button
+ size="small"
+ theme="primary"
+ @click="downloadModel('vlm', formData.multimodal.vlm.modelName)"
+ class="download-btn"
+ :disabled="modelStatus.vlm.downloading"
+ >
+ <t-icon name="download" />
+ </t-button>
+ </t-tooltip>
+ </div>
+
+ </div>
+ </t-form-item>
+
+ <!-- 下载进度:下载中时显示 -->
+ <div v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.downloading" class="download-progress">
+ <div class="progress-info">
+ <t-icon name="loading" class="loading-icon spinning" />
+ <span class="progress-text">下载中 {{ modelStatus.vlm.progress.toFixed(1) }}%</span>
+ </div>
+ <t-progress :percentage="Number(modelStatus.vlm.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
+ <div class="progress-message">{{ modelStatus.vlm.message }}</div>
</div>
+ </div>
<div class="form-row">
- <t-form-item label="VLM 接口类型" name="multimodal.vlm.interfaceType">
+ <t-form-item label="接口类型" name="multimodal.vlm.interfaceType">
<t-radio-group v-model="formData.multimodal.vlm.interfaceType" @change="onVlmInterfaceTypeChange">
<t-radio value="ollama">Ollama (本地)</t-radio>
<t-radio value="openai">OpenAI 兼容接口</t-radio>
@@ -320,98 +476,95 @@
</t-form-item>
</div>
<div class="form-row" v-if="formData.multimodal.vlm.interfaceType === 'openai'">
- <t-form-item label="VLM Base URL" name="multimodal.vlm.baseUrl">
+ <t-form-item label="Base URL" name="multimodal.vlm.baseUrl">
<t-input v-model="formData.multimodal.vlm.baseUrl" placeholder="例如: http://localhost:11434/v1,去除末尾/chat/completions路径后的URL的前面部分"
@blur="onVlmBaseUrlChange"
@input="onVlmBaseUrlInput" />
</t-form-item>
</div>
<div class="form-row" v-if="formData.multimodal.vlm.interfaceType === 'openai'">
- <t-form-item label="VLM API Key" name="multimodal.vlm.apiKey">
+ <t-form-item label="API Key" name="multimodal.vlm.apiKey">
<t-input v-model="formData.multimodal.vlm.apiKey" type="password" placeholder="请输入API Key (可选)"
@blur="onVlmApiKeyChange" />
</t-form-item>
</div>
- <!-- VLM模型状态检查 -->
- <div v-if="formData.multimodal.vlm.modelName && isVlmOllama" class="ollama-status">
- <div class="status-item">
- <div class="status-header">
- <span class="status-label">VLM模型状态:</span>
- <t-tag v-if="modelStatus.vlm.checked" :theme="modelStatus.vlm.available ? 'success' : 'warning'">
- {{ modelStatus.vlm.available ? '已安装' : '未安装' }}
- </t-tag>
- <t-tag v-else theme="default">检查中...</t-tag>
-
- <t-button v-if="!modelStatus.vlm.available && modelStatus.vlm.checked && ollamaStatus.available && !modelStatus.vlm.downloading"
- theme="primary" size="small"
- @click="downloadModel('vlm', formData.multimodal.vlm.modelName)">
- 下载模型
- </t-button>
- </div>
-
- <!-- 下载进度显示 -->
- <div v-if="modelStatus.vlm.downloading" class="download-progress">
- <t-progress
- :percentage="modelStatus.vlm.progress"
- :label="false"
- size="small"
- status="active">
- </t-progress>
- <span class="progress-text">{{ modelStatus.vlm.message }} ({{ modelStatus.vlm.progress.toFixed(1) }}%)</span>
- </div>
+
+
+ <!-- 对象存储服务配置 -->
+ <h4>对象存储服务配置</h4>
+ <div class="form-row">
+ <t-form-item label="存储类型">
+ <t-radio-group v-model="formData.storageType" @change="onStorageTypeChange">
+ <t-radio value="cos">COS</t-radio>
+ <t-radio value="minio">MinIO</t-radio>
+ </t-radio-group>
+ </t-form-item>
+ </div>
+
+ <!-- MinIO 配置区域 -->
+ <div v-if="formData.storageType === 'minio'">
+ <div class="form-row">
+ <t-form-item label="Bucket Name" name="multimodal.minio.bucketName">
+ <t-input v-model="formData.multimodal.minio.bucketName" placeholder="请输入Bucket名称" />
+ </t-form-item>
+ </div>
+
+ <div class="form-row">
+ <t-form-item label="Path Prefix" name="multimodal.minio.pathPrefix">
+ <t-input v-model="formData.multimodal.minio.pathPrefix" placeholder="例如: images/" />
+ </t-form-item>
</div>
</div>
- <!-- COS 配置 -->
- <h4>对象存储服务 (COS) 配置</h4>
+ <!-- COS 配置区域 -->
<div class="form-row">
- <t-form-item label="Secret ID" name="multimodal.cos.secretId">
+ <t-form-item v-if="formData.storageType === 'cos'" label="Secret ID" name="multimodal.cos.secretId">
<t-input v-model="formData.multimodal.cos.secretId" placeholder="请输入COS Secret ID"
@blur="onCosConfigChange" />
</t-form-item>
</div>
<div class="form-row">
- <t-form-item label="Secret Key" name="multimodal.cos.secretKey">
+ <t-form-item v-if="formData.storageType === 'cos'" label="Secret Key" name="multimodal.cos.secretKey">
<t-input v-model="formData.multimodal.cos.secretKey" type="password" placeholder="请输入COS Secret Key"
@blur="onCosConfigChange" />
</t-form-item>
</div>
<div class="form-row">
- <t-form-item label="Region" name="multimodal.cos.region">
+ <t-form-item v-if="formData.storageType === 'cos'" label="Region" name="multimodal.cos.region">
<t-input v-model="formData.multimodal.cos.region" placeholder="例如: ap-beijing"
@blur="onCosConfigChange" />
</t-form-item>
</div>
<div class="form-row">
- <t-form-item label="Bucket Name" name="multimodal.cos.bucketName">
+ <t-form-item v-if="formData.storageType === 'cos'" label="Bucket Name" name="multimodal.cos.bucketName">
<t-input v-model="formData.multimodal.cos.bucketName" placeholder="请输入Bucket名称"
@blur="onCosConfigChange" />
</t-form-item>
</div>
<div class="form-row">
- <t-form-item label="App ID" name="multimodal.cos.appId">
+ <t-form-item v-if="formData.storageType === 'cos'" label="App ID" name="multimodal.cos.appId">
<t-input v-model="formData.multimodal.cos.appId" placeholder="请输入App ID"
@blur="onCosConfigChange" />
</t-form-item>
</div>
<div class="form-row">
- <t-form-item label="Path Prefix" name="multimodal.cos.pathPrefix">
+ <t-form-item v-if="formData.storageType === 'cos'" label="Path Prefix" name="multimodal.cos.pathPrefix">
<t-input v-model="formData.multimodal.cos.pathPrefix" placeholder="例如: images/"
@blur="onCosConfigChange" />
</t-form-item>
</div>
- <!-- 多模态测试功能 -->
+ <!-- 多模态功能测试区域 -->
<div v-if="canTestMultimodal" class="multimodal-test">
<h5>多模态功能测试</h5>
<div class="test-description">
<p>上传一张测试图片,验证VLM模型的Caption生成和OCR文字识别功能</p>
</div>
- <!-- 测试操作区 -->
+ <!-- 测试操作区域 -->
<div class="multimodal-test-container">
- <!-- 左侧:图片上传和预览区 -->
+ <!-- 左侧:图片上传和预览区域 -->
<div class="test-image-section">
<div class="test-upload">
<t-upload
@@ -487,8 +640,8 @@
</div>
</div>
- <!-- 文档分割配置 -->
- <div class="config-section">
+ <!-- 文档分割配置区域 -->
+ <div class="config-section" id="section-docsplit">
<h3><t-icon name="cut" class="section-icon" />文档分割配置</h3>
<!-- 预设配置选择 -->
@@ -520,10 +673,10 @@
</div>
</t-radio>
</t-radio-group>
- <div class="form-tip">选择适合您场景的文档分割策略</div>
</t-form-item>
</div>
+ <!-- 参数配置网格 -->
<div class="parameters-grid" :class="{ 'disabled-grid': selectedPreset !== 'custom' }">
<div class="parameter-group">
<div class="parameter-label">分块大小</div>
@@ -532,7 +685,7 @@
v-model="formData.documentSplitting.chunkSize"
:min="100"
:max="4000"
- :step="100"
+ :step="1"
:disabled="selectedPreset !== 'custom'"
:marks="{ 100: '100', 1000: '1000', 2000: '2000', 4000: '4000' }"
class="parameter-slider"
@@ -549,7 +702,7 @@
v-model="formData.documentSplitting.chunkOverlap"
:min="0"
:max="1000"
- :step="50"
+ :step="1"
:disabled="selectedPreset !== 'custom'"
:marks="{ 0: '0', 200: '200', 500: '500', 1000: '1000' }"
class="parameter-slider"
@@ -573,18 +726,17 @@
:options="separatorOptions"
/>
</div>
- <div class="parameter-desc">选择文档分割的优先级分隔符,支持自定义</div>
</div>
</div>
</div>
- <!-- 提交按钮 -->
- <div class="submit-section">
+ <!-- 提交按钮区域 -->
+ <div class="submit-section" id="section-submit">
<t-button theme="primary" type="button" size="large"
- :loading="submitting" :disabled="!canSubmit"
+ :loading="submitting" :disabled="!canSubmit || isSubmitDebounced"
@click="handleSubmit">
- {{ isUpdateMode ? '更新初始化配置' : '完成初始化配置' }}
+ {{ isUpdateMode ? '更新配置信息' : '完成初始化配置' }}
</t-button>
<!-- 提交状态提示 -->
@@ -592,15 +744,22 @@
<t-icon name="info-circle" class="tip-icon" />
<span>请等待所有Ollama模型下载完成后再进行初始化</span>
</div>
+
+
</div>
</t-form>
+ </div> <!-- .init-main -->
+ </div> <!-- .init-layout -->
</div>
</template>
<script setup lang="ts">
+/**
+ * 导入必要的 Vue 组合式 API 和外部依赖
+ */
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
-import { MessagePlugin, FormRule } from 'tdesign-vue-next';
+import { MessagePlugin } from 'tdesign-vue-next';
import {
initializeSystem,
checkOllamaStatus,
@@ -611,22 +770,35 @@ import {
checkRemoteModel,
type DownloadTask,
checkRerankModel,
- testMultimodalFunction
+ testMultimodalFunction,
+ listOllamaModels
} from '@/api/initialization';
const router = useRouter();
-const form = ref(null);
+type TFormRef = {
+ validate: (fields?: string[] | undefined) => Promise<true | any>;
+ clearValidate?: (fields?: string | string[]) => void;
+} | null;
+const form = ref<TFormRef>(null);
const submitting = ref(false);
const hasFiles = ref(false);
const isUpdateMode = ref(false); // 是否为更新模式
+// 防抖机制:防止按钮快速重复点击
+const submitDebounceTimer = ref<ReturnType<typeof setTimeout> | null>(null);
+const isSubmitDebounced = ref(false);
+
// Ollama服务状态
const ollamaStatus = reactive({
checked: false,
available: false,
version: '',
- error: ''
+ error: '',
+ baseUrl: ''
});
+// 顶部摘要:已安装模型
+const installedModels = ref<string[]>([]);
+const summaryRefreshing = ref<boolean>(false);
// 下载任务管理
const downloadTasks = reactive<Record<string, DownloadTask>>({});
@@ -638,6 +810,7 @@ const modelStatus = reactive({
checked: false,
available: false,
downloading: false,
+ checking: false,
taskId: '',
progress: 0,
message: ''
@@ -646,6 +819,7 @@ const modelStatus = reactive({
checked: false,
available: false,
downloading: false,
+ checking: false,
taskId: '',
progress: 0,
message: ''
@@ -654,6 +828,7 @@ const modelStatus = reactive({
checked: false,
available: false,
downloading: false,
+ checking: false,
taskId: '',
progress: 0,
message: ''
@@ -662,6 +837,7 @@ const modelStatus = reactive({
checked: false,
available: false,
downloading: false,
+ checking: false,
taskId: '',
progress: 0,
message: ''
@@ -704,13 +880,19 @@ const formData = reactive({
bucketName: '',
appId: '',
pathPrefix: ''
+ },
+ minio: {
+ bucketName: '',
+ useSSL: false,
+ pathPrefix: ''
}
},
documentSplitting: {
chunkSize: 1000,
chunkOverlap: 200,
separators: ['\n\n', '\n', '。', '!', '?', ';', ';']
- }
+ },
+ storageType: 'minio'
});
// 预设配置选择
@@ -743,6 +925,41 @@ const multimodalTest = reactive({
const imageUpload = ref(null);
+// 左侧导航区段
+type Section = { id: string; label: string };
+const sections: Section[] = [
+ { id: 'ollama', label: 'Ollama 服务' },
+ { id: 'llm', label: 'LLM 模型' },
+ { id: 'embedding', label: 'Embedding 模型' },
+ { id: 'rerank', label: 'Rerank 配置' },
+ { id: 'multimodal', label: '多模态配置' },
+ { id: 'docsplit', label: '文档分割' },
+ { id: 'submit', label: '完成配置' },
+];
+
+const activeSectionId = ref<string>('ollama');
+const goToSection = (id: string) => {
+ const el = document.getElementById(`section-${id}`);
+ if (el) {
+ el.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ activeSectionId.value = id;
+ }
+};
+
+// 监听滚动,高亮当前区块
+const onScroll = () => {
+ const order = ['ollama','llm','embedding','rerank','multimodal','docsplit','submit'];
+ for (const id of order) {
+ const el = document.getElementById(`section-${id}`);
+ if (!el) continue;
+ const rect = el.getBoundingClientRect();
+ if (rect.top <= 120 && rect.bottom >= 120) {
+ activeSectionId.value = id;
+ break;
+ }
+ }
+};
+
// 配置回填
const loadCurrentConfig = async () => {
try {
@@ -765,6 +982,7 @@ const loadCurrentConfig = async () => {
if (config.rerank) {
Object.assign(formData.rerank, config.rerank);
}
+ formData.storageType = config.multimodal.storageType;
if (config.multimodal) {
formData.multimodal.enabled = config.multimodal.enabled || false;
if (config.multimodal.vlm) {
@@ -774,8 +992,10 @@ const loadCurrentConfig = async () => {
formData.multimodal.vlm.interfaceType = 'ollama';
}
}
- if (config.multimodal.cos) {
+ if (config.multimodal.storageType === 'cos') {
Object.assign(formData.multimodal.cos, config.multimodal.cos);
+ } else if (config.multimodal.storageType === 'minio') {
+ Object.assign(formData.multimodal.minio, config.multimodal.minio);
}
}
if (config.documentSplitting) {
@@ -893,19 +1113,22 @@ const rules = {
{ required: (t: any) => formData.multimodal.enabled && formData.multimodal.vlm.interfaceType === 'openai', message: '请输入VLM BaseURL', type: 'error' }
],
'multimodal.cos.secretId': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入COS Secret ID', type: 'error' }
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Secret ID', type: 'error' }
],
'multimodal.cos.secretKey': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入COS Secret Key', type: 'error' }
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Secret Key', type: 'error' }
],
'multimodal.cos.region': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入COS Region', type: 'error' }
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Region', type: 'error' }
],
'multimodal.cos.bucketName': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入COS Bucket Name', type: 'error' }
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Bucket Name', type: 'error' }
],
'multimodal.cos.appId': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入COS App ID', type: 'error' }
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS App ID', type: 'error' }
+ ],
+ 'multimodal.minio.bucketName': [
+ { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'minio', message: '请输入Bucket Name', type: 'error' }
]
};
@@ -917,6 +1140,7 @@ const checkOllama = async () => {
ollamaStatus.available = result.available;
ollamaStatus.version = result.version || '';
ollamaStatus.error = result.error || '';
+ ollamaStatus.baseUrl = result.baseUrl || '';
if (ollamaStatus.available) {
// 如果Ollama可用,检查已配置的模型
@@ -930,6 +1154,22 @@ const checkOllama = async () => {
}
};
+// 刷新顶部摘要(状态 + 已安装模型)
+const refreshOllamaSummary = async () => {
+ if (summaryRefreshing.value) return;
+ summaryRefreshing.value = true;
+ try {
+ await checkOllama();
+ const models = await listOllamaModels();
+ installedModels.value = models;
+ } catch (e) {
+ installedModels.value = [];
+ } finally {
+ // 略延时以保证旋转动画可见
+ setTimeout(() => { summaryRefreshing.value = false; }, 300);
+ }
+};
+
// 检查所有Ollama模型状态
const checkAllOllamaModels = async () => {
const modelsToCheck = [];
@@ -973,14 +1213,23 @@ const checkAllOllamaModels = async () => {
// 下载模型
const downloadModel = async (type: 'llm' | 'embedding' | 'vlm', modelName: string) => {
+ // 防止重复点击
+ if (modelStatus[type].downloading) {
+ return;
+ }
+
try {
+ // 立即更新状态,防止重复点击
+ modelStatus[type].downloading = true;
+ modelStatus[type].progress = 0;
+ modelStatus[type].message = '正在启动下载...';
+
// 启动下载任务
const result = await downloadOllamaModel(modelName);
- // 更新模型状态
- modelStatus[type].downloading = true;
+ // 更新任务ID和初始进度
modelStatus[type].taskId = result.taskId;
- modelStatus[type].progress = result.progress;
+ modelStatus[type].progress = result.progress || 0;
modelStatus[type].message = '下载已开始';
// 如果已经完成,直接更新状态
@@ -1000,6 +1249,7 @@ const downloadModel = async (type: 'llm' | 'embedding' | 'vlm', modelName: strin
console.error(`启动模型 ${modelName} 下载失败:`, error);
MessagePlugin.error(`启动模型 ${modelName} 下载失败`);
modelStatus[type].downloading = false;
+ modelStatus[type].message = '下载启动失败';
}
};
@@ -1073,6 +1323,14 @@ onUnmounted(() => {
delete inputDebounceTimers[key];
}
});
+
+ // 清理提交防抖定时器
+ if (submitDebounceTimer.value) {
+ clearTimeout(submitDebounceTimer.value);
+ submitDebounceTimer.value = null;
+ }
+
+ window.removeEventListener('scroll', onScroll);
});
// 事件处理
@@ -1236,6 +1494,7 @@ const checkRemoteModelStatus = async (type: 'llm' | 'embedding') => {
}
try {
+ modelStatus[type].checking = true;
modelStatus[type].checked = false;
modelStatus[type].available = false;
modelStatus[type].message = '';
@@ -1259,7 +1518,10 @@ const checkRemoteModelStatus = async (type: 'llm' | 'embedding') => {
console.error(`检查远程${type}模型失败:`, error);
modelStatus[type].checked = true;
modelStatus[type].available = false;
- modelStatus[type].message = error.message || '网络连接失败';
+ const err = error as any;
+ modelStatus[type].message = (err && err.message) || '网络连接失败';
+ } finally {
+ modelStatus[type].checking = false;
}
};
@@ -1287,7 +1549,8 @@ const onSeparatorsChange = (value: string) => {
// 最终模型检查
const performFinalModelCheck = async () => {
// 收集需要检查的本地模型
- const modelsToCheck = [];
+ type ModelItem = { name: string; type: string };
+ const modelsToCheck: ModelItem[] = [];
if (formData.llm.source === 'local' && formData.llm.modelName) {
modelsToCheck.push({ name: formData.llm.modelName, type: 'LLM' });
@@ -1313,14 +1576,62 @@ const performFinalModelCheck = async () => {
};
}
+ // 快速检查:如果所有模型状态已知且可用,直接返回成功
+ let allModelsAvailable = true;
+ const quickCheckResults = [];
+
+ if (formData.llm.source === 'local' && formData.llm.modelName) {
+ if (modelStatus.llm.checked && modelStatus.llm.available && !modelStatus.llm.downloading) {
+ quickCheckResults.push({ name: formData.llm.modelName, type: 'LLM', available: true });
+ } else if (modelStatus.llm.downloading) {
+ return {
+ success: false,
+ message: 'LLM模型正在下载中,请等待下载完成后再提交配置。'
+ };
+ } else {
+ allModelsAvailable = false;
+ }
+ }
+
+ if (formData.embedding.source === 'local' && formData.embedding.modelName) {
+ if (modelStatus.embedding.checked && modelStatus.embedding.available && !modelStatus.embedding.downloading) {
+ quickCheckResults.push({ name: formData.embedding.modelName, type: 'Embedding', available: true });
+ } else if (modelStatus.embedding.downloading) {
+ return {
+ success: false,
+ message: 'Embedding模型正在下载中,请等待下载完成后再提交配置。'
+ };
+ } else {
+ allModelsAvailable = false;
+ }
+ }
+
+ if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
+ if (modelStatus.vlm.checked && modelStatus.vlm.available && !modelStatus.vlm.downloading) {
+ quickCheckResults.push({ name: formData.multimodal.vlm.modelName, type: 'VLM', available: true });
+ } else if (modelStatus.vlm.downloading) {
+ return {
+ success: false,
+ message: 'VLM模型正在下载中,请等待下载完成后再提交配置。'
+ };
+ } else {
+ allModelsAvailable = false;
+ }
+ }
+
+ // 如果所有模型状态已知且可用,直接返回成功
+ if (allModelsAvailable && quickCheckResults.length === modelsToCheck.length) {
+ return { success: true };
+ }
+
+ // 需要重新检查的模型
try {
- // 重新检查所有模型状态
const modelNames = modelsToCheck.map(m => m.name);
const result = await checkOllamaModels(modelNames);
// 检查是否有未安装的模型
- const unavailableModels = [];
- modelsToCheck.forEach(model => {
+ const unavailableModels: ModelItem[] = [];
+ modelsToCheck.forEach((model: ModelItem) => {
if (!result.models[model.name]) {
unavailableModels.push(model);
}
@@ -1334,25 +1645,6 @@ const performFinalModelCheck = async () => {
};
}
- // 检查是否有正在下载的模型
- const downloadingModels = [];
- if (formData.llm.source === 'local' && modelStatus.llm.downloading) {
- downloadingModels.push('LLM');
- }
- if (formData.embedding.source === 'local' && modelStatus.embedding.downloading) {
- downloadingModels.push('Embedding');
- }
- if (formData.multimodal.enabled && isVlmOllama.value && modelStatus.vlm.downloading) {
- downloadingModels.push('VLM');
- }
-
- if (downloadingModels.length > 0) {
- return {
- success: false,
- message: `${downloadingModels.join('、')}模型正在下载中,请等待下载完成后再提交配置。`
- };
- }
-
return { success: true };
} catch (error) {
@@ -1366,6 +1658,20 @@ const performFinalModelCheck = async () => {
// 处理按钮提交
const handleSubmit = async () => {
+ // 防止重复提交和防抖
+ if (submitting.value || isSubmitDebounced.value) {
+ return;
+ }
+
+ // 设置防抖状态
+ isSubmitDebounced.value = true;
+ if (submitDebounceTimer.value) {
+ clearTimeout(submitDebounceTimer.value);
+ }
+ submitDebounceTimer.value = setTimeout(() => {
+ isSubmitDebounced.value = false;
+ }, 500); // 500ms防抖
+
// 先进行表单验证
const validateResult = await form.value?.validate();
@@ -1393,17 +1699,18 @@ const handleSubmit = async () => {
}
submitting.value = true;
+
try {
// 最终检查:确保所有本地模型都已下载完成
const finalCheck = await performFinalModelCheck();
if (!finalCheck.success) {
- MessagePlugin.error(finalCheck.message);
- submitting.value = false;
+ MessagePlugin.error(finalCheck.message || '模型检查失败');
return;
}
// 调用初始化API
- await initializeSystem(formData);
+ const payload: any = JSON.parse(JSON.stringify(formData));
+ await initializeSystem(payload);
const successMessage = isUpdateMode.value ? '配置更新成功!' : '系统初始化成功!';
MessagePlugin.success(successMessage);
@@ -1411,15 +1718,16 @@ const handleSubmit = async () => {
// 记录初始化状态,强制刷新路由状态
localStorage.setItem('system_initialized', 'true');
- // 跳转到知识库页面
- setTimeout(() => {
- router.replace('/platform/knowledgeBase');
- }, 300);
+ // 立即跳转到知识库页面,减少延迟感
+ router.replace('/platform/knowledgeBase');
+
} catch (error) {
console.error('初始化失败:', error);
const errorMessage = isUpdateMode.value ? '配置更新失败,请检查配置并重试' : '初始化失败,请检查配置并重试';
- MessagePlugin.error(error.message || errorMessage);
+ const err = error as any;
+ MessagePlugin.error((err && err.message) || errorMessage);
} finally {
+ // 确保在所有情况下都重置提交状态
submitting.value = false;
}
}
@@ -1441,11 +1749,14 @@ onMounted(async () => {
(formData.multimodal.enabled && formData.multimodal.vlm.interfaceType === 'ollama');
if (needOllamaCheck) {
- await checkOllama();
+ await refreshOllamaSummary();
}
// 检查已配置模型状态
await checkAllConfiguredModels();
+
+ // 绑定滚动监听,用于左侧导航高亮
+ window.addEventListener('scroll', onScroll, { passive: true });
});
const onRerankChange = () => {
@@ -1498,6 +1809,7 @@ const checkRerankModelStatus = async () => {
}
try {
+ modelStatus.rerank.checking = true;
modelStatus.rerank.checked = false;
modelStatus.rerank.available = false;
modelStatus.rerank.message = '';
@@ -1521,7 +1833,10 @@ const checkRerankModelStatus = async () => {
console.error('检查Rerank模型失败:', error);
modelStatus.rerank.checked = true;
modelStatus.rerank.available = false;
- modelStatus.rerank.message = error.message || '网络连接失败';
+ const err = error as any;
+ modelStatus.rerank.message = (err && err.message) || '网络连接失败';
+ } finally {
+ modelStatus.rerank.checking = false;
}
};
@@ -1537,23 +1852,17 @@ const getTestUploadData = () => {
const onImageChange = (files: any) => {
if (files && files.length > 0) {
// 检查多模态配置是否完整
- const missingConfigs = [];
+ const missingConfigs: string[] = [];
- // 检查COS配置
- if (!formData.multimodal.cos.secretId) {
- missingConfigs.push('COS Secret ID');
- }
- if (!formData.multimodal.cos.secretKey) {
- missingConfigs.push('COS Secret Key');
- }
- if (!formData.multimodal.cos.region) {
- missingConfigs.push('COS Region');
- }
- if (!formData.multimodal.cos.bucketName) {
- missingConfigs.push('COS Bucket Name');
- }
- if (!formData.multimodal.cos.appId) {
- missingConfigs.push('COS App ID');
+ // 根据存储类型检查必填项
+ if (formData.storageType === 'cos') {
+ if (!formData.multimodal.cos.secretId) missingConfigs.push('COS Secret ID');
+ if (!formData.multimodal.cos.secretKey) missingConfigs.push('COS Secret Key');
+ if (!formData.multimodal.cos.region) missingConfigs.push('COS Region');
+ if (!formData.multimodal.cos.bucketName) missingConfigs.push('COS Bucket Name');
+ if (!formData.multimodal.cos.appId) missingConfigs.push('COS App ID');
+ } else if (formData.storageType === 'minio') {
+ if (!formData.multimodal.minio.bucketName) missingConfigs.push('MinIO Bucket Name');
}
// 检查VLM配置
@@ -1605,12 +1914,16 @@ const startMultimodalTest = async () => {
vlm_base_url: string;
vlm_api_key: string;
vlm_interface_type: string;
- cos_secret_id: string;
- cos_secret_key: string;
- cos_region: string;
- cos_bucket_name: string;
- cos_app_id: string;
- cos_path_prefix: string;
+ storage_type?: 'cos' | 'minio';
+ cos_secret_id?: string;
+ cos_secret_key?: string;
+ cos_region?: string;
+ cos_bucket_name?: string;
+ cos_app_id?: string;
+ cos_path_prefix?: string;
+ minio_bucket_name?: string;
+ minio_use_ssl?: boolean;
+ minio_path_prefix?: string;
chunk_size: number;
chunk_overlap: number;
separators: string[];
@@ -1620,16 +1933,26 @@ const startMultimodalTest = async () => {
vlm_base_url: '', // 将在下方设置
vlm_api_key: '', // 将在下方设置
vlm_interface_type: formData.multimodal.vlm.interfaceType,
- cos_secret_id: formData.multimodal.cos.secretId,
- cos_secret_key: formData.multimodal.cos.secretKey,
- cos_region: formData.multimodal.cos.region,
- cos_bucket_name: formData.multimodal.cos.bucketName,
- cos_app_id: formData.multimodal.cos.appId,
- cos_path_prefix: formData.multimodal.cos.pathPrefix || '',
chunk_size: formData.documentSplitting.chunkSize,
chunk_overlap: formData.documentSplitting.chunkOverlap,
separators: formData.documentSplitting.separators
};
+
+ // 根据存储类型附带不同的参数
+ if (formData.storageType === 'cos') {
+ apiParams.storage_type = 'cos';
+ apiParams.cos_secret_id = formData.multimodal.cos.secretId;
+ apiParams.cos_secret_key = formData.multimodal.cos.secretKey;
+ apiParams.cos_region = formData.multimodal.cos.region;
+ apiParams.cos_bucket_name = formData.multimodal.cos.bucketName;
+ apiParams.cos_app_id = formData.multimodal.cos.appId;
+ apiParams.cos_path_prefix = formData.multimodal.cos.pathPrefix || '';
+ } else if (formData.storageType === 'minio') {
+ apiParams.storage_type = 'minio';
+ apiParams.minio_bucket_name = formData.multimodal.minio.bucketName;
+ apiParams.minio_use_ssl = formData.multimodal.minio.useSSL;
+ apiParams.minio_path_prefix = formData.multimodal.minio.pathPrefix;
+ }
// 如果是OpenAI兼容接口,设置baseUrl和apiKey
if (formData.multimodal.vlm.interfaceType === 'openai') {
@@ -1654,7 +1977,7 @@ const startMultimodalTest = async () => {
console.error('多模态测试失败:', error);
multimodalTest.result = {
success: false,
- message: error.message || '测试过程中发生错误'
+ message: (error as any)?.message || '测试过程中发生错误'
};
MessagePlugin.error('多模态测试失败');
} finally {
@@ -1683,12 +2006,18 @@ const canTestMultimodal = computed(() => {
const baseUrlValid = formData.multimodal.vlm.interfaceType === 'ollama' ||
(formData.multimodal.vlm.interfaceType === 'openai' && formData.multimodal.vlm.baseUrl);
- return formData.multimodal.cos.secretId &&
- formData.multimodal.cos.secretKey &&
- formData.multimodal.cos.region &&
- formData.multimodal.cos.bucketName &&
- formData.multimodal.cos.appId &&
- formData.multimodal.vlm.modelName &&
+ const cosReady = formData.storageType == 'cos' &&
+ formData.multimodal.cos.secretId &&
+ formData.multimodal.cos.secretKey &&
+ formData.multimodal.cos.region &&
+ formData.multimodal.cos.bucketName &&
+ formData.multimodal.cos.appId;
+
+ const minioReady = formData.storageType == 'minio' &&
+ formData.multimodal.minio.bucketName;
+
+ return (cosReady || minioReady) &&
+ !!formData.multimodal.vlm.modelName &&
baseUrlValid;
});
@@ -1707,10 +2036,7 @@ const onVlmInterfaceTypeChange = () => {
checkVlmModelStatus();
}
} else {
- // 如果是OpenAI兼容接口,清空Base URL让用户输入
- if (formData.multimodal.vlm.baseUrl.includes('localhost:11434')) {
- formData.multimodal.vlm.baseUrl = '';
- }
+ formData.multimodal.vlm.baseUrl = '';
// 重置模型状态检查
modelStatus.vlm.checked = false;
modelStatus.vlm.available = false;
@@ -1748,7 +2074,8 @@ const checkVlmModelStatus = async () => {
console.error('检查VLM模型状态失败:', error);
modelStatus.vlm.checked = true;
modelStatus.vlm.available = false;
- modelStatus.vlm.message = error.message || '网络连接失败';
+ const err = error as any;
+ modelStatus.vlm.message = (err && err.message) || '网络连接失败';
}
};
@@ -1837,16 +2164,36 @@ const onVlmApiKeyChange = () => {
const onCosConfigChange = () => {
// 触发表单验证,确保COS配置的完整性
setTimeout(() => {
- form.value?.validate([
+ if (formData.storageType === 'cos') {
+ form.value?.validate([
+ 'multimodal.cos.secretId',
+ 'multimodal.cos.secretKey',
+ 'multimodal.cos.region',
+ 'multimodal.cos.bucketName',
+ 'multimodal.cos.appId'
+ ]);
+ }
+ }, 100);
+
+ console.log('COS config changed:', formData.multimodal.cos);
+};
+
+const onStorageTypeChange = () => {
+ // 切换到 MinIO 时,清理 COS 校验状态
+ if (formData.storageType === 'minio') {
+ form.value?.clearValidate?.([
'multimodal.cos.secretId',
'multimodal.cos.secretKey',
'multimodal.cos.region',
'multimodal.cos.bucketName',
'multimodal.cos.appId'
]);
- }, 100);
-
- console.log('COS config changed:', formData.multimodal.cos);
+ } else {
+ form.value?.clearValidate?.([
+ 'multimodal.minio.bucketName',
+ 'multimodal.minio.pathPrefix'
+ ]);
+ }
};
// 检查所有已配置模型的状态
@@ -1889,9 +2236,137 @@ const onDimensionInput = (event: any) => {
<style lang="less" scoped>
.initialization-container {
+ .init-layout {
+ display: grid;
+ grid-template-columns: 220px 1fr;
+ gap: 16px;
+ max-width: 1200px;
+ margin: 0 auto;
+ }
+
+ .sidebar {
+ position: sticky;
+ top: 20px;
+ height: fit-content;
+ padding-right: 20px;
+ }
+
+ .sidebar-card {
+ background: #fff;
+ border: 1px solid #e8f5e8;
+ border-radius: 14px;
+ box-shadow: 0 8px 24px rgba(7, 192, 95, 0.08);
+ padding: 16px 12px;
+ }
+
+ .nav-title {
+ font-weight: 600;
+ color: #2c5234;
+ padding: 8px 10px 12px;
+ border-bottom: 2px solid #f0fdf4;
+ margin-bottom: 12px;
+ font-size: 15px;
+ }
+
+ .nav-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+
+ .nav-item {
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: #6b7280;
+ padding: 10px 12px;
+ border-radius: 10px;
+ transition: all 0.2s ease;
+ font-size: 14px;
+ font-weight: 500;
+ }
+
+ .nav-item:hover {
+ background: #f0fdf4;
+ color: #166534;
+ transform: translateX(2px);
+ }
+
+ .nav-item.active {
+ background: linear-gradient(135deg, #07c05f, #00a651);
+ color: white;
+ font-weight: 600;
+ box-shadow: 0 4px 12px rgba(7, 192, 95, 0.2);
+ transform: translateX(2px);
+ }
+
+ .nav-item .dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: currentColor;
+ transition: all 0.2s ease;
+ }
+
+ .nav-item.active .dot {
+ background: white;
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3);
+ }
+
+ .init-main { min-width: 0; }
+ .ollama-summary-card {
+ max-width: 960px;
+ margin: 0 auto 16px auto;
+ background: #ffffff;
+ border: 1px solid #e9edf5;
+ border-radius: 12px;
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05);
+ padding: 14px 16px;
+
+ .summary-header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 6px;
+
+ .title {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-weight: 600;
+ color: #1f2937;
+ }
+ .state{ margin-left: 4px; }
+ .refresh-icon{
+ margin-left: 4px;
+ cursor: pointer;
+ color: #6b7280;
+ transition: transform .2s ease, color .2s ease;
+ }
+ .refresh-icon:hover{ color: #0ea5e9; }
+ .refresh-icon.spinning{ animation: spin 1s linear infinite; }
+ }
+
+ .summary-body {
+ .models {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ .label { color:#6b7280; font-size: 12px; margin-top: 2px; }
+ .model-list { display: flex; gap: 6px; flex-wrap: wrap; }
+ .model-pill { border-radius: 10px; }
+ .empty { color:#9ca3af; font-size:12px; }
+ }
+ }
+ }
min-height: 100vh;
- background: linear-gradient(135deg, #f0f9f0 0%, #e8f5e8 100%);
- padding: 40px 20px;
+ /* 更柔和的浅色背景,贴近截图的干净感 */
+ background: linear-gradient(180deg, #f7fbff 0%, #f8fff9 100%);
+ padding: 48px 20px;
.initialization-header {
text-align: center;
@@ -1930,19 +2405,20 @@ const onDimensionInput = (event: any) => {
}
:deep(.t-form) {
- max-width: 800px;
+ /* 表单容器卡片化:更宽一点、更浅的阴影与细边框 */
+ max-width: 960px;
margin: 0 auto;
- background: white;
- padding: 40px;
- border-radius: 16px;
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
- backdrop-filter: blur(10px);
+ background: #fff;
+ padding: 32px 36px;
+ border-radius: 14px;
+ border: 1px solid #e9edf5;
+ box-shadow: 0 12px 32px rgba(15, 23, 42, 0.06);
}
.config-section {
- margin-bottom: 40px;
- border-bottom: 1px solid #e8f5e8;
- padding-bottom: 30px;
+ margin-bottom: 32px;
+ border-bottom: 1px solid #eef2f7;
+ padding-bottom: 24px;
&:last-of-type {
border-bottom: none;
@@ -1953,12 +2429,13 @@ const onDimensionInput = (event: any) => {
color: #07c05f;
font-size: 18px;
font-weight: 600;
- margin-bottom: 20px;
+ margin-bottom: 16px;
display: flex;
align-items: center;
padding: 10px 16px;
- background: linear-gradient(90deg, #e8f5e8, #f0faf0);
- border-radius: 8px;
+ /* 标题条更清爽的浅色渐变 */
+ background: linear-gradient(90deg, #f6f9ff, #f4fff6);
+ border-radius: 10px;
border-left: 4px solid #07c05f;
.section-icon {
@@ -1978,12 +2455,12 @@ const onDimensionInput = (event: any) => {
}
}
- .remote-config, .multimodal-config {
- margin-top: 20px;
- padding: 20px;
- background: #f8fdf8;
- border-radius: 8px;
- border-left: 4px solid #07c05f;
+ .remote-config, .multimodal-config, .rerank-config {
+ margin-top: 16px;
+ padding: 18px 16px;
+ background: #f9fcff;
+ border-radius: 12px;
+ border: 1px solid #edf2f7;
}
.ollama-status {
@@ -2018,21 +2495,26 @@ const onDimensionInput = (event: any) => {
:deep(.t-tag) {
margin-right: 10px;
-
+ border-radius: 8px;
+ font-weight: 500;
&.t-tag--success {
background-color: #f6ffed;
border-color: #b7eb8f;
- color: #52c41a;
+ color: #2f9a28;
+ }
+ &.t-tag--danger {
+ background-color: #fff2f0;
+ border-color: #ffccc7;
+ color: #d4380d;
}
}
:deep(.t-button) {
margin-bottom: 5px;
-
+ border-radius: 10px;
&.t-button--theme-primary {
background-color: #07c05f;
border-color: #07c05f;
-
&:hover {
background-color: #00a651;
border-color: #00a651;
@@ -2046,11 +2528,6 @@ const onDimensionInput = (event: any) => {
width: 100%;
max-width: 400px;
- :deep(.t-progress) {
- .t-progress__bar {
- background-color: #07c05f;
- }
- }
.progress-text {
font-size: 12px;
@@ -2076,7 +2553,7 @@ const onDimensionInput = (event: any) => {
align-items: center;
gap: 4px;
padding: 4px 8px;
- border-radius: 6px;
+ border-radius: 8px;
font-size: 12px;
font-weight: 500;
transition: all 0.3s ease;
@@ -2121,8 +2598,7 @@ const onDimensionInput = (event: any) => {
&:hover {
color: #40a9ff;
- background-color: #f0f9ff;
- transform: translateY(-1px);
+ background-color: #eef6ff;
}
}
}
@@ -2186,26 +2662,40 @@ const onDimensionInput = (event: any) => {
.submit-section {
text-align: center;
padding-top: 20px;
- border-top: 1px solid #e8f5e8;
:deep(.t-button--theme-primary) {
background: linear-gradient(135deg, #07c05f, #00a651);
border: none;
- border-radius: 8px;
+ border-radius: 12px;
font-weight: 600;
padding: 12px 32px;
font-size: 16px;
- transition: all 0.3s ease;
+ transition: all 0.2s ease;
+ min-height: 48px;
+ min-width: 160px;
&:hover:not(.t-is-disabled) {
background: linear-gradient(135deg, #00a651, #009645);
- transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(7, 192, 95, 0.3);
}
+ &:active:not(.t-is-disabled) {
+ transform: translateY(0);
+ box-shadow: 0 4px 15px rgba(7, 192, 95, 0.2);
+ }
+
&.t-is-disabled {
background: #ccc;
color: #999;
+ transform: none;
+ box-shadow: none;
+ }
+
+ &.t-is-loading {
+ background: linear-gradient(135deg, #07c05f, #00a651);
+ color: white;
+ transform: none;
+ box-shadow: 0 4px 15px rgba(7, 192, 95, 0.2);
}
}
@@ -2229,6 +2719,10 @@ const onDimensionInput = (event: any) => {
.tip-icon {
margin-right: 5px;
+
+ &.spinning {
+ animation: spin 1s linear infinite;
+ }
}
}
}
@@ -2270,11 +2764,6 @@ const onDimensionInput = (event: any) => {
}
}
- :deep(.t-switch) {
- &.t-is-checked .t-switch__handle::before {
- background-color: #07c05f;
- }
- }
:deep(.t-button) {
min-width: 120px;
@@ -2289,6 +2778,315 @@ const onDimensionInput = (event: any) => {
line-height: 1.4;
}
+ /* 模型输入框与状态图标布局 */
+ .model-input-with-status {
+ display: flex;
+ gap: 10px;
+ }
+
+ /* 模型名称输入框样式 */
+ .model-input-with-status :deep(.t-input) {
+ flex: 1;
+ min-width: 300px;
+
+ .t-input__inner {
+ height: 40px;
+ font-size: 14px;
+ padding: 8px 12px;
+ }
+ }
+
+ /* 下载按钮样式 - 简化设计 */
+ .download-action {
+ flex-shrink: 0;
+ }
+
+ .download-action .download-btn {
+ height: 22px;
+ width: 22px;
+ min-width: 22px;
+ padding: 0;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: linear-gradient(135deg, #07c05f, #00a651);
+ border: none;
+ color: white;
+ transition: all 0.2s ease;
+ box-shadow: 0 2px 8px rgba(7, 192, 95, 0.2);
+
+ &:hover:not(:disabled) {
+ background: linear-gradient(135deg, #00a651, #008f47);
+ box-shadow: 0 4px 12px rgba(7, 192, 95, 0.3);
+ }
+
+ &:active:not(:disabled) {
+ transform: translateY(0);
+ box-shadow: 0 2px 6px rgba(7, 192, 95, 0.2);
+ }
+
+ &:disabled {
+ background: #e5e7eb;
+ color: #9ca3af;
+ cursor: not-allowed;
+ transform: none;
+ box-shadow: none;
+ }
+
+ .t-icon {
+ font-size: 14px;
+ }
+ }
+
+ /* 下载进度样式 */
+ .download-progress {
+ margin-top: 8px;
+ margin-bottom: 8px;
+ padding: 10px 12px;
+ background: linear-gradient(135deg, #f0fdf4, #f8fafc);
+ border-radius: 8px;
+ border: 1px solid #dcfce7;
+ box-shadow: 0 1px 4px rgba(7, 192, 95, 0.08);
+ width: 100%;
+
+ .progress-info {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 6px;
+
+ .loading-icon {
+ color: #07c05f;
+ font-size: 14px;
+ animation: spin 1s linear infinite;
+ }
+
+ .progress-text {
+ font-size: 12px;
+ color: #166534;
+ font-weight: 600;
+ }
+ }
+
+ .progress-bar {
+ margin-bottom: 4px;
+
+ :deep(.t-progress__bar) {
+ background: linear-gradient(90deg, #07c05f, #00a651);
+ border-radius: 4px;
+ height: 4px;
+ box-shadow: 0 1px 2px rgba(7, 192, 95, 0.2);
+ }
+
+ :deep(.t-progress__track) {
+ background-color: #e5e7eb;
+ border-radius: 4px;
+ height: 4px;
+ }
+ }
+
+ .progress-message {
+ font-size: 10px;
+ color: #6b7280;
+ text-align: center;
+ line-height: 1.2;
+ font-style: italic;
+ }
+ }
+
+ /* URL输入框与检查按钮布局 */
+ .url-input-with-check {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ }
+
+ .url-input-with-check :deep(.t-input) {
+ flex: 1;
+ min-width: 0;
+ width: 100%;
+
+ .t-input__inner {
+ height: 40px;
+ font-size: 14px;
+ padding: 8px 12px;
+ width: 100%;
+ }
+ }
+
+ /* 检查按钮和状态图标样式 - 与Ollama状态图标保持一致 */
+ .check-action {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .check-action .status-icon,
+ .check-action .input-icon {
+ font-size: 18px;
+ cursor: help;
+ color: #666;
+ }
+
+ .check-action .status-icon.installed,
+ .check-action .input-icon.installed {
+ color: #00a870;
+ }
+
+ .check-action .status-icon.not-installed,
+ .check-action .input-icon.not-installed {
+ color: #e34d59;
+ }
+
+ .check-action .status-icon.unknown,
+ .check-action .input-icon.unknown {
+ color: #d54941;
+ }
+
+ .check-action .status-icon.checking,
+ .check-action .input-icon.checking {
+ color: #0052d9;
+ }
+
+ /* 错误信息样式 */
+ .error-message {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 8px;
+ padding: 8px 12px;
+ background-color: #fff2f0;
+ border: 1px solid #ffccc7;
+ border-radius: 6px;
+ color: #d4380d;
+ font-size: 13px;
+
+ .t-icon {
+ color: #d4380d;
+ font-size: 16px;
+ flex-shrink: 0;
+ }
+
+ span {
+ line-height: 1.4;
+ }
+ }
+
+ /* 输入框样式优化 */
+ :deep(.t-input) {
+ border-radius: 8px;
+
+ &.t-is-focused {
+ border-color: #07c05f;
+ box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);
+ }
+
+ .t-input__inner {
+ border-radius: 8px;
+ transition: all 0.2s ease;
+
+ &:focus {
+ border-color: #07c05f;
+ box-shadow: none;
+ outline: none;
+ }
+
+ &:hover {
+ border-color: #07c05f;
+ }
+ }
+ }
+
+ :deep(.t-textarea) {
+ border-radius: 8px;
+
+ &.t-is-focused {
+ border-color: #07c05f;
+ box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);
+ }
+
+ .t-textarea__inner {
+ border-radius: 8px;
+ border: 1px solid #dcdcdc;
+ transition: all 0.2s ease;
+
+ &:focus {
+ border-color: #07c05f;
+ box-shadow: none;
+ outline: none;
+ }
+
+ &:hover {
+ border-color: #07c05f;
+ }
+ }
+ }
+
+ .model-status-icon {
+ flex-shrink: 0;
+ }
+
+ .model-status-icon .status-icon {
+ font-size: 18px;
+ cursor: help;
+ }
+
+ .model-status-icon .status-icon.installed {
+ color: #00a870;
+ }
+
+ .model-status-icon .status-icon.not-installed {
+ color: #e34d59;
+ }
+
+ .model-status-icon .status-icon.unknown {
+ color: #d54941;
+ }
+
+ .model-status-icon .status-icon.downloading {
+ color: #0052d9;
+ }
+
+ /* 紧随输入框的精简状态行 */
+ .inline-status-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 8px 0;
+ }
+
+ .inline-progress {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 180px;
+ padding: 4px 8px;
+ background: #f8f9fa;
+ border-radius: 12px;
+ border: 1px solid #e9ecef;
+
+ :deep(.t-progress) {
+ flex: 1;
+ min-width: 100px;
+
+ .t-progress__track {
+ background-color: #e9ecef;
+ border-radius: 6px;
+ }
+ }
+
+ .progress-text {
+ font-size: 11px;
+ color: #6c757d;
+ font-weight: 500;
+ min-width: 45px;
+ text-align: right;
+ }
+ }
+
.form-row {
margin-bottom: 20px;
}
@@ -2311,7 +3109,8 @@ const onDimensionInput = (event: any) => {
.switch-container {
display: flex;
align-items: center;
- margin-top: 10px;
+ justify-content: flex-start;
+ margin-left: -100px;
.switch-label {
margin-left: 10px;
@@ -2345,9 +3144,8 @@ const onDimensionInput = (event: any) => {
.preset-radio-group {
display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ grid-template-columns: repeat(2, 1fr);
gap: 15px;
- margin-top: 15px;
:deep(.t-radio) {
border: 2px solid #e8f5e8;
@@ -2360,7 +3158,6 @@ const onDimensionInput = (event: any) => {
&:hover {
border-color: #07c05f;
background-color: #f8fdf8;
- transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.1);
}
@@ -2408,11 +3205,11 @@ const onDimensionInput = (event: any) => {
flex-direction: column;
gap: 24px;
margin-top: 20px;
- padding: 24px;
- background: white;
+ padding: 20px 16px;
+ background: #fff;
border-radius: 12px;
- border: 2px solid #e8f5e8;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
+ border: 1px solid #edf2f7;
+ box-shadow: 0 6px 16px rgba(15, 23, 42, 0.04);
&.disabled-grid {
opacity: 0.6;
@@ -2433,11 +3230,10 @@ const onDimensionInput = (event: any) => {
display: flex;
align-items: center;
gap: 12px;
- margin-bottom: 12px;
+ margin-bottom: 20px;
.parameter-slider {
- width: 100%;
- max-width: 300px;
+ flex: 1;
:deep(.t-slider__rail) {
background-color: #e8f5e8;
@@ -2463,8 +3259,7 @@ const onDimensionInput = (event: any) => {
}
.parameter-select {
- width: 100%;
- max-width: 400px;
+ flex: 1;
}
}
@@ -2472,19 +3267,11 @@ const onDimensionInput = (event: any) => {
font-size: 12px;
color: #999;
line-height: 1.4;
- padding-left: 4px;
margin-top: 8px;
}
}
}
- .rerank-config {
- margin-top: 20px;
- padding: 20px;
- background: #f8fdf8;
- border-radius: 8px;
- border-left: 4px solid #07c05f;
- }
.multimodal-test {
margin-top: 20px;
diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go
index 34fbf5da4..bafb66980 100644
--- a/internal/application/service/knowledge.go
+++ b/internal/application/service/knowledge.go
@@ -112,11 +112,19 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
logger.Info(ctx, "Non-image file with multimodal enabled, skipping COS/VLM validation")
} else {
// 检查COS配置
- if kb.COSConfig.SecretID == "" || kb.COSConfig.SecretKey == "" ||
- kb.COSConfig.Region == "" || kb.COSConfig.BucketName == "" ||
- kb.COSConfig.AppID == "" {
- logger.Error(ctx, "COS configuration incomplete for image multimodal processing")
- return nil, werrors.NewBadRequestError("上传图片文件需要完整的COS配置信息, 请前往系统设置页面进行补全")
+ switch kb.StorageConfig.Provider {
+ case "cos":
+ if kb.StorageConfig.SecretID == "" || kb.StorageConfig.SecretKey == "" ||
+ kb.StorageConfig.Region == "" || kb.StorageConfig.BucketName == "" ||
+ kb.StorageConfig.AppID == "" {
+ logger.Error(ctx, "COS configuration incomplete for image multimodal processing")
+ return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往系统设置页面进行补全")
+ }
+ case "minio":
+ if kb.StorageConfig.BucketName == "" {
+ logger.Error(ctx, "MinIO configuration incomplete for image multimodal processing")
+ return nil, werrors.NewBadRequestError("上传图片文件需要完整的对象存储配置信息, 请前往系统设置页面进行补全")
+ }
}
// 检查VLM配置
@@ -317,7 +325,8 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
if enableMultimodel == nil {
enableMultimodel = &kb.ChunkingConfig.EnableMultimodal
}
- go s.processDocumentFromURL(ctx, kb, knowledge, url, *enableMultimodel)
+ newCtx := logger.CloneContext(ctx)
+ go s.processDocumentFromURL(newCtx, kb, knowledge, url, *enableMultimodel)
logger.Infof(ctx, "Knowledge from URL created successfully, ID: %s", knowledge.ID)
return knowledge, nil
@@ -670,13 +679,14 @@ func (s *knowledgeService) processDocument(ctx context.Context,
ChunkOverlap: int32(kb.ChunkingConfig.ChunkOverlap),
Separators: kb.ChunkingConfig.Separators,
EnableMultimodal: enableMultimodel,
- CosConfig: &proto.COSConfig{
- SecretId: kb.COSConfig.SecretID,
- SecretKey: kb.COSConfig.SecretKey,
- Region: kb.COSConfig.Region,
- BucketName: kb.COSConfig.BucketName,
- AppId: kb.COSConfig.AppID,
- PathPrefix: kb.COSConfig.PathPrefix,
+ StorageConfig: &proto.StorageConfig{
+ Provider: proto.StorageProvider(proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)]),
+ Region: kb.StorageConfig.Region,
+ BucketName: kb.StorageConfig.BucketName,
+ AccessKeyId: kb.StorageConfig.SecretID,
+ SecretAccessKey: kb.StorageConfig.SecretKey,
+ AppId: kb.StorageConfig.AppID,
+ PathPrefix: kb.StorageConfig.PathPrefix,
},
VlmConfig: &proto.VLMConfig{
ModelName: kb.VLMConfig.ModelName,
@@ -724,13 +734,14 @@ func (s *knowledgeService) processDocumentFromURL(ctx context.Context,
ChunkOverlap: int32(kb.ChunkingConfig.ChunkOverlap),
Separators: kb.ChunkingConfig.Separators,
EnableMultimodal: enableMultimodel,
- CosConfig: &proto.COSConfig{
- SecretId: kb.COSConfig.SecretID,
- SecretKey: kb.COSConfig.SecretKey,
- Region: kb.COSConfig.Region,
- BucketName: kb.COSConfig.BucketName,
- AppId: kb.COSConfig.AppID,
- PathPrefix: kb.COSConfig.PathPrefix,
+ StorageConfig: &proto.StorageConfig{
+ Provider: proto.StorageProvider(proto.StorageProvider_value[strings.ToUpper(kb.StorageConfig.Provider)]),
+ Region: kb.StorageConfig.Region,
+ BucketName: kb.StorageConfig.BucketName,
+ AccessKeyId: kb.StorageConfig.SecretID,
+ SecretAccessKey: kb.StorageConfig.SecretKey,
+ AppId: kb.StorageConfig.AppID,
+ PathPrefix: kb.StorageConfig.PathPrefix,
},
VlmConfig: &proto.VLMConfig{
ModelName: kb.VLMConfig.ModelName,
diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go
index 1710d3149..19e7a7fef 100644
--- a/internal/application/service/knowledgebase.go
+++ b/internal/application/service/knowledgebase.go
@@ -249,7 +249,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
SummaryModelID: sourceKB.SummaryModelID,
RerankModelID: sourceKB.RerankModelID,
VLMModelID: sourceKB.VLMModelID,
- COSConfig: sourceKB.COSConfig,
+ StorageConfig: sourceKB.StorageConfig,
}
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
return nil, nil, err
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go
index bef87e3a7..e16dcd09e 100644
--- a/internal/handler/initialization.go
+++ b/internal/handler/initialization.go
@@ -80,7 +80,9 @@ func NewInitializationHandler(
// InitializationRequest 初始化请求结构
type InitializationRequest struct {
- LLM struct {
+ // 前端传入的存储类型:cos 或 minio
+ StorageType string `json:"storageType"`
+ LLM struct {
Source string `json:"source" binding:"required"`
ModelName string `json:"modelName" binding:"required"`
BaseURL string `json:"baseUrl"`
@@ -118,6 +120,10 @@ type InitializationRequest struct {
AppID string `json:"appId"`
PathPrefix string `json:"pathPrefix"`
} `json:"cos,omitempty"`
+ Minio *struct {
+ BucketName string `json:"bucketName"`
+ PathPrefix string `json:"pathPrefix"`
+ } `json:"minio,omitempty"`
} `json:"multimodal"`
DocumentSplitting struct {
@@ -195,9 +201,10 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
// 验证多模态配置
if req.Multimodal.Enabled {
- if req.Multimodal.VLM == nil || req.Multimodal.COS == nil {
- logger.Error(ctx, "Multimodal enabled but missing VLM or COS configuration")
- c.Error(errors.NewBadRequestError("启用多模态时需要配置VLM和COS信息"))
+ storageType := strings.ToLower(req.StorageType)
+ if req.Multimodal.VLM == nil {
+ logger.Error(ctx, "Multimodal enabled but missing VLM configuration")
+ c.Error(errors.NewBadRequestError("启用多模态时需要配置VLM信息"))
return
}
if req.Multimodal.VLM.InterfaceType == "ollama" {
@@ -208,12 +215,22 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
c.Error(errors.NewBadRequestError("VLM配置不完整"))
return
}
- if req.Multimodal.COS.SecretID == "" || req.Multimodal.COS.SecretKey == "" ||
- req.Multimodal.COS.Region == "" || req.Multimodal.COS.BucketName == "" ||
- req.Multimodal.COS.AppID == "" {
- logger.Error(ctx, "COS configuration incomplete")
- c.Error(errors.NewBadRequestError("COS配置不完整"))
- return
+ switch storageType {
+ case "cos":
+ if req.Multimodal.COS == nil || req.Multimodal.COS.SecretID == "" || req.Multimodal.COS.SecretKey == "" ||
+ req.Multimodal.COS.Region == "" || req.Multimodal.COS.BucketName == "" ||
+ req.Multimodal.COS.AppID == "" {
+ logger.Error(ctx, "COS configuration incomplete")
+ c.Error(errors.NewBadRequestError("COS配置不完整"))
+ return
+ }
+ case "minio":
+ if req.Multimodal.Minio == nil || req.Multimodal.Minio.BucketName == "" ||
+ os.Getenv("MINIO_ACCESS_KEY_ID") == "" || os.Getenv("MINIO_SECRET_ACCESS_KEY") == "" {
+ logger.Error(ctx, "MinIO configuration incomplete")
+ c.Error(errors.NewBadRequestError("MinIO配置不完整"))
+ return
+ }
}
}
@@ -520,14 +537,30 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
APIKey: req.Multimodal.VLM.APIKey,
InterfaceType: req.Multimodal.VLM.InterfaceType,
},
- COSConfig: types.COSConfig{
- SecretID: req.Multimodal.COS.SecretID,
- SecretKey: req.Multimodal.COS.SecretKey,
- Region: req.Multimodal.COS.Region,
- BucketName: req.Multimodal.COS.BucketName,
- AppID: req.Multimodal.COS.AppID,
- PathPrefix: req.Multimodal.COS.PathPrefix,
- },
+ }
+ switch req.StorageType {
+ case "cos":
+ if req.Multimodal.COS != nil {
+ kb.StorageConfig = types.StorageConfig{
+ Provider: req.StorageType,
+ BucketName: req.Multimodal.COS.BucketName,
+ AppID: req.Multimodal.COS.AppID,
+ PathPrefix: req.Multimodal.COS.PathPrefix,
+ SecretID: req.Multimodal.COS.SecretID,
+ SecretKey: req.Multimodal.COS.SecretKey,
+ Region: req.Multimodal.COS.Region,
+ }
+ }
+ case "minio":
+ if req.Multimodal.Minio != nil {
+ kb.StorageConfig = types.StorageConfig{
+ Provider: req.StorageType,
+ BucketName: req.Multimodal.Minio.BucketName,
+ PathPrefix: req.Multimodal.Minio.PathPrefix,
+ SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
+ SecretKey: os.Getenv("MINIO_SECRET_ACCESS_KEY"),
+ }
+ }
}
_, err = h.kbService.CreateKnowledgeBase(newCtx, kb)
@@ -562,19 +595,35 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
APIKey: req.Multimodal.VLM.APIKey,
InterfaceType: req.Multimodal.VLM.InterfaceType,
}
- kb.COSConfig = types.COSConfig{
- SecretID: req.Multimodal.COS.SecretID,
- SecretKey: req.Multimodal.COS.SecretKey,
- Region: req.Multimodal.COS.Region,
- BucketName: req.Multimodal.COS.BucketName,
- AppID: req.Multimodal.COS.AppID,
- PathPrefix: req.Multimodal.COS.PathPrefix,
+ switch req.StorageType {
+ case "cos":
+ if req.Multimodal.COS != nil {
+ kb.StorageConfig = types.StorageConfig{
+ Provider: req.StorageType,
+ SecretID: req.Multimodal.COS.SecretID,
+ SecretKey: req.Multimodal.COS.SecretKey,
+ Region: req.Multimodal.COS.Region,
+ BucketName: req.Multimodal.COS.BucketName,
+ AppID: req.Multimodal.COS.AppID,
+ PathPrefix: req.Multimodal.COS.PathPrefix,
+ }
+ }
+ case "minio":
+ if req.Multimodal.Minio != nil {
+ kb.StorageConfig = types.StorageConfig{
+ Provider: req.StorageType,
+ BucketName: req.Multimodal.Minio.BucketName,
+ PathPrefix: req.Multimodal.Minio.PathPrefix,
+ SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
+ SecretKey: os.Getenv("MINIO_SECRET_ACCESS_KEY"),
+ }
+ }
}
} else {
kb.VLMModelID = "" // 清空VLM模型ID
// 清空VLM配置
kb.VLMConfig = types.VLMConfig{}
- kb.COSConfig = types.COSConfig{}
+ kb.StorageConfig = types.StorageConfig{}
}
if !hasFiles {
kb.EmbeddingModelID = embeddingModelID
@@ -642,6 +691,12 @@ func (h *InitializationHandler) CheckOllamaStatus(c *gin.Context) {
logger.Info(ctx, "Checking Ollama service status")
+ // Determine Ollama base URL for display
+ baseURL := os.Getenv("OLLAMA_BASE_URL")
+ if baseURL == "" {
+ baseURL = "http://host.docker.internal:11434"
+ }
+
// 检查Ollama服务是否可用
err := h.ollamaService.StartService(ctx)
if err != nil {
@@ -651,6 +706,7 @@ func (h *InitializationHandler) CheckOllamaStatus(c *gin.Context) {
"data": gin.H{
"available": false,
"error": err.Error(),
+ "baseUrl": baseURL,
},
})
return
@@ -668,6 +724,7 @@ func (h *InitializationHandler) CheckOllamaStatus(c *gin.Context) {
"data": gin.H{
"available": h.ollamaService.IsAvailable(),
"version": version,
+ "baseUrl": baseURL,
},
})
}
@@ -702,7 +759,11 @@ func (h *InitializationHandler) CheckOllamaModels(c *gin.Context) {
// 检查每个模型是否存在
for _, modelName := range req.Models {
- available, err := h.ollamaService.IsModelAvailable(ctx, modelName)
+ checkModelName := modelName
+ if !strings.Contains(modelName, ":") {
+ checkModelName = modelName + ":latest"
+ }
+ available, err := h.ollamaService.IsModelAvailable(ctx, checkModelName)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_name": modelName,
@@ -867,6 +928,36 @@ func (h *InitializationHandler) ListDownloadTasks(c *gin.Context) {
})
}
+// ListOllamaModels 列出已安装的 Ollama 模型
+func (h *InitializationHandler) ListOllamaModels(c *gin.Context) {
+ ctx := c.Request.Context()
+
+ logger.Info(ctx, "Listing installed Ollama models")
+
+ // 确保服务可用
+ if !h.ollamaService.IsAvailable() {
+ if err := h.ollamaService.StartService(ctx); err != nil {
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(errors.NewInternalServerError("Ollama服务不可用: " + err.Error()))
+ return
+ }
+ }
+
+ models, err := h.ollamaService.ListModels(ctx)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(errors.NewInternalServerError("获取模型列表失败: " + err.Error()))
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "models": models,
+ },
+ })
+}
+
// downloadModelAsync 异步下载模型
func (h *InitializationHandler) downloadModelAsync(ctx context.Context,
taskID, modelName string,
@@ -974,20 +1065,6 @@ func (h *InitializationHandler) updateTaskStatus(
}
}
-// 清理过期任务 (可以在后台定期执行)
-func (h *InitializationHandler) cleanupExpiredTasks() {
- tasksMutex.Lock()
- defer tasksMutex.Unlock()
-
- cutoff := time.Now().Add(-24 * time.Hour) // 保留24小时内的任务
-
- for id, task := range downloadTasks {
- if task.EndTime != nil && task.EndTime.Before(cutoff) {
- delete(downloadTasks, id)
- }
- }
-}
-
// GetCurrentConfig 获取当前系统配置信息
func (h *InitializationHandler) GetCurrentConfig(c *gin.Context) {
ctx := c.Request.Context()
@@ -1109,20 +1186,29 @@ func buildConfigResponse(models []*types.Model,
}
// 添加多模态的COS配置信息
- if kb.COSConfig.SecretID != "" {
+ if kb.StorageConfig.SecretID != "" {
if config["multimodal"] == nil {
config["multimodal"] = map[string]interface{}{
"enabled": true,
}
}
multimodal := config["multimodal"].(map[string]interface{})
- multimodal["cos"] = map[string]interface{}{
- "secretId": kb.COSConfig.SecretID,
- "secretKey": kb.COSConfig.SecretKey,
- "region": kb.COSConfig.Region,
- "bucketName": kb.COSConfig.BucketName,
- "appId": kb.COSConfig.AppID,
- "pathPrefix": kb.COSConfig.PathPrefix,
+ multimodal["storageType"] = kb.StorageConfig.Provider
+ switch kb.StorageConfig.Provider {
+ case "cos":
+ multimodal["cos"] = map[string]interface{}{
+ "secretId": kb.StorageConfig.SecretID,
+ "secretKey": kb.StorageConfig.SecretKey,
+ "region": kb.StorageConfig.Region,
+ "bucketName": kb.StorageConfig.BucketName,
+ "appId": kb.StorageConfig.AppID,
+ "pathPrefix": kb.StorageConfig.PathPrefix,
+ }
+ case "minio":
+ multimodal["minio"] = map[string]interface{}{
+ "bucketName": kb.StorageConfig.BucketName,
+ "pathPrefix": kb.StorageConfig.PathPrefix,
+ }
}
}
}
@@ -1434,110 +1520,84 @@ func (h *InitializationHandler) CheckRerankModel(c *gin.Context) {
})
}
+// 使用结构体解析表单数据
+type testMultimodalForm struct {
+ VLMModel string `form:"vlm_model"`
+ VLMBaseURL string `form:"vlm_base_url"`
+ VLMAPIKey string `form:"vlm_api_key"`
+ VLMInterfaceType string `form:"vlm_interface_type"`
+
+ StorageType string `form:"storage_type"`
+
+ // COS 配置
+ COSSecretID string `form:"cos_secret_id"`
+ COSSecretKey string `form:"cos_secret_key"`
+ COSRegion string `form:"cos_region"`
+ COSBucketName string `form:"cos_bucket_name"`
+ COSAppID string `form:"cos_app_id"`
+ COSPathPrefix string `form:"cos_path_prefix"`
+
+ // MinIO 配置(当存储为 minio 时)
+ MinioBucketName string `form:"minio_bucket_name"`
+ MinioPathPrefix string `form:"minio_path_prefix"`
+
+ // 文档切分配置(字符串后续自行解析,以避免类型绑定失败)
+ ChunkSize string `form:"chunk_size"`
+ ChunkOverlap string `form:"chunk_overlap"`
+ SeparatorsRaw string `form:"separators"`
+}
+
// TestMultimodalFunction 测试多模态功能
func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Testing multimodal functionality")
- // 解析表单数据
- vlmModel := c.PostForm("vlm_model")
- vlmBaseURL := c.PostForm("vlm_base_url")
- vlmAPIKey := c.PostForm("vlm_api_key")
- vlmInterfaceType := c.PostForm("vlm_interface_type")
-
- if vlmInterfaceType == "ollama" {
- vlmBaseURL = os.Getenv("OLLAMA_BASE_URL") + "/v1"
+ var req testMultimodalForm
+ if err := c.ShouldBind(&req); err != nil {
+ logger.Error(ctx, "Failed to parse form data", err)
+ c.Error(errors.NewBadRequestError("表单参数解析失败"))
+ return
}
-
- // 如果没有提供VLM配置,尝试从KnowledgeBase获取
- if vlmModel == "" || vlmBaseURL == "" {
- logger.Info(ctx, "VLM configuration not provided, trying to get from KnowledgeBase")
-
- // 获取默认知识库
- kb, err := h.kbService.GetKnowledgeBaseByID(ctx, types.InitDefaultKnowledgeBaseID)
- if err != nil {
- logger.Error(ctx, "Failed to get KnowledgeBase", err)
- c.Error(errors.NewBadRequestError("获取知识库配置失败"))
- return
- }
-
- // 使用知识库中的VLM配置
- if kb.VLMConfig.ModelName != "" && kb.VLMConfig.BaseURL != "" {
- vlmModel = kb.VLMConfig.ModelName
- vlmBaseURL = kb.VLMConfig.BaseURL
- vlmAPIKey = kb.VLMConfig.APIKey
- vlmInterfaceType = kb.VLMConfig.InterfaceType
- logger.Infof(ctx, "Using VLM config from KnowledgeBase: Model=%s, URL=%s, Type=%s",
- vlmModel, vlmBaseURL, vlmInterfaceType)
- } else {
- logger.Error(ctx, "VLM configuration not found in KnowledgeBase")
- c.Error(errors.NewBadRequestError("知识库中未找到VLM配置信息"))
- return
- }
+ // ollama 场景自动拼接 base url
+ if req.VLMInterfaceType == "ollama" {
+ req.VLMBaseURL = os.Getenv("OLLAMA_BASE_URL") + "/v1"
}
- // COS配置
- cosSecretID := c.PostForm("cos_secret_id")
- cosSecretKey := c.PostForm("cos_secret_key")
- cosRegion := c.PostForm("cos_region")
- cosBucketName := c.PostForm("cos_bucket_name")
- cosAppID := c.PostForm("cos_app_id")
- cosPathPrefix := c.PostForm("cos_path_prefix")
+ req.StorageType = strings.ToLower(req.StorageType)
- // 如果没有提供COS配置,尝试从KnowledgeBase获取
- if cosSecretID == "" || cosSecretKey == "" ||
- cosRegion == "" || cosBucketName == "" || cosAppID == "" {
- logger.Info(ctx, "COS configuration not provided, trying to get from KnowledgeBase")
-
- // 获取默认知识库
- kb, err := h.kbService.GetKnowledgeBaseByID(ctx, types.InitDefaultKnowledgeBaseID)
- if err != nil {
- logger.Error(ctx, "Failed to get KnowledgeBase", err)
- c.Error(errors.NewBadRequestError("获取知识库配置失败"))
- return
- }
-
- // 使用知识库中的COS配置
- if kb.COSConfig.SecretID != "" && kb.COSConfig.SecretKey != "" {
- cosSecretID = kb.COSConfig.SecretID
- cosSecretKey = kb.COSConfig.SecretKey
- cosRegion = kb.COSConfig.Region
- cosBucketName = kb.COSConfig.BucketName
- cosAppID = kb.COSConfig.AppID
- cosPathPrefix = kb.COSConfig.PathPrefix
- logger.Infof(ctx, "Using COS config from KnowledgeBase: Region=%s, Bucket=%s, App=%s",
- cosRegion, cosBucketName, cosAppID)
- } else {
- logger.Error(ctx, "COS configuration not found in KnowledgeBase")
- c.Error(errors.NewBadRequestError("知识库中未找到COS配置信息"))
- return
- }
- }
-
- // 文档分割配置
- chunkSizeStr := c.PostForm("chunk_size")
- chunkOverlapStr := c.PostForm("chunk_overlap")
- separatorsStr := c.PostForm("separators")
-
- if vlmModel == "" || vlmBaseURL == "" {
+ if req.VLMModel == "" || req.VLMBaseURL == "" {
logger.Error(ctx, "VLM model name and base URL are required")
c.Error(errors.NewBadRequestError("VLM模型名称和Base URL不能为空"))
return
}
-
- if cosSecretID == "" || cosSecretKey == "" ||
- cosRegion == "" || cosBucketName == "" || cosAppID == "" {
- logger.Error(ctx, "COS configuration is required")
- c.Error(errors.NewBadRequestError("COS配置信息不能为空"))
+ switch req.StorageType {
+ case "cos":
+ logger.Infof(ctx, "COS config: ID=%s, Region=%s, Bucket=%s, App=%s, Prefix=%s",
+ req.COSSecretID, req.COSRegion, req.COSBucketName, req.COSAppID, req.COSPathPrefix)
+ // 必填:SecretID/SecretKey/Region/BucketName/AppID;PathPrefix 可选
+ if req.COSSecretID == "" || req.COSSecretKey == "" ||
+ req.COSRegion == "" || req.COSBucketName == "" ||
+ req.COSAppID == "" {
+ logger.Error(ctx, "COS configuration is required")
+ c.Error(errors.NewBadRequestError("COS配置信息不能为空"))
+ return
+ }
+ case "minio":
+ logger.Infof(ctx, "MinIO config: Bucket=%s, PathPrefix=%s", req.MinioBucketName, req.MinioPathPrefix)
+ if req.MinioBucketName == "" {
+ logger.Error(ctx, "MinIO configuration is required")
+ c.Error(errors.NewBadRequestError("MinIO配置信息不能为空"))
+ return
+ }
+ default:
+ logger.Error(ctx, "Invalid storage type")
+ c.Error(errors.NewBadRequestError("无效的存储类型"))
return
}
- // 记录COS配置信息用于日志
- logger.Infof(ctx, "COS config: ID=%s, Region=%s, Bucket=%s, App=%s, Prefix=%s",
- cosSecretID, cosRegion, cosBucketName, cosAppID, cosPathPrefix)
logger.Infof(ctx, "VLM config: Model=%s, URL=%s, HasKey=%v, Type=%s",
- vlmModel, vlmBaseURL, vlmAPIKey != "", vlmInterfaceType)
+ req.VLMModel, req.VLMBaseURL, req.VLMAPIKey != "", req.VLMInterfaceType)
// 获取上传的图片文件
file, header, err := c.Request.FormFile("image")
@@ -1561,27 +1621,26 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
c.Error(errors.NewBadRequestError("图片文件大小不能超过10MB"))
return
}
-
logger.Infof(ctx, "Processing image: %s, size: %d bytes", header.Filename, header.Size)
// 解析文档分割配置
- chunkSize, err := strconv.Atoi(chunkSizeStr)
+ chunkSize, err := strconv.Atoi(req.ChunkSize)
if err != nil || chunkSize < 100 || chunkSize > 10000 {
- chunkSize = 1000 // 默认值
+ chunkSize = 1000
}
- chunkOverlap, err := strconv.Atoi(chunkOverlapStr)
+ chunkOverlap, err := strconv.Atoi(req.ChunkOverlap)
if err != nil || chunkOverlap < 0 || chunkOverlap >= chunkSize {
- chunkOverlap = 200 // 默认值
+ chunkOverlap = 200
}
var separators []string
- if separatorsStr != "" {
- if err := json.Unmarshal([]byte(separatorsStr), &separators); err != nil {
- separators = []string{"\n\n", "\n", "。", "!", "?", ";", ";"} // 默认值
+ if req.SeparatorsRaw != "" {
+ if err := json.Unmarshal([]byte(req.SeparatorsRaw), &separators); err != nil {
+ separators = []string{"\n\n", "\n", "。", "!", "?", ";", ";"}
}
} else {
- separators = []string{"\n\n", "\n", "。", "!", "?", ";", ";"} // 默认值
+ separators = []string{"\n\n", "\n", "。", "!", "?", ";", ";"}
}
// 读取图片文件内容
@@ -1594,16 +1653,17 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
// 调用多模态测试
startTime := time.Now()
- result, err := h.testMultimodalWithDocReader(ctx, imageContent, header.Filename,
- chunkSize, chunkOverlap, separators,
- vlmModel, vlmBaseURL, vlmAPIKey, vlmInterfaceType,
- cosSecretID, cosSecretKey, cosRegion, cosBucketName, cosAppID, cosPathPrefix)
+ result, err := h.testMultimodalWithDocReader(
+ ctx,
+ imageContent, header.Filename,
+ chunkSize, chunkOverlap, separators, &req,
+ )
processingTime := time.Since(startTime).Milliseconds()
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "vlm_model": vlmModel,
- "vlm_base_url": vlmBaseURL,
+ "vlm_model": req.VLMModel,
+ "vlm_base_url": req.VLMBaseURL,
"filename": header.Filename,
})
c.JSON(http.StatusOK, gin.H{
@@ -1631,12 +1691,12 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
}
// testMultimodalWithDocReader 调用docreader服务进行多模态处理
-func (h *InitializationHandler) testMultimodalWithDocReader(ctx context.Context,
+func (h *InitializationHandler) testMultimodalWithDocReader(
+ ctx context.Context,
imageContent []byte, filename string,
chunkSize, chunkOverlap int, separators []string,
- vlmModel, vlmBaseURL, vlmAPIKey, vlmInterfaceType,
- cosSecretID, cosSecretKey, cosRegion, cosBucketName, cosAppID, cosPathPrefix string) (
- map[string]string, error) {
+ req *testMultimodalForm,
+) (map[string]string, error) {
// 获取文件扩展名
fileExt := ""
if idx := strings.LastIndex(filename, "."); idx != -1 {
@@ -1659,23 +1719,37 @@ func (h *InitializationHandler) testMultimodalWithDocReader(ctx context.Context,
Separators: separators,
EnableMultimodal: true, // 启用多模态处理
VlmConfig: &proto.VLMConfig{
- ModelName: vlmModel,
- BaseUrl: vlmBaseURL,
- ApiKey: vlmAPIKey,
- InterfaceType: vlmInterfaceType,
- },
- CosConfig: &proto.COSConfig{
- SecretId: cosSecretID,
- SecretKey: cosSecretKey,
- Region: cosRegion,
- BucketName: cosBucketName,
- AppId: cosAppID,
- PathPrefix: cosPathPrefix,
+ ModelName: req.VLMModel,
+ BaseUrl: req.VLMBaseURL,
+ ApiKey: req.VLMAPIKey,
+ InterfaceType: req.VLMInterfaceType,
},
},
RequestId: ctx.Value(types.RequestIDContextKey).(string),
}
+ // 设置对象存储配置(通用)
+ switch strings.ToLower(req.StorageType) {
+ case "cos":
+ request.ReadConfig.StorageConfig = &proto.StorageConfig{
+ Provider: proto.StorageProvider_COS,
+ Region: req.COSRegion,
+ BucketName: req.COSBucketName,
+ AccessKeyId: req.COSSecretID,
+ SecretAccessKey: req.COSSecretKey,
+ AppId: req.COSAppID,
+ PathPrefix: req.COSPathPrefix,
+ }
+ case "minio":
+ request.ReadConfig.StorageConfig = &proto.StorageConfig{
+ Provider: proto.StorageProvider_MINIO,
+ BucketName: req.MinioBucketName,
+ PathPrefix: req.MinioPathPrefix,
+ AccessKeyId: os.Getenv("MINIO_ACCESS_KEY_ID"),
+ SecretAccessKey: os.Getenv("MINIO_SECRET_ACCESS_KEY"),
+ }
+ }
+
// 调用docreader服务
response, err := h.docReaderClient.ReadFromFile(ctx, request)
if err != nil {
diff --git a/internal/router/router.go b/internal/router/router.go
index 4e1997ec3..2f2a728cb 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -70,6 +70,7 @@ func NewRouter(params RouterParams) *gin.Engine {
// Ollama相关接口(不需要认证)
r.GET("/api/v1/initialization/ollama/status", params.InitializationHandler.CheckOllamaStatus)
+ r.GET("/api/v1/initialization/ollama/models", params.InitializationHandler.ListOllamaModels)
r.POST("/api/v1/initialization/ollama/models/check", params.InitializationHandler.CheckOllamaModels)
r.POST("/api/v1/initialization/ollama/models/download", params.InitializationHandler.DownloadOllamaModel)
r.GET("/api/v1/initialization/ollama/download/progress/:taskId", params.InitializationHandler.GetDownloadProgress)
diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go
index e4be93527..22b9eaeff 100644
--- a/internal/types/knowledgebase.go
+++ b/internal/types/knowledgebase.go
@@ -36,8 +36,8 @@ type KnowledgeBase struct {
VLMModelID string `yaml:"vlm_model_id" json:"vlm_model_id"`
// VLM config
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"`
- // COS config
- COSConfig COSConfig `yaml:"cos_config" json:"cos_config" gorm:"type:json"`
+ // Storage config
+ StorageConfig StorageConfig `yaml:"cos_config" json:"cos_config" gorm:"column:cos_config;type:json"`
// Creation time of the knowledge base
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time of the knowledge base
@@ -67,7 +67,7 @@ type ChunkingConfig struct {
}
// COSConfig represents the COS configuration
-type COSConfig struct {
+type StorageConfig struct {
// Secret ID
SecretID string `yaml:"secret_id" json:"secret_id"`
// Secret Key
@@ -80,13 +80,15 @@ type COSConfig struct {
AppID string `yaml:"app_id" json:"app_id"`
// Path Prefix
PathPrefix string `yaml:"path_prefix" json:"path_prefix"`
+ // Provider
+ Provider string `yaml:"provider" json:"provider"`
}
-func (c *COSConfig) Value() (driver.Value, error) {
+func (c *StorageConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
-func (c *COSConfig) Scan(value interface{}) error {
+func (c *StorageConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
diff --git a/scripts/start_all.sh b/scripts/start_all.sh
index 838cb7f47..178ee7282 100755
--- a/scripts/start_all.sh
+++ b/scripts/start_all.sh
@@ -80,18 +80,20 @@ check_env_file() {
if [ -z "$DB_DRIVER" ]; then missing_vars+=("DB_DRIVER"); fi
if [ -z "$STORAGE_TYPE" ]; then missing_vars+=("STORAGE_TYPE"); fi
- if [ ${#missing_vars[@]} -gt 0 ]; then
- log_warning "以下环境变量未设置,将使用默认值: ${missing_vars[*]}"
- else
- log_success "所有必要的环境变量已设置"
- fi
-
return 0
}
# 安装Ollama(根据平台不同采用不同方法)
install_ollama() {
- log_info "Ollama未安装,正在安装..."
+ # 检查是否为远程服务
+ get_ollama_base_url
+
+ if [ $IS_REMOTE -eq 1 ]; then
+ log_info "检测到远程Ollama服务配置,无需在本地安装Ollama"
+ return 0
+ fi
+
+ log_info "本地Ollama未安装,正在安装..."
OS=$(uname)
if [ "$OS" = "Darwin" ]; then
@@ -114,18 +116,54 @@ install_ollama() {
fi
if [ $? -eq 0 ]; then
- log_success "Ollama安装完成"
+ log_success "本地Ollama安装完成"
return 0
else
- log_error "Ollama安装失败"
+ log_error "本地Ollama安装失败"
return 1
fi
}
+# 获取Ollama基础URL,检查是否为远程服务
+get_ollama_base_url() {
+
+ check_env_file
+
+ # 从环境变量获取Ollama基础URL
+ OLLAMA_URL=${OLLAMA_BASE_URL:-"http://host.docker.internal:11434"}
+ # 提取主机部分
+ OLLAMA_HOST=$(echo "$OLLAMA_URL" | sed -E 's|^https?://||' | sed -E 's|:[0-9]+$||' | sed -E 's|/.*$||')
+ # 提取端口部分
+ OLLAMA_PORT=$(echo "$OLLAMA_URL" | grep -oE ':[0-9]+' | grep -oE '[0-9]+' || echo "11434")
+ # 检查是否为localhost或127.0.0.1
+ IS_REMOTE=0
+ if [ "$OLLAMA_HOST" = "localhost" ] || [ "$OLLAMA_HOST" = "127.0.0.1" ] || [ "$OLLAMA_HOST" = "host.docker.internal" ]; then
+ IS_REMOTE=0 # 本地服务
+ else
+ IS_REMOTE=1 # 远程服务
+ fi
+}
+
# 启动Ollama服务
start_ollama() {
log_info "正在检查Ollama服务..."
+ # 提取主机和端口
+ get_ollama_base_url
+ log_info "Ollama服务地址: $OLLAMA_URL"
+
+ if [ $IS_REMOTE -eq 1 ]; then
+ log_info "检测到远程Ollama服务,将直接使用远程服务,不进行本地安装和启动"
+ # 检查远程服务是否可用
+ if curl -s "$OLLAMA_URL/api/tags" &> /dev/null; then
+ log_success "远程Ollama服务可访问"
+ return 0
+ else
+ log_warning "远程Ollama服务不可访问,请确认服务地址正确且已启动"
+ return 1
+ fi
+ fi
+ # 以下为本地服务的处理
# 检查Ollama是否已安装
if ! command -v ollama &> /dev/null; then
install_ollama
@@ -135,19 +173,19 @@ start_ollama() {
fi
# 检查Ollama服务是否已运行
- if curl -s http://localhost:11434/api/tags &> /dev/null; then
- log_success "Ollama服务已经在运行"
+ if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
+ log_success "本地Ollama服务已经在运行,端口:$OLLAMA_PORT"
else
- log_info "启动Ollama服务..."
+ log_info "启动本地Ollama服务..."
# 注意:官方推荐使用 systemctl 或 launchctl 管理服务,直接后台运行仅用于临时场景
- systemctl restart ollama || (ollama serve > /dev/null 2>&1 &)
+ systemctl restart ollama || (ollama serve > /dev/null 2>&1 < /dev/null &)
# 等待服务启动
MAX_RETRIES=30
COUNT=0
while [ $COUNT -lt $MAX_RETRIES ]; do
- if curl -s http://localhost:11434/api/tags &> /dev/null; then
- log_success "Ollama服务已成功启动"
+ if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
+ log_success "本地Ollama服务已成功启动,端口:$OLLAMA_PORT"
break
fi
echo -ne "等待Ollama服务启动... ($COUNT/$MAX_RETRIES)\r"
@@ -157,12 +195,12 @@ start_ollama() {
echo "" # 换行
if [ $COUNT -eq $MAX_RETRIES ]; then
- log_error "Ollama服务启动失败"
+ log_error "本地Ollama服务启动失败"
return 1
fi
fi
- log_success "Ollama服务地址: http://localhost:11434"
+ log_success "本地Ollama服务地址: http://localhost:$OLLAMA_PORT"
return 0
}
@@ -170,9 +208,17 @@ start_ollama() {
stop_ollama() {
log_info "正在停止Ollama服务..."
+ # 检查是否为远程服务
+ get_ollama_base_url
+
+ if [ $IS_REMOTE -eq 1 ]; then
+ log_info "检测到远程Ollama服务,无需在本地停止"
+ return 0
+ fi
+
# 检查Ollama是否已安装
if ! command -v ollama &> /dev/null; then
- log_info "Ollama未安装,无需停止"
+ log_info "本地Ollama未安装,无需停止"
return 0
fi
@@ -184,9 +230,9 @@ stop_ollama() {
else
pkill -f "ollama serve"
fi
- log_success "Ollama服务已停止"
+ log_success "本地Ollama服务已停止"
else
- log_info "Ollama服务未运行"
+ log_info "本地Ollama服务未运行"
fi
return 0
@@ -217,6 +263,20 @@ check_docker() {
return 0
}
+check_platform() {
+ # 检测当前系统平台
+ log_info "检测系统平台信息..."
+ if [ "$(uname -m)" = "x86_64" ]; then
+ export PLATFORM="linux/amd64"
+ elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then
+ export PLATFORM="linux/arm64"
+ else
+ log_warning "未识别的平台类型:$(uname -m),将使用默认平台 linux/amd64"
+ export PLATFORM="linux/amd64"
+ fi
+ log_info "当前平台:$PLATFORM"
+}
+
# 启动Docker容器
start_docker() {
log_info "正在启动Docker容器..."
@@ -233,18 +293,8 @@ start_docker() {
# 读取.env文件
source "$PROJECT_ROOT/.env"
storage_type=${STORAGE_TYPE:-local}
-
- # 检测当前系统平台
- log_info "检测系统平台信息..."
- if [ "$(uname -m)" = "x86_64" ]; then
- export PLATFORM="linux/amd64"
- elif [ "$(uname -m)" = "aarch64" ] || [ "$(uname -m)" = "arm64" ]; then
- export PLATFORM="linux/arm64"
- else
- log_warning "未识别的平台类型:$(uname -m),将使用默认平台 linux/amd64"
- export PLATFORM="linux/amd64"
- fi
- log_info "当前平台:$PLATFORM"
+
+ check_platform
# 进入项目根目录再执行docker-compose命令
cd "$PROJECT_ROOT"
@@ -258,20 +308,6 @@ start_docker() {
return 1
fi
- # 如果存储类型是minio,则启动MinIO服务
- if [ "$storage_type" == "minio" ]; then
- log_info "检测到MinIO存储配置,启动MinIO服务..."
- # *** 修改点: 使用新的 docker compose 命令 ***
- docker compose -f ./docker/docker-compose.minio.yml up --build -d
- if [ $? -ne 0 ]; then
- log_error "MinIO服务启动失败"
- return 1
- fi
- log_success "MinIO服务已启动"
- else
- log_info "使用本地存储,不启动MinIO服务"
- fi
-
log_success "所有Docker容器已成功启动"
# 显示容器状态
@@ -304,12 +340,6 @@ stop_docker() {
return 1
fi
- # 如果存在minio配置,也停止minio
- if [ -f "$PROJECT_ROOT/docker/docker-compose.minio.yml" ]; then
- # *** 修改点: 使用新的 docker compose 命令 ***
- docker compose -f "./docker/docker-compose.minio.yml" down
- fi
-
log_success "所有Docker容器已停止"
return 0
}
@@ -354,6 +384,8 @@ restart_container() {
return 1
fi
+ check_platform
+
# 进入项目根目录再执行docker-compose命令
cd "$PROJECT_ROOT"
@@ -369,7 +401,7 @@ restart_container() {
# 构建并重启容器
log_info "正在重新构建容器 '$container_name'..."
# *** 修改点: 使用新的 docker compose 命令 ***
- docker compose build "$container_name"
+ PLATFORM=$PLATFORM docker compose build "$container_name"
if [ $? -ne 0 ]; then
log_error "容器 '$container_name' 构建失败"
return 1
@@ -377,7 +409,7 @@ restart_container() {
log_info "正在重启容器 '$container_name'..."
# *** 修改点: 使用新的 docker compose 命令 ***
- docker compose up -d --no-deps "$container_name"
+ PLATFORM=$PLATFORM docker compose up -d --no-deps "$container_name"
if [ $? -ne 0 ]; then
log_error "容器 '$container_name' 重启失败"
return 1
@@ -401,17 +433,28 @@ check_environment() {
# 检查.env文件
check_env_file
- # 检查Ollama
- if command -v ollama &> /dev/null; then
- log_success "Ollama已安装"
- if curl -s http://localhost:11434/api/tags &> /dev/null; then
- version=$(curl -s http://localhost:11434/api/tags | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
- log_success "Ollama服务正在运行,版本: $version"
+ get_ollama_base_url
+
+ if [ $IS_REMOTE -eq 1 ]; then
+ log_info "检测到远程Ollama服务配置"
+ if curl -s "$OLLAMA_URL/api/tags" &> /dev/null; then
+ version=$(curl -s "$OLLAMA_URL/api/tags" | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
+ log_success "远程Ollama服务可访问,版本: $version"
else
- log_warning "Ollama已安装但服务未运行"
+ log_warning "远程Ollama服务不可访问,请确认服务地址正确且已启动"
fi
else
- log_warning "Ollama未安装"
+ if command -v ollama &> /dev/null; then
+ log_success "本地Ollama已安装"
+ if curl -s "http://localhost:$OLLAMA_PORT/api/tags" &> /dev/null; then
+ version=$(curl -s "http://localhost:$OLLAMA_PORT/api/tags" | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
+ log_success "本地Ollama服务正在运行,版本: $version"
+ else
+ log_warning "本地Ollama已安装但服务未运行"
+ fi
+ else
+ log_warning "本地Ollama未安装"
+ fi
fi
# 检查磁盘空间
@@ -580,7 +623,7 @@ else
fi
elif [ "$START_OLLAMA" = true ] && [ $OLLAMA_RESULT -eq 0 ]; then
log_success "Ollama服务启动完成,可通过以下地址访问:"
- echo -e "${GREEN} - Ollama API: http://localhost:11434${NC}"
+ echo -e "${GREEN} - Ollama API: http://localhost:$OLLAMA_PORT${NC}"
elif [ "$START_DOCKER" = true ] && [ $DOCKER_RESULT -eq 0 ]; then
log_success "Docker容器启动完成,可通过以下地址访问:"
echo -e "${GREEN} - 前端界面: http://localhost${NC}"
diff --git a/services/docreader/requirements.txt b/services/docreader/requirements.txt
index 245d1c14a..d610c04cd 100644
--- a/services/docreader/requirements.txt
+++ b/services/docreader/requirements.txt
@@ -17,6 +17,7 @@ paddleocr==3.0.0
markdown
pypdf
cos-python-sdk-v5
+minio
textract
antiword
openai
diff --git a/services/docreader/scripts/generate_proto.sh b/services/docreader/scripts/generate_proto.sh
old mode 100644
new mode 100755
diff --git a/services/docreader/src/parser/__init__.py b/services/docreader/src/parser/__init__.py
index a03ffcf0c..c60a01847 100644
--- a/services/docreader/src/parser/__init__.py
+++ b/services/docreader/src/parser/__init__.py
@@ -21,7 +21,8 @@ from .markdown_parser import MarkdownParser
from .text_parser import TextParser
from .image_parser import ImageParser
from .web_parser import WebParser
-from .parser import Parser, ChunkingConfig
+from .parser import Parser
+from .config import ChunkingConfig
from .ocr_engine import OCREngine
# Export public classes and modules
diff --git a/services/docreader/src/parser/base_parser.py b/services/docreader/src/parser/base_parser.py
index 1a1c2f782..eb395b5bf 100644
--- a/services/docreader/src/parser/base_parser.py
+++ b/services/docreader/src/parser/base_parser.py
@@ -1,19 +1,22 @@
# -*- coding: utf-8 -*-
import re
import os
-import uuid
import asyncio
from typing import List, Dict, Any, Optional, Tuple, Union
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
import logging
-from qcloud_cos import CosConfig, CosS3Client
import sys
import traceback
import numpy as np
import time
+import io
+import json
from .ocr_engine import OCREngine
from .image_utils import image_to_base64
+from .config import ChunkingConfig
+from .storage import create_storage
+from PIL import Image
# Add parent directory to Python path for src imports
current_dir = os.path.dirname(os.path.abspath(__file__))
@@ -101,7 +104,7 @@ class BaseParser(ABC):
max_image_size: int = 1920, # Maximum image size
max_concurrent_tasks: int = 5, # Max concurrent tasks
max_chunks: int = 1000, # Max number of returned chunks
- chunking_config: object = None, # Chunking configuration object
+ chunking_config: ChunkingConfig = None, # Chunking configuration object
):
"""Initialize parser
@@ -118,6 +121,8 @@ class BaseParser(ABC):
max_concurrent_tasks: Max concurrent tasks
max_chunks: Max number of returned chunks
"""
+ # Storage client instance
+ self._storage = None
self.file_name = file_name
self.file_type = file_type or os.path.splitext(file_name)[1]
self.enable_multimodal = enable_multimodal
@@ -144,12 +149,7 @@ class BaseParser(ABC):
# Only initialize Caption service if multimodal is enabled
if self.enable_multimodal:
try:
- # Get VLM config from chunking config if available
- vlm_config = None
- if self.chunking_config and hasattr(self.chunking_config, 'vlm_config'):
- vlm_config = self.chunking_config.vlm_config
-
- self.caption_parser = Caption(vlm_config)
+ self.caption_parser = Caption(self.chunking_config.vlm_config)
except Exception as e:
logger.warning(f"Failed to initialize Caption service: {str(e)}")
self.caption_parser = None
@@ -526,70 +526,16 @@ class BaseParser(ABC):
caption = self.get_image_caption(image_data)
return image_data, caption
- def _init_cos_client(self, cos_config=None):
- """Initialize Tencent Cloud COS client"""
- try:
- # Use provided COS config if available, otherwise fall back to environment variables
- if cos_config:
- secret_id = cos_config.get("secret_id")
- secret_key = cos_config.get("secret_key")
- region = cos_config.get("region")
- bucket_name = cos_config.get("bucket_name")
- appid = cos_config.get("app_id")
- prefix = cos_config.get("path_prefix", "")
- enable_old_domain = cos_config.get("enable_old_domain", "true").lower() == "true"
- else:
- # Get COS configuration from environment variables
- secret_id = os.getenv("COS_SECRET_ID")
- secret_key = os.getenv("COS_SECRET_KEY")
- region = os.getenv("COS_REGION")
- bucket_name = os.getenv("COS_BUCKET_NAME")
- appid = os.getenv("COS_APP_ID")
- prefix = os.getenv("COS_PATH_PREFIX")
- enable_old_domain = (
- os.getenv("COS_ENABLE_OLD_DOMAIN", "true").lower() == "true"
- )
-
- if not all([secret_id, secret_key, region, bucket_name, appid]):
- logger.error(
- "Incomplete COS configuration, missing required environment variables"
- )
- return None, None, None, None
-
- # Initialize COS configuration
- logger.info(
- f"Initializing COS client with region: {region}, bucket: {bucket_name}"
- )
- config = CosConfig(
- Appid=appid,
- Region=region,
- SecretId=secret_id,
- SecretKey=secret_key,
- EnableOldDomain=enable_old_domain,
- )
-
- # Create client
- client = CosS3Client(config)
- return client, bucket_name, region, prefix
- except Exception as e:
- logger.error(f"Failed to initialize COS client: {str(e)}")
- return None, None, None, None
-
- def _get_file_url(self, bucket_name, region, object_key):
- """Generate COS object URL
-
- Args:
- bucket_name: Bucket name
- region: Region
- object_key: Object key
-
- Returns:
- File URL
- """
- return f"https://{bucket_name}.cos.{region}.myqcloud.com/{object_key}"
+ def __init_storage(self):
+ """Initialize storage client based on configuration"""
+ if self._storage is None:
+ storage_config = self.chunking_config.storage_config if self.chunking_config else None
+ self._storage = create_storage(storage_config)
+ logger.info(f"Initialized storage client: {self._storage.__class__.__name__}")
+ return self._storage
def upload_file(self, file_path: str) -> str:
- """Upload file to Tencent Cloud COS
+ """Upload file to object storage
Args:
file_path: File path
@@ -597,84 +543,43 @@ class BaseParser(ABC):
Returns:
File URL
"""
- logger.info(f"Uploading file to COS: {file_path}")
+ logger.info(f"Uploading file: {file_path}")
try:
- client, bucket_name, region, prefix = self._init_cos_client()
- if not client:
- return ""
-
- # Generate object key, use UUID to avoid conflicts
- file_name = os.path.basename(file_path)
- object_key = (
- f"{prefix}/images/{uuid.uuid4().hex}{os.path.splitext(file_name)[1]}"
- )
- logger.info(f"Generated object key: {object_key}")
-
- # Upload file
- logger.info("Attempting to upload file to COS")
- response = client.upload_file(
- Bucket=bucket_name, LocalFilePath=file_path, Key=object_key
- )
-
- # Get file URL
- file_url = self._get_file_url(bucket_name, region, object_key)
-
- logger.info(f"Successfully uploaded file to COS: {file_url}")
- return file_url
-
+ storage = self.__init_storage()
+ return storage.upload_file(file_path)
except Exception as e:
- logger.error(f"Failed to upload file to COS: {str(e)}")
+ logger.error(f"Failed to upload file: {str(e)}")
return ""
- def upload_bytes(self, content: bytes, file_ext: str = ".png", cos_config=None) -> str:
- """Directly upload file content to Tencent Cloud COS
+ def upload_bytes(self, content: bytes, file_ext: str = ".png") -> str:
+ """Upload bytes to object storage
Args:
- content: File byte content
- file_ext: File extension, default is .png
- cos_config: COS configuration dictionary
+ content: Byte content to upload
+ file_ext: File extension
Returns:
File URL
"""
- logger.info(
- f"Uploading bytes content to COS, content size: {len(content)} bytes"
- )
+ logger.info(f"Uploading bytes content, size: {len(content)} bytes")
try:
- client, bucket_name, region, prefix = self._init_cos_client(cos_config)
- if not client:
- return ""
-
- # Generate object key, use UUID to avoid conflicts
- object_key = f"{prefix}/images/{uuid.uuid4().hex}{file_ext}"
- logger.info(f"Generated object key: {object_key}")
-
- # Directly upload file content
- logger.info("Attempting to upload bytes content to COS")
- response = client.put_object(
- Bucket=bucket_name, Body=content, Key=object_key
- )
-
- # Get file URL
- file_url = self._get_file_url(bucket_name, region, object_key)
-
- logger.info(f"Successfully uploaded bytes to COS: {file_url}")
- return file_url
-
+ storage = self.__init_storage()
+ return storage.upload_bytes(content, file_ext)
except Exception as e:
- logger.error(f"Failed to upload bytes to COS: {str(e)}")
+ logger.error(f"Failed to upload bytes to storage: {str(e)}")
traceback.print_exc()
return ""
@abstractmethod
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""Parse document content
Args:
content: Document content
Returns:
- Parse result
+ Either a string containing the parsed text, or a tuple of (text, image_map)
+ where image_map is a dict mapping image URLs to Image objects
"""
pass
@@ -690,7 +595,12 @@ class BaseParser(ABC):
logger.info(
f"Parsing document with {self.__class__.__name__}, content size: {len(content)} bytes"
)
- text = self.parse_into_text(content)
+ parse_result = self.parse_into_text(content)
+ if isinstance(parse_result, tuple):
+ text, image_map = parse_result
+ else:
+ text = parse_result
+ image_map = {}
logger.info(f"Extracted {len(text)} characters of text from {self.file_name}")
logger.info(f"Beginning chunking process for text")
chunks = self.chunk_text(text)
@@ -725,7 +635,7 @@ class BaseParser(ABC):
if file_ext in allowed_types:
logger.info(f"Processing images in each chunk for file type: {file_ext}")
- chunks = self.process_chunks_images(chunks)
+ chunks = self.process_chunks_images(chunks, image_map)
else:
logger.info(f"Skipping image processing for unsupported file type: {file_ext}")
@@ -1053,15 +963,16 @@ class BaseParser(ABC):
return images_info
- async def download_and_upload_image(self, img_url: str, current_request_id=None):
- """Download image and upload to COS, if it's already a COS path or local path, use directly
+ async def download_and_upload_image(self, img_url: str, current_request_id=None, image_map=None):
+ """Download image and upload to object storage, if it's already an object storage path or local path, use directly
Args:
img_url: Image URL or local path
current_request_id: Current request ID
+ image_map: Optional dictionary mapping image URLs to Image objects
Returns:
- tuple: (original URL, COS URL, image object), if failed returns (original URL, None, None)
+ tuple: (original URL, storage URL, image object), if failed returns (original URL, None, None)
"""
# Set request ID context in the asynchronous task
try:
@@ -1077,8 +988,14 @@ class BaseParser(ABC):
from PIL import Image
import io
- # Check if it's already a COS path
- if "cos" in img_url and "myqcloud.com" in img_url:
+ # Check if image is already in the image_map
+ if image_map and img_url in image_map:
+ logger.info(f"Image already in image_map: {img_url}, using cached object")
+ return img_url, img_url, image_map[img_url]
+
+ # Check if it's already a storage URL (COS or MinIO)
+ is_storage_url = any(pattern in img_url for pattern in ["cos", "myqcloud.com", "minio", ".s3."])
+ if is_storage_url:
logger.info(f"Image already on COS: {img_url}, no need to re-upload")
try:
# Still need to get image object for OCR processing
@@ -1101,10 +1018,10 @@ class BaseParser(ABC):
# Image will be closed by the caller
pass
else:
- logger.warning(f"Failed to get COS image: {response.status_code}")
+ logger.warning(f"Failed to get storage image: {response.status_code}")
return img_url, img_url, None
except Exception as e:
- logger.error(f"Error getting COS image: {str(e)}")
+ logger.error(f"Error getting storage image: {str(e)}")
return img_url, img_url, None
# Check if it's a local file path
@@ -1114,12 +1031,12 @@ class BaseParser(ABC):
try:
# Read local image
image = Image.open(img_url)
- # Upload to COS
+ # Upload to storage
with open(img_url, 'rb') as f:
content = f.read()
- cos_url = self.upload_bytes(content)
- logger.info(f"Successfully uploaded local image to COS: {cos_url}")
- return img_url, cos_url, image
+ storage_url = self.upload_bytes(content)
+ logger.info(f"Successfully uploaded local image to storage: {storage_url}")
+ return img_url, storage_url, image
except Exception as e:
logger.error(f"Error processing local image: {str(e)}")
if image and hasattr(image, 'close'):
@@ -1144,10 +1061,10 @@ class BaseParser(ABC):
# Download successful, create image object
image = Image.open(io.BytesIO(response.content))
try:
- # Upload to COS using the method in BaseParser
- cos_url = self.upload_bytes(response.content)
- logger.info(f"Successfully uploaded image to COS: {cos_url}")
- return img_url, cos_url, image
+ # Upload to storage using the method in BaseParser
+ storage_url = self.upload_bytes(response.content)
+ logger.info(f"Successfully uploaded image to storage: {storage_url}")
+ return img_url, storage_url, image
finally:
# Image will be closed by the caller
pass
@@ -1159,7 +1076,7 @@ class BaseParser(ABC):
logger.error(f"Error downloading or processing image: {str(e)}")
return img_url, None, None
- async def process_chunk_images_async(self, chunk, chunk_idx, total_chunks, current_request_id=None):
+ async def process_chunk_images_async(self, chunk, chunk_idx, total_chunks, current_request_id=None, image_map=None):
"""Asynchronously process images in a single Chunk
Args:
@@ -1201,7 +1118,7 @@ class BaseParser(ABC):
loop = asyncio.get_event_loop()
# Concurrent download and upload of images
- tasks = [self.download_and_upload_image(url, current_request_id) for url in url_to_info_map.keys()]
+ tasks = [self.download_and_upload_image(url, current_request_id, image_map) for url in url_to_info_map.keys()]
results = await asyncio.gather(*tasks)
# Process download results, prepare for OCR processing
@@ -1248,7 +1165,7 @@ class BaseParser(ABC):
logger.info(f"Completed image processing in Chunk #{chunk_idx+1}")
return chunk
- def process_chunks_images(self, chunks: List[Chunk]) -> List[Chunk]:
+ def process_chunks_images(self, chunks: List[Chunk], image_map=None) -> List[Chunk]:
"""Concurrent processing of images in all Chunks
Args:
@@ -1282,7 +1199,7 @@ class BaseParser(ABC):
async def process_with_limit(chunk, idx, total):
"""Use semaphore to control concurrent processing of Chunks"""
async with semaphore:
- return await self.process_chunk_images_async(chunk, idx, total, current_request_id)
+ return await self.process_chunk_images_async(chunk, idx, total, current_request_id, image_map)
# Create tasks for all Chunks
tasks = [
diff --git a/services/docreader/src/parser/config.py b/services/docreader/src/parser/config.py
new file mode 100644
index 000000000..85f9cb587
--- /dev/null
+++ b/services/docreader/src/parser/config.py
@@ -0,0 +1,21 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class ChunkingConfig:
+ """
+ Configuration for text chunking process.
+ Controls how documents are split into smaller pieces for processing.
+ """
+
+ chunk_size: int = 512 # Maximum size of each chunk in tokens/chars
+ chunk_overlap: int = 50 # Number of tokens/chars to overlap between chunks
+ separators: list = field(
+ default_factory=lambda: ["\n\n", "\n", "。"]
+ ) # Text separators in order of priority
+ enable_multimodal: bool = (
+ False # Whether to enable multimodal processing (text + images)
+ )
+ storage_config: dict = None # Preferred field name going forward
+ vlm_config: dict = None # VLM configuration for image captioning
+
diff --git a/services/docreader/src/parser/docx_parser.py b/services/docreader/src/parser/docx_parser.py
index 6b9663b68..54d1f0cfa 100644
--- a/services/docreader/src/parser/docx_parser.py
+++ b/services/docreader/src/parser/docx_parser.py
@@ -4,7 +4,8 @@ import os
import sys
import time
from io import BytesIO
-from typing import Optional
+from typing import Optional, Dict, Any, Tuple, List, Union
+from dataclasses import dataclass, field
from PIL import Image
from docx import Document
from docx.image.exceptions import (
@@ -13,6 +14,7 @@ from docx.image.exceptions import (
InvalidImageStreamError,
)
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
+import tempfile
import threading
import traceback
from multiprocessing import Manager
@@ -26,6 +28,26 @@ logger.setLevel(logging.INFO)
thread_local = threading.local()
+class ImageData:
+ """Represents a processed image of document content"""
+ local_path: str = ""
+ object: Image.Image = None
+ url: str = ""
+
+
+@dataclass
+class LineData:
+ """Represents a processed line of document content with associated images"""
+
+ text: str = "" # Extracted text content
+ images: List[ImageData] = field(default_factory=list) # List of images or image paths
+ extra_info: str = "" # Placeholder for additional info (currently unused)
+ page_num: int = 0 # Page number
+ content_sequence: List[Tuple[str, Any]] = field(
+ default_factory=list
+ ) # Sequence of content items (text/images)
+
+
class DocxParser(BaseParser):
"""DOCX document parser"""
@@ -42,7 +64,7 @@ class DocxParser(BaseParser):
max_image_size: int = 1920,
max_concurrent_tasks: int = 5,
max_pages: int = 100, # Maximum number of pages to process, default to 50 pages
- chunking_config = None,
+ chunking_config=None,
):
"""Initialize DOCX document parser
@@ -75,14 +97,15 @@ class DocxParser(BaseParser):
self.max_pages = max_pages
logger.info(f"DocxParser initialized with max_pages={max_pages}")
- def parse_into_text(self, content: bytes) -> str:
- """Parse DOCX document, only extract text content and image Markdown links
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
+ """Parse DOCX document, extract text content and image Markdown links
Args:
content: DOCX document content
Returns:
- Parsed text
+ Tuple of (parsed_text, image_map) where image_map maps image URLs to Image objects
+ All LineData objects are used internally but not returned directly through this interface
"""
logger.info(f"Parsing DOCX document, content size: {len(content)} bytes")
logger.info(f"Max pages limit set to: {self.max_pages}")
@@ -90,14 +113,18 @@ class DocxParser(BaseParser):
start_time = time.time()
# Use concurrent processing to handle the document
- max_workers = min(4, os.cpu_count() or 2) # Reduce thread count to avoid excessive memory consumption
+ max_workers = min(
+ 4, os.cpu_count() or 2
+ ) # Reduce thread count to avoid excessive memory consumption
logger.info(f"Setting max_workers to {max_workers} for document processing")
try:
logger.info(f"Starting Docx processing with max_pages={self.max_pages}")
- docx_processor = Docx(max_image_size=self.max_image_size,
- enable_multimodal=self.enable_multimodal,
- upload_file=self.upload_file)
+ docx_processor = Docx(
+ max_image_size=self.max_image_size,
+ enable_multimodal=self.enable_multimodal,
+ upload_file=self.upload_file,
+ )
all_lines, tables = docx_processor(
binary=content,
max_workers=max_workers,
@@ -109,40 +136,26 @@ class DocxParser(BaseParser):
f"extracted {len(all_lines)} sections and {len(tables)} tables"
)
- # Add debug log to print the structure of all_lines
- if all_lines:
- logger.info(f"all_lines type: {type(all_lines)}")
- if len(all_lines) > 0:
- first_line = all_lines[0]
- logger.info(f"First line type: {type(first_line)}, length: {len(first_line)}")
- logger.info(f"First line content types: {[type(item) for item in first_line]}")
- if len(all_lines) > 1:
- second_line = all_lines[1]
- logger.info(f"Second line type: {type(second_line)}, length: {len(second_line)}")
- logger.info(f"Second line content types: {[type(item) for item in second_line]}")
- else:
- logger.warning("all_lines is empty")
-
logger.info("Processing document sections")
section_start_time = time.time()
text_parts = []
+ image_parts = {}
for sec_idx, line in enumerate(all_lines):
try:
- text = None
- if isinstance(line, (tuple, list)) and len(line) >= 1:
- text = line[0]
-
- if text:
- text_parts.append(text)
+ if line.text is not None and line.text != "":
+ text_parts.append(line.text)
if sec_idx < 3 or sec_idx % 50 == 0:
logger.info(
- f"Added section {sec_idx+1} text: {text[:50]}..."
- if len(text) > 50
- else f"Added section {sec_idx+1} text: {text}"
+ f"Added section {sec_idx+1} text: {line.text[:50]}..."
+ if len(line.text) > 50
+ else f"Added section {sec_idx+1} text: {line.text}"
)
-
+ if line.images:
+ for image_data in line.images:
+ if image_data.url:
+ image_parts[image_data.url] = image_data.object
except Exception as e:
logger.error(f"Error processing section {sec_idx+1}: {str(e)}")
logger.error(f"Detailed stack trace: {traceback.format_exc()}")
@@ -150,7 +163,9 @@ class DocxParser(BaseParser):
# Combine text
section_processing_time = time.time() - section_start_time
- logger.info(f"Section processing completed in {section_processing_time:.2f}s")
+ logger.info(
+ f"Section processing completed in {section_processing_time:.2f}s"
+ )
logger.info("Combining all text parts")
text = "\n\n".join([part for part in text_parts if part])
@@ -164,11 +179,12 @@ class DocxParser(BaseParser):
f"Parsing complete in {total_processing_time:.2f}s, generated {len(text)} characters of text "
)
- return text
+ return text, image_parts
except Exception as e:
logger.error(f"Error parsing DOCX document: {str(e)}")
logger.error(f"Detailed stack trace: {traceback.format_exc()}")
- return self._parse_using_simple_method(content)
+ fallback_text = self._parse_using_simple_method(content)
+ return fallback_text, {}
def _parse_using_simple_method(self, content: bytes) -> str:
"""Parse document using a simplified method, as a fallback
@@ -214,7 +230,9 @@ class DocxParser(BaseParser):
table_has_content = False
for row in table.rows:
rows_processed += 1
- row_text = ' | '.join([cell.text.strip() for cell in row.cells if cell.text.strip()])
+ row_text = " | ".join(
+ [cell.text.strip() for cell in row.cells if cell.text.strip()]
+ )
if row_text:
text_parts.append(row_text)
table_has_content = True
@@ -238,20 +256,25 @@ class DocxParser(BaseParser):
# If the result is still empty, return an error message
if not result_text:
logger.warning("No text extracted using simplified method")
- return ""
+ return "", {}
- return result_text
+ return result_text, {}
except Exception as backup_error:
processing_time = time.time() - start_time
- logger.error(f"Simplified parsing failed after {processing_time:.2f}s: {str(backup_error)}")
+ logger.error(
+ f"Simplified parsing failed after {processing_time:.2f}s: {str(backup_error)}"
+ )
logger.error(f"Detailed traceback: {traceback.format_exc()}")
- return ""
+ return "", {}
+
class Docx:
def __init__(self, max_image_size=1920, enable_multimodal=False, upload_file=None):
logger.info("Initializing DOCX processor")
self.max_image_size = max_image_size # Maximum image size limit
- self.picture_cache = {} # Image cache to avoid processing the same image repeatedly
+ self.picture_cache = (
+ {}
+ ) # Image cache to avoid processing the same image repeatedly
self.enable_multimodal = enable_multimodal
self.upload_file = upload_file
@@ -297,11 +320,6 @@ class Docx:
logger.error(f"Error extracting image: {str(e)}")
return None
- def __clean(self, line):
- logger.info(f"Cleaning text line of length: {len(line)}")
- line = re.sub(r"\u3000", " ", line).strip()
- return line
-
def _identify_page_paragraph_mapping(self, max_page=100000):
"""Identify the paragraph range included on each page
@@ -327,13 +345,17 @@ class Docx:
# For large documents, using a heuristic can reduce XML parsing overhead
if total_paragraphs > 1000:
logger.info("Large document detected, using heuristic paragraph mapping")
- estimated_paras_per_page = 25 # Estimate approximately 25 paragraphs per page
+ estimated_paras_per_page = (
+ 25 # Estimate approximately 25 paragraphs per page
+ )
# Create an estimated page mapping
for p_idx in range(total_paragraphs):
est_page = p_idx // estimated_paras_per_page
if est_page > max_page:
- logger.info(f"Reached max page limit ({max_page}) at paragraph {p_idx}, stopping paragraph mapping")
+ logger.info(
+ f"Reached max page limit ({max_page}) at paragraph {p_idx}, stopping paragraph mapping"
+ )
break
if est_page not in page_to_paragraphs:
@@ -342,10 +364,14 @@ class Docx:
page_to_paragraphs[est_page].append(p_idx)
if p_idx > 0 and p_idx % 1000 == 0:
- logger.info(f"Heuristic mapping: processed {p_idx}/{total_paragraphs} paragraphs")
+ logger.info(
+ f"Heuristic mapping: processed {p_idx}/{total_paragraphs} paragraphs"
+ )
mapping_time = time.time() - start_time
- logger.info(f"Created heuristic mapping with {len(page_to_paragraphs)} pages in {mapping_time:.2f}s")
+ logger.info(
+ f"Created heuristic mapping with {len(page_to_paragraphs)} pages in {mapping_time:.2f}s"
+ )
return page_to_paragraphs
# Standard method: iterate through all paragraphs to find page breaks
@@ -357,7 +383,9 @@ class Docx:
# Log every 100 paragraphs
if p_idx > 0 and p_idx % 100 == 0:
- logger.info(f"Processed {p_idx}/{total_paragraphs} paragraphs in page mapping")
+ logger.info(
+ f"Processed {p_idx}/{total_paragraphs} paragraphs in page mapping"
+ )
# Check for page breaks
page_break_found = False
@@ -381,7 +409,9 @@ class Docx:
page_breaks_found += 1
current_page += 1
if current_page > max_page:
- logger.info(f"Reached max page limit ({max_page}), stopping page mapping")
+ logger.info(
+ f"Reached max page limit ({max_page}), stopping page mapping"
+ )
break
# Initialize the paragraph list for the new page
@@ -389,7 +419,9 @@ class Docx:
page_to_paragraphs[current_page] = []
if page_breaks_found % 10 == 0:
- logger.info(f"Found {page_breaks_found} page breaks so far, current page: {current_page}")
+ logger.info(
+ f"Found {page_breaks_found} page breaks so far, current page: {current_page}"
+ )
# Handle potential empty page mappings
empty_pages = [page for page, paras in page_to_paragraphs.items() if not paras]
@@ -399,7 +431,9 @@ class Docx:
del page_to_paragraphs[page]
mapping_time = time.time() - start_time
- logger.info(f"Created paragraph mapping with {len(page_to_paragraphs)} pages in {mapping_time:.2f}s")
+ logger.info(
+ f"Created paragraph mapping with {len(page_to_paragraphs)} pages in {mapping_time:.2f}s"
+ )
# Check the validity of the result
if not page_to_paragraphs:
@@ -421,105 +455,13 @@ class Docx:
return page_to_paragraphs
- def _process_page(self, page_num, paragraphs, from_page, to_page):
- """Process the content of one page
-
- Args:
- page_num: Page number
- paragraphs: List of paragraph indices
- from_page: Starting page number
- to_page: Ending page number
-
- Returns:
- list: List of processed result lines
- """
- logger.info(f"Processing page {page_num} with {len(paragraphs)} paragraphs")
-
- # Initialize thread local storage
- if not hasattr(thread_local, 'last_text'):
- thread_local.last_text = ""
- thread_local.last_image = None
-
- # Track content in sequence
- content_sequence = []
- current_text = ""
- current_images = []
-
- for para_idx in paragraphs:
- if para_idx >= len(self.doc.paragraphs):
- logger.warning(f"Paragraph index {para_idx} out of range")
- continue
-
- paragraph = self.doc.paragraphs[para_idx]
-
- # Get paragraph text
- text = paragraph.text.strip()
- if text:
- cleaned_text = self.__clean(text)
-
- # If we have pending images, add text after them
- if current_images:
- # Add all accumulated images to the sequence
- for img in current_images:
- content_sequence.append(("image", img))
- current_images = []
-
- # Accumulate text
- current_text += cleaned_text + "\n"
-
- # Attempt to extract image
- image = self.get_picture(self.doc, paragraph)
- if image:
- # If we have text, add it to sequence first
- if current_text:
- content_sequence.append(("text", current_text))
- current_text = ""
-
- # Add image directly to sequence to maintain order
- content_sequence.append(("image", image))
-
- # Add any remaining text
- if current_text:
- content_sequence.append(("text", current_text))
-
- # Add any remaining images
- for img in current_images:
- content_sequence.append(("image", img))
-
- # Extract text and images in their original sequence for compatibility
- text_parts = []
- images = []
-
- for content_type, content in content_sequence:
- if content_type == "text":
- text_parts.append(content)
- else: # image
- images.append(content)
-
- combined_text = "\n\n".join(text_parts) if text_parts else ""
-
- # After processing all paragraphs, add to results
- line_data = (combined_text, images, "", page_num, content_sequence)
-
- # Add to page-specific results
- page_lines = [line_data]
-
- # Add to global results
- with self.lines_lock:
- self.all_lines.append(line_data)
-
- # Update thread local storage
- thread_local.last_text = combined_text
- thread_local.last_image = images[-1] if images else None
-
- # Set last_image for this page
- if images:
- with self.last_image_lock:
- self.last_image_map[page_num] = images[-1]
-
- return page_lines
-
- def __call__(self, binary=None, from_page=0, to_page=100000, max_workers=None):
+ def __call__(
+ self,
+ binary: Optional[bytes] = None,
+ from_page: int = 0,
+ to_page: int = 100000,
+ max_workers: Optional[int] = None,
+ ) -> Tuple[List[LineData], List[Any]]:
"""
Process DOCX document, supporting concurrent processing of each page
@@ -530,7 +472,7 @@ class Docx:
max_workers: Maximum number of workers, default to None (system decides)
Returns:
- tuple: (List of text lines, List of tables)
+ tuple: (List of LineData objects with document content, List of tables)
"""
logger.info("Processing DOCX document")
@@ -545,10 +487,14 @@ class Docx:
# Identify page structure
self.para_page_mapping = self._identify_page_paragraph_mapping(to_page)
- logger.info(f"Identified page to paragraph mapping for {len(self.para_page_mapping)} pages")
+ logger.info(
+ f"Identified page to paragraph mapping for {len(self.para_page_mapping)} pages"
+ )
# Apply page limits
- pages_to_process = self._apply_page_limit(self.para_page_mapping, from_page, to_page)
+ pages_to_process = self._apply_page_limit(
+ self.para_page_mapping, from_page, to_page
+ )
if not pages_to_process:
logger.warning("No pages to process after applying page limits!")
return [], []
@@ -556,37 +502,25 @@ class Docx:
# Initialize shared resources
self._init_shared_resources()
- # Get current request ID
- current_request_id = self._get_request_id()
-
# Process document content
- doc_size_mb = sys.getsizeof(binary) / (1024 * 1024)
- logger.info(f"Document binary size: {doc_size_mb:.2f} MB")
-
- # Decide on processing strategy
- if len(self.doc.paragraphs) < 30:
- # For small documents, use single-threaded processing
- self._process_small_document(pages_to_process, from_page, to_page)
- else:
- # For large documents, use multiprocessing
- self._process_large_document(binary,
- pages_to_process,
- from_page,
- to_page,
- max_workers,
- doc_size_mb,
- current_request_id,
- )
+ self._process_document(
+ binary,
+ pages_to_process,
+ from_page,
+ to_page,
+ max_workers,
+ )
# Process tables
tbls = self._process_tables()
# Clean up document resources
self.doc = None
- self.last_image_map = None
- logger.info(f"Document processing complete, "
- f"extracted {len(self.all_lines)} text sections and {len(tbls)} tables")
+ logger.info(
+ f"Document processing complete, "
+ f"extracted {len(self.all_lines)} text sections and {len(tbls)} tables"
+ )
return self.all_lines, tbls
def _load_document(self, binary):
@@ -610,19 +544,20 @@ class Docx:
"""Initialize shared resources"""
# Create shared resource locks to protect data structures shared between threads
self.lines_lock = threading.Lock()
- self.last_image_lock = threading.Lock()
# Initialize result containers
self.all_lines = []
- self.last_image_map = {} # Last image for each page
def _get_request_id(self):
"""Get current request ID"""
current_request_id = None
try:
from utils.request import get_request_id
+
current_request_id = get_request_id()
- logger.info(f"Getting current request ID: {current_request_id} to pass to processing threads")
+ logger.info(
+ f"Getting current request ID: {current_request_id} to pass to processing threads"
+ )
except Exception as e:
logger.warning(f"Failed to get current request ID: {str(e)}")
return current_request_id
@@ -641,10 +576,14 @@ class Docx:
# Add page limits
total_pages = len(para_page_mapping)
if total_pages > to_page:
- logger.info(f"Document has {total_pages} pages, limiting processing to first {to_page} pages")
+ logger.info(
+ f"Document has {total_pages} pages, limiting processing to first {to_page} pages"
+ )
logger.info(f"Setting to_page limit to {to_page}")
else:
- logger.info(f"Document has {total_pages} pages, processing all pages (limit: {to_page})")
+ logger.info(
+ f"Document has {total_pages} pages, processing all pages (limit: {to_page})"
+ )
# Filter out pages outside the range
all_pages = sorted(para_page_mapping.keys())
@@ -658,43 +597,29 @@ class Docx:
)
if len(pages_to_process) < len(all_pages):
- logger.info(f"Skipping {len(all_pages) - len(pages_to_process)} pages due to page limit")
+ logger.info(
+ f"Skipping {len(all_pages) - len(pages_to_process)} pages due to page limit"
+ )
# Log detailed page index information
if len(pages_to_process) <= 10:
logger.info(f"Pages to process: {pages_to_process}")
else:
- logger.info(f"First 5 pages to process: {pages_to_process[:5]}, last 5: {pages_to_process[-5:]}")
+ logger.info(
+ f"First 5 pages to process: {pages_to_process[:5]}, last 5: {pages_to_process[-5:]}"
+ )
return pages_to_process
- def _process_small_document(self, pages_to_process, from_page, to_page):
- """Process small documents (less than 30 paragraphs)
- Args:
- pages_to_process: List of pages to process
- from_page: Starting page number
- to_page: Ending page number
- """
- logger.info(f"Small document detected ({len(self.doc.paragraphs)} paragraphs), "
- f"processing without threading")
- for page_num in sorted(pages_to_process):
- if from_page <= page_num < to_page:
- logger.info(f"Processing page {page_num} (single-threaded mode)")
- self._process_page(page_num, self.para_page_mapping[page_num], from_page, to_page)
- logger.info(f"Completed processing page {page_num} (single-threaded mode)")
- else:
- logger.info(f"Skipping page {page_num} (out of requested range: {from_page}-{to_page})")
-
- def _process_large_document(self,
- binary,
- pages_to_process,
- from_page,
- to_page,
- max_workers,
- doc_size_mb,
- current_request_id,
- ):
+ def _process_document(
+ self,
+ binary,
+ pages_to_process,
+ from_page,
+ to_page,
+ max_workers,
+ ):
"""Process large documents, using multiprocessing
Args:
@@ -703,8 +628,6 @@ class Docx:
from_page: Starting page number
to_page: Ending page number
max_workers: Maximum number of workers
- doc_size_mb: Document size (MB)
- current_request_id: Current request ID
"""
# If the number of pages is too large, process in batches to reduce memory consumption
cpu_count = os.cpu_count() or 2
@@ -714,15 +637,19 @@ class Docx:
# Optimize process count: dynamically adjust based on number of pages and CPU cores
if max_workers is None:
- max_workers = self._calculate_optimal_workers(doc_contains_images, pages_to_process, cpu_count)
+ max_workers = self._calculate_optimal_workers(
+ doc_contains_images, pages_to_process, cpu_count
+ )
- # Use temporary file to share large documents
- temp_file_path = self._prepare_document_sharing(binary, doc_size_mb)
+ temp_file_path = self._prepare_document_sharing(binary)
# Prepare multiprocess processing arguments
args_list = self._prepare_multiprocess_args(
- pages_to_process, from_page, to_page, doc_contains_images,
- binary, temp_file_path
+ pages_to_process,
+ from_page,
+ to_page,
+ doc_contains_images,
+ temp_file_path,
)
# Execute multiprocess tasks
@@ -738,12 +665,16 @@ class Docx:
bool: Whether the document contains images
"""
doc_contains_images = False
- if hasattr(self.doc, 'inline_shapes') and len(self.doc.inline_shapes) > 0:
+ if hasattr(self.doc, "inline_shapes") and len(self.doc.inline_shapes) > 0:
doc_contains_images = True
- logger.info(f"Document contains {len(self.doc.inline_shapes)} inline images")
+ logger.info(
+ f"Document contains {len(self.doc.inline_shapes)} inline images"
+ )
return doc_contains_images
- def _calculate_optimal_workers(self, doc_contains_images, pages_to_process, cpu_count):
+ def _calculate_optimal_workers(
+ self, doc_contains_images, pages_to_process, cpu_count
+ ):
"""Calculate the optimal number of workers
Args:
@@ -762,33 +693,30 @@ class Docx:
logger.info(f"Automatically set worker count to {max_workers}")
return max_workers
- def _prepare_document_sharing(self, binary, doc_size_mb):
+ def _prepare_document_sharing(self, binary):
"""Prepare document sharing method
Args:
binary: Document binary content
- doc_size_mb: Document size (MB)
Returns:
str: Temporary file path, or None if not using
"""
- # For large documents, consider using temporary file to share data
- use_temp_file = doc_size_mb > 50 # If document is larger than 50MB, use temporary file for sharing
- temp_file_path = None
-
- if use_temp_file:
- logger.info(f"Large document detected ({doc_size_mb:.2f} MB), using temporary file for sharing")
- import tempfile
- temp_file = tempfile.NamedTemporaryFile(delete=False)
- temp_file_path = temp_file.name
- temp_file.write(binary)
- temp_file.close()
- logger.info(f"Wrote document to temporary file: {temp_file_path}")
+ temp_file = tempfile.NamedTemporaryFile(delete=False)
+ temp_file_path = temp_file.name
+ temp_file.write(binary)
+ temp_file.close()
return temp_file_path
- def _prepare_multiprocess_args(self, pages_to_process, from_page, to_page,
- doc_contains_images, binary, temp_file_path):
+ def _prepare_multiprocess_args(
+ self,
+ pages_to_process,
+ from_page,
+ to_page,
+ doc_contains_images,
+ temp_file_path,
+ ):
"""Prepare a list of arguments for multiprocess processing
Args:
@@ -796,30 +724,25 @@ class Docx:
from_page: Starting page number
to_page: Ending page number
doc_contains_images: Whether the document contains images
- binary: Document binary content
temp_file_path: Temporary file path
Returns:
list: List of arguments
"""
- use_temp_file = temp_file_path is not None
-
- logger.info(f"Preparing multiprocess args with enable_multimodal={self.enable_multimodal}")
-
- # Pass parameters required by the page processing function
args_list = []
for page_num in pages_to_process:
- args_list.append((
- page_num,
- self.para_page_mapping[page_num],
- from_page,
- to_page,
- doc_contains_images,
- self.max_image_size,
- binary if not use_temp_file else None,
- temp_file_path if use_temp_file else None,
- self.enable_multimodal
- ))
+ args_list.append(
+ (
+ page_num,
+ self.para_page_mapping[page_num],
+ from_page,
+ to_page,
+ doc_contains_images,
+ self.max_image_size,
+ temp_file_path,
+ self.enable_multimodal,
+ )
+ )
return args_list
@@ -834,9 +757,10 @@ class Docx:
with Manager() as manager:
# Create shared data structures
self.all_lines = manager.list()
- self.last_image_map = manager.dict()
- logger.info(f"Processing {len(args_list)} pages using {max_workers} processes")
+ logger.info(
+ f"Processing {len(args_list)} pages using {max_workers} processes"
+ )
# Use ProcessPoolExecutor to truly implement multi-core parallelization
batch_start_time = time.time()
@@ -845,16 +769,17 @@ class Docx:
# Submit all tasks
future_to_idx = {
- executor.submit(
- process_page_multiprocess,
- *args
- ): i
+ executor.submit(process_page_multiprocess, *args): i
for i, args in enumerate(args_list)
}
- logger.info(f"Submitted {len(future_to_idx)} processing tasks to process pool")
+ logger.info(
+ f"Submitted {len(future_to_idx)} processing tasks to process pool"
+ )
# Collect results
- self._collect_process_results(future_to_idx, args_list, batch_start_time)
+ self._collect_process_results(
+ future_to_idx, args_list, batch_start_time
+ )
def _collect_process_results(self, future_to_idx, args_list, batch_start_time):
"""Collect multiprocess processing results
@@ -863,6 +788,9 @@ class Docx:
future_to_idx: Mapping of Future to index
args_list: List of arguments
batch_start_time: Batch start time
+
+ Returns:
+ List[LineData]: Processed results as LineData objects
"""
# Collect results
completed_count = 0
@@ -877,15 +805,16 @@ class Docx:
# Collect temporary image paths for later cleanup
for line in page_lines:
- if len(line) > 1 and isinstance(line[1], list):
- for item in line[1]:
- if isinstance(item, str) and item.startswith("/tmp/docx_img_"):
- temp_img_paths.add(item)
+ for image_data in line.images:
+ if image_data.local_path and image_data.local_path.startswith("/tmp/docx_img_"):
+ temp_img_paths.add(image_data.local_path)
results.extend(page_lines)
completed_count += 1
- if completed_count % max(1, len(args_list) // 10) == 0 or completed_count == len(args_list):
+ if completed_count % max(
+ 1, len(args_list) // 10
+ ) == 0 or completed_count == len(args_list):
elapsed_ms = int((time.time() - batch_start_time) * 1000)
progress_pct = int((completed_count / len(args_list)) * 100)
logger.info(
@@ -895,7 +824,9 @@ class Docx:
except Exception as e:
logger.error(f"Error processing page {page_num}: {str(e)}")
- logger.error(f"Detailed traceback for page {page_num}: {traceback.format_exc()}")
+ logger.error(
+ f"Detailed traceback for page {page_num}: {traceback.format_exc()}"
+ )
# Process completion
processing_elapsed_ms = int((time.time() - batch_start_time) * 1000)
@@ -907,105 +838,108 @@ class Docx:
# Clean up temporary image files
self._cleanup_temp_image_files(temp_img_paths)
- def _process_multiprocess_results(self, results):
+ def _process_multiprocess_results(self, results: List[LineData]):
"""Process multiprocess results
Args:
- results: List of processed results
+ results: List of processed LineData results
"""
lines = list(results)
# Process images - must be handled in the main process for upload
# If images are being processed, they need to be handled in the main process for upload
image_upload_start = time.time()
-
+
# Count total images to process
images_to_process = []
+ processed_lines = []
for i, line_data in enumerate(lines):
- if len(line_data) > 1 and line_data[1]: # Check if there are images
- # Confirm image data is valid - it might be lost during inter-process communication
- if isinstance(line_data[1], list) and len(line_data[1]) > 0:
- images_to_process.append(i)
- logger.info(f"Found line {i} with {len(line_data[1])} images to process")
- else:
- logger.warning(f"Line {i} has invalid image data: {type(line_data[1])}")
+ # Check if there are images
+ if line_data.images and len(line_data.images) > 0:
+ images_to_process.append(i)
+ logger.info(
+ f"Found line {i} with {len(line_data.images)} images to process"
+ )
# Process images if needed
image_url_map = {} # Map from image path to URL
if images_to_process:
- logger.info(f"Found {len(images_to_process)} lines with images to process in main process")
-
+ logger.info(
+ f"Found {len(images_to_process)} lines with images to process in main process"
+ )
+
# First, create a mapping of image paths to uploaded URLs
for line_idx in images_to_process:
line_data = lines[line_idx]
- _, image_paths, _, page_num = line_data[:4]
-
- # Process all image file paths
- for img_path in image_paths:
- if os.path.exists(img_path) and img_path not in image_url_map:
+ image_paths = line_data.images
+ page_num = line_data.page_num
+
+ # Process all image data objects
+ for image_data in image_paths:
+ if image_data.local_path and os.path.exists(image_data.local_path) and image_data.local_path not in image_url_map:
try:
- image_url = self.upload_file(img_path)
- if image_url:
- # Add image URL as Markdown format
- markdown_image = f"![]({image_url})"
- image_url_map[img_path] = markdown_image
- logger.info(f"Added image URL for {img_path}: {image_url}")
+ # Upload the image if it doesn't have a URL yet
+ if not image_data.url:
+ image_url = self.upload_file(image_data.local_path)
+ if image_url:
+ # Store the URL in the ImageData object
+ image_data.url = image_url
+ # Add image URL as Markdown format
+ markdown_image = f"![]({image_url})"
+ image_url_map[image_data.local_path] = markdown_image
+ logger.info(
+ f"Added image URL for {image_data.local_path}: {image_url}"
+ )
+ else:
+ logger.warning(f"Failed to upload image: {image_data.local_path}")
else:
- logger.warning(f"Failed to upload image: {img_path}")
+ # Already has a URL, use it
+ markdown_image = f"![]({image_data.url})"
+ image_url_map[image_data.local_path] = markdown_image
+ logger.info(
+ f"Using existing URL for image {image_data.local_path}: {image_data.url}"
+ )
except Exception as e:
- logger.error(f"Error processing image from page {page_num}: {str(e)}")
+ logger.error(
+ f"Error processing image from page {page_num}: {str(e)}"
+ )
image_upload_elapsed = time.time() - image_upload_start
- logger.info(f"Finished uploading {len(image_url_map)} images in {image_upload_elapsed:.2f}s")
-
- # Process content in original sequence order
- processed_lines = []
- for line_data in lines:
- if len(line_data) >= 5 and line_data[4]: # Check if we have processed_content
- processed_content = line_data[4]
- page_num = line_data[3]
-
+ logger.info(
+ f"Finished uploading {len(image_url_map)} images in {image_upload_elapsed:.2f}s"
+ )
+
+ # Process content in original sequence order
+ for line_data in lines:
+ if line_data.content_sequence: # Check if we have processed_content
+ processed_content = line_data.content_sequence
+ page_num = line_data.page_num
+
# Reconstruct text with images in original positions
combined_parts = []
for content_type, content in processed_content:
if content_type == "text":
combined_parts.append(content)
- elif content_type == "image" and content in image_url_map:
- combined_parts.append(image_url_map[content])
-
+ elif content_type == "image":
+ # For ImageData objects, use the URL
+ if isinstance(content, str) and content in image_url_map:
+ combined_parts.append(image_url_map[content])
+ elif hasattr(content, 'local_path') and content.local_path in image_url_map:
+ combined_parts.append(image_url_map[content.local_path])
+
# Create the final text with proper ordering
final_text = "\n\n".join(part for part in combined_parts if part)
- processed_lines.append((final_text, None, "", page_num))
-
- else:
- # Fallback to original approach if no processed_content
- text, image_paths, _, page_num = line_data[:4]
-
- if image_paths:
- # Process all image URLs
- processed_urls = []
- for img_path in image_paths:
- if img_path in image_url_map:
- processed_urls.append(image_url_map[img_path])
-
- if processed_urls:
- # Add all images at the end (legacy approach)
- image_text = "\n\n".join(processed_urls)
- if text:
- updated_text = text + "\n\n" + image_text
- else:
- updated_text = image_text
- processed_lines.append((updated_text, None, "", page_num))
- else:
- processed_lines.append((text, None, "", page_num))
- else:
- processed_lines.append((text, None, "", page_num))
+ processed_lines.append(LineData(text=final_text, page_num=page_num, images=line_data.images))
+ else:
+ processed_lines = lines
# Sort results by page number
- sorted_lines = sorted(processed_lines, key=lambda x: x[3] if len(x) > 3 else 0)
- self.all_lines = [(line[0], line[1], line[2]) for line in sorted_lines if len(line) > 2]
-
- logger.info(f"Finished processing {len(self.all_lines)} lines with interleaved images and text")
+ sorted_lines = sorted(processed_lines, key=lambda x: x.page_num)
+ self.all_lines = sorted_lines
+
+ logger.info(
+ f"Finished processing {len(self.all_lines)} lines with interleaved images and text"
+ )
def _cleanup_temp_image_files(self, temp_paths):
"""Clean up temporary image files created by multiprocessing
@@ -1028,7 +962,9 @@ class Docx:
# Delete temporary directory (if empty)
try:
temp_dir = os.path.dirname(path)
- if temp_dir.startswith("/tmp/docx_img_") and os.path.exists(temp_dir):
+ if temp_dir.startswith("/tmp/docx_img_") and os.path.exists(
+ temp_dir
+ ):
os.rmdir(temp_dir)
except OSError:
# If directory is not empty, ignore error
@@ -1037,80 +973,9 @@ class Docx:
logger.error(f"Failed to delete temp file {path}: {str(e)}")
error_count += 1
- logger.info(f"Temporary file cleanup: deleted {deleted_count}, errors {error_count}")
-
- def _process_images_in_main_process(self, lines, images_to_process):
- """Process image uploads in the main process
-
- Args:
- lines: List of line data
- images_to_process: Indices of lines with images to process
- """
- # Process all images
- with tempfile.TemporaryDirectory() as temp_dir:
- for line_idx in images_to_process:
- line_data = lines[line_idx]
- text, image_data, _, page_num = line_data
-
- image_paths = []
-
- # If it's a list of image objects (single-process), save them as temporary files
- if image_data and isinstance(image_data, list):
- if all(isinstance(item, str) for item in image_data):
- # Multi-process mode, images are already saved as temporary files
- logger.info(f"Found {len(image_data)} image paths for page {page_num}")
- image_paths = image_data
- elif all(hasattr(item, 'save') for item in image_data):
- # Single-process mode, need to save image objects as temporary files
- logger.info(f"Converting {len(image_data)} image objects to files for page {page_num}")
- for img_idx, image in enumerate(image_data):
- try:
- # Save temporary image file
- temp_file_path = os.path.join(temp_dir, f"page_{page_num}_img_{img_idx}.png")
- image.save(temp_file_path, format="PNG")
- image_paths.append(temp_file_path)
- logger.info(f"Saved image from page {page_num} to {temp_file_path}")
- except Exception as e:
- logger.error(f"Failed to save image: {str(e)}")
- else:
- logger.warning(f"Unknown image data format for page {page_num}: {type(image_data[0])}")
-
- # Process all image file paths
- processed_urls = []
- for img_path in image_paths:
- if os.path.exists(img_path):
- try:
- image_url = self.upload_file(img_path)
- if image_url:
- # Add image URL as Markdown format
- markdown_image = f"![]({image_url})"
- processed_urls.append(markdown_image)
- logger.info(f"Added image URL to page {page_num} result: {image_url}")
- else:
- logger.warning(f"Failed to upload image: {img_path}")
-
- # Do not delete temporary files created by multiprocessing, they will be cleaned up later
- if not img_path.startswith("/tmp/docx_img_"):
- try:
- os.unlink(img_path)
- logger.info(f"Deleted temporary file: {img_path}")
- except Exception as e:
- logger.error(f"Failed to delete temporary file: {str(e)}")
-
- except Exception as e:
- logger.error(f"Error processing image from page {page_num}: {str(e)}")
-
- # Update text, add all image links
- if processed_urls:
- image_text = "\n\n".join(processed_urls)
- if text:
- updated_text = text + "\n\n" + image_text
- else:
- updated_text = image_text
-
- # Update text in results, clear image list (since processing is complete)
- lines[line_idx] = (updated_text, [], "", page_num)
- logger.info(f"Updated text for page {page_num} with {len(processed_urls)} image URLs")
+ logger.info(
+ f"Temporary file cleanup: deleted {deleted_count}, errors {error_count}"
+ )
def _cleanup_temp_file(self, temp_file_path):
"""Clean up temporary file
@@ -1145,6 +1010,7 @@ class Docx:
continue
table_html = self._convert_table_to_html(tb)
+ # Still using tuple format for tables as they are handled differently
tbls.append(((None, table_html), ""))
return tbls
@@ -1199,8 +1065,8 @@ class Docx:
from PIL import Image
# Calculate the size of the concatenated image
- total_width = max(img.width for img in images if hasattr(img, 'width'))
- total_height = sum(img.height for img in images if hasattr(img, 'height'))
+ total_width = max(img.width for img in images if hasattr(img, "width"))
+ total_height = sum(img.height for img in images if hasattr(img, "height"))
if total_width <= 0 or total_height <= 0:
logger.warning("Invalid image size, returning the first image")
@@ -1212,13 +1078,15 @@ class Docx:
# Paste images one by one
y_offset = 0
for img in images:
- if not hasattr(img, 'width') or not hasattr(img, 'height'):
+ if not hasattr(img, "width") or not hasattr(img, "height"):
continue
new_image.paste(img, (0, y_offset))
y_offset += img.height
- logger.info(f"Successfully concatenated images, final size: {total_width}x{total_height}")
+ logger.info(
+ f"Successfully concatenated images, final size: {total_width}x{total_height}"
+ )
return new_image
except Exception as e:
logger.error(f"Failed to concatenate images: {str(e)}")
@@ -1227,7 +1095,6 @@ class Docx:
return images[0]
-
def _save_image_to_temp(logger, image, page_num, img_idx):
"""Save image to a temporary file to pass between processes
@@ -1253,7 +1120,9 @@ def _save_image_to_temp(logger, image, page_num, img_idx):
# Save the image
image.save(temp_file_path, format="PNG")
- logger.info(f"[PID:{os.getpid()}] Saved image to temporary file: {temp_file_path}")
+ logger.info(
+ f"[PID:{os.getpid()}] Saved image to temporary file: {temp_file_path}"
+ )
return temp_file_path
except Exception as e:
@@ -1261,16 +1130,16 @@ def _save_image_to_temp(logger, image, page_num, img_idx):
return None
-def process_page_multiprocess(page_num,
- paragraphs,
- from_page,
- to_page,
- doc_contains_images,
- max_image_size,
- doc_binary,
- temp_file_path,
- enable_multimodal,
- ):
+def process_page_multiprocess(
+ page_num: int,
+ paragraphs: List[int],
+ from_page: int,
+ to_page: int,
+ doc_contains_images: bool,
+ max_image_size: int,
+ temp_file_path: Optional[str],
+ enable_multimodal: bool,
+) -> List[LineData]:
"""Page processing function specifically designed for multiprocessing
Args:
@@ -1293,60 +1162,72 @@ def process_page_multiprocess(page_num,
# If outside processing range, do not process
if page_num < from_page or page_num >= to_page:
- process_logger.info(f"[PID:{os.getpid()}] Skipping page {page_num} (out of requested range)")
+ process_logger.info(
+ f"[PID:{os.getpid()}] Skipping page {page_num} (out of requested range)"
+ )
return []
- process_logger.info(f"[PID:{os.getpid()}] Processing page {page_num} with {len(paragraphs)} paragraphs, "
- f"enable_multimodal={enable_multimodal}")
+ process_logger.info(
+ f"[PID:{os.getpid()}] Processing page {page_num} with {len(paragraphs)} paragraphs, "
+ f"enable_multimodal={enable_multimodal}"
+ )
start_time = time.time()
# Load document in the process
- doc = _load_document_in_process(process_logger, page_num, doc_binary, temp_file_path)
+ doc = _load_document_in_process(process_logger, page_num, temp_file_path)
if not doc:
return []
# If paragraph indices are empty, return empty result
if not paragraphs:
- process_logger.info(f"[PID:{os.getpid()}] No paragraphs to process for page {page_num}")
+ process_logger.info(
+ f"[PID:{os.getpid()}] No paragraphs to process for page {page_num}"
+ )
return []
# Extract page content
- combined_text, images, content_sequence = _extract_page_content_in_process(
- process_logger,
- doc,
- page_num,
- paragraphs,
- enable_multimodal,
- max_image_size
+ combined_text, image_objects, content_sequence = _extract_page_content_in_process(
+ process_logger, doc, page_num, paragraphs, enable_multimodal, max_image_size
)
# Process content sequence to maintain order between processes
processed_content = []
temp_image_index = 0
-
+
if enable_multimodal:
# First pass: save all images to temporary files
- image_paths = []
- for i, img in enumerate(images):
- img_path = _save_image_to_temp(process_logger, img, page_num, i)
+ image_data_list = []
+ for i, image_object in enumerate(image_objects):
+ img_path = _save_image_to_temp(process_logger, image_object, page_num, i)
if img_path:
- image_paths.append(img_path)
-
+ # Create ImageData object
+ image_data = ImageData()
+ image_data.local_path = img_path
+ image_data.object = image_object
+ image_data_list.append(image_data)
+
process_logger.info(
- f"[PID:{os.getpid()}] Saved {len(image_paths)} images to temp files for page {page_num}"
+ f"[PID:{os.getpid()}] Saved {len(image_data_list)} images to temp files for page {page_num}"
)
-
- # Second pass: reconstruct the content sequence with image paths
+
+ # Second pass: reconstruct the content sequence with image data objects
for content_type, content in content_sequence:
if content_type == "text":
processed_content.append(("text", content))
else: # image
- if temp_image_index < len(image_paths):
- processed_content.append(("image", image_paths[temp_image_index]))
+ if temp_image_index < len(image_data_list):
+ processed_content.append(
+ ("image", image_data_list[temp_image_index])
+ )
temp_image_index += 1
# Create result line with the ordered content sequence
- line_data = (combined_text, image_paths, "", page_num, processed_content)
+ line_data = LineData(
+ text=combined_text,
+ images=image_data_list,
+ page_num=page_num,
+ content_sequence=processed_content,
+ )
page_lines = [line_data]
processing_time = time.time() - start_time
@@ -1358,18 +1239,19 @@ def process_page_multiprocess(page_num,
except Exception as e:
process_logger = logging.getLogger(__name__)
- process_logger.error(f"[PID:{os.getpid()}] Error processing page {page_num}: {str(e)}")
+ process_logger.error(
+ f"[PID:{os.getpid()}] Error processing page {page_num}: {str(e)}"
+ )
process_logger.error(f"[PID:{os.getpid()}] Traceback: {traceback.format_exc()}")
return []
-def _load_document_in_process(logger, page_num, doc_binary, temp_file_path):
+def _load_document_in_process(logger, page_num, temp_file_path):
"""Load document in a process
Args:
logger: Logger
page_num: Page number
- doc_binary: Document binary data
temp_file_path: Temporary file path
Returns:
@@ -1377,24 +1259,15 @@ def _load_document_in_process(logger, page_num, doc_binary, temp_file_path):
"""
logger.info(f"[PID:{os.getpid()}] Loading document in process for page {page_num}")
try:
- from docx import Document
- from io import BytesIO
-
- # Load document based on the provided method
- if doc_binary is not None:
- # Load document from binary content
- doc = Document(BytesIO(doc_binary))
- logger.info(f"[PID:{os.getpid()}] Loaded document from binary data")
- elif temp_file_path is not None:
- # Load document from temporary file
+ # Load document from temporary file
+ if temp_file_path is not None and os.path.exists(temp_file_path):
doc = Document(temp_file_path)
- logger.info(f"[PID:{os.getpid()}] Loaded document from temp file: {temp_file_path}")
+ logger.info(
+ f"[PID:{os.getpid()}] Loaded document from temp file: {temp_file_path}"
+ )
else:
logger.error(f"[PID:{os.getpid()}] No document source provided")
return None
-
- logger.info(f"[PID:{os.getpid()}] "
- f"Successfully loaded document with {len(doc.paragraphs)} paragraphs")
return doc
except Exception as e:
@@ -1403,7 +1276,14 @@ def _load_document_in_process(logger, page_num, doc_binary, temp_file_path):
return None
-def _extract_page_content_in_process(logger, doc, page_num, paragraphs, enable_multimodal, max_image_size):
+def _extract_page_content_in_process(
+ logger,
+ doc,
+ page_num: int,
+ paragraphs: List[int],
+ enable_multimodal: bool,
+ max_image_size: int,
+) -> Tuple[str, List[Any], List[Tuple[str, Any]]]:
"""Extract page content in a process
Args:
@@ -1415,27 +1295,30 @@ def _extract_page_content_in_process(logger, doc, page_num, paragraphs, enable_m
max_image_size: Maximum image size
Returns:
- tuple: (Extracted text, List of extracted images)
+ tuple: (Extracted text, List of extracted images, Content sequence)
"""
- logger.info(f"[PID:{os.getpid()}] Page {page_num}: Processing {len(paragraphs)} paragraphs, "
- f"enable_multimodal={enable_multimodal}")
+ logger.info(
+ f"[PID:{os.getpid()}] Page {page_num}: Processing {len(paragraphs)} paragraphs, "
+ f"enable_multimodal={enable_multimodal}"
+ )
# Instead of separate collections, track content in paragraph sequence
content_sequence = []
current_text = ""
-
+
processed_paragraphs = 0
paragraphs_with_text = 0
paragraphs_with_images = 0
for para_idx in paragraphs:
if para_idx >= len(doc.paragraphs):
- logger.warning(f"[PID:{os.getpid()}] Paragraph index {para_idx} out of range")
+ logger.warning(
+ f"[PID:{os.getpid()}] Paragraph index {para_idx} out of range"
+ )
continue
paragraph = doc.paragraphs[para_idx]
processed_paragraphs += 1
-
# Extract text content
text = paragraph.text.strip()
@@ -1447,15 +1330,17 @@ def _extract_page_content_in_process(logger, doc, page_num, paragraphs, enable_m
# Process image - if multimodal processing is enabled
if enable_multimodal:
- image = _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_image_size)
- if image:
+ image_object = _extract_image_in_process(
+ logger, doc, paragraph, page_num, para_idx, max_image_size
+ )
+ if image_object:
# If we have accumulated text, add it to sequence first
if current_text:
content_sequence.append(("text", current_text))
current_text = ""
-
+
# Add image to sequence
- content_sequence.append(("image", image))
+ content_sequence.append(("image", image_object))
paragraphs_with_images += 1
if processed_paragraphs % 50 == 0:
@@ -1478,19 +1363,22 @@ def _extract_page_content_in_process(logger, doc, page_num, paragraphs, enable_m
# Extract text and images in their original sequence
text_parts = []
images = []
-
+
+ # Split content sequence into text and images
for content_type, content in content_sequence:
if content_type == "text":
text_parts.append(content)
else: # image
images.append(content)
-
+
combined_text = "\n\n".join(text_parts) if text_parts else ""
-
+
return combined_text, images, content_sequence
-def _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_image_size):
+def _extract_image_in_process(
+ logger, doc, paragraph, page_num, para_idx, max_image_size
+):
"""Extract image from a paragraph in a process
Args:
@@ -1508,22 +1396,27 @@ def _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_im
# Attempt to extract image
img = paragraph._element.xpath(".//pic:pic")
if not img:
- logger.warning(f"[PID:{os.getpid()}] Page {page_num}: No pic element found in paragraph {para_idx}")
return None
img = img[0]
- logger.info(f"[PID:{os.getpid()}] Page {page_num}: Found pic element in paragraph {para_idx}")
+ logger.info(
+ f"[PID:{os.getpid()}] Page {page_num}: Found pic element in paragraph {para_idx}"
+ )
try:
# Extract image ID and related part
embed = img.xpath(".//a:blip/@r:embed")
if not embed:
- logger.warning(f"[PID:{os.getpid()}] Page {page_num}: No embed attribute found in image")
+ logger.warning(
+ f"[PID:{os.getpid()}] Page {page_num}: No embed attribute found in image"
+ )
return None
embed = embed[0]
if embed not in doc.part.related_parts:
- logger.warning(f"[PID:{os.getpid()}] Page {page_num}: Embed ID {embed} not found in related parts")
+ logger.warning(
+ f"[PID:{os.getpid()}] Page {page_num}: Embed ID {embed} not found in related parts"
+ )
return None
related_part = doc.part.related_parts[embed]
@@ -1532,7 +1425,9 @@ def _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_im
# Attempt to get image data
try:
image_blob = related_part.image.blob
- logger.info(f"[PID:{os.getpid()}] Successfully extracted image blob, size: {len(image_blob)} bytes")
+ logger.info(
+ f"[PID:{os.getpid()}] Successfully extracted image blob, size: {len(image_blob)} bytes"
+ )
except Exception as blob_error:
logger.warning(
f"[PID:{os.getpid()}] Error extracting image blob: {str(blob_error)}"
@@ -1541,12 +1436,10 @@ def _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_im
# Convert data to PIL image
try:
- from PIL import Image
- from io import BytesIO
image = Image.open(BytesIO(image_blob)).convert("RGBA")
# Check image size
- if hasattr(image, 'width') and hasattr(image, 'height'):
+ if hasattr(image, "width") and hasattr(image, "height"):
logger.info(
f"[PID:{os.getpid()}] Successfully created image object, "
f"size: {image.width}x{image.height}"
@@ -1562,26 +1455,34 @@ def _extract_image_in_process(logger, doc, paragraph, page_num, para_idx, max_im
# Scale large images
if image.width > max_image_size or image.height > max_image_size:
- scale = min(max_image_size / image.width, max_image_size / image.height)
+ scale = min(
+ max_image_size / image.width, max_image_size / image.height
+ )
new_width = int(image.width * scale)
new_height = int(image.height * scale)
resized_image = image.resize((new_width, new_height))
- logger.info(f"[PID:{os.getpid()}] Resized image to {new_width}x{new_height}")
+ logger.info(
+ f"[PID:{os.getpid()}] Resized image to {new_width}x{new_height}"
+ )
return resized_image
logger.info(f"[PID:{os.getpid()}] Found image in paragraph {para_idx}")
return image
except Exception as e:
- logger.error(f"[PID:{os.getpid()}] Failed to create image from blob: {str(e)}")
- logger.error(f"[PID:{os.getpid()}] Error traceback: {traceback.format_exc()}")
+ logger.error(
+ f"[PID:{os.getpid()}] Failed to create image from blob: {str(e)}"
+ )
+ logger.error(
+ f"[PID:{os.getpid()}] Error traceback: {traceback.format_exc()}"
+ )
return None
except Exception as e:
logger.error(f"[PID:{os.getpid()}] Error extracting image: {str(e)}")
- logger.error(f"[PID:{os.getpid()}] Error traceback: {traceback.format_exc()}")
+ logger.error(
+ f"[PID:{os.getpid()}] Error traceback: {traceback.format_exc()}"
+ )
return None
except Exception as e:
logger.error(f"[PID:{os.getpid()}] Error processing image: {str(e)}")
logger.error(f"[PID:{os.getpid()}] Error traceback: {traceback.format_exc()}")
return None
- finally:
- logger.info(f"[PID:{os.getpid()}] Page {page_num}: Image extraction completed")
diff --git a/services/docreader/src/parser/image_parser.py b/services/docreader/src/parser/image_parser.py
index f29f68a9a..4ebbcee27 100644
--- a/services/docreader/src/parser/image_parser.py
+++ b/services/docreader/src/parser/image_parser.py
@@ -3,12 +3,13 @@ import os
import asyncio
from PIL import Image
import io
+from typing import Dict, Any, Tuple, Union
from .base_parser import BaseParser, ParseResult
import numpy as np
# Set up logger for this module
logger = logging.getLogger(__name__)
-
+logger.setLevel(logging.INFO)
class ImageParser(BaseParser):
"""
@@ -22,43 +23,46 @@ class ImageParser(BaseParser):
4. Returning a combined result with both text and image reference
"""
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""
- Parse image content, only upload the image and return Markdown reference, no OCR or caption processing.
+ Parse image content, upload the image and return Markdown reference along with image map.
Args:
content: Raw image data (bytes)
Returns:
- String containing Markdown image reference
+ Tuple of (markdown_text, image_map) where image_map maps image URLs to PIL Image objects
"""
logger.info(f"Parsing image content, size: {len(content)} bytes")
+ image_map = {}
+
try:
# Upload image to storage service
logger.info("Uploading image to storage")
_, ext = os.path.splitext(self.file_name)
-
- # Get COS config from chunking config if available
- cos_config = None
- if hasattr(self, 'chunking_config') and self.chunking_config and hasattr(self.chunking_config, 'cos_config'):
- cos_config = self.chunking_config.cos_config
-
- image_url = self.upload_bytes(content, file_ext=ext, cos_config=cos_config)
+ image_url = self.upload_bytes(content, file_ext=ext)
if not image_url:
logger.error("Failed to upload image to storage")
- return ""
+ return "", {}
logger.info(
f"Successfully uploaded image, URL: {image_url[:50]}..."
if len(image_url) > 50
else f"Successfully uploaded image, URL: {image_url}"
)
- # Directly generate Markdown image reference, no OCR or caption processing
- markdown_text = f"![{self.file_name}]({image_url})"
- logger.info("Generated Markdown image reference without OCR or caption processing")
+ # Create image object and add to map
+ try:
+ from PIL import Image
+ import io
+ image = Image.open(io.BytesIO(content))
+ image_map[image_url] = image
+ logger.info(f"Added image to image_map for URL: {image_url}")
+ except Exception as img_err:
+ logger.error(f"Error creating image object: {str(img_err)}")
- return markdown_text
+ markdown_text = f"![{self.file_name}]({image_url})"
+ return markdown_text, image_map
except Exception as e:
logger.error(f"Error parsing image: {str(e)}")
- return ""
+ return "", {}
diff --git a/services/docreader/src/parser/markdown_parser.py b/services/docreader/src/parser/markdown_parser.py
index 7e504517f..330d5a081 100644
--- a/services/docreader/src/parser/markdown_parser.py
+++ b/services/docreader/src/parser/markdown_parser.py
@@ -3,7 +3,7 @@ import re
import logging
import numpy as np
import os # Import os module to get environment variables
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional, Tuple, Union, Any
from .base_parser import BaseParser
# Get logger object
@@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
class MarkdownParser(BaseParser):
"""Markdown document parser"""
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""Parse Markdown document, only extract text content, do not process images
Args:
diff --git a/services/docreader/src/parser/parser.py b/services/docreader/src/parser/parser.py
index d81a19102..8e1668d2e 100644
--- a/services/docreader/src/parser/parser.py
+++ b/services/docreader/src/parser/parser.py
@@ -10,30 +10,11 @@ from .markdown_parser import MarkdownParser
from .text_parser import TextParser
from .image_parser import ImageParser
from .web_parser import WebParser
+from .config import ChunkingConfig
import traceback
logger = logging.getLogger(__name__)
-
-@dataclass
-class ChunkingConfig:
- """
- Configuration for text chunking process.
- Controls how documents are split into smaller pieces for processing.
- """
-
- chunk_size: int = 512 # Maximum size of each chunk in tokens/chars
- chunk_overlap: int = 50 # Number of tokens/chars to overlap between chunks
- separators: list = field(
- default_factory=lambda: ["\n\n", "\n", "。"]
- ) # Text separators in order of priority
- enable_multimodal: bool = (
- False # Whether to enable multimodal processing (text + images)
- )
- cos_config: dict = None # COS configuration for file storage
- vlm_config: dict = None # VLM configuration for image captioning
-
-
@dataclass
class Chunk:
"""
@@ -100,7 +81,6 @@ class Parser:
file_type: str,
content: bytes,
config: ChunkingConfig,
- enable_multimodal: bool = False,
) -> Optional[ParseResult]:
"""
Parse file content using appropriate parser based on file type.
diff --git a/services/docreader/src/parser/pdf_parser.py b/services/docreader/src/parser/pdf_parser.py
index bc41a1d5e..c1240129a 100644
--- a/services/docreader/src/parser/pdf_parser.py
+++ b/services/docreader/src/parser/pdf_parser.py
@@ -1,7 +1,7 @@
import logging
import os
import io
-from typing import Any, List, Iterator, Optional, Mapping, Tuple, Dict
+from typing import Any, List, Iterator, Optional, Mapping, Tuple, Dict, Union
from pypdf import PdfReader
from .base_parser import BaseParser
@@ -16,7 +16,7 @@ class PDFParser(BaseParser):
It uses the pypdf library for simple text extraction.
"""
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""
Parse PDF document content into text
diff --git a/services/docreader/src/parser/storage.py b/services/docreader/src/parser/storage.py
new file mode 100644
index 000000000..8957a7c19
--- /dev/null
+++ b/services/docreader/src/parser/storage.py
@@ -0,0 +1,363 @@
+# -*- coding: utf-8 -*-
+import os
+import uuid
+import logging
+import io
+import traceback
+from abc import ABC, abstractmethod
+from typing import Tuple, Optional
+
+from qcloud_cos import CosConfig, CosS3Client
+from minio import Minio
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.INFO)
+
+
+class Storage(ABC):
+ """Abstract base class for object storage operations"""
+
+ @abstractmethod
+ def upload_file(self, file_path: str) -> str:
+ """Upload file to object storage
+
+ Args:
+ file_path: File path
+
+ Returns:
+ File URL
+ """
+ pass
+
+ @abstractmethod
+ def upload_bytes(self, content: bytes, file_ext: str = ".png") -> str:
+ """Upload bytes to object storage
+
+ Args:
+ content: Byte content to upload
+ file_ext: File extension
+
+ Returns:
+ File URL
+ """
+ pass
+
+
+class CosStorage(Storage):
+ """Tencent Cloud COS storage implementation"""
+
+ def __init__(self, storage_config=None):
+ """Initialize COS storage
+
+ Args:
+ storage_config: Storage configuration
+ """
+ self.storage_config = storage_config
+ self.client, self.bucket_name, self.region, self.prefix = self._init_cos_client()
+
+ def _init_cos_client(self):
+ """Initialize Tencent Cloud COS client"""
+ try:
+ # Use provided COS config if available, otherwise fall back to environment variables
+ if self.storage_config and self.storage_config.get("access_key_id") != "":
+ cos_config = self.storage_config
+ secret_id = cos_config.get("access_key_id")
+ secret_key = cos_config.get("secret_access_key")
+ region = cos_config.get("region")
+ bucket_name = cos_config.get("bucket_name")
+ appid = cos_config.get("app_id")
+ prefix = cos_config.get("path_prefix", "")
+ else:
+ # Get COS configuration from environment variables
+ secret_id = os.getenv("COS_SECRET_ID")
+ secret_key = os.getenv("COS_SECRET_KEY")
+ region = os.getenv("COS_REGION")
+ bucket_name = os.getenv("COS_BUCKET_NAME")
+ appid = os.getenv("COS_APP_ID")
+ prefix = os.getenv("COS_PATH_PREFIX")
+
+ enable_old_domain = (
+ os.getenv("COS_ENABLE_OLD_DOMAIN", "true").lower() == "true"
+ )
+
+ if not all([secret_id, secret_key, region, bucket_name, appid]):
+ logger.error(
+ "Incomplete COS configuration, missing required environment variables"
+ f"secret_id: {secret_id}, secret_key: {secret_key}, region: {region}, bucket_name: {bucket_name}, appid: {appid}"
+ )
+ return None, None, None, None
+
+ # Initialize COS configuration
+ logger.info(
+ f"Initializing COS client with region: {region}, bucket: {bucket_name}"
+ )
+ config = CosConfig(
+ Appid=appid,
+ Region=region,
+ SecretId=secret_id,
+ SecretKey=secret_key,
+ EnableOldDomain=enable_old_domain,
+ )
+
+ # Create client
+ client = CosS3Client(config)
+ return client, bucket_name, region, prefix
+ except Exception as e:
+ logger.error(f"Failed to initialize COS client: {str(e)}")
+ return None, None, None, None
+
+ def _get_download_url(self, bucket_name, region, object_key):
+ """Generate COS object URL
+
+ Args:
+ bucket_name: Bucket name
+ region: Region
+ object_key: Object key
+
+ Returns:
+ File URL
+ """
+ return f"https://{bucket_name}.cos.{region}.myqcloud.com/{object_key}"
+
+
+ def upload_file(self, file_path: str) -> str:
+ """Upload file to Tencent Cloud COS
+
+ Args:
+ file_path: File path
+
+ Returns:
+ File URL
+ """
+ logger.info(f"Uploading file to COS: {file_path}")
+ try:
+ if not self.client:
+ return ""
+
+ # Generate object key, use UUID to avoid conflicts
+ file_name = os.path.basename(file_path)
+ object_key = (
+ f"{self.prefix}/images/{uuid.uuid4().hex}{os.path.splitext(file_name)[1]}"
+ )
+ logger.info(f"Generated object key: {object_key}")
+
+ # Upload file
+ logger.info("Attempting to upload file to COS")
+ response = self.client.upload_file(
+ Bucket=self.bucket_name, LocalFilePath=file_path, Key=object_key
+ )
+
+ # Get file URL
+ file_url = self._get_download_url(self.bucket_name, self.region, object_key)
+
+ logger.info(f"Successfully uploaded file to COS: {file_url}")
+ return file_url
+
+ except Exception as e:
+ logger.error(f"Failed to upload file to COS: {str(e)}")
+ return ""
+
+ def upload_bytes(self, content: bytes, file_ext: str = ".png") -> str:
+ """Upload bytes to Tencent Cloud COS
+
+ Args:
+ content: Byte content to upload
+ file_ext: File extension
+
+ Returns:
+ File URL
+ """
+ try:
+ logger.info(f"Uploading bytes content to COS, size: {len(content)} bytes")
+ if not self.client:
+ return ""
+
+ object_key = f"{self.prefix}/images/{uuid.uuid4().hex}{file_ext}" if self.prefix else f"images/{uuid.uuid4().hex}{file_ext}"
+ logger.info(f"Generated object key: {object_key}")
+ self.client.put_object(Bucket=self.bucket_name, Body=content, Key=object_key)
+ file_url = self._get_download_url(self.bucket_name, self.region, object_key)
+ logger.info(f"Successfully uploaded bytes to COS: {file_url}")
+ return file_url
+ except Exception as e:
+ logger.error(f"Failed to upload bytes to COS: {str(e)}")
+ traceback.print_exc()
+ return ""
+
+
+class MinioStorage(Storage):
+ """MinIO storage implementation"""
+
+ def __init__(self, storage_config=None):
+ """Initialize MinIO storage
+
+ Args:
+ storage_config: Storage configuration
+ """
+ self.storage_config = storage_config
+ self.client, self.bucket_name, self.use_ssl, self.endpoint, self.path_prefix = self._init_minio_client()
+
+ def _init_minio_client(self):
+ """Initialize MinIO client from environment variables or injected config.
+
+ If storage_config.path_prefix contains JSON from server (for minio case),
+ prefer those values to override envs.
+ """
+ try:
+ endpoint = os.getenv("MINIO_ENDPOINT")
+ access_key = os.getenv("MINIO_ACCESS_KEY_ID")
+ secret_key = os.getenv("MINIO_SECRET_ACCESS_KEY")
+ bucket_name = os.getenv("MINIO_BUCKET_NAME")
+ use_ssl = os.getenv("MINIO_USE_SSL", "false").lower() == "true"
+ path_prefix = os.getenv("MINIO_PATH_PREFIX")
+
+ # Attempt to override with new generic storage fields
+ if self.storage_config:
+ storage_config = self.storage_config
+ # Direct fields
+ endpoint = storage_config.get("endpoint", endpoint)
+ bucket_name = storage_config.get("bucket_name", bucket_name)
+ path_prefix = storage_config.get("path_prefix", path_prefix)
+ access_key = storage_config.get("access_key_id", access_key)
+ secret_key = storage_config.get("secret_access_key", secret_key)
+
+ if not all([endpoint, access_key, secret_key, bucket_name]):
+ logger.error("Incomplete MinIO configuration, missing required environment variables")
+ return None, None, None, None, None
+
+ # Initialize client
+ client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=use_ssl)
+
+ # Ensure bucket exists
+ found = client.bucket_exists(bucket_name)
+ if not found:
+ client.make_bucket(bucket_name)
+ policy = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::%s"]},{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}' % (bucket_name, bucket_name)
+ client.set_bucket_policy(bucket_name, policy)
+
+ return client, bucket_name, use_ssl, endpoint, path_prefix
+ except Exception as e:
+ logger.error(f"Failed to initialize MinIO client: {str(e)}")
+ return None, None, None, None, None
+
+ def _get_download_url(self, bucket_name: str, object_key: str, use_ssl: bool, endpoint: str, public_endpoint: str = None):
+ """Construct a public URL for MinIO object.
+
+ If MINIO_PUBLIC_ENDPOINT is provided, use it; otherwise fallback to endpoint.
+ """
+ if public_endpoint:
+ base = public_endpoint
+ else:
+ scheme = "https" if use_ssl else "http"
+ base = f"{scheme}://{endpoint}"
+ # Path-style URL for MinIO
+ return f"{base}/{bucket_name}/{object_key}"
+
+ def upload_file(self, file_path: str) -> str:
+ """Upload file to MinIO
+
+ Args:
+ file_path: File path
+
+ Returns:
+ File URL
+ """
+ logger.info(f"Uploading file to MinIO: {file_path}")
+ try:
+ if not self.client:
+ return ""
+
+ # Generate object key, use UUID to avoid conflicts
+ file_name = os.path.basename(file_path)
+ object_key = f"{self.path_prefix}/images/{uuid.uuid4().hex}{os.path.splitext(file_name)[1]}" if self.path_prefix else f"images/{uuid.uuid4().hex}{os.path.splitext(file_name)[1]}"
+ logger.info(f"Generated MinIO object key: {object_key}")
+
+ # Upload file
+ logger.info("Attempting to upload file to MinIO")
+ with open(file_path, 'rb') as file_data:
+ file_size = os.path.getsize(file_path)
+ self.client.put_object(
+ bucket_name=self.bucket_name,
+ object_name=object_key,
+ data=file_data,
+ length=file_size,
+ content_type='application/octet-stream'
+ )
+
+ # Get file URL
+ file_url = self._get_download_url(
+ self.bucket_name,
+ object_key,
+ self.use_ssl,
+ self.endpoint,
+ os.getenv("MINIO_PUBLIC_ENDPOINT", None)
+ )
+
+ logger.info(f"Successfully uploaded file to MinIO: {file_url}")
+ return file_url
+
+ except Exception as e:
+ logger.error(f"Failed to upload file to MinIO: {str(e)}")
+ return ""
+
+ def upload_bytes(self, content: bytes, file_ext: str = ".png") -> str:
+ """Upload bytes to MinIO
+
+ Args:
+ content: Byte content to upload
+ file_ext: File extension
+
+ Returns:
+ File URL
+ """
+ try:
+ logger.info(f"Uploading bytes content to MinIO, size: {len(content)} bytes")
+ if not self.client:
+ return ""
+
+ object_key = f"{self.path_prefix}/images/{uuid.uuid4().hex}{file_ext}" if self.path_prefix else f"images/{uuid.uuid4().hex}{file_ext}"
+ logger.info(f"Generated MinIO object key: {object_key}")
+ self.client.put_object(
+ self.bucket_name,
+ object_key,
+ data=io.BytesIO(content),
+ length=len(content),
+ content_type="application/octet-stream"
+ )
+ file_url = self._get_download_url(
+ self.bucket_name,
+ object_key,
+ self.use_ssl,
+ self.endpoint,
+ os.getenv("MINIO_PUBLIC_ENDPOINT", None)
+ )
+ logger.info(f"Successfully uploaded bytes to MinIO: {file_url}")
+ return file_url
+ except Exception as e:
+ logger.error(f"Failed to upload bytes to MinIO: {str(e)}")
+ traceback.print_exc()
+ return ""
+
+
+def create_storage(storage_config=None) -> Storage:
+ """Create a storage instance based on configuration or environment variables
+
+ Args:
+ storage_config: Storage configuration dictionary
+
+ Returns:
+ Storage instance
+ """
+ storage_type = os.getenv("STORAGE_TYPE", "cos").lower()
+
+ if storage_config:
+ storage_type = str(storage_config.get("provider", storage_type)).lower()
+
+ logger.info(f"Creating {storage_type} storage instance")
+
+ if storage_type == "minio":
+ return MinioStorage(storage_config)
+ elif storage_type == "cos":
+ # Default to COS
+ return CosStorage(storage_config)
+ else:
+ return None
\ No newline at end of file
diff --git a/services/docreader/src/parser/text_parser.py b/services/docreader/src/parser/text_parser.py
index 625f346e6..0bd0dd719 100644
--- a/services/docreader/src/parser/text_parser.py
+++ b/services/docreader/src/parser/text_parser.py
@@ -1,5 +1,6 @@
import logging
from .base_parser import BaseParser
+from typing import Dict, Any, Tuple, Union
logger = logging.getLogger(__name__)
@@ -10,7 +11,7 @@ class TextParser(BaseParser):
This parser handles text extraction and chunking from plain text documents.
"""
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""
Parse text document content by decoding bytes to string.
diff --git a/services/docreader/src/parser/web_parser.py b/services/docreader/src/parser/web_parser.py
index dceca7f21..44c42abf9 100644
--- a/services/docreader/src/parser/web_parser.py
+++ b/services/docreader/src/parser/web_parser.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any, Optional, Tuple, Dict, Union
from playwright.async_api import async_playwright
from bs4 import BeautifulSoup
@@ -66,7 +66,7 @@ class WebParser(BaseParser):
# Return empty BeautifulSoup object on error
return BeautifulSoup("", "html.parser")
- def parse_into_text(self, content: bytes) -> str:
+ def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
"""Parse web page
Args:
diff --git a/services/docreader/src/proto/docreader.pb.go b/services/docreader/src/proto/docreader.pb.go
index 70901b947..95199af50 100644
--- a/services/docreader/src/proto/docreader.pb.go
+++ b/services/docreader/src/proto/docreader.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.7
+// protoc-gen-go v1.36.6
// protoc v5.29.3
// source: docreader.proto
@@ -21,33 +21,84 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
-// COS 配置
-type COSConfig struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- SecretId string `protobuf:"bytes,1,opt,name=secret_id,json=secretId,proto3" json:"secret_id,omitempty"` // COS Secret ID
- SecretKey string `protobuf:"bytes,2,opt,name=secret_key,json=secretKey,proto3" json:"secret_key,omitempty"` // COS Secret Key
- Region string `protobuf:"bytes,3,opt,name=region,proto3" json:"region,omitempty"` // COS Region
- BucketName string `protobuf:"bytes,4,opt,name=bucket_name,json=bucketName,proto3" json:"bucket_name,omitempty"` // COS Bucket Name
- AppId string `protobuf:"bytes,5,opt,name=app_id,json=appId,proto3" json:"app_id,omitempty"` // COS App ID
- PathPrefix string `protobuf:"bytes,6,opt,name=path_prefix,json=pathPrefix,proto3" json:"path_prefix,omitempty"` // COS Path Prefix
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+// 对象存储提供方
+type StorageProvider int32
+
+const (
+ StorageProvider_STORAGE_PROVIDER_UNSPECIFIED StorageProvider = 0
+ StorageProvider_COS StorageProvider = 1 // 腾讯云 COS
+ StorageProvider_MINIO StorageProvider = 2 // MinIO/S3 兼容
+)
+
+// Enum value maps for StorageProvider.
+var (
+ StorageProvider_name = map[int32]string{
+ 0: "STORAGE_PROVIDER_UNSPECIFIED",
+ 1: "COS",
+ 2: "MINIO",
+ }
+ StorageProvider_value = map[string]int32{
+ "STORAGE_PROVIDER_UNSPECIFIED": 0,
+ "COS": 1,
+ "MINIO": 2,
+ }
+)
+
+func (x StorageProvider) Enum() *StorageProvider {
+ p := new(StorageProvider)
+ *p = x
+ return p
+}
+
+func (x StorageProvider) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (StorageProvider) Descriptor() protoreflect.EnumDescriptor {
+ return file_docreader_proto_enumTypes[0].Descriptor()
+}
+
+func (StorageProvider) Type() protoreflect.EnumType {
+ return &file_docreader_proto_enumTypes[0]
}
-func (x *COSConfig) Reset() {
- *x = COSConfig{}
+func (x StorageProvider) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use StorageProvider.Descriptor instead.
+func (StorageProvider) EnumDescriptor() ([]byte, []int) {
+ return file_docreader_proto_rawDescGZIP(), []int{0}
+}
+
+// 通用对象存储配置,兼容 COS 与 MinIO
+type StorageConfig struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Provider StorageProvider `protobuf:"varint,1,opt,name=provider,proto3,enum=docreader.StorageProvider" json:"provider,omitempty"` // 存储提供方
+ Region string `protobuf:"bytes,2,opt,name=region,proto3" json:"region,omitempty"` // 区域(COS 使用)
+ BucketName string `protobuf:"bytes,3,opt,name=bucket_name,json=bucketName,proto3" json:"bucket_name,omitempty"` // 桶名
+ AccessKeyId string `protobuf:"bytes,4,opt,name=access_key_id,json=accessKeyId,proto3" json:"access_key_id,omitempty"` // 访问密钥 ID(MinIO/S3 使用)
+ SecretAccessKey string `protobuf:"bytes,5,opt,name=secret_access_key,json=secretAccessKey,proto3" json:"secret_access_key,omitempty"` // 访问密钥 Secret(MinIO/S3 使用)
+ AppId string `protobuf:"bytes,6,opt,name=app_id,json=appId,proto3" json:"app_id,omitempty"` // 应用 ID(COS 使用)
+ PathPrefix string `protobuf:"bytes,7,opt,name=path_prefix,json=pathPrefix,proto3" json:"path_prefix,omitempty"` // 路径前缀
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StorageConfig) Reset() {
+ *x = StorageConfig{}
mi := &file_docreader_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *COSConfig) String() string {
+func (x *StorageConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*COSConfig) ProtoMessage() {}
+func (*StorageConfig) ProtoMessage() {}
-func (x *COSConfig) ProtoReflect() protoreflect.Message {
+func (x *StorageConfig) ProtoReflect() protoreflect.Message {
mi := &file_docreader_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
@@ -59,47 +110,54 @@ func (x *COSConfig) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use COSConfig.ProtoReflect.Descriptor instead.
-func (*COSConfig) Descriptor() ([]byte, []int) {
+// Deprecated: Use StorageConfig.ProtoReflect.Descriptor instead.
+func (*StorageConfig) Descriptor() ([]byte, []int) {
return file_docreader_proto_rawDescGZIP(), []int{0}
}
-func (x *COSConfig) GetSecretId() string {
+func (x *StorageConfig) GetProvider() StorageProvider {
if x != nil {
- return x.SecretId
+ return x.Provider
+ }
+ return StorageProvider_STORAGE_PROVIDER_UNSPECIFIED
+}
+
+func (x *StorageConfig) GetRegion() string {
+ if x != nil {
+ return x.Region
}
return ""
}
-func (x *COSConfig) GetSecretKey() string {
+func (x *StorageConfig) GetBucketName() string {
if x != nil {
- return x.SecretKey
+ return x.BucketName
}
return ""
}
-func (x *COSConfig) GetRegion() string {
+func (x *StorageConfig) GetAccessKeyId() string {
if x != nil {
- return x.Region
+ return x.AccessKeyId
}
return ""
}
-func (x *COSConfig) GetBucketName() string {
+func (x *StorageConfig) GetSecretAccessKey() string {
if x != nil {
- return x.BucketName
+ return x.SecretAccessKey
}
return ""
}
-func (x *COSConfig) GetAppId() string {
+func (x *StorageConfig) GetAppId() string {
if x != nil {
return x.AppId
}
return ""
}
-func (x *COSConfig) GetPathPrefix() string {
+func (x *StorageConfig) GetPathPrefix() string {
if x != nil {
return x.PathPrefix
}
@@ -181,7 +239,7 @@ type ReadConfig struct {
ChunkOverlap int32 `protobuf:"varint,2,opt,name=chunk_overlap,json=chunkOverlap,proto3" json:"chunk_overlap,omitempty"` // 分块重叠
Separators []string `protobuf:"bytes,3,rep,name=separators,proto3" json:"separators,omitempty"` // 分隔符
EnableMultimodal bool `protobuf:"varint,4,opt,name=enable_multimodal,json=enableMultimodal,proto3" json:"enable_multimodal,omitempty"` // 多模态处理
- CosConfig *COSConfig `protobuf:"bytes,5,opt,name=cos_config,json=cosConfig,proto3" json:"cos_config,omitempty"` // COS 配置
+ StorageConfig *StorageConfig `protobuf:"bytes,5,opt,name=storage_config,json=storageConfig,proto3" json:"storage_config,omitempty"` // 对象存储配置(通用)
VlmConfig *VLMConfig `protobuf:"bytes,6,opt,name=vlm_config,json=vlmConfig,proto3" json:"vlm_config,omitempty"` // VLM 配置
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -245,9 +303,9 @@ func (x *ReadConfig) GetEnableMultimodal() bool {
return false
}
-func (x *ReadConfig) GetCosConfig() *COSConfig {
+func (x *ReadConfig) GetStorageConfig() *StorageConfig {
if x != nil {
- return x.CosConfig
+ return x.StorageConfig
}
return nil
}
@@ -623,23 +681,23 @@ var File_docreader_proto protoreflect.FileDescriptor
const file_docreader_proto_rawDesc = "" +
"\n" +
- "\x0fdocreader.proto\x12\tdocreader\"\xb8\x01\n" +
- "\tCOSConfig\x12\x1b\n" +
- "\tsecret_id\x18\x01 \x01(\tR\bsecretId\x12\x1d\n" +
- "\n" +
- "secret_key\x18\x02 \x01(\tR\tsecretKey\x12\x16\n" +
- "\x06region\x18\x03 \x01(\tR\x06region\x12\x1f\n" +
- "\vbucket_name\x18\x04 \x01(\tR\n" +
- "bucketName\x12\x15\n" +
- "\x06app_id\x18\x05 \x01(\tR\x05appId\x12\x1f\n" +
- "\vpath_prefix\x18\x06 \x01(\tR\n" +
+ "\x0fdocreader.proto\x12\tdocreader\"\x88\x02\n" +
+ "\rStorageConfig\x126\n" +
+ "\bprovider\x18\x01 \x01(\x0e2\x1a.docreader.StorageProviderR\bprovider\x12\x16\n" +
+ "\x06region\x18\x02 \x01(\tR\x06region\x12\x1f\n" +
+ "\vbucket_name\x18\x03 \x01(\tR\n" +
+ "bucketName\x12\"\n" +
+ "\raccess_key_id\x18\x04 \x01(\tR\vaccessKeyId\x12*\n" +
+ "\x11secret_access_key\x18\x05 \x01(\tR\x0fsecretAccessKey\x12\x15\n" +
+ "\x06app_id\x18\x06 \x01(\tR\x05appId\x12\x1f\n" +
+ "\vpath_prefix\x18\a \x01(\tR\n" +
"pathPrefix\"\x85\x01\n" +
"\tVLMConfig\x12\x1d\n" +
"\n" +
"model_name\x18\x01 \x01(\tR\tmodelName\x12\x19\n" +
"\bbase_url\x18\x02 \x01(\tR\abaseUrl\x12\x17\n" +
"\aapi_key\x18\x03 \x01(\tR\x06apiKey\x12%\n" +
- "\x0einterface_type\x18\x04 \x01(\tR\rinterfaceType\"\x87\x02\n" +
+ "\x0einterface_type\x18\x04 \x01(\tR\rinterfaceType\"\x93\x02\n" +
"\n" +
"ReadConfig\x12\x1d\n" +
"\n" +
@@ -648,9 +706,8 @@ const file_docreader_proto_rawDesc = "" +
"\n" +
"separators\x18\x03 \x03(\tR\n" +
"separators\x12+\n" +
- "\x11enable_multimodal\x18\x04 \x01(\bR\x10enableMultimodal\x123\n" +
- "\n" +
- "cos_config\x18\x05 \x01(\v2\x14.docreader.COSConfigR\tcosConfig\x123\n" +
+ "\x11enable_multimodal\x18\x04 \x01(\bR\x10enableMultimodal\x12?\n" +
+ "\x0estorage_config\x18\x05 \x01(\v2\x18.docreader.StorageConfigR\rstorageConfig\x123\n" +
"\n" +
"vlm_config\x18\x06 \x01(\v2\x14.docreader.VLMConfigR\tvlmConfig\"\xc9\x01\n" +
"\x13ReadFromFileRequest\x12!\n" +
@@ -683,7 +740,11 @@ const file_docreader_proto_rawDesc = "" +
"\x06images\x18\x05 \x03(\v2\x10.docreader.ImageR\x06images\"N\n" +
"\fReadResponse\x12(\n" +
"\x06chunks\x18\x01 \x03(\v2\x10.docreader.ChunkR\x06chunks\x12\x14\n" +
- "\x05error\x18\x02 \x01(\tR\x05error2\x9f\x01\n" +
+ "\x05error\x18\x02 \x01(\tR\x05error*G\n" +
+ "\x0fStorageProvider\x12 \n" +
+ "\x1cSTORAGE_PROVIDER_UNSPECIFIED\x10\x00\x12\a\n" +
+ "\x03COS\x10\x01\x12\t\n" +
+ "\x05MINIO\x10\x022\x9f\x01\n" +
"\tDocReader\x12I\n" +
"\fReadFromFile\x12\x1e.docreader.ReadFromFileRequest\x1a\x17.docreader.ReadResponse\"\x00\x12G\n" +
"\vReadFromURL\x12\x1d.docreader.ReadFromURLRequest\x1a\x17.docreader.ReadResponse\"\x00B5Z3github.com/Tencent/WeKnora/internal/docreader/protob\x06proto3"
@@ -700,33 +761,36 @@ func file_docreader_proto_rawDescGZIP() []byte {
return file_docreader_proto_rawDescData
}
+var file_docreader_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_docreader_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_docreader_proto_goTypes = []any{
- (*COSConfig)(nil), // 0: docreader.COSConfig
- (*VLMConfig)(nil), // 1: docreader.VLMConfig
- (*ReadConfig)(nil), // 2: docreader.ReadConfig
- (*ReadFromFileRequest)(nil), // 3: docreader.ReadFromFileRequest
- (*ReadFromURLRequest)(nil), // 4: docreader.ReadFromURLRequest
- (*Image)(nil), // 5: docreader.Image
- (*Chunk)(nil), // 6: docreader.Chunk
- (*ReadResponse)(nil), // 7: docreader.ReadResponse
+ (StorageProvider)(0), // 0: docreader.StorageProvider
+ (*StorageConfig)(nil), // 1: docreader.StorageConfig
+ (*VLMConfig)(nil), // 2: docreader.VLMConfig
+ (*ReadConfig)(nil), // 3: docreader.ReadConfig
+ (*ReadFromFileRequest)(nil), // 4: docreader.ReadFromFileRequest
+ (*ReadFromURLRequest)(nil), // 5: docreader.ReadFromURLRequest
+ (*Image)(nil), // 6: docreader.Image
+ (*Chunk)(nil), // 7: docreader.Chunk
+ (*ReadResponse)(nil), // 8: docreader.ReadResponse
}
var file_docreader_proto_depIdxs = []int32{
- 0, // 0: docreader.ReadConfig.cos_config:type_name -> docreader.COSConfig
- 1, // 1: docreader.ReadConfig.vlm_config:type_name -> docreader.VLMConfig
- 2, // 2: docreader.ReadFromFileRequest.read_config:type_name -> docreader.ReadConfig
- 2, // 3: docreader.ReadFromURLRequest.read_config:type_name -> docreader.ReadConfig
- 5, // 4: docreader.Chunk.images:type_name -> docreader.Image
- 6, // 5: docreader.ReadResponse.chunks:type_name -> docreader.Chunk
- 3, // 6: docreader.DocReader.ReadFromFile:input_type -> docreader.ReadFromFileRequest
- 4, // 7: docreader.DocReader.ReadFromURL:input_type -> docreader.ReadFromURLRequest
- 7, // 8: docreader.DocReader.ReadFromFile:output_type -> docreader.ReadResponse
- 7, // 9: docreader.DocReader.ReadFromURL:output_type -> docreader.ReadResponse
- 8, // [8:10] is the sub-list for method output_type
- 6, // [6:8] is the sub-list for method input_type
- 6, // [6:6] is the sub-list for extension type_name
- 6, // [6:6] is the sub-list for extension extendee
- 0, // [0:6] is the sub-list for field type_name
+ 0, // 0: docreader.StorageConfig.provider:type_name -> docreader.StorageProvider
+ 1, // 1: docreader.ReadConfig.storage_config:type_name -> docreader.StorageConfig
+ 2, // 2: docreader.ReadConfig.vlm_config:type_name -> docreader.VLMConfig
+ 3, // 3: docreader.ReadFromFileRequest.read_config:type_name -> docreader.ReadConfig
+ 3, // 4: docreader.ReadFromURLRequest.read_config:type_name -> docreader.ReadConfig
+ 6, // 5: docreader.Chunk.images:type_name -> docreader.Image
+ 7, // 6: docreader.ReadResponse.chunks:type_name -> docreader.Chunk
+ 4, // 7: docreader.DocReader.ReadFromFile:input_type -> docreader.ReadFromFileRequest
+ 5, // 8: docreader.DocReader.ReadFromURL:input_type -> docreader.ReadFromURLRequest
+ 8, // 9: docreader.DocReader.ReadFromFile:output_type -> docreader.ReadResponse
+ 8, // 10: docreader.DocReader.ReadFromURL:output_type -> docreader.ReadResponse
+ 9, // [9:11] is the sub-list for method output_type
+ 7, // [7:9] is the sub-list for method input_type
+ 7, // [7:7] is the sub-list for extension type_name
+ 7, // [7:7] is the sub-list for extension extendee
+ 0, // [0:7] is the sub-list for field type_name
}
func init() { file_docreader_proto_init() }
@@ -739,13 +803,14 @@ func file_docreader_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_docreader_proto_rawDesc), len(file_docreader_proto_rawDesc)),
- NumEnums: 0,
+ NumEnums: 1,
NumMessages: 8,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_docreader_proto_goTypes,
DependencyIndexes: file_docreader_proto_depIdxs,
+ EnumInfos: file_docreader_proto_enumTypes,
MessageInfos: file_docreader_proto_msgTypes,
}.Build()
File_docreader_proto = out.File
diff --git a/services/docreader/src/proto/docreader.proto b/services/docreader/src/proto/docreader.proto
index 3a9ce2920..44ff4acea 100644
--- a/services/docreader/src/proto/docreader.proto
+++ b/services/docreader/src/proto/docreader.proto
@@ -12,14 +12,22 @@ service DocReader {
rpc ReadFromURL(ReadFromURLRequest) returns (ReadResponse) {}
}
-// COS 配置
-message COSConfig {
- string secret_id = 1; // COS Secret ID
- string secret_key = 2; // COS Secret Key
- string region = 3; // COS Region
- string bucket_name = 4; // COS Bucket Name
- string app_id = 5; // COS App ID
- string path_prefix = 6; // COS Path Prefix
+// 对象存储提供方
+enum StorageProvider {
+ STORAGE_PROVIDER_UNSPECIFIED = 0;
+ COS = 1; // 腾讯云 COS
+ MINIO = 2; // MinIO/S3 兼容
+}
+
+// 通用对象存储配置,兼容 COS 与 MinIO
+message StorageConfig {
+ StorageProvider provider = 1; // 存储提供方
+ string region = 2; // 区域(COS 使用)
+ string bucket_name = 3; // 桶名
+ string access_key_id = 4; // 访问密钥 ID(MinIO/S3 使用)
+ string secret_access_key = 5; // 访问密钥 Secret(MinIO/S3 使用)
+ string app_id = 6; // 应用 ID(COS 使用)
+ string path_prefix = 7; // 路径前缀
}
// VLM 配置
@@ -35,7 +43,7 @@ message ReadConfig {
int32 chunk_overlap = 2; // 分块重叠
repeated string separators = 3; // 分隔符
bool enable_multimodal = 4; // 多模态处理
- COSConfig cos_config = 5; // COS 配置
+ StorageConfig storage_config = 5; // 对象存储配置(通用)
VLMConfig vlm_config = 6; // VLM 配置
}
diff --git a/services/docreader/src/server/server.py b/services/docreader/src/server/server.py
index c6a3403aa..c24cdb80d 100644
--- a/services/docreader/src/server/server.py
+++ b/services/docreader/src/server/server.py
@@ -14,7 +14,8 @@ if parent_dir not in sys.path:
from proto.docreader_pb2 import ReadResponse, Chunk, Image
from proto import docreader_pb2_grpc
-from parser import Parser, ChunkingConfig, OCREngine
+from parser import Parser, OCREngine
+from parser.config import ChunkingConfig
from utils.request import request_id_context, init_logging_request_id
# Ensure no existing handlers
@@ -74,38 +75,39 @@ class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
f"multimodal={enable_multimodal}"
)
- # Get COS and VLM config from request
- cos_config = None
+ # Get Storage and VLM config from request
+ storage_config = None
vlm_config = None
- if hasattr(request.read_config, 'cos_config') and request.read_config.cos_config:
- cos_config = {
- 'secret_id': request.read_config.cos_config.secret_id,
- 'secret_key': request.read_config.cos_config.secret_key,
- 'region': request.read_config.cos_config.region,
- 'bucket_name': request.read_config.cos_config.bucket_name,
- 'app_id': request.read_config.cos_config.app_id,
- 'path_prefix': request.read_config.cos_config.path_prefix or '',
- }
- logger.info(f"Using COS config: region={cos_config['region']}, bucket={cos_config['bucket_name']}")
+ sc = request.read_config.storage_config
+ # Keep parser-side key name as cos_config for backward compatibility
+ storage_config = {
+ 'provider': 'minio' if sc.provider == 2 else 'cos',
+ 'region': sc.region,
+ 'bucket_name': sc.bucket_name,
+ 'access_key_id': sc.access_key_id,
+ 'secret_access_key': sc.secret_access_key,
+ 'app_id': sc.app_id,
+ 'path_prefix': sc.path_prefix,
+ }
+ logger.info(f"Using Storage config: provider={storage_config.get('provider')}, bucket={storage_config['bucket_name']}")
- if hasattr(request.read_config, 'vlm_config') and request.read_config.vlm_config:
- vlm_config = {
- 'model_name': request.read_config.vlm_config.model_name,
- 'base_url': request.read_config.vlm_config.base_url,
- 'api_key': request.read_config.vlm_config.api_key or '',
- 'interface_type': request.read_config.vlm_config.interface_type or 'openai',
- }
- logger.info(f"Using VLM config: model={vlm_config['model_name']}, "
- f"base_url={vlm_config['base_url']}, "
- f"interface_type={vlm_config['interface_type']}")
+ vlm_config = {
+ 'model_name': request.read_config.vlm_config.model_name,
+ 'base_url': request.read_config.vlm_config.base_url,
+ 'api_key': request.read_config.vlm_config.api_key or '',
+ 'interface_type': request.read_config.vlm_config.interface_type or 'openai',
+ }
+ logger.info(f"Using VLM config: model={vlm_config['model_name']}, "
+ f"base_url={vlm_config['base_url']}, "
+ f"interface_type={vlm_config['interface_type']}")
chunking_config = ChunkingConfig(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=separators,
enable_multimodal=enable_multimodal,
- cos_config=cos_config,
+ storage_config=storage_config,
vlm_config=vlm_config,
)
@@ -166,38 +168,38 @@ class DocReaderServicer(docreader_pb2_grpc.DocReaderServicer):
f"multimodal={enable_multimodal}"
)
- # Get COS and VLM config from request
- cos_config = None
+ # Get Storage and VLM config from request
+ storage_config = None
vlm_config = None
- if hasattr(request.read_config, 'cos_config') and request.read_config.cos_config:
- cos_config = {
- 'secret_id': request.read_config.cos_config.secret_id,
- 'secret_key': request.read_config.cos_config.secret_key,
- 'region': request.read_config.cos_config.region,
- 'bucket_name': request.read_config.cos_config.bucket_name,
- 'app_id': request.read_config.cos_config.app_id,
- 'path_prefix': request.read_config.cos_config.path_prefix or '',
- }
- logger.info(f"Using COS config: region={cos_config['region']}, bucket={cos_config['bucket_name']}")
-
- if hasattr(request.read_config, 'vlm_config') and request.read_config.vlm_config:
- vlm_config = {
- 'model_name': request.read_config.vlm_config.model_name,
- 'base_url': request.read_config.vlm_config.base_url,
- 'api_key': request.read_config.vlm_config.api_key or '',
- 'interface_type': request.read_config.vlm_config.interface_type or 'openai',
- }
- logger.info(f"Using VLM config: model={vlm_config['model_name']}, "
- f"base_url={vlm_config['base_url']}, "
- f"interface_type={vlm_config['interface_type']}")
+ sc = request.read_config.storage_config
+ storage_config = {
+ 'provider': 'minio' if sc.provider == 2 else 'cos',
+ 'region': sc.region,
+ 'bucket_name': sc.bucket_name,
+ 'access_key_id': sc.access_key_id,
+ 'secret_access_key': sc.secret_access_key,
+ 'app_id': sc.app_id,
+ 'path_prefix': sc.path_prefix,
+ }
+ logger.info(f"Using Storage config: provider={storage_config.get('provider')}, bucket={storage_config['bucket_name']}")
+
+ vlm_config = {
+ 'model_name': request.read_config.vlm_config.model_name,
+ 'base_url': request.read_config.vlm_config.base_url,
+ 'api_key': request.read_config.vlm_config.api_key or '',
+ 'interface_type': request.read_config.vlm_config.interface_type or 'openai',
+ }
+ logger.info(f"Using VLM config: model={vlm_config['model_name']}, "
+ f"base_url={vlm_config['base_url']}, "
+ f"interface_type={vlm_config['interface_type']}")
chunking_config = ChunkingConfig(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=separators,
enable_multimodal=enable_multimodal,
- cos_config=cos_config,
+ storage_config=storage_config,
vlm_config=vlm_config,
)