feat: introduce WeKnora Lite edition with lightweight configuration and deployment
- Added a new `.env.lite.example` file for the Lite version, providing a minimal configuration template. - Updated `.env.example` to remove deprecated variables and include new Docreader settings. - Enhanced Docker configurations to support the Lite version, including a new Dockerfile for the Docreader service. - Introduced a Makefile target for building and running the Lite version, along with packaging capabilities. - Created GitHub workflows for building and releasing Lite binaries, including Homebrew formula support. - Implemented a new service file for managing the Lite version as a system service. This update enables a streamlined, single-binary deployment of WeKnora, reducing external dependencies and simplifying setup.
This commit is contained in:
@@ -470,9 +470,10 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
return
|
||||
}
|
||||
|
||||
// Wrap results with metadata
|
||||
// Wrap results with metadata and write back KB ID
|
||||
mu.Lock()
|
||||
for _, r := range kbResults {
|
||||
r.KnowledgeBaseID = st.KnowledgeBaseID
|
||||
allResults = append(allResults, &searchResultWithMeta{
|
||||
SearchResult: r,
|
||||
SourceQuery: q,
|
||||
|
||||
@@ -246,11 +246,11 @@ func (r *chunkRepository) ListChunkByParentID(
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// UpdateChunk updates a chunk using GORM Save, which updates ALL fields.
|
||||
// Note: This will update all fields including metadata and content_hash.
|
||||
// UpdateChunk updates a chunk using GORM Save, which updates ALL fields
|
||||
// except SeqID (auto-increment, must not be overwritten).
|
||||
// Make sure the chunk object is complete (e.g., fetched from DB) before calling this method.
|
||||
func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) error {
|
||||
return r.db.WithContext(ctx).Save(chunk).Error
|
||||
return r.db.WithContext(ctx).Omit("SeqID").Save(chunk).Error
|
||||
}
|
||||
|
||||
// UpdateChunks updates chunks in batch using raw SQL for efficiency.
|
||||
@@ -332,23 +332,46 @@ func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chun
|
||||
args = append(args, id)
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(`
|
||||
UPDATE chunks SET
|
||||
content = CASE %s END,
|
||||
is_enabled = (CASE %s END)::boolean,
|
||||
tag_id = CASE %s END,
|
||||
flags = (CASE %s END)::integer,
|
||||
status = (CASE %s END)::integer,
|
||||
updated_at = NOW()
|
||||
WHERE id IN (%s)
|
||||
`,
|
||||
strings.Join(contentCases, " "),
|
||||
strings.Join(isEnabledCases, " "),
|
||||
strings.Join(tagIDCases, " "),
|
||||
strings.Join(flagsCases, " "),
|
||||
strings.Join(statusCases, " "),
|
||||
strings.Join(inPlaceholders, ","),
|
||||
)
|
||||
isPostgres := r.db.Dialector.Name() == "postgres"
|
||||
|
||||
var sql string
|
||||
if isPostgres {
|
||||
sql = fmt.Sprintf(`
|
||||
UPDATE chunks SET
|
||||
content = CASE %s END,
|
||||
is_enabled = (CASE %s END)::boolean,
|
||||
tag_id = CASE %s END,
|
||||
flags = (CASE %s END)::integer,
|
||||
status = (CASE %s END)::integer,
|
||||
updated_at = NOW()
|
||||
WHERE id IN (%s)
|
||||
`,
|
||||
strings.Join(contentCases, " "),
|
||||
strings.Join(isEnabledCases, " "),
|
||||
strings.Join(tagIDCases, " "),
|
||||
strings.Join(flagsCases, " "),
|
||||
strings.Join(statusCases, " "),
|
||||
strings.Join(inPlaceholders, ","),
|
||||
)
|
||||
} else {
|
||||
sql = fmt.Sprintf(`
|
||||
UPDATE chunks SET
|
||||
content = CASE %s END,
|
||||
is_enabled = CASE %s END,
|
||||
tag_id = CASE %s END,
|
||||
flags = CASE %s END,
|
||||
status = CASE %s END,
|
||||
updated_at = datetime('now')
|
||||
WHERE id IN (%s)
|
||||
`,
|
||||
strings.Join(contentCases, " "),
|
||||
strings.Join(isEnabledCases, " "),
|
||||
strings.Join(tagIDCases, " "),
|
||||
strings.Join(flagsCases, " "),
|
||||
strings.Join(statusCases, " "),
|
||||
strings.Join(inPlaceholders, ","),
|
||||
)
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Exec(sql, args...).Error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// sqliteEmbedding stores metadata alongside the vec0 virtual table rows
|
||||
type sqliteEmbedding struct {
|
||||
ID uint `gorm:"primarykey;autoIncrement"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
SourceID string `gorm:"column:source_id;not null;uniqueIndex:idx_sqlite_emb_source"`
|
||||
SourceType int `gorm:"column:source_type;not null;uniqueIndex:idx_sqlite_emb_source"`
|
||||
ChunkID string `gorm:"column:chunk_id;index"`
|
||||
KnowledgeID string `gorm:"column:knowledge_id;index"`
|
||||
KnowledgeBaseID string `gorm:"column:knowledge_base_id;index"`
|
||||
TagID string `gorm:"column:tag_id;index"`
|
||||
Content string `gorm:"column:content;not null"`
|
||||
Dimension int `gorm:"column:dimension;not null"`
|
||||
IsEnabled *bool `gorm:"column:is_enabled;default:true;index"`
|
||||
}
|
||||
|
||||
func (sqliteEmbedding) TableName() string { return "lite_embeddings" }
|
||||
|
||||
type sqliteRepository struct {
|
||||
db *gorm.DB
|
||||
vecTables map[int]bool // tracks which vec0 tables have been created (keyed by dimension)
|
||||
}
|
||||
|
||||
func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRepository {
|
||||
logger.GetLogger(context.Background()).Info("[SQLite] Initializing SQLite retriever engine repository with sqlite-vec")
|
||||
|
||||
if err := db.AutoMigrate(&sqliteEmbedding{}); err != nil {
|
||||
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to auto-migrate lite_embeddings: %v", err)
|
||||
}
|
||||
|
||||
initFTS5(db)
|
||||
|
||||
repo := &sqliteRepository{
|
||||
db: db,
|
||||
vecTables: make(map[int]bool),
|
||||
}
|
||||
|
||||
repo.ensureExistingVecTables()
|
||||
|
||||
return repo
|
||||
}
|
||||
|
||||
func initFTS5(db *gorm.DB) {
|
||||
sql := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
|
||||
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
|
||||
content='lite_embeddings', content_rowid='id',
|
||||
tokenize='unicode61'
|
||||
)`
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
logger.GetLogger(context.Background()).Warnf("[SQLite] Failed to create FTS5 table: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func vecTableName(dim int) string {
|
||||
return fmt.Sprintf("vec_embeddings_%d", dim)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) ensureVecTable(dim int) {
|
||||
if dim <= 0 || r.vecTables[dim] {
|
||||
return
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
createSQL := fmt.Sprintf(
|
||||
`CREATE VIRTUAL TABLE IF NOT EXISTS %s USING vec0(embedding float[%d] distance_metric=cosine)`,
|
||||
tbl, dim,
|
||||
)
|
||||
if err := r.db.Exec(createSQL).Error; err != nil {
|
||||
if strings.Contains(err.Error(), "already exists") {
|
||||
r.vecTables[dim] = true
|
||||
return
|
||||
}
|
||||
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to create vec0 table for dim %d: %v", dim, err)
|
||||
return
|
||||
}
|
||||
r.vecTables[dim] = true
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) ensureExistingVecTables() {
|
||||
var dims []int
|
||||
r.db.Model(&sqliteEmbedding{}).Distinct("dimension").Where("dimension > 0").Pluck("dimension", &dims)
|
||||
for _, dim := range dims {
|
||||
r.ensureVecTable(dim)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) EngineType() types.RetrieverEngineType {
|
||||
return types.SQLiteRetrieverEngineType
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Support() []types.RetrieverType {
|
||||
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error {
|
||||
row := toSQLiteEmbedding(indexInfo)
|
||||
emb := extractEmbedding(params, indexInfo.SourceID)
|
||||
if len(emb) > 0 {
|
||||
row.Dimension = len(emb)
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(row).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
r.syncFTS5Insert(ctx, row)
|
||||
if len(emb) > 0 && row.ID > 0 {
|
||||
r.insertVec(ctx, row.ID, row.Dimension, emb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error {
|
||||
if len(indexInfoList) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows := make([]*sqliteEmbedding, len(indexInfoList))
|
||||
embs := make([][]float32, len(indexInfoList))
|
||||
for i, info := range indexInfoList {
|
||||
rows[i] = toSQLiteEmbedding(info)
|
||||
emb := extractEmbedding(params, info.SourceID)
|
||||
embs[i] = emb
|
||||
if len(emb) > 0 {
|
||||
rows[i].Dimension = len(emb)
|
||||
}
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for i, row := range rows {
|
||||
r.syncFTS5Insert(ctx, row)
|
||||
if len(embs[i]) > 0 && row.ID > 0 {
|
||||
r.insertVec(ctx, row.ID, row.Dimension, embs[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) EstimateStorageSize(_ context.Context, indexInfoList []*types.IndexInfo, _ map[string]any) int64 {
|
||||
var total int64
|
||||
for _, info := range indexInfoList {
|
||||
total += int64(len(info.Content)) + 200
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Find(&rows)
|
||||
r.deleteRowsAndVecs(ctx, rows)
|
||||
return r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Find(&rows)
|
||||
r.deleteRowsAndVecs(ctx, rows)
|
||||
return r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, _ int, _ string) error {
|
||||
var rows []sqliteEmbedding
|
||||
r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Find(&rows)
|
||||
r.deleteRowsAndVecs(ctx, rows)
|
||||
return r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&sqliteEmbedding{}).Error
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) CopyIndices(ctx context.Context,
|
||||
_ string,
|
||||
sourceToTargetKBIDMap map[string]string,
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string,
|
||||
_ int, _ string,
|
||||
) error {
|
||||
for sourceChunkID, targetChunkID := range sourceToTargetChunkIDMap {
|
||||
var src sqliteEmbedding
|
||||
if err := r.db.WithContext(ctx).Where("chunk_id = ?", sourceChunkID).First(&src).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
newRow := sqliteEmbedding{
|
||||
SourceID: uuid.New().String(),
|
||||
SourceType: src.SourceType,
|
||||
ChunkID: targetChunkID,
|
||||
KnowledgeID: sourceToTargetKBIDMap[src.KnowledgeID],
|
||||
KnowledgeBaseID: targetKnowledgeBaseID,
|
||||
TagID: src.TagID,
|
||||
Content: src.Content,
|
||||
Dimension: src.Dimension,
|
||||
IsEnabled: src.IsEnabled,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(&newRow).Error; err != nil {
|
||||
logger.GetLogger(ctx).Warnf("[SQLite] CopyIndices: failed to copy chunk %s: %v", sourceChunkID, err)
|
||||
continue
|
||||
}
|
||||
r.syncFTS5Insert(ctx, &newRow)
|
||||
if src.Dimension > 0 && newRow.ID > 0 {
|
||||
r.copyVec(ctx, src.ID, newRow.ID, src.Dimension)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
r.db.WithContext(ctx).Model(&sqliteEmbedding{}).Where("chunk_id = ?", chunkID).Update("is_enabled", enabled)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
|
||||
for chunkID, tagID := range chunkTagMap {
|
||||
r.db.WithContext(ctx).Model(&sqliteEmbedding{}).Where("chunk_id = ?", chunkID).Update("tag_id", tagID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Retrieve ---
|
||||
|
||||
func (r *sqliteRepository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
var results []*types.RetrieveResult
|
||||
|
||||
if params.RetrieverType == types.KeywordsRetrieverType || params.RetrieverType == "" {
|
||||
res, err := r.keywordsRetrieve(ctx, params)
|
||||
if err != nil {
|
||||
results = append(results, &types.RetrieveResult{
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
Error: err,
|
||||
})
|
||||
} else {
|
||||
results = append(results, res...)
|
||||
}
|
||||
}
|
||||
|
||||
if params.RetrieverType == types.VectorRetrieverType || params.RetrieverType == "" {
|
||||
res, err := r.vectorRetrieve(ctx, params)
|
||||
if err != nil {
|
||||
results = append(results, &types.RetrieveResult{
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
Error: err,
|
||||
})
|
||||
} else {
|
||||
results = append(results, res...)
|
||||
}
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// --- Keywords retrieval via FTS5 ---
|
||||
func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
if params.Query == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ftsQuery := sanitizeFTS5Query(params.Query)
|
||||
|
||||
sql := `
|
||||
SELECT e.id, e.source_id, e.source_type, e.chunk_id,
|
||||
e.knowledge_id, e.knowledge_base_id, e.tag_id,
|
||||
e.content,
|
||||
bm25(lite_embeddings_fts) AS score
|
||||
FROM lite_embeddings_fts
|
||||
JOIN lite_embeddings e ON e.id = lite_embeddings_fts.rowid
|
||||
WHERE lite_embeddings_fts MATCH ?
|
||||
AND (e.is_enabled IS NULL OR e.is_enabled = 1)
|
||||
`
|
||||
|
||||
args := []interface{}{ftsQuery}
|
||||
|
||||
for _, wp := range buildFilterWhere(params) {
|
||||
sql += " AND " + wp.clause
|
||||
args = append(args, wp.args...)
|
||||
}
|
||||
|
||||
sql += " ORDER BY score ASC LIMIT ?"
|
||||
args = append(args, params.TopK)
|
||||
|
||||
type ftsResult struct {
|
||||
ID uint
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
Content string
|
||||
Score float64
|
||||
}
|
||||
|
||||
var rows []ftsResult
|
||||
if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("FTS5 query failed: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: query=%q, ftsQuery=%q, matched=%d rows", params.Query, ftsQuery, len(rows))
|
||||
|
||||
items := make([]*types.IndexWithScore, len(rows))
|
||||
for i, row := range rows {
|
||||
|
||||
// bm25 越小越相关 → 转成正向分数
|
||||
score := -row.Score
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, bm25_raw=%.4f, score=%.4f, content_preview=%.60s",
|
||||
i+1, row.ChunkID, row.Score, score, row.Content)
|
||||
|
||||
items[i] = &types.IndexWithScore{
|
||||
ID: fmt.Sprintf("%d", row.ID),
|
||||
SourceID: row.SourceID,
|
||||
SourceType: types.SourceType(row.SourceType),
|
||||
ChunkID: row.ChunkID,
|
||||
KnowledgeID: row.KnowledgeID,
|
||||
KnowledgeBaseID: row.KnowledgeBaseID,
|
||||
TagID: row.TagID,
|
||||
Content: row.Content,
|
||||
Score: score,
|
||||
MatchType: types.MatchTypeKeywords,
|
||||
}
|
||||
}
|
||||
|
||||
return []*types.RetrieveResult{{
|
||||
Results: items,
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
}}, nil
|
||||
}
|
||||
func (r *sqliteRepository) vectorRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
if len(params.Embedding) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dim := len(params.Embedding)
|
||||
r.ensureVecTable(dim)
|
||||
|
||||
queryBlob, err := sqlite_vec.SerializeFloat32(params.Embedding)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize query vector failed: %w", err)
|
||||
}
|
||||
|
||||
tbl := vecTableName(dim)
|
||||
|
||||
// ⚠️ sqlite-vec 要求必须有 k = ?
|
||||
vecSQL := fmt.Sprintf(`
|
||||
SELECT v.rowid, v.distance,
|
||||
e.source_id, e.source_type, e.chunk_id,
|
||||
e.knowledge_id, e.knowledge_base_id,
|
||||
e.tag_id, e.content
|
||||
FROM %s v
|
||||
JOIN lite_embeddings e ON e.id = v.rowid
|
||||
WHERE v.embedding MATCH ?
|
||||
AND k = ?
|
||||
AND (e.is_enabled IS NULL OR e.is_enabled = 1)
|
||||
`, tbl)
|
||||
|
||||
args := []interface{}{
|
||||
queryBlob,
|
||||
params.TopK, // 这里就是 k
|
||||
}
|
||||
|
||||
// 追加过滤条件
|
||||
for _, wp := range buildFilterWhere(params) {
|
||||
vecSQL += " AND " + wp.clause
|
||||
args = append(args, wp.args...)
|
||||
}
|
||||
|
||||
// ⚠️ 这里仍然建议加 ORDER BY,虽然 vec0 已经按距离返回
|
||||
vecSQL += " ORDER BY v.distance ASC"
|
||||
|
||||
type row struct {
|
||||
Rowid uint
|
||||
Distance float64
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
Content string
|
||||
}
|
||||
|
||||
var rows []row
|
||||
if err := r.db.WithContext(ctx).
|
||||
Raw(vecSQL, args...).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("sqlite-vec query failed: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: query_dim=%d, threshold=%.4f, matched=%d rows", dim, params.Threshold, len(rows))
|
||||
|
||||
items := make([]*types.IndexWithScore, 0, len(rows))
|
||||
|
||||
for i, v := range rows {
|
||||
// cosine distance = 1 - cosine_similarity
|
||||
score := 1 - v.Distance
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: #%d chunk_id=%s, distance=%.4f, score=%.4f, content_preview=%.60s",
|
||||
i+1, v.ChunkID, v.Distance, score, v.Content)
|
||||
|
||||
items = append(items, &types.IndexWithScore{
|
||||
ID: fmt.Sprintf("%d", v.Rowid),
|
||||
SourceID: v.SourceID,
|
||||
SourceType: types.SourceType(v.SourceType),
|
||||
ChunkID: v.ChunkID,
|
||||
KnowledgeID: v.KnowledgeID,
|
||||
KnowledgeBaseID: v.KnowledgeBaseID,
|
||||
TagID: v.TagID,
|
||||
Content: v.Content,
|
||||
Score: score,
|
||||
MatchType: types.MatchTypeEmbedding,
|
||||
})
|
||||
}
|
||||
|
||||
return []*types.RetrieveResult{{
|
||||
Results: items,
|
||||
RetrieverEngineType: types.SQLiteRetrieverEngineType,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
}}, nil
|
||||
}
|
||||
|
||||
// --- Internal helpers ---
|
||||
|
||||
func toSQLiteEmbedding(info *types.IndexInfo) *sqliteEmbedding {
|
||||
enabled := true
|
||||
return &sqliteEmbedding{
|
||||
SourceID: info.SourceID,
|
||||
SourceType: int(info.SourceType),
|
||||
ChunkID: info.ChunkID,
|
||||
KnowledgeID: info.KnowledgeID,
|
||||
KnowledgeBaseID: info.KnowledgeBaseID,
|
||||
TagID: info.TagID,
|
||||
Content: common.CleanInvalidUTF8(info.Content),
|
||||
Dimension: 0,
|
||||
IsEnabled: &enabled,
|
||||
}
|
||||
}
|
||||
|
||||
func extractEmbedding(params map[string]any, sourceID string) []float32 {
|
||||
if params == nil {
|
||||
return nil
|
||||
}
|
||||
embMap, ok := params["embedding"].(map[string][]float32)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return embMap[sourceID]
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) insertVec(_ context.Context, rowID uint, dim int, emb []float32) {
|
||||
r.ensureVecTable(dim)
|
||||
blob, err := sqlite_vec.SerializeFloat32(emb)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sql := fmt.Sprintf("INSERT INTO %s(rowid, embedding) VALUES (?, ?)", vecTableName(dim))
|
||||
r.db.Exec(sql, rowID, blob)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) deleteRowsAndVecs(_ context.Context, rows []sqliteEmbedding) {
|
||||
dimIDs := make(map[int][]uint)
|
||||
for _, row := range rows {
|
||||
if row.Dimension > 0 {
|
||||
dimIDs[row.Dimension] = append(dimIDs[row.Dimension], row.ID)
|
||||
}
|
||||
}
|
||||
for dim, ids := range dimIDs {
|
||||
if !r.vecTables[dim] {
|
||||
continue
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
for _, id := range ids {
|
||||
r.db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) copyVec(_ context.Context, srcID, dstID uint, dim int) {
|
||||
if !r.vecTables[dim] {
|
||||
return
|
||||
}
|
||||
tbl := vecTableName(dim)
|
||||
r.db.Exec(fmt.Sprintf(
|
||||
"INSERT INTO %s(rowid, embedding) SELECT ?, embedding FROM %s WHERE rowid = ?",
|
||||
tbl, tbl,
|
||||
), dstID, srcID)
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) syncFTS5Insert(_ context.Context, row *sqliteEmbedding) {
|
||||
if row.ID == 0 {
|
||||
return
|
||||
}
|
||||
sql := `INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)`
|
||||
r.db.Exec(sql, row.ID, row.Content, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID)
|
||||
}
|
||||
|
||||
type whereClause struct {
|
||||
clause string
|
||||
args []interface{}
|
||||
}
|
||||
|
||||
func buildFilterWhere(params types.RetrieveParams) []whereClause {
|
||||
var parts []whereClause
|
||||
if len(params.KnowledgeBaseIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: "e.knowledge_base_id IN (" + placeholders(len(params.KnowledgeBaseIDs)) + ")",
|
||||
args: toInterfaceSlice(params.KnowledgeBaseIDs),
|
||||
})
|
||||
}
|
||||
if len(params.KnowledgeIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: "e.knowledge_id IN (" + placeholders(len(params.KnowledgeIDs)) + ")",
|
||||
args: toInterfaceSlice(params.KnowledgeIDs),
|
||||
})
|
||||
}
|
||||
if len(params.TagIDs) > 0 {
|
||||
parts = append(parts, whereClause{
|
||||
clause: "e.tag_id IN (" + placeholders(len(params.TagIDs)) + ")",
|
||||
args: toInterfaceSlice(params.TagIDs),
|
||||
})
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func placeholders(n int) string {
|
||||
p := make([]string, n)
|
||||
for i := range p {
|
||||
p[i] = "?"
|
||||
}
|
||||
return strings.Join(p, ",")
|
||||
}
|
||||
|
||||
func toInterfaceSlice(ss []string) []interface{} {
|
||||
out := make([]interface{}, len(ss))
|
||||
for i, s := range ss {
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sanitizeFTS5Query builds an FTS5 query from user input.
|
||||
// CJK characters are split into overlapping bigrams (mimicking CJK analyzers used
|
||||
// by Elasticsearch etc.) and joined with OR for broad partial matching.
|
||||
// Non-CJK words are kept intact. BM25 ranking naturally boosts documents
|
||||
// that match more tokens.
|
||||
func sanitizeFTS5Query(q string) string {
|
||||
q = strings.TrimSpace(q)
|
||||
if q == "" {
|
||||
return q
|
||||
}
|
||||
|
||||
var cjkRunes []rune
|
||||
var nonCJKWords []string
|
||||
var buf strings.Builder
|
||||
|
||||
flushNonCJK := func() {
|
||||
if buf.Len() > 0 {
|
||||
nonCJKWords = append(nonCJKWords, buf.String())
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range q {
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
flushNonCJK()
|
||||
cjkRunes = append(cjkRunes, r)
|
||||
} else if unicode.IsSpace(r) || r == '|' {
|
||||
flushNonCJK()
|
||||
} else if r == '"' || r == '*' || r == '(' || r == ')' || r == '{' || r == '}' {
|
||||
// skip FTS5 special characters
|
||||
} else {
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
flushNonCJK()
|
||||
|
||||
var parts []string
|
||||
|
||||
// CJK bigrams for better matching (e.g. "苹果第四季度" → "苹果" OR "果第" OR "第四" OR ...)
|
||||
if len(cjkRunes) == 1 {
|
||||
parts = append(parts, `"`+string(cjkRunes[0])+`"`)
|
||||
} else {
|
||||
for i := 0; i < len(cjkRunes)-1; i++ {
|
||||
bigram := string(cjkRunes[i]) + string(cjkRunes[i+1])
|
||||
parts = append(parts, `"`+bigram+`"`)
|
||||
}
|
||||
}
|
||||
|
||||
for _, w := range nonCJKWords {
|
||||
w = strings.ReplaceAll(w, `"`, `""`)
|
||||
parts = append(parts, `"`+w+`"`)
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return `"` + strings.ReplaceAll(q, `"`, `""`) + `"`
|
||||
}
|
||||
return strings.Join(parts, " OR ")
|
||||
}
|
||||
@@ -114,7 +114,7 @@ func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint6
|
||||
tenant.StorageUsed += delta
|
||||
// 保存更新并验证业务规则
|
||||
if tenant.StorageUsed < 0 {
|
||||
logger.Error(ctx, "tenant storage used is negative %s: %d", tenant.ID, tenant.StorageUsed)
|
||||
logger.Errorf(ctx, "tenant storage used is negative %d: %d", tenant.ID, tenant.StorageUsed)
|
||||
tenant.StorageUsed = 0
|
||||
}
|
||||
|
||||
|
||||
@@ -183,6 +183,9 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
return
|
||||
}
|
||||
if len(res) > 0 {
|
||||
for _, r := range res {
|
||||
r.KnowledgeBaseID = t.KnowledgeBaseID
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "expansion_hits", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"query": q,
|
||||
@@ -338,6 +341,9 @@ func (p *PluginSearch) searchByTargets(
|
||||
directResults, skippedIDs := p.tryDirectChunkLoading(ctx, chatManage.TenantID, t.KnowledgeIDs)
|
||||
|
||||
if len(directResults) > 0 {
|
||||
for _, r := range directResults {
|
||||
r.KnowledgeBaseID = t.KnowledgeBaseID
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "direct_load", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"loaded_count": len(directResults),
|
||||
@@ -383,6 +389,9 @@ func (p *PluginSearch) searchByTargets(
|
||||
})
|
||||
return
|
||||
}
|
||||
for _, r := range res {
|
||||
r.KnowledgeBaseID = t.KnowledgeBaseID
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "kb_result", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"target_type": t.Type,
|
||||
|
||||
@@ -222,5 +222,6 @@ func chunk2SearchResult(chunk *types.Chunk, knowledge *types.Knowledge) *types.S
|
||||
KnowledgeFilename: knowledge.FileName,
|
||||
KnowledgeSource: knowledge.Source,
|
||||
ChunkMetadata: chunk.Metadata,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ const (
|
||||
// NewChunkExtractTask creates a new chunk extract task
|
||||
func NewChunkExtractTask(
|
||||
ctx context.Context,
|
||||
client *asynq.Client,
|
||||
client interfaces.TaskEnqueuer,
|
||||
tenantID uint64,
|
||||
chunkID string,
|
||||
modelID string,
|
||||
@@ -109,7 +109,7 @@ func NewChunkExtractTask(
|
||||
// NewTableExtractTask creates a new table extract task
|
||||
func NewDataTableSummaryTask(
|
||||
ctx context.Context,
|
||||
client *asynq.Client,
|
||||
client interfaces.TaskEnqueuer,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
summaryModel string,
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/google/uuid"
|
||||
@@ -23,11 +24,28 @@ type cosFileService struct {
|
||||
client *cos.Client
|
||||
bucketURL string
|
||||
cosPathPrefix string
|
||||
// 临时桶配置(用于存放自动过期的临时文件)
|
||||
tempClient *cos.Client
|
||||
tempBucketURL string
|
||||
}
|
||||
|
||||
// newCosClient creates a bare cosFileService with just the SDK client initialised.
|
||||
// Shared by NewCosFileService* constructors and CheckCosConnectivity.
|
||||
func newCosClient(bucketName, region, secretID, secretKey string) (*cosFileService, error) {
|
||||
bucketURL := fmt.Sprintf("https://%s.cos.%s.myqcloud.com/", bucketName, region)
|
||||
u, err := url.Parse(bucketURL)
|
||||
logger.Infof(context.Background(), "newCosClient: bucketURL: %s", bucketURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse bucketURL: %w", err)
|
||||
}
|
||||
client := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{
|
||||
Transport: &cos.AuthorizationTransport{
|
||||
SecretID: secretID,
|
||||
SecretKey: secretKey,
|
||||
},
|
||||
})
|
||||
return &cosFileService{client: client, bucketURL: bucketURL}, nil
|
||||
}
|
||||
|
||||
// NewCosFileService creates a new COS file service instance
|
||||
func NewCosFileService(bucketName, region, secretId, secretKey, cosPathPrefix string) (interfaces.FileService, error) {
|
||||
return NewCosFileServiceWithTempBucket(bucketName, region, secretId, secretKey, cosPathPrefix, "", "")
|
||||
@@ -35,49 +53,51 @@ func NewCosFileService(bucketName, region, secretId, secretKey, cosPathPrefix st
|
||||
|
||||
// NewCosFileServiceWithTempBucket creates a new COS file service instance with optional temp bucket
|
||||
func NewCosFileServiceWithTempBucket(bucketName, region, secretId, secretKey, cosPathPrefix, tempBucketName, tempRegion string) (interfaces.FileService, error) {
|
||||
bucketURL := fmt.Sprintf("https://%s.cos.%s.tencentcos.cn/", bucketName, region)
|
||||
u, err := url.Parse(bucketURL)
|
||||
svc, err := newCosClient(bucketName, region, secretId, secretKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse bucketURL: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
b := &cos.BaseURL{BucketURL: u}
|
||||
client := cos.NewClient(b, &http.Client{
|
||||
Transport: &cos.AuthorizationTransport{
|
||||
SecretID: secretId,
|
||||
SecretKey: secretKey,
|
||||
},
|
||||
})
|
||||
svc.cosPathPrefix = cosPathPrefix
|
||||
|
||||
svc := &cosFileService{
|
||||
client: client,
|
||||
bucketURL: bucketURL,
|
||||
cosPathPrefix: cosPathPrefix,
|
||||
}
|
||||
|
||||
// 如果配置了临时桶,初始化临时桶客户端
|
||||
if tempBucketName != "" {
|
||||
if tempRegion == "" {
|
||||
tempRegion = region // 默认使用相同的 region
|
||||
tempRegion = region
|
||||
}
|
||||
tempBucketURL := fmt.Sprintf("https://%s.cos.%s.tencentcos.cn/", tempBucketName, tempRegion)
|
||||
tempBucketURL := fmt.Sprintf("https://%s.cos.%s.myqcloud.com/", tempBucketName, tempRegion)
|
||||
tempU, err := url.Parse(tempBucketURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse temp bucketURL: %w", err)
|
||||
}
|
||||
tempB := &cos.BaseURL{BucketURL: tempU}
|
||||
tempClient := cos.NewClient(tempB, &http.Client{
|
||||
svc.tempClient = cos.NewClient(&cos.BaseURL{BucketURL: tempU}, &http.Client{
|
||||
Transport: &cos.AuthorizationTransport{
|
||||
SecretID: secretId,
|
||||
SecretKey: secretKey,
|
||||
},
|
||||
})
|
||||
svc.tempClient = tempClient
|
||||
svc.tempBucketURL = tempBucketURL
|
||||
}
|
||||
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
// CheckConnectivity verifies COS is reachable by performing a HEAD request on the bucket.
|
||||
func (s *cosFileService) CheckConnectivity(ctx context.Context) error {
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
_, err := s.client.Bucket.Head(checkCtx)
|
||||
return err
|
||||
}
|
||||
|
||||
// CheckCosConnectivity tests COS connectivity using the provided credentials.
|
||||
// It creates a temporary service instance internally and delegates to CheckConnectivity.
|
||||
func CheckCosConnectivity(ctx context.Context, bucketName, region, secretID, secretKey string) error {
|
||||
svc, err := newCosClient(bucketName, region, secretID, secretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return svc.CheckConnectivity(ctx)
|
||||
}
|
||||
|
||||
// SaveFile saves a file to COS storage
|
||||
// It generates a unique name for the file and organizes it by tenant and knowledge ID
|
||||
func (s *cosFileService) SaveFile(ctx context.Context,
|
||||
|
||||
@@ -14,6 +14,11 @@ import (
|
||||
// used for testing or when file storage is not required
|
||||
type DummyFileService struct{}
|
||||
|
||||
// CheckConnectivity always succeeds for the dummy service.
|
||||
func (s *DummyFileService) CheckConnectivity(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewDummyFileService creates a new instance of DummyFileService
|
||||
func NewDummyFileService() interfaces.FileService {
|
||||
return &DummyFileService{}
|
||||
|
||||
@@ -19,6 +19,18 @@ type localFileService struct {
|
||||
baseDir string // Base directory for file storage
|
||||
}
|
||||
|
||||
// CheckConnectivity verifies the local storage directory exists and is accessible.
|
||||
func (s *localFileService) CheckConnectivity(ctx context.Context) error {
|
||||
info, err := os.Stat(s.baseDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storage directory not accessible: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return fmt.Errorf("storage path is not a directory: %s", s.baseDir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewLocalFileService creates a new local file service instance
|
||||
func NewLocalFileService(baseDir string) interfaces.FileService {
|
||||
return &localFileService{
|
||||
|
||||
@@ -22,11 +22,10 @@ type minioFileService struct {
|
||||
bucketName string
|
||||
}
|
||||
|
||||
// NewMinioFileService creates a MinIO file service
|
||||
func NewMinioFileService(endpoint,
|
||||
accessKeyID, secretAccessKey, bucketName string, useSSL bool,
|
||||
) (interfaces.FileService, error) {
|
||||
// Initialize MinIO client
|
||||
// newMinioClient creates a bare minioFileService with just the SDK client initialised.
|
||||
// Shared by NewMinioFileService (which also ensures the bucket exists) and
|
||||
// CheckMinioConnectivity (read-only probe).
|
||||
func newMinioClient(endpoint, accessKeyID, secretAccessKey, bucketName string, useSSL bool) (*minioFileService, error) {
|
||||
client, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: useSSL,
|
||||
@@ -34,24 +33,60 @@ func NewMinioFileService(endpoint,
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize MinIO client: %w", err)
|
||||
}
|
||||
return &minioFileService{client: client, bucketName: bucketName}, nil
|
||||
}
|
||||
|
||||
// Check if bucket exists, create if not
|
||||
exists, err := client.BucketExists(context.Background(), bucketName)
|
||||
// NewMinioFileService creates a MinIO file service.
|
||||
// It verifies that the bucket exists and creates it if missing.
|
||||
func NewMinioFileService(endpoint,
|
||||
accessKeyID, secretAccessKey, bucketName string, useSSL bool,
|
||||
) (interfaces.FileService, error) {
|
||||
svc, err := newMinioClient(endpoint, accessKeyID, secretAccessKey, bucketName, useSSL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exists, err := svc.client.BucketExists(context.Background(), bucketName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to check bucket: %w", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
err = client.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{})
|
||||
if err != nil {
|
||||
if err = svc.client.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{}); err != nil {
|
||||
return nil, fmt.Errorf("failed to create bucket: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &minioFileService{
|
||||
client: client,
|
||||
bucketName: bucketName,
|
||||
}, nil
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
// CheckConnectivity verifies MinIO is reachable and, if a bucket is configured,
|
||||
// that the bucket exists. This is a read-only probe — it never creates a bucket.
|
||||
func (s *minioFileService) CheckConnectivity(ctx context.Context) error {
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if s.bucketName != "" {
|
||||
exists, err := s.client.BucketExists(checkCtx, s.bucketName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return fmt.Errorf("bucket %q does not exist", s.bucketName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_, err := s.client.ListBuckets(checkCtx)
|
||||
return err
|
||||
}
|
||||
|
||||
// CheckMinioConnectivity tests MinIO connectivity using the provided credentials.
|
||||
// It creates a temporary service instance internally and delegates to CheckConnectivity.
|
||||
func CheckMinioConnectivity(ctx context.Context, endpoint, accessKeyID, secretAccessKey, bucketName string, useSSL bool) error {
|
||||
svc, err := newMinioClient(endpoint, accessKeyID, secretAccessKey, bucketName, useSSL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return svc.CheckConnectivity(ctx)
|
||||
}
|
||||
|
||||
// SaveFile saves a file to MinIO
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/models/vlm"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
const (
|
||||
vlmOCRPrompt = "请提取这张文档图片中的所有正文内容,用纯 Markdown 格式输出。要求:\n" +
|
||||
"1. 忽略页眉、页脚\n" +
|
||||
"2. 表格使用 Markdown 表格语法\n" +
|
||||
"3. 公式使用 LaTeX 格式(用 $ 或 $$ 包裹)\n" +
|
||||
"4. 按照原文阅读顺序组织\n" +
|
||||
"5. 只输出提取到的文本内容,不要添加任何 HTML 标签\n" +
|
||||
"如果图片中没有可识别的文字内容,请回复:无文字内容。"
|
||||
vlmCaptionPrompt = "简单凝炼的描述图片的主要内容"
|
||||
)
|
||||
|
||||
// ImageMultimodalService handles image:multimodal asynq tasks.
|
||||
// It reads images from local storage, performs OCR and VLM caption,
|
||||
// and creates child chunks for the processed content.
|
||||
type ImageMultimodalService struct {
|
||||
chunkService interfaces.ChunkService
|
||||
modelService interfaces.ModelService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
tenantRepo interfaces.TenantRepository
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
ollamaService *ollama.OllamaService
|
||||
}
|
||||
|
||||
func NewImageMultimodalService(
|
||||
chunkService interfaces.ChunkService,
|
||||
modelService interfaces.ModelService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
ollamaService *ollama.OllamaService,
|
||||
) interfaces.TaskHandler {
|
||||
return &ImageMultimodalService{
|
||||
chunkService: chunkService,
|
||||
modelService: modelService,
|
||||
kbService: kbService,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
tenantRepo: tenantRepo,
|
||||
retrieveEngine: retrieveEngine,
|
||||
ollamaService: ollamaService,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle implements asynq handler for TypeImageMultimodal.
|
||||
func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) error {
|
||||
var payload types.ImageMultimodalPayload
|
||||
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
|
||||
return fmt.Errorf("unmarshal image multimodal payload: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[ImageMultimodal] Processing image: chunk=%s, url=%s, local_path=%s, ocr=%v, caption=%v",
|
||||
payload.ChunkID, payload.ImageURL, payload.ImageLocalPath, payload.EnableOCR, payload.EnableCaption)
|
||||
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
||||
|
||||
vlmModel, err := s.resolveVLM(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve VLM: %w", err)
|
||||
}
|
||||
|
||||
imgBytes, err := os.ReadFile(payload.ImageLocalPath)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Local file %s not available (%v), trying to download from URL", payload.ImageLocalPath, err)
|
||||
imgBytes, err = downloadImageFromURL(payload.ImageURL)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[ImageMultimodal] Failed to download image from URL %s: %v", payload.ImageURL, err)
|
||||
return fmt.Errorf("read image: local file %s not found and URL download failed: %w", payload.ImageLocalPath, err)
|
||||
}
|
||||
logger.Infof(ctx, "[ImageMultimodal] Image downloaded from URL, len=%d", len(imgBytes))
|
||||
} else {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Image bytes read from %s, len=%d", payload.ImageLocalPath, len(imgBytes))
|
||||
defer os.Remove(payload.ImageLocalPath)
|
||||
}
|
||||
|
||||
imageInfo := types.ImageInfo{
|
||||
URL: payload.ImageURL,
|
||||
OriginalURL: payload.ImageURL,
|
||||
}
|
||||
|
||||
if payload.EnableOCR {
|
||||
ocrText, ocrErr := vlmModel.Predict(ctx, imgBytes, vlmOCRPrompt)
|
||||
if ocrErr != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] OCR failed for %s: %v", payload.ImageURL, ocrErr)
|
||||
} else {
|
||||
ocrText = sanitizeOCRText(ocrText)
|
||||
if ocrText != "" {
|
||||
imageInfo.OCRText = ocrText
|
||||
} else {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] OCR returned empty/invalid content for %s, discarded", payload.ImageURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if payload.EnableCaption {
|
||||
caption, capErr := vlmModel.Predict(ctx, imgBytes, vlmCaptionPrompt)
|
||||
if capErr != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Caption failed for %s: %v", payload.ImageURL, capErr)
|
||||
} else if caption != "" {
|
||||
imageInfo.Caption = caption
|
||||
}
|
||||
}
|
||||
|
||||
// Build child chunks for OCR and caption results
|
||||
imageInfoJSON, _ := json.Marshal([]types.ImageInfo{imageInfo})
|
||||
var newChunks []*types.Chunk
|
||||
|
||||
if imageInfo.OCRText != "" {
|
||||
newChunks = append(newChunks, &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: payload.TenantID,
|
||||
KnowledgeID: payload.KnowledgeID,
|
||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||
Content: imageInfo.OCRText,
|
||||
ChunkType: types.ChunkTypeImageOCR,
|
||||
ParentChunkID: payload.ChunkID,
|
||||
IsEnabled: true,
|
||||
Flags: types.ChunkFlagRecommended,
|
||||
ImageInfo: string(imageInfoJSON),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
if imageInfo.Caption != "" {
|
||||
newChunks = append(newChunks, &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: payload.TenantID,
|
||||
KnowledgeID: payload.KnowledgeID,
|
||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||
Content: imageInfo.Caption,
|
||||
ChunkType: types.ChunkTypeImageCaption,
|
||||
ParentChunkID: payload.ChunkID,
|
||||
IsEnabled: true,
|
||||
Flags: types.ChunkFlagRecommended,
|
||||
ImageInfo: string(imageInfoJSON),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
if len(newChunks) == 0 {
|
||||
// Even if OCR/caption both failed, mark knowledge as completed
|
||||
s.finalizeImageKnowledge(ctx, payload, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Persist chunks
|
||||
if err := s.chunkService.CreateChunks(ctx, newChunks); err != nil {
|
||||
return fmt.Errorf("create multimodal chunks: %w", err)
|
||||
}
|
||||
for _, c := range newChunks {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Created %s chunk %s for image %s, len=%d",
|
||||
c.ChunkType, c.ID, payload.ImageURL, len(c.Content))
|
||||
}
|
||||
|
||||
// Index chunks so they can be retrieved
|
||||
s.indexChunks(ctx, payload, newChunks)
|
||||
|
||||
// Update the parent text chunk's ImageInfo (mirrors old docreader behaviour)
|
||||
s.updateParentChunkImageInfo(ctx, payload, imageInfo)
|
||||
|
||||
// For standalone image files, use caption as the knowledge description
|
||||
// and mark the knowledge as completed (it was kept in "processing" until now).
|
||||
s.finalizeImageKnowledge(ctx, payload, imageInfo.Caption)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// finalizeImageKnowledge updates the knowledge after multimodal processing:
|
||||
// - For standalone image files: sets Description from caption and marks ParseStatus as completed
|
||||
// (processChunks kept it in "processing" to wait for multimodal results).
|
||||
// - For images extracted from PDFs: no-op (description comes from summary generation).
|
||||
func (s *ImageMultimodalService) finalizeImageKnowledge(ctx context.Context, payload types.ImageMultimodalPayload, caption string) {
|
||||
knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to get knowledge %s: %v", payload.KnowledgeID, err)
|
||||
return
|
||||
}
|
||||
if knowledge == nil {
|
||||
return
|
||||
}
|
||||
if !IsImageType(knowledge.FileType) {
|
||||
return
|
||||
}
|
||||
|
||||
if caption != "" {
|
||||
knowledge.Description = caption
|
||||
}
|
||||
knowledge.ParseStatus = types.ParseStatusCompleted
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
if err := s.knowledgeRepo.UpdateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to finalize knowledge: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Finalized image knowledge %s (status=completed, description=%d chars)",
|
||||
payload.KnowledgeID, len(knowledge.Description))
|
||||
}
|
||||
}
|
||||
|
||||
// indexChunks indexes the newly created multimodal chunks into the retrieval engine
|
||||
// so they can participate in semantic search.
|
||||
func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.ImageMultimodalPayload, chunks []*types.Chunk) {
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
||||
if err != nil || kb == nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to get KB for indexing: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to get embedding model for indexing: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to get tenant for indexing: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
engine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to init retrieve engine: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
indexInfoList := make([]*types.IndexInfo, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: chunk.Content,
|
||||
SourceID: chunk.ID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
})
|
||||
}
|
||||
|
||||
if err := engine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
|
||||
logger.Errorf(ctx, "[ImageMultimodal] Failed to index multimodal chunks: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Mark chunks as indexed.
|
||||
// Must re-fetch from DB because the in-memory objects lack auto-generated fields
|
||||
// (e.g. seq_id), and GORM Save would overwrite them with zero values.
|
||||
for _, chunk := range chunks {
|
||||
dbChunk, err := s.chunkService.GetChunkByIDOnly(ctx, chunk.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to fetch chunk %s for status update: %v", chunk.ID, err)
|
||||
continue
|
||||
}
|
||||
dbChunk.Status = int(types.ChunkStatusIndexed)
|
||||
if err := s.chunkService.UpdateChunk(ctx, dbChunk); err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to update chunk %s status to indexed: %v", chunk.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[ImageMultimodal] Indexed %d multimodal chunks for image %s", len(chunks), payload.ImageURL)
|
||||
}
|
||||
|
||||
// updateParentChunkImageInfo updates the parent text chunk's ImageInfo field,
|
||||
// replicating the behaviour of the old docreader flow where the parent chunk
|
||||
// carried the full image metadata (URL, OCR, caption).
|
||||
func (s *ImageMultimodalService) updateParentChunkImageInfo(ctx context.Context, payload types.ImageMultimodalPayload, imageInfo types.ImageInfo) {
|
||||
if payload.ChunkID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
chunk, err := s.chunkService.GetChunkByIDOnly(ctx, payload.ChunkID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to get parent chunk %s: %v", payload.ChunkID, err)
|
||||
return
|
||||
}
|
||||
|
||||
var existingInfos []types.ImageInfo
|
||||
if chunk.ImageInfo != "" {
|
||||
_ = json.Unmarshal([]byte(chunk.ImageInfo), &existingInfos)
|
||||
}
|
||||
|
||||
found := false
|
||||
for i, info := range existingInfos {
|
||||
if info.URL == imageInfo.URL {
|
||||
existingInfos[i] = imageInfo
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
existingInfos = append(existingInfos, imageInfo)
|
||||
}
|
||||
|
||||
imageInfoJSON, _ := json.Marshal(existingInfos)
|
||||
chunk.ImageInfo = string(imageInfoJSON)
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] Failed to update parent chunk %s ImageInfo: %v", chunk.ID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[ImageMultimodal] Updated parent chunk %s ImageInfo for image %s", chunk.ID, payload.ImageURL)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveVLM creates a vlm.VLM instance for the given knowledge base,
|
||||
// supporting both new-style (ModelID) and legacy (inline BaseURL) configs.
|
||||
func (s *ImageMultimodalService) resolveVLM(ctx context.Context, kbID string) (vlm.VLM, error) {
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get knowledge base %s: %w", kbID, err)
|
||||
}
|
||||
if kb == nil {
|
||||
return nil, fmt.Errorf("knowledge base %s not found", kbID)
|
||||
}
|
||||
|
||||
vlmCfg := kb.VLMConfig
|
||||
if !vlmCfg.IsEnabled() {
|
||||
return nil, fmt.Errorf("VLM is not enabled for knowledge base %s", kbID)
|
||||
}
|
||||
|
||||
// New-style: resolve model through ModelService
|
||||
if vlmCfg.ModelID != "" {
|
||||
return s.modelService.GetVLMModel(ctx, vlmCfg.ModelID)
|
||||
}
|
||||
|
||||
// Legacy: create VLM from inline config
|
||||
return vlm.NewVLMFromLegacyConfig(vlmCfg, s.ollamaService)
|
||||
}
|
||||
|
||||
// downloadImageFromURL downloads image bytes from an HTTP(S) URL.
|
||||
func downloadImageFromURL(imageURL string) ([]byte, error) {
|
||||
if !strings.HasPrefix(imageURL, "http://") && !strings.HasPrefix(imageURL, "https://") {
|
||||
return nil, fmt.Errorf("unsupported URL scheme: %s", imageURL)
|
||||
}
|
||||
client := &http.Client{Timeout: 60 * time.Second}
|
||||
resp, err := client.Get(imageURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("HTTP GET: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP %d for %s", resp.StatusCode, imageURL)
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,7 @@ type knowledgeBaseService struct {
|
||||
tenantRepo interfaces.TenantRepository
|
||||
fileSvc interfaces.FileService
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
asynqClient *asynq.Client
|
||||
asynqClient interfaces.TaskEnqueuer
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseService creates a new knowledge base service
|
||||
@@ -46,7 +46,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
fileSvc interfaces.FileService,
|
||||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
asynqClient *asynq.Client,
|
||||
asynqClient interfaces.TaskEnqueuer,
|
||||
) interfaces.KnowledgeBaseService {
|
||||
return &knowledgeBaseService{
|
||||
repo: repo,
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/models/vlm"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
@@ -405,5 +406,56 @@ func (s *modelService) GetChatModel(ctx context.Context, modelId string) (chat.C
|
||||
return chatModel, nil
|
||||
}
|
||||
|
||||
// GetVLMModel retrieves and initializes a vision language model instance.
|
||||
func (s *modelService) GetVLMModel(ctx context.Context, modelId string) (vlm.VLM, error) {
|
||||
if modelId == "" {
|
||||
return nil, errors.New("model ID cannot be empty")
|
||||
}
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
model, err := s.repo.GetByID(ctx, tenantID, modelId)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": modelId,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if model == nil {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting VLM model: %s, source: %s", model.Name, model.Source)
|
||||
|
||||
ifType := model.Parameters.InterfaceType
|
||||
if ifType == "" {
|
||||
if model.Source == types.ModelSourceLocal {
|
||||
ifType = "ollama"
|
||||
} else {
|
||||
ifType = "openai"
|
||||
}
|
||||
}
|
||||
|
||||
vlmModel, err := vlm.NewVLM(&vlm.Config{
|
||||
ModelID: model.ID,
|
||||
APIKey: model.Parameters.APIKey,
|
||||
BaseURL: model.Parameters.BaseURL,
|
||||
ModelName: model.Name,
|
||||
Source: model.Source,
|
||||
InterfaceType: ifType,
|
||||
}, s.ollamaService)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": model.ID,
|
||||
"model_name": model.Name,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return vlmModel, nil
|
||||
}
|
||||
|
||||
// Note: default model selection logic has been removed; models no longer
|
||||
// maintain a per-type default flag at the service layer.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
htmltomd "github.com/JohannesKaufmann/html-to-markdown/v2"
|
||||
)
|
||||
|
||||
var (
|
||||
htmlTagPattern = regexp.MustCompile(`<[^>]+>`)
|
||||
codeBlockPattern = regexp.MustCompile("(?s)^\\s*```[a-zA-Z]*\\s*\n(.*?)\n\\s*```\\s*$")
|
||||
htmlDocPattern = regexp.MustCompile(`(?i)^\s*(<\!DOCTYPE|<html|<body|<div|<p[\s>]|<table|<h[1-6][\s>])`)
|
||||
multipleNewlines = regexp.MustCompile(`\n{3,}`)
|
||||
knownEmptyReplies = []string{
|
||||
"无文字内容",
|
||||
"无法识别",
|
||||
"no text",
|
||||
"no content",
|
||||
"empty",
|
||||
"图片中没有文字",
|
||||
"图片中没有可识别的文字",
|
||||
}
|
||||
)
|
||||
|
||||
// sanitizeOCRText cleans up VLM OCR output by stripping HTML wrappers,
|
||||
// converting HTML to markdown, and filtering out useless responses.
|
||||
func sanitizeOCRText(raw string) string {
|
||||
text := strings.TrimSpace(raw)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
text = stripMarkdownCodeBlock(text)
|
||||
|
||||
// If stripping HTML tags leaves almost no text, the response is useless
|
||||
// (e.g. "<html><body><div class="image"><img/></div></body></html>").
|
||||
plainText := strings.TrimSpace(htmlTagPattern.ReplaceAllString(text, ""))
|
||||
if len(plainText) < 10 && htmlTagPattern.MatchString(text) {
|
||||
return ""
|
||||
}
|
||||
|
||||
if looksLikeHTML(text) {
|
||||
text = ocrHTMLToMarkdown(text)
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
if isKnownEmptyReply(text) {
|
||||
return ""
|
||||
}
|
||||
|
||||
text = multipleNewlines.ReplaceAllString(text, "\n\n")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// stripMarkdownCodeBlock removes a markdown code-fence wrapper that some
|
||||
// models add around their output (e.g. ```html\n...\n``` or ```markdown\n...\n```).
|
||||
func stripMarkdownCodeBlock(text string) string {
|
||||
if m := codeBlockPattern.FindStringSubmatch(text); len(m) == 2 {
|
||||
return strings.TrimSpace(m[1])
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// looksLikeHTML returns true when the text appears to be an HTML document
|
||||
// or contains a significant amount of HTML tags.
|
||||
func looksLikeHTML(text string) bool {
|
||||
if htmlDocPattern.MatchString(text) {
|
||||
return true
|
||||
}
|
||||
tags := htmlTagPattern.FindAllString(text, -1)
|
||||
if len(tags) == 0 {
|
||||
return false
|
||||
}
|
||||
tagChars := 0
|
||||
for _, t := range tags {
|
||||
tagChars += len(t)
|
||||
}
|
||||
return float64(tagChars)/float64(len(text)) > 0.3
|
||||
}
|
||||
|
||||
// ocrHTMLToMarkdown converts HTML content to markdown, falling back to the
|
||||
// original text on failure.
|
||||
func ocrHTMLToMarkdown(content string) string {
|
||||
md, err := htmltomd.ConvertString(content)
|
||||
if err != nil {
|
||||
return content
|
||||
}
|
||||
return md
|
||||
}
|
||||
|
||||
// isKnownEmptyReply checks whether the text matches a known "no content"
|
||||
// reply pattern that VLM models produce when the image has no text.
|
||||
func isKnownEmptyReply(text string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(text))
|
||||
for _, phrase := range knownEmptyReplies {
|
||||
if lower == strings.ToLower(phrase) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package service
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSanitizeOCRText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "empty string",
|
||||
input: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "whitespace only",
|
||||
input: " \n\t ",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "pure HTML skeleton with no text",
|
||||
input: `<html><body><div class="image"><img/></div></body></html>`,
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "HTML with only whitespace text",
|
||||
input: "<html><body> \n </body></html>",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "valid markdown passes through",
|
||||
input: "# 标题\n\n这是一段正文,包含一些内容。\n\n| 列1 | 列2 |\n| --- | --- |\n| 数据1 | 数据2 |",
|
||||
want: "# 标题\n\n这是一段正文,包含一些内容。\n\n| 列1 | 列2 |\n| --- | --- |\n| 数据1 | 数据2 |",
|
||||
},
|
||||
{
|
||||
name: "code block wrapper stripped",
|
||||
input: "```markdown\n# 文档标题\n\n正文内容在这里。\n```",
|
||||
want: "# 文档标题\n\n正文内容在这里。",
|
||||
},
|
||||
{
|
||||
name: "html code block wrapper stripped",
|
||||
input: "```html\n<p>这是一段内容</p>\n```",
|
||||
want: "这是一段内容",
|
||||
},
|
||||
{
|
||||
name: "HTML document converted to markdown",
|
||||
input: "<html><body><h1>标题</h1><p>这是一段很长的正文内容,用来测试 HTML 到 Markdown 的转换。</p></body></html>",
|
||||
want: "# 标题\n\n这是一段很长的正文内容,用来测试 HTML 到 Markdown 的转换。",
|
||||
},
|
||||
{
|
||||
name: "known empty reply - Chinese",
|
||||
input: "无文字内容",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "known empty reply - no text",
|
||||
input: "No text",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "known empty reply - 图片中没有文字",
|
||||
input: "图片中没有文字",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "plain text with minimal HTML not converted",
|
||||
input: "这是一段正常文本,价格 <100 元。",
|
||||
want: "这是一段正常文本,价格 <100 元。",
|
||||
},
|
||||
{
|
||||
name: "multiple blank lines collapsed",
|
||||
input: "段落一\n\n\n\n\n段落二",
|
||||
want: "段落一\n\n段落二",
|
||||
},
|
||||
{
|
||||
name: "HTML with substantial text content is converted",
|
||||
input: "<div><h2>报告摘要</h2><p>本季度营收同比增长 15%,净利润达到 2.3 亿元。</p><table><tr><th>指标</th><th>数值</th></tr><tr><td>营收</td><td>10亿</td></tr></table></div>",
|
||||
want: "", // placeholder; will be checked for non-empty
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := sanitizeOCRText(tt.input)
|
||||
|
||||
if tt.name == "HTML with substantial text content is converted" {
|
||||
if got == "" {
|
||||
t.Errorf("sanitizeOCRText() returned empty for substantial HTML content")
|
||||
}
|
||||
if got == tt.input {
|
||||
t.Errorf("sanitizeOCRText() did not convert HTML, got original")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if got != tt.want {
|
||||
t.Errorf("sanitizeOCRText() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownCodeBlock(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "no code block",
|
||||
input: "just normal text",
|
||||
want: "just normal text",
|
||||
},
|
||||
{
|
||||
name: "markdown code block",
|
||||
input: "```markdown\n# Title\nContent here\n```",
|
||||
want: "# Title\nContent here",
|
||||
},
|
||||
{
|
||||
name: "html code block",
|
||||
input: "```html\n<p>hello</p>\n```",
|
||||
want: "<p>hello</p>",
|
||||
},
|
||||
{
|
||||
name: "plain code block",
|
||||
input: "```\nsome text\n```",
|
||||
want: "some text",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := stripMarkdownCodeBlock(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("stripMarkdownCodeBlock() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLooksLikeHTML(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "HTML document",
|
||||
input: "<html><body><p>text</p></body></html>",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "DOCTYPE",
|
||||
input: "<!DOCTYPE html><html><body></body></html>",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "body tag",
|
||||
input: "<body><p>content</p></body>",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "plain markdown",
|
||||
input: "# Title\n\nSome paragraph text",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "text with minor HTML",
|
||||
input: "This is mostly text with a <b>bold</b> word.",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "heavy HTML tags",
|
||||
input: "<div><p><span>x</span></p></div><div><p><span>y</span></p></div>",
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := looksLikeHTML(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("looksLikeHTML() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsKnownEmptyReply(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{"无文字内容", true},
|
||||
{"无法识别", true},
|
||||
{"no text", true},
|
||||
{"No Text", true},
|
||||
{"NO CONTENT", true},
|
||||
{"empty", true},
|
||||
{"这是正常内容", false},
|
||||
{"", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
got := isKnownEmptyReply(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("isKnownEmptyReply(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ type knowledgeTagService struct {
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
modelService interfaces.ModelService
|
||||
task *asynq.Client
|
||||
task interfaces.TaskEnqueuer
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ func NewKnowledgeTagService(
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
modelService interfaces.ModelService,
|
||||
task *asynq.Client,
|
||||
task interfaces.TaskEnqueuer,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) (interfaces.KnowledgeTagService, error) {
|
||||
return &knowledgeTagService{
|
||||
|
||||
@@ -29,8 +29,12 @@ type Config struct {
|
||||
PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"`
|
||||
}
|
||||
|
||||
// DocReaderConfig configures the document parser client (gRPC or HTTP).
|
||||
type DocReaderConfig struct {
|
||||
// Addr: for gRPC it is the server address (e.g. "localhost:50051"); for HTTP it is the base URL (e.g. "http://localhost:8080").
|
||||
Addr string `yaml:"addr" json:"addr"`
|
||||
// Transport: "grpc" (default) or "http"
|
||||
Transport string `yaml:"transport" json:"transport"`
|
||||
}
|
||||
|
||||
type VectorDatabaseConfig struct {
|
||||
|
||||
+122
-29
@@ -9,11 +9,13 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
|
||||
_ "github.com/duckdb/duckdb-go/v2"
|
||||
esv7 "github.com/elastic/go-elasticsearch/v7"
|
||||
"github.com/elastic/go-elasticsearch/v8"
|
||||
@@ -25,9 +27,9 @@ import (
|
||||
"go.uber.org/dig"
|
||||
"google.golang.org/grpc"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/Tencent/WeKnora/docreader/client"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
|
||||
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
|
||||
@@ -36,6 +38,7 @@ import (
|
||||
neo4jRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/neo4j"
|
||||
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
@@ -48,6 +51,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/handler"
|
||||
"github.com/Tencent/WeKnora/internal/handler/session"
|
||||
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
@@ -94,6 +98,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
// External service clients
|
||||
logger.Debugf(ctx, "[Container] Registering external service clients...")
|
||||
must(container.Provide(initDocReaderClient))
|
||||
must(container.Provide(initImageResolver))
|
||||
must(container.Provide(initOllamaService))
|
||||
must(container.Provide(initNeo4jClient))
|
||||
must(container.Provide(stream.NewStreamManager))
|
||||
@@ -146,6 +151,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
// Extract services - register individual extracters with names
|
||||
must(container.Provide(service.NewChunkExtractService, dig.Name("chunkExtractor")))
|
||||
must(container.Provide(service.NewDataTableSummaryService, dig.Name("dataTableSummary")))
|
||||
must(container.Provide(service.NewImageMultimodalService, dig.Name("imageMultimodal")))
|
||||
|
||||
must(container.Provide(service.NewMessageService))
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
@@ -169,9 +175,16 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
logger.Debugf(ctx, "[Container] Registering session service...")
|
||||
must(container.Provide(service.NewSessionService))
|
||||
|
||||
logger.Debugf(ctx, "[Container] Registering asynq client and server...")
|
||||
must(container.Provide(router.NewAsyncqClient))
|
||||
must(container.Provide(router.NewAsynqServer))
|
||||
logger.Debugf(ctx, "[Container] Registering task enqueuer...")
|
||||
redisAvailable := os.Getenv("REDIS_ADDR") != ""
|
||||
if redisAvailable {
|
||||
must(container.Provide(router.NewAsyncqClient, dig.As(new(interfaces.TaskEnqueuer))))
|
||||
must(container.Provide(router.NewAsynqServer))
|
||||
} else {
|
||||
syncExec := router.NewSyncTaskExecutor()
|
||||
must(container.Provide(func() interfaces.TaskEnqueuer { return syncExec }))
|
||||
must(container.Provide(func() *router.SyncTaskExecutor { return syncExec }))
|
||||
}
|
||||
|
||||
// Chat pipeline components for processing chat requests
|
||||
logger.Debugf(ctx, "[Container] Registering chat pipeline plugins...")
|
||||
@@ -218,9 +231,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
logger.Debugf(ctx, "[Container] HTTP handlers registered")
|
||||
|
||||
// Router configuration
|
||||
logger.Debugf(ctx, "[Container] Registering router and starting asynq server...")
|
||||
logger.Debugf(ctx, "[Container] Registering router and starting task server...")
|
||||
must(container.Provide(router.NewRouter))
|
||||
must(container.Invoke(router.RunAsynqServer))
|
||||
if redisAvailable {
|
||||
must(container.Invoke(router.RunAsynqServer))
|
||||
} else {
|
||||
must(container.Invoke(router.RegisterSyncHandlers))
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Container] Container initialization completed successfully")
|
||||
return container
|
||||
@@ -249,19 +266,23 @@ func initTracer() (*tracing.Tracer, error) {
|
||||
}
|
||||
|
||||
func initRedisClient() (*redis.Client, error) {
|
||||
redisAddr := os.Getenv("REDIS_ADDR")
|
||||
if redisAddr == "" {
|
||||
logger.Infof(context.Background(), "[Redis] No REDIS_ADDR configured, Redis disabled (Lite mode)")
|
||||
return nil, nil
|
||||
}
|
||||
db, err := strconv.Atoi(os.Getenv("REDIS_DB"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
db = 0
|
||||
}
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: os.Getenv("REDIS_ADDR"),
|
||||
Addr: redisAddr,
|
||||
Username: os.Getenv("REDIS_USERNAME"),
|
||||
Password: os.Getenv("REDIS_PASSWORD"),
|
||||
DB: db,
|
||||
})
|
||||
|
||||
// 验证连接
|
||||
_, err = client.Ping(context.Background()).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接Redis失败: %w", err)
|
||||
@@ -271,6 +292,10 @@ func initRedisClient() (*redis.Client, error) {
|
||||
}
|
||||
|
||||
func initContextStorage(redisClient *redis.Client) (llmcontext.ContextStorage, error) {
|
||||
if redisClient == nil {
|
||||
logger.Infof(context.Background(), "[ContextStorage] Redis not available, using in-memory storage")
|
||||
return llmcontext.NewMemoryStorage(), nil
|
||||
}
|
||||
storage, err := llmcontext.NewRedisStorage(redisClient, 24*time.Hour, "context:")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -334,6 +359,21 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
os.Getenv("DB_PORT"),
|
||||
os.Getenv("DB_NAME"),
|
||||
)
|
||||
case "sqlite":
|
||||
dbPath := os.Getenv("DB_PATH")
|
||||
if dbPath == "" {
|
||||
dbPath = "./data/weknora.db"
|
||||
}
|
||||
if dir := filepath.Dir(dbPath); dir != "." && dir != "" {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create SQLite data directory %s: %w", dir, err)
|
||||
}
|
||||
}
|
||||
sqlite_vec.Auto()
|
||||
dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=5000&_foreign_keys=on"
|
||||
dialector = sqlite.Open(dsn)
|
||||
migrateDSN = "sqlite3://" + dbPath
|
||||
logger.Infof(context.Background(), "DB Config: driver=sqlite path=%s", dbPath)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported database driver: %s", os.Getenv("DB_DRIVER"))
|
||||
}
|
||||
@@ -342,6 +382,16 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if os.Getenv("DB_DRIVER") == "sqlite" {
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err)
|
||||
}
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
return nil, fmt.Errorf("failed to ping SQLite database: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Run database migrations automatically (optional, can be disabled via env var)
|
||||
// To disable auto-migration, set AUTO_MIGRATE=false
|
||||
// To enable auto-recovery from dirty state, set AUTO_RECOVER_DIRTY=true
|
||||
@@ -374,7 +424,14 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
}
|
||||
|
||||
// Configure connection pool parameters
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
if os.Getenv("DB_DRIVER") == "sqlite" {
|
||||
// SQLite only supports one concurrent writer even in WAL mode.
|
||||
// Limiting to a single open connection serialises all DB access and
|
||||
// prevents "database is locked" errors from concurrent goroutines.
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
} else {
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
}
|
||||
sqlDB.SetConnMaxLifetime(time.Duration(10) * time.Minute)
|
||||
|
||||
return db, nil
|
||||
@@ -390,7 +447,11 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
// - Configured file service implementation
|
||||
// - Error if initialization fails
|
||||
func initFileService(cfg *config.Config) (interfaces.FileService, error) {
|
||||
switch os.Getenv("STORAGE_TYPE") {
|
||||
storageType := strings.TrimSpace(os.Getenv("STORAGE_TYPE"))
|
||||
if storageType == "" {
|
||||
storageType = "local"
|
||||
}
|
||||
switch storageType {
|
||||
case "minio":
|
||||
if os.Getenv("MINIO_ENDPOINT") == "" ||
|
||||
os.Getenv("MINIO_ACCESS_KEY_ID") == "" ||
|
||||
@@ -419,8 +480,8 @@ func initFileService(cfg *config.Config) (interfaces.FileService, error) {
|
||||
os.Getenv("COS_SECRET_ID"),
|
||||
os.Getenv("COS_SECRET_KEY"),
|
||||
os.Getenv("COS_PATH_PREFIX"),
|
||||
os.Getenv("COS_TEMP_BUCKET_NAME"), // 可选:临时桶名称(桶需配置生命周期规则自动过期)
|
||||
os.Getenv("COS_TEMP_REGION"), // 可选:临时桶 region,默认与主桶相同
|
||||
os.Getenv("COS_TEMP_BUCKET_NAME"),
|
||||
os.Getenv("COS_TEMP_REGION"),
|
||||
)
|
||||
case "tos":
|
||||
if os.Getenv("TOS_ENDPOINT") == "" ||
|
||||
@@ -441,11 +502,15 @@ func initFileService(cfg *config.Config) (interfaces.FileService, error) {
|
||||
os.Getenv("TOS_TEMP_REGION"), // 可选:临时桶 region,默认与主桶相同
|
||||
)
|
||||
case "local":
|
||||
return file.NewLocalFileService(os.Getenv("LOCAL_STORAGE_BASE_DIR")), nil
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
baseDir = "/data/files"
|
||||
}
|
||||
return file.NewLocalFileService(baseDir), nil
|
||||
case "dummy":
|
||||
return file.NewDummyFileService(), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported storage type: %s", os.Getenv("STORAGE_TYPE"))
|
||||
return nil, fmt.Errorf("unsupported storage type: %s", storageType)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,6 +539,16 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
|
||||
log.Infof("Register postgres retrieve engine success")
|
||||
}
|
||||
}
|
||||
if slices.Contains(retrieveDriver, "sqlite") {
|
||||
sqliteRepo := sqliteRetrieverRepo.NewSQLiteRetrieveEngineRepository(db)
|
||||
if err := registry.Register(
|
||||
retriever.NewKVHybridRetrieveEngine(sqliteRepo, types.SQLiteRetrieverEngineType),
|
||||
); err != nil {
|
||||
log.Errorf("Register sqlite retrieve engine failed: %v", err)
|
||||
} else {
|
||||
log.Infof("Register sqlite retrieve engine success")
|
||||
}
|
||||
}
|
||||
if slices.Contains(retrieveDriver, "elasticsearch_v8") {
|
||||
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
|
||||
Addresses: []string{os.Getenv("ELASTICSEARCH_ADDR")},
|
||||
@@ -639,21 +714,39 @@ func registerPoolCleanup(pool *ants.Pool, cleaner interfaces.ResourceCleaner) {
|
||||
})
|
||||
}
|
||||
|
||||
// initDocReaderClient initializes the document reader client
|
||||
// Creates a client for interacting with the document reader service
|
||||
// Parameters:
|
||||
// - cfg: Application configuration
|
||||
//
|
||||
// Returns:
|
||||
// - Configured document reader client
|
||||
// - Error if initialization fails
|
||||
func initDocReaderClient(cfg *config.Config) (*client.Client, error) {
|
||||
// Use the DocReader URL from environment or config
|
||||
docReaderURL := os.Getenv("DOCREADER_ADDR")
|
||||
if docReaderURL == "" && cfg.DocReader != nil {
|
||||
docReaderURL = cfg.DocReader.Addr
|
||||
// initDocReaderClient initializes the DocumentReader client (lightweight API).
|
||||
func initDocReaderClient(cfg *config.Config) (interfaces.DocumentReader, error) {
|
||||
addr := strings.TrimSpace(os.Getenv("DOCREADER_ADDR"))
|
||||
transport := strings.TrimSpace(os.Getenv("DOCREADER_TRANSPORT"))
|
||||
if transport == "" {
|
||||
transport = "grpc"
|
||||
}
|
||||
return client.NewClient(docReaderURL)
|
||||
if addr == "" {
|
||||
logger.Infof(context.Background(), "[DocConverter] No DOCREADER_ADDR configured, starting disconnected")
|
||||
}
|
||||
transport = strings.ToLower(transport)
|
||||
switch transport {
|
||||
case "http", "https":
|
||||
if addr != "" && !strings.HasPrefix(addr, "http://") && !strings.HasPrefix(addr, "https://") {
|
||||
addr = "http://" + addr
|
||||
}
|
||||
return docparser.NewHTTPDocumentReader(addr)
|
||||
default:
|
||||
return docparser.NewGRPCDocumentReader(addr)
|
||||
}
|
||||
}
|
||||
|
||||
// initImageResolver creates the ImageResolver for storing images from DocReader.
|
||||
func initImageResolver(cfg *config.Config) *docparser.ImageResolver {
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
baseDir = "/data/files"
|
||||
}
|
||||
urlPrefix := os.Getenv("LOCAL_STORAGE_URL_PREFIX")
|
||||
if urlPrefix == "" {
|
||||
urlPrefix = "/files"
|
||||
}
|
||||
return docparser.NewImageResolver(baseDir, urlPrefix)
|
||||
}
|
||||
|
||||
// initOllamaService initializes the Ollama service client
|
||||
|
||||
@@ -4,10 +4,12 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
)
|
||||
|
||||
@@ -30,8 +32,10 @@ func RunMigrationsWithOptions(dsn string, opts MigrationOptions) error {
|
||||
|
||||
logger.Infof(ctx, "Starting database migration...")
|
||||
|
||||
// Use versioned migrations directory
|
||||
migrationsPath := "file://migrations/versioned"
|
||||
if strings.HasPrefix(dsn, "sqlite3://") {
|
||||
migrationsPath = "file://migrations/sqlite"
|
||||
}
|
||||
|
||||
m, err := migrate.New(migrationsPath, dsn)
|
||||
if err != nil {
|
||||
|
||||
@@ -13,8 +13,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/docreader/client"
|
||||
"github.com/Tencent/WeKnora/docreader/proto"
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
@@ -57,7 +55,7 @@ type InitializationHandler struct {
|
||||
kbRepository interfaces.KnowledgeBaseRepository
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
ollamaService *ollama.OllamaService
|
||||
docReaderClient *client.Client
|
||||
documentReader interfaces.DocumentReader
|
||||
pooler embedding.EmbedderPooler
|
||||
}
|
||||
|
||||
@@ -70,7 +68,7 @@ func NewInitializationHandler(
|
||||
kbRepository interfaces.KnowledgeBaseRepository,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
ollamaService *ollama.OllamaService,
|
||||
docReaderClient *client.Client,
|
||||
documentReader interfaces.DocumentReader,
|
||||
pooler embedding.EmbedderPooler,
|
||||
) *InitializationHandler {
|
||||
return &InitializationHandler{
|
||||
@@ -81,7 +79,7 @@ func NewInitializationHandler(
|
||||
kbRepository: kbRepository,
|
||||
knowledgeService: knowledgeService,
|
||||
ollamaService: ollamaService,
|
||||
docReaderClient: docReaderClient,
|
||||
documentReader: documentReader,
|
||||
pooler: pooler,
|
||||
}
|
||||
}
|
||||
@@ -94,30 +92,20 @@ type KBModelConfigRequest struct {
|
||||
|
||||
// 文档分块配置
|
||||
DocumentSplitting struct {
|
||||
ChunkSize int `json:"chunkSize"`
|
||||
ChunkOverlap int `json:"chunkOverlap"`
|
||||
Separators []string `json:"separators"`
|
||||
ChunkSize int `json:"chunkSize"`
|
||||
ChunkOverlap int `json:"chunkOverlap"`
|
||||
Separators []string `json:"separators"`
|
||||
ParserEngineRules []types.ParserEngineRule `json:"parserEngineRules,omitempty"`
|
||||
} `json:"documentSplitting"`
|
||||
|
||||
// 多模态配置
|
||||
// 多模态配置(仅模型相关;存储引擎在 storageProvider 中配置)
|
||||
Multimodal struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
StorageType string `json:"storageType"` // "cos" or "minio"
|
||||
COS *struct {
|
||||
SecretID string `json:"secretId"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
Region string `json:"region"`
|
||||
BucketName string `json:"bucketName"`
|
||||
AppID string `json:"appId"`
|
||||
PathPrefix string `json:"pathPrefix"`
|
||||
} `json:"cos"`
|
||||
Minio *struct {
|
||||
BucketName string `json:"bucketName"`
|
||||
UseSSL bool `json:"useSSL"`
|
||||
PathPrefix string `json:"pathPrefix"`
|
||||
} `json:"minio"`
|
||||
Enabled bool `json:"enabled"`
|
||||
} `json:"multimodal"`
|
||||
|
||||
// 存储引擎选择("local" | "minio" | "cos"),影响文档上传与文档内图片存储,参数从全局设置读取
|
||||
StorageProvider string `json:"storageProvider"`
|
||||
|
||||
// 知识图谱配置
|
||||
NodeExtract struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
@@ -300,38 +288,22 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
|
||||
if len(req.DocumentSplitting.Separators) > 0 {
|
||||
kb.ChunkingConfig.Separators = req.DocumentSplitting.Separators
|
||||
}
|
||||
kb.ChunkingConfig.ParserEngineRules = req.DocumentSplitting.ParserEngineRules
|
||||
|
||||
// 更新多模态配置
|
||||
if req.Multimodal.Enabled {
|
||||
switch strings.ToLower(req.Multimodal.StorageType) {
|
||||
case "cos":
|
||||
if req.Multimodal.COS != nil {
|
||||
kb.StorageConfig = types.StorageConfig{
|
||||
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,
|
||||
Provider: "cos",
|
||||
}
|
||||
}
|
||||
case "minio":
|
||||
if req.Multimodal.Minio != nil {
|
||||
kb.StorageConfig = types.StorageConfig{
|
||||
BucketName: req.Multimodal.Minio.BucketName,
|
||||
PathPrefix: req.Multimodal.Minio.PathPrefix,
|
||||
Provider: "minio",
|
||||
SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
|
||||
SecretKey: os.Getenv("MINIO_SECRET_ACCESS_KEY"),
|
||||
}
|
||||
}
|
||||
}
|
||||
// VLM model already set above
|
||||
} else {
|
||||
// 多模态未启用时,清空存储配置
|
||||
kb.StorageConfig = types.StorageConfig{}
|
||||
kb.VLMConfig.ModelID = ""
|
||||
}
|
||||
|
||||
// 存储引擎:仅写入 provider,参数从租户全局 StorageEngineConfig 读取
|
||||
provider := strings.ToLower(strings.TrimSpace(req.StorageProvider))
|
||||
if provider == "" {
|
||||
provider = "local"
|
||||
}
|
||||
kb.StorageConfig = types.StorageConfig{Provider: provider}
|
||||
|
||||
// 更新知识图谱配置
|
||||
if req.NodeExtract.Enabled {
|
||||
// 转换 Nodes 和 Relations 为指针类型
|
||||
@@ -1910,97 +1882,43 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// testMultimodalWithDocReader 调用docreader服务进行多模态处理
|
||||
// testMultimodalWithDocReader uses DocumentReader.Read for document reading,
|
||||
// then returns basic information about the result.
|
||||
func (h *InitializationHandler) testMultimodalWithDocReader(
|
||||
ctx context.Context,
|
||||
imageContent []byte, filename string,
|
||||
chunkSize, chunkOverlap int32, separators []string,
|
||||
req *testMultimodalForm,
|
||||
) (map[string]string, error) {
|
||||
// 获取文件扩展名
|
||||
fileExt := ""
|
||||
if idx := strings.LastIndex(filename, "."); idx != -1 {
|
||||
fileExt = strings.ToLower(filename[idx+1:])
|
||||
}
|
||||
|
||||
// 检查docreader服务配置
|
||||
if h.docReaderClient == nil {
|
||||
if h.documentReader == nil {
|
||||
return nil, fmt.Errorf("DocReader service not configured")
|
||||
}
|
||||
|
||||
// 构造请求
|
||||
request := &proto.ReadFromFileRequest{
|
||||
requestID, _ := ctx.Value(types.RequestIDContextKey).(string)
|
||||
|
||||
readResult, err := h.documentReader.Read(ctx, &types.ReadRequest{
|
||||
FileContent: imageContent,
|
||||
FileName: filename,
|
||||
FileType: fileExt,
|
||||
ReadConfig: &proto.ReadConfig{
|
||||
ChunkSize: chunkSize,
|
||||
ChunkOverlap: chunkOverlap,
|
||||
Separators: separators,
|
||||
EnableMultimodal: true, // 启用多模态处理
|
||||
VlmConfig: &proto.VLMConfig{
|
||||
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)
|
||||
RequestID: requestID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("调用DocReader服务失败: %v", err)
|
||||
}
|
||||
|
||||
if response.Error != "" {
|
||||
return nil, fmt.Errorf("DocReader服务返回错误: %s", response.Error)
|
||||
if readResult.Error != "" {
|
||||
return nil, fmt.Errorf("DocReader服务返回错误: %s", readResult.Error)
|
||||
}
|
||||
|
||||
// 处理响应,提取Caption和OCR信息
|
||||
result := make(map[string]string)
|
||||
var allCaptions, allOCRTexts []string
|
||||
|
||||
for _, chunk := range response.Chunks {
|
||||
if len(chunk.Images) > 0 {
|
||||
for _, image := range chunk.Images {
|
||||
if image.Caption != "" {
|
||||
allCaptions = append(allCaptions, image.Caption)
|
||||
}
|
||||
if image.OcrText != "" {
|
||||
allOCRTexts = append(allOCRTexts, image.OcrText)
|
||||
}
|
||||
}
|
||||
}
|
||||
result := map[string]string{
|
||||
"markdown": readResult.MarkdownContent,
|
||||
"caption": "",
|
||||
"ocr": "",
|
||||
}
|
||||
|
||||
// 合并所有Caption和OCR结果
|
||||
result["caption"] = strings.Join(allCaptions, "; ")
|
||||
result["ocr"] = strings.Join(allOCRTexts, "; ")
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -738,6 +738,102 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// mimeTypeByExt returns the MIME type for a given file extension.
|
||||
func mimeTypeByExt(filename string) string {
|
||||
ext := strings.ToLower(filename)
|
||||
if idx := strings.LastIndex(ext, "."); idx >= 0 {
|
||||
ext = ext[idx:]
|
||||
} else {
|
||||
ext = ""
|
||||
}
|
||||
m := map[string]string{
|
||||
".pdf": "application/pdf",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".doc": "application/msword",
|
||||
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
".ppt": "application/vnd.ms-powerpoint",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
".xls": "application/vnd.ms-excel",
|
||||
".csv": "text/csv",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".bmp": "image/bmp",
|
||||
".webp": "image/webp",
|
||||
".svg": "image/svg+xml",
|
||||
".tiff": "image/tiff",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
".md": "text/markdown; charset=utf-8",
|
||||
".markdown": "text/markdown; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".xml": "application/xml; charset=utf-8",
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".ts": "text/typescript; charset=utf-8",
|
||||
".py": "text/x-python; charset=utf-8",
|
||||
".go": "text/x-go; charset=utf-8",
|
||||
".java": "text/x-java; charset=utf-8",
|
||||
".yaml": "text/yaml; charset=utf-8",
|
||||
".yml": "text/yaml; charset=utf-8",
|
||||
".sh": "text/x-shellscript; charset=utf-8",
|
||||
}
|
||||
if ct, ok := m[ext]; ok {
|
||||
return ct
|
||||
}
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// PreviewKnowledgeFile godoc
|
||||
// @Summary 预览知识文件
|
||||
// @Description 返回知识条目关联的原始文件,Content-Type 根据文件类型设置,用于浏览器内嵌预览
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce application/pdf,image/jpeg,image/png,text/plain
|
||||
// @Param id path string true "知识ID"
|
||||
// @Success 200 {file} file "文件内容"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge/{id}/preview [get]
|
||||
func (h *KnowledgeHandler) PreviewKnowledgeFile(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
file, filename, err := h.kgService.GetKnowledgeFile(effCtx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to retrieve file").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
contentType := mimeTypeByExt(filename)
|
||||
c.Header("Content-Type", contentType)
|
||||
c.Header("Content-Disposition", fmt.Sprintf("inline; filename=%s", filename))
|
||||
c.Header("Cache-Control", "private, max-age=3600")
|
||||
|
||||
c.Stream(func(w io.Writer) bool {
|
||||
if _, err := io.Copy(w, file); err != nil {
|
||||
logger.Errorf(ctx, "Failed to stream preview: %v", err)
|
||||
return false
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// GetKnowledgeBatchRequest defines parameters for batch knowledge retrieval
|
||||
type GetKnowledgeBatchRequest struct {
|
||||
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
|
||||
|
||||
@@ -26,7 +26,7 @@ type KnowledgeBaseHandler struct {
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
agentShareService interfaces.AgentShareService
|
||||
asynqClient *asynq.Client
|
||||
asynqClient interfaces.TaskEnqueuer
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseHandler creates a new knowledge base handler instance
|
||||
@@ -35,7 +35,7 @@ func NewKnowledgeBaseHandler(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
agentShareService interfaces.AgentShareService,
|
||||
asynqClient *asynq.Client,
|
||||
asynqClient interfaces.TaskEnqueuer,
|
||||
) *KnowledgeBaseHandler {
|
||||
return &KnowledgeBaseHandler{
|
||||
service: service,
|
||||
|
||||
@@ -232,12 +232,13 @@ func (h *AgentStreamHandler) handleReferences(ctx context.Context, evt event.Eve
|
||||
} else if refMap, ok := ref.(map[string]interface{}); ok {
|
||||
// Parse from map if needed
|
||||
searchResult := &types.SearchResult{
|
||||
ID: getString(refMap, "id"),
|
||||
Content: getString(refMap, "content"),
|
||||
Score: getFloat64(refMap, "score"),
|
||||
KnowledgeID: getString(refMap, "knowledge_id"),
|
||||
KnowledgeTitle: getString(refMap, "knowledge_title"),
|
||||
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
|
||||
ID: getString(refMap, "id"),
|
||||
Content: getString(refMap, "content"),
|
||||
Score: getFloat64(refMap, "score"),
|
||||
KnowledgeID: getString(refMap, "knowledge_id"),
|
||||
KnowledgeTitle: getString(refMap, "knowledge_title"),
|
||||
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
|
||||
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
|
||||
}
|
||||
|
||||
if meta, ok := refMap["metadata"].(map[string]interface{}); ok {
|
||||
|
||||
@@ -84,6 +84,7 @@ func buildStreamResponse(evt interfaces.StreamEvent, requestID string) *types.St
|
||||
ImageInfo: getString(refMap, "image_info"),
|
||||
KnowledgeFilename: getString(refMap, "knowledge_filename"),
|
||||
KnowledgeSource: getString(refMap, "knowledge_source"),
|
||||
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
|
||||
}
|
||||
searchResults = append(searchResults, sr)
|
||||
}
|
||||
|
||||
+420
-20
@@ -3,12 +3,18 @@ package handler
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
@@ -17,21 +23,24 @@ import (
|
||||
|
||||
// SystemHandler handles system-related requests
|
||||
type SystemHandler struct {
|
||||
cfg *config.Config
|
||||
neo4jDriver neo4j.Driver
|
||||
cfg *config.Config
|
||||
neo4jDriver neo4j.Driver
|
||||
documentReader interfaces.DocumentReader
|
||||
}
|
||||
|
||||
// NewSystemHandler creates a new system handler
|
||||
func NewSystemHandler(cfg *config.Config, neo4jDriver neo4j.Driver) *SystemHandler {
|
||||
func NewSystemHandler(cfg *config.Config, neo4jDriver neo4j.Driver, documentReader interfaces.DocumentReader) *SystemHandler {
|
||||
return &SystemHandler{
|
||||
cfg: cfg,
|
||||
neo4jDriver: neo4jDriver,
|
||||
cfg: cfg,
|
||||
neo4jDriver: neo4jDriver,
|
||||
documentReader: documentReader,
|
||||
}
|
||||
}
|
||||
|
||||
// GetSystemInfoResponse defines the response structure for system info
|
||||
type GetSystemInfoResponse struct {
|
||||
Version string `json:"version"`
|
||||
Edition string `json:"edition"`
|
||||
CommitID string `json:"commit_id,omitempty"`
|
||||
BuildTime string `json:"build_time,omitempty"`
|
||||
GoVersion string `json:"go_version,omitempty"`
|
||||
@@ -44,6 +53,7 @@ type GetSystemInfoResponse struct {
|
||||
// 编译时注入的版本信息
|
||||
var (
|
||||
Version = "unknown"
|
||||
Edition = "standard"
|
||||
CommitID = "unknown"
|
||||
BuildTime = "unknown"
|
||||
GoVersion = "unknown"
|
||||
@@ -70,10 +80,11 @@ func (h *SystemHandler) GetSystemInfo(c *gin.Context) {
|
||||
graphDatabaseEngine := h.getGraphDatabaseEngine()
|
||||
|
||||
// Get MinIO enabled status
|
||||
minioEnabled := h.isMinioEnabled()
|
||||
minioEnabled := h.isMinioConfigured(c)
|
||||
|
||||
response := GetSystemInfoResponse{
|
||||
Version: Version,
|
||||
Edition: Edition,
|
||||
CommitID: CommitID,
|
||||
BuildTime: BuildTime,
|
||||
GoVersion: GoVersion,
|
||||
@@ -91,6 +102,125 @@ func (h *SystemHandler) GetSystemInfo(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) getDocReaderConnInfo() (addr, transport string) {
|
||||
addr = strings.TrimSpace(os.Getenv("DOCREADER_ADDR"))
|
||||
transport = strings.TrimSpace(os.Getenv("DOCREADER_TRANSPORT"))
|
||||
if transport == "" {
|
||||
transport = "grpc"
|
||||
}
|
||||
transport = strings.ToLower(transport)
|
||||
return addr, transport
|
||||
}
|
||||
|
||||
// ListParserEngines returns available document parser engines.
|
||||
// Merges Go-native static engines with engines discovered from the remote
|
||||
// docreader service, so newly added Python engines are auto-discovered.
|
||||
// @Summary 列出可用的文档解析引擎
|
||||
// @Tags 系统
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "解析引擎列表"
|
||||
// @Router /system/parser-engines [get]
|
||||
func (h *SystemHandler) ListParserEngines(c *gin.Context) {
|
||||
docreaderAddr, docreaderTransport := h.getDocReaderConnInfo()
|
||||
connected := h.documentReader != nil && h.documentReader.IsConnected()
|
||||
|
||||
var overrides map[string]string
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.ParserEngineConfig != nil {
|
||||
overrides = tenant.ParserEngineConfig.ToOverridesMap()
|
||||
}
|
||||
}
|
||||
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
engines := docparser.ListAllEngines(connected, overrides, remoteEngines)
|
||||
c.JSON(200, gin.H{"code": 0, "msg": "success", "data": engines, "docreader_addr": docreaderAddr, "docreader_transport": docreaderTransport, "connected": connected})
|
||||
}
|
||||
|
||||
// ReconnectDocReader reconnects the document converter to a new (or same) DocReader address.
|
||||
// @Summary 重连文档解析服务
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body object{addr string} true "DocReader 地址"
|
||||
// @Success 200
|
||||
// @Router /system/docreader/reconnect [post]
|
||||
func (h *SystemHandler) ReconnectDocReader(c *gin.Context) {
|
||||
var req struct {
|
||||
Addr string `json:"addr" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"code": 1, "msg": "请提供 addr 参数"})
|
||||
return
|
||||
}
|
||||
addr := strings.TrimSpace(req.Addr)
|
||||
if addr == "" {
|
||||
c.JSON(400, gin.H{"code": 1, "msg": "addr 不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
if h.documentReader == nil {
|
||||
c.JSON(500, gin.H{"code": 1, "msg": "document converter not initialized"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.documentReader.Reconnect(addr); err != nil {
|
||||
logger.Errorf(c.Request.Context(), "Failed to reconnect docreader to %s: %v", addr, err)
|
||||
c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("连接失败: %v", err)})
|
||||
return
|
||||
}
|
||||
|
||||
var overrides map[string]string
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.ParserEngineConfig != nil {
|
||||
overrides = tenant.ParserEngineConfig.ToOverridesMap()
|
||||
}
|
||||
}
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
engines := docparser.ListAllEngines(true, overrides, remoteEngines)
|
||||
|
||||
_, docreaderTransport := h.getDocReaderConnInfo()
|
||||
c.JSON(200, gin.H{"code": 0, "msg": "连接成功", "data": engines, "docreader_addr": addr, "docreader_transport": docreaderTransport, "connected": true})
|
||||
}
|
||||
|
||||
// CheckParserEngines runs availability check with the given config overrides (e.g. current form values).
|
||||
// Used to test engine availability without saving; body shape matches ParserEngineConfig.
|
||||
// @Summary 使用当前参数检测解析引擎可用性
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body object true "解析引擎配置(与保存接口同结构)"
|
||||
// @Success 200
|
||||
// @Router /system/parser-engines/check [post]
|
||||
func (h *SystemHandler) CheckParserEngines(c *gin.Context) {
|
||||
docreaderAddr, docreaderTransport := h.getDocReaderConnInfo()
|
||||
connected := h.documentReader != nil && h.documentReader.IsConnected()
|
||||
|
||||
var body types.ParserEngineConfig
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(400, gin.H{"code": 1, "msg": "请求体格式错误"})
|
||||
return
|
||||
}
|
||||
overrides := body.ToOverridesMap()
|
||||
remoteEngines := h.fetchRemoteEngines(c.Request.Context(), overrides)
|
||||
engines := docparser.ListAllEngines(connected, overrides, remoteEngines)
|
||||
c.JSON(200, gin.H{"code": 0, "msg": "success", "data": engines, "docreader_addr": docreaderAddr, "docreader_transport": docreaderTransport, "connected": connected})
|
||||
}
|
||||
|
||||
// fetchRemoteEngines queries the remote docreader for its engine list.
|
||||
// Returns nil on any error (e.g. not connected), letting the caller
|
||||
// fall back to Go's static registry only.
|
||||
func (h *SystemHandler) fetchRemoteEngines(ctx context.Context, overrides map[string]string) []types.ParserEngineInfo {
|
||||
if h.documentReader == nil || !h.documentReader.IsConnected() {
|
||||
return nil
|
||||
}
|
||||
engines, err := h.documentReader.ListEngines(ctx, overrides)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch remote engines from docreader: %v", err)
|
||||
return nil
|
||||
}
|
||||
return engines
|
||||
}
|
||||
|
||||
// getKeywordIndexEngine returns the keyword index engine name
|
||||
func (h *SystemHandler) getKeywordIndexEngine() string {
|
||||
retrieveDriver := os.Getenv("RETRIEVE_DRIVER")
|
||||
@@ -172,16 +302,46 @@ func (h *SystemHandler) supportsRetrieverType(driver string, retrieverType types
|
||||
return false
|
||||
}
|
||||
|
||||
// isMinioEnabled checks if MinIO is enabled
|
||||
func (h *SystemHandler) isMinioEnabled() bool {
|
||||
// Check if all required MinIO environment variables are set
|
||||
endpoint := os.Getenv("MINIO_ENDPOINT")
|
||||
accessKeyID := os.Getenv("MINIO_ACCESS_KEY_ID")
|
||||
secretAccessKey := os.Getenv("MINIO_SECRET_ACCESS_KEY")
|
||||
// getMinioConfig resolves MinIO connection parameters from tenant config (if mode=remote) or env vars (mode=docker/default).
|
||||
func (h *SystemHandler) getMinioConfig(c *gin.Context) (endpoint, accessKeyID, secretAccessKey string) {
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
m := tenant.StorageEngineConfig.MinIO
|
||||
if m.Mode == "remote" {
|
||||
return m.Endpoint, m.AccessKeyID, m.SecretAccessKey
|
||||
}
|
||||
}
|
||||
}
|
||||
endpoint = os.Getenv("MINIO_ENDPOINT")
|
||||
accessKeyID = os.Getenv("MINIO_ACCESS_KEY_ID")
|
||||
secretAccessKey = os.Getenv("MINIO_SECRET_ACCESS_KEY")
|
||||
return
|
||||
}
|
||||
|
||||
// isMinioConfigured checks whether MinIO connection info is available (from tenant config or env).
|
||||
func (h *SystemHandler) isMinioConfigured(c *gin.Context) bool {
|
||||
endpoint, accessKeyID, secretAccessKey := h.getMinioConfig(c)
|
||||
return endpoint != "" && accessKeyID != "" && secretAccessKey != ""
|
||||
}
|
||||
|
||||
// isMinioEnvAvailable checks whether MinIO env vars (MINIO_ENDPOINT etc.) are set.
|
||||
func (h *SystemHandler) isMinioEnvAvailable() bool {
|
||||
return os.Getenv("MINIO_ENDPOINT") != "" &&
|
||||
os.Getenv("MINIO_ACCESS_KEY_ID") != "" &&
|
||||
os.Getenv("MINIO_SECRET_ACCESS_KEY") != ""
|
||||
}
|
||||
|
||||
// isCOSConfigured checks whether COS connection info is available from tenant config.
|
||||
func (h *SystemHandler) isCOSConfigured(c *gin.Context) bool {
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.COS != nil {
|
||||
cosConf := tenant.StorageEngineConfig.COS
|
||||
return cosConf.SecretID != "" && cosConf.SecretKey != "" && cosConf.Region != "" && cosConf.BucketName != ""
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MinioBucketInfo represents bucket information with access policy
|
||||
type MinioBucketInfo struct {
|
||||
Name string `json:"name"`
|
||||
@@ -194,6 +354,42 @@ type ListMinioBucketsResponse struct {
|
||||
Buckets []MinioBucketInfo `json:"buckets"`
|
||||
}
|
||||
|
||||
// StorageEngineStatusItem describes one storage engine's availability and description.
|
||||
type StorageEngineStatusItem struct {
|
||||
Name string `json:"name"` // "local", "minio", "cos"
|
||||
Available bool `json:"available"` // whether the engine can be used
|
||||
Description string `json:"description"` // short description for UI
|
||||
}
|
||||
|
||||
// GetStorageEngineStatusResponse is the response for GET /system/storage-engine-status.
|
||||
type GetStorageEngineStatusResponse struct {
|
||||
Engines []StorageEngineStatusItem `json:"engines"`
|
||||
MinioEnvAvailable bool `json:"minio_env_available"`
|
||||
}
|
||||
|
||||
// GetStorageEngineStatus godoc
|
||||
// @Summary 获取存储引擎状态
|
||||
// @Description 返回 Local、MinIO、COS 各存储引擎的可用状态及说明,供全局设置与知识库选择使用
|
||||
// @Tags 系统
|
||||
// @Produce json
|
||||
// @Success 200 {object} GetStorageEngineStatusResponse
|
||||
// @Router /system/storage-engine-status [get]
|
||||
func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
minioConfigured := h.isMinioConfigured(c)
|
||||
minioEnvAvailable := h.isMinioEnvAvailable()
|
||||
cosConfigured := h.isCOSConfigured(c)
|
||||
engines := []StorageEngineStatusItem{
|
||||
{Name: "local", Available: true, Description: "本地文件系统存储,仅适合单机部署"},
|
||||
{Name: "minio", Available: minioConfigured || minioEnvAvailable, Description: "S3 兼容的自托管对象存储,适合内网和私有云部署"},
|
||||
{Name: "cos", Available: cosConfigured, Description: "腾讯云对象存储服务,适合公有云部署,支持 CDN 加速"},
|
||||
}
|
||||
c.JSON(200, gin.H{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": GetStorageEngineStatusResponse{Engines: engines, MinioEnvAvailable: minioEnvAvailable},
|
||||
})
|
||||
}
|
||||
|
||||
// ListMinioBuckets godoc
|
||||
// @Summary 列出 MinIO 存储桶
|
||||
// @Description 获取所有 MinIO 存储桶及其访问权限
|
||||
@@ -207,22 +403,23 @@ type ListMinioBucketsResponse struct {
|
||||
func (h *SystemHandler) ListMinioBuckets(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
// Check if MinIO is enabled
|
||||
if !h.isMinioEnabled() {
|
||||
logger.Warn(ctx, "MinIO is not enabled")
|
||||
endpoint, accessKeyID, secretAccessKey := h.getMinioConfig(c)
|
||||
if endpoint == "" || accessKeyID == "" || secretAccessKey == "" {
|
||||
logger.Warn(ctx, "MinIO is not configured")
|
||||
c.JSON(400, gin.H{
|
||||
"code": 400,
|
||||
"msg": "MinIO is not enabled",
|
||||
"msg": "MinIO is not configured",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Get MinIO configuration from environment
|
||||
endpoint := os.Getenv("MINIO_ENDPOINT")
|
||||
accessKeyID := os.Getenv("MINIO_ACCESS_KEY_ID")
|
||||
secretAccessKey := os.Getenv("MINIO_SECRET_ACCESS_KEY")
|
||||
useSSL := os.Getenv("MINIO_USE_SSL") == "true"
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
useSSL = tenant.StorageEngineConfig.MinIO.UseSSL
|
||||
}
|
||||
}
|
||||
|
||||
// Create MinIO client
|
||||
minioClient, err := minio.New(endpoint, &minio.Options{
|
||||
@@ -372,3 +569,206 @@ func hasGetObjectAction(action interface{}) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Storage engine helpers ---
|
||||
|
||||
// cosFieldPattern validates COS region and bucket name format to prevent URL injection.
|
||||
var cosFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
|
||||
|
||||
// sanitizeStorageCheckError converts a raw storage connectivity error into a safe
|
||||
// user-facing message that does not leak internal network details (hostnames, IPs, ports).
|
||||
func sanitizeStorageCheckError(err error) string {
|
||||
msg := err.Error()
|
||||
switch {
|
||||
case strings.Contains(msg, "no such host"):
|
||||
return "DNS 解析失败,请检查地址是否正确"
|
||||
case strings.Contains(msg, "connection refused"):
|
||||
return "连接被拒绝,请确认服务已启动且端口正确"
|
||||
case strings.Contains(msg, "no route to host"):
|
||||
return "无法路由到目标地址,请检查网络配置"
|
||||
case strings.Contains(msg, "i/o timeout") || strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "context deadline"):
|
||||
return "连接超时,请检查网络或服务状态"
|
||||
case strings.Contains(msg, "403") || strings.Contains(msg, "AccessDenied") || strings.Contains(msg, "access denied"):
|
||||
return "认证失败,请检查访问凭证是否正确"
|
||||
case strings.Contains(msg, "certificate") || strings.Contains(msg, "tls") || strings.Contains(msg, "x509"):
|
||||
return "TLS/SSL 证书错误,请检查 SSL 配置"
|
||||
case strings.Contains(msg, "404") || strings.Contains(msg, "NoSuchBucket"):
|
||||
return "Bucket 不存在,请检查名称和 Region"
|
||||
default:
|
||||
return "连接失败,请检查配置参数是否正确"
|
||||
}
|
||||
}
|
||||
|
||||
// isBlockedStorageEndpoint checks whether a storage endpoint resolves to a dangerous
|
||||
// address (cloud metadata, loopback, link-local). Unlike the stricter IsSSRFSafeURL,
|
||||
// this allows private IPs since MinIO is commonly deployed on internal networks.
|
||||
func isBlockedStorageEndpoint(endpoint string) (bool, string) {
|
||||
host, _, err := net.SplitHostPort(endpoint)
|
||||
if err != nil {
|
||||
host = endpoint
|
||||
}
|
||||
hostLower := strings.ToLower(host)
|
||||
|
||||
blockedHosts := []string{
|
||||
"metadata.google.internal",
|
||||
"metadata.tencentyun.com",
|
||||
"metadata.aws.internal",
|
||||
"169.254.169.254",
|
||||
}
|
||||
for _, bh := range blockedHosts {
|
||||
if hostLower == bh {
|
||||
return true, "该地址不允许访问"
|
||||
}
|
||||
}
|
||||
|
||||
checkIP := func(ip net.IP) (bool, string) {
|
||||
if ip.IsLoopback() {
|
||||
return true, "不允许访问本地回环地址"
|
||||
}
|
||||
if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
|
||||
return true, "不允许访问链路本地地址"
|
||||
}
|
||||
if ip.IsUnspecified() {
|
||||
return true, "无效的地址"
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return checkIP(ip)
|
||||
}
|
||||
|
||||
ips, err := net.LookupIP(host)
|
||||
if err != nil {
|
||||
return false, ""
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if blocked, reason := checkIP(ip); blocked {
|
||||
return blocked, reason
|
||||
}
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// --- Storage engine connectivity check ---
|
||||
|
||||
// StorageCheckRequest is the body for POST /system/storage-engine-check.
|
||||
type StorageCheckRequest struct {
|
||||
Provider string `json:"provider"` // "minio" or "cos"
|
||||
MinIO *types.MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *types.COSEngineConfig `json:"cos,omitempty"`
|
||||
}
|
||||
|
||||
// StorageCheckResponse is the response for a single-engine connectivity check.
|
||||
type StorageCheckResponse struct {
|
||||
OK bool `json:"ok"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// CheckStorageEngine tests connectivity for a single storage engine using the provided config.
|
||||
// @Summary 测试存储引擎连通性
|
||||
// @Description 使用当前填写的参数测试 MinIO/COS 连通性,不保存配置
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body StorageCheckRequest true "存储引擎配置"
|
||||
// @Success 200 {object} StorageCheckResponse
|
||||
// @Router /system/storage-engine-check [post]
|
||||
func (h *SystemHandler) CheckStorageEngine(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
var req StorageCheckRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"code": 1, "msg": "请求体格式错误"})
|
||||
return
|
||||
}
|
||||
|
||||
switch req.Provider {
|
||||
case "minio":
|
||||
h.checkMinio(c, ctx, req.MinIO)
|
||||
case "cos":
|
||||
h.checkCOS(c, ctx, req.COS)
|
||||
default:
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: "本地存储无需检测"}})
|
||||
}
|
||||
}
|
||||
|
||||
func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *types.MinIOEngineConfig) {
|
||||
if cfg == nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 MinIO 配置"}})
|
||||
return
|
||||
}
|
||||
|
||||
endpoint, accessKeyID, secretAccessKey := cfg.Endpoint, cfg.AccessKeyID, cfg.SecretAccessKey
|
||||
if cfg.Mode != "remote" {
|
||||
endpoint = os.Getenv("MINIO_ENDPOINT")
|
||||
accessKeyID = os.Getenv("MINIO_ACCESS_KEY_ID")
|
||||
secretAccessKey = os.Getenv("MINIO_SECRET_ACCESS_KEY")
|
||||
}
|
||||
if endpoint == "" || accessKeyID == "" || secretAccessKey == "" {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Endpoint、Access Key、Secret Key 不能为空"}})
|
||||
return
|
||||
}
|
||||
|
||||
if cfg.Mode == "remote" {
|
||||
if blocked, reason := isBlockedStorageEndpoint(endpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection", "endpoint", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := file.CheckMinioConnectivity(ctx, endpoint, accessKeyID, secretAccessKey, cfg.BucketName, cfg.UseSSL)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Storage check: MinIO connectivity failed", "error", err)
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "does not exist") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: sanitizeStorageCheckError(err)}})
|
||||
return
|
||||
}
|
||||
|
||||
msg := "连接成功"
|
||||
if cfg.BucketName != "" {
|
||||
msg = fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: msg}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) checkCOS(c *gin.Context, ctx context.Context, cfg *types.COSEngineConfig) {
|
||||
if cfg == nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 COS 配置"}})
|
||||
return
|
||||
}
|
||||
if cfg.SecretID == "" || cfg.SecretKey == "" || cfg.Region == "" || cfg.BucketName == "" {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Secret ID、Secret Key、Region、Bucket 名称不能为空"}})
|
||||
return
|
||||
}
|
||||
if !cosFieldPattern.MatchString(cfg.Region) {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Region 格式不正确,仅允许字母、数字、点、连字符"}})
|
||||
return
|
||||
}
|
||||
if !cosFieldPattern.MatchString(cfg.BucketName) {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}})
|
||||
return
|
||||
}
|
||||
|
||||
err := file.CheckCosConnectivity(ctx, cfg.BucketName, cfg.Region, cfg.SecretID, cfg.SecretKey)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Storage check: COS connectivity failed, bucket: %s, error: %v", cfg.BucketName, err)
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "403") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Secret ID / Secret Key 是否正确"}})
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在,请检查名称和 Region", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: sanitizeStorageCheckError(err)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
@@ -599,6 +599,12 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
|
||||
case "prompt-templates":
|
||||
h.GetPromptTemplates(c)
|
||||
return
|
||||
case "parser-engine-config":
|
||||
h.GetTenantParserEngineConfig(c)
|
||||
return
|
||||
case "storage-engine-config":
|
||||
h.GetTenantStorageEngineConfig(c)
|
||||
return
|
||||
default:
|
||||
logger.Info(ctx, "KV key not supported", "key", key)
|
||||
c.Error(errors.NewBadRequestError("unsupported key"))
|
||||
@@ -633,6 +639,12 @@ func (h *TenantHandler) UpdateTenantKV(c *gin.Context) {
|
||||
case "conversation-config":
|
||||
h.updateTenantConversationInternal(c)
|
||||
return
|
||||
case "parser-engine-config":
|
||||
h.updateTenantParserEngineConfigInternal(c)
|
||||
return
|
||||
case "storage-engine-config":
|
||||
h.updateTenantStorageEngineConfigInternal(c)
|
||||
return
|
||||
default:
|
||||
logger.Info(ctx, "KV key not supported", "key", key)
|
||||
c.Error(errors.NewBadRequestError("unsupported key"))
|
||||
@@ -713,6 +725,110 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// GetTenantParserEngineConfig returns the tenant's parser engine config (MinerU endpoint, API key, etc.).
|
||||
func (h *TenantHandler) GetTenantParserEngineConfig(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
data := tenant.ParserEngineConfig
|
||||
if data == nil {
|
||||
data = &types.ParserEngineConfig{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": data,
|
||||
})
|
||||
}
|
||||
|
||||
// updateTenantParserEngineConfigInternal updates the tenant's parser engine config.
|
||||
func (h *TenantHandler) updateTenantParserEngineConfigInternal(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var cfg types.ParserEngineConfig
|
||||
if err := c.ShouldBindJSON(&cfg); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
tenant.ParserEngineConfig = &cfg
|
||||
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
} else {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to update tenant parser engine config").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": updatedTenant.ParserEngineConfig,
|
||||
"message": "解析引擎配置已更新",
|
||||
})
|
||||
}
|
||||
|
||||
// GetTenantStorageEngineConfig returns the tenant's storage engine config (Local, MinIO, COS parameters).
|
||||
func (h *TenantHandler) GetTenantStorageEngineConfig(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
data := tenant.StorageEngineConfig
|
||||
if data == nil {
|
||||
data = &types.StorageEngineConfig{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": data,
|
||||
})
|
||||
}
|
||||
|
||||
// updateTenantStorageEngineConfigInternal updates the tenant's storage engine config.
|
||||
func (h *TenantHandler) updateTenantStorageEngineConfigInternal(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var cfg types.StorageEngineConfig
|
||||
if err := c.ShouldBindJSON(&cfg); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
logger.Error(ctx, "Tenant is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant is empty"))
|
||||
return
|
||||
}
|
||||
tenant.StorageEngineConfig = &cfg
|
||||
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
} else {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to update tenant storage engine config").WithDetails(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": updatedTenant.StorageEngineConfig,
|
||||
"message": "存储引擎配置已更新",
|
||||
})
|
||||
}
|
||||
|
||||
func (h *TenantHandler) buildDefaultConversationConfig() *types.ConversationConfig {
|
||||
return &types.ConversationConfig{
|
||||
Prompt: h.config.Conversation.Summary.Prompt,
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
// Package chunker implements text splitting for document chunking.
|
||||
//
|
||||
// Ported from the Python docreader/splitter/splitter.py recursive text splitter.
|
||||
package chunker
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Chunk represents a piece of split text with position tracking.
|
||||
type Chunk struct {
|
||||
Content string
|
||||
Seq int
|
||||
Start int
|
||||
End int
|
||||
}
|
||||
|
||||
// ImageRef is an image reference found within a chunk's content.
|
||||
type ImageRef struct {
|
||||
OriginalRef string
|
||||
AltText string
|
||||
Start int // offset within the chunk content
|
||||
End int
|
||||
}
|
||||
|
||||
// SplitterConfig configures the text splitter.
|
||||
type SplitterConfig struct {
|
||||
ChunkSize int
|
||||
ChunkOverlap int
|
||||
Separators []string
|
||||
}
|
||||
|
||||
// DefaultConfig returns sensible defaults.
|
||||
func DefaultConfig() SplitterConfig {
|
||||
return SplitterConfig{
|
||||
ChunkSize: 512,
|
||||
ChunkOverlap: 50,
|
||||
Separators: []string{"\n\n", "\n", "。"},
|
||||
}
|
||||
}
|
||||
|
||||
// protectedPatterns are regex patterns for content that must not be split.
|
||||
var protectedPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?s)\$\$.*?\$\$`), // LaTeX block math
|
||||
regexp.MustCompile(`!\[[^\]]*\]\([^)]+\)`), // Markdown images
|
||||
regexp.MustCompile(`\[[^\]]*\]\([^)]+\)`), // Markdown links
|
||||
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+\\s*(?:\\|\\s*:?-{3,}:?\\s*)+\\|[\\r\\n]+"), // Table header+separator
|
||||
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+"), // Table rows
|
||||
regexp.MustCompile("(?s)```(?:\\w+)?[\\r\\n].*?```"), // Fenced code blocks
|
||||
}
|
||||
|
||||
type span struct {
|
||||
start, end int
|
||||
}
|
||||
|
||||
// protectedSpans finds all non-overlapping protected regions in text.
|
||||
func protectedSpans(text string) []span {
|
||||
type match struct {
|
||||
start, end int
|
||||
}
|
||||
var all []match
|
||||
for _, pat := range protectedPatterns {
|
||||
locs := pat.FindAllStringIndex(text, -1)
|
||||
for _, loc := range locs {
|
||||
if loc[1]-loc[0] > 0 {
|
||||
all = append(all, match{loc[0], loc[1]})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(all) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sort by start, then by length descending
|
||||
for i := 1; i < len(all); i++ {
|
||||
for j := i; j > 0; j-- {
|
||||
if all[j].start < all[j-1].start ||
|
||||
(all[j].start == all[j-1].start && (all[j].end-all[j].start) > (all[j-1].end-all[j-1].start)) {
|
||||
all[j], all[j-1] = all[j-1], all[j]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove overlaps
|
||||
var result []span
|
||||
lastEnd := 0
|
||||
for _, m := range all {
|
||||
if m.start >= lastEnd {
|
||||
result = append(result, span{m.start, m.end})
|
||||
lastEnd = m.end
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// splitUnit is a piece of text with its original position.
|
||||
type splitUnit struct {
|
||||
text string
|
||||
start, end int
|
||||
}
|
||||
|
||||
// splitBySeparators splits text by separators in priority order, keeping separators.
|
||||
func splitBySeparators(text string, separators []string) []string {
|
||||
if len(separators) == 0 || text == "" {
|
||||
return []string{text}
|
||||
}
|
||||
|
||||
// Build regex that captures separators
|
||||
var parts []string
|
||||
for _, sep := range separators {
|
||||
parts = append(parts, regexp.QuoteMeta(sep))
|
||||
}
|
||||
pattern := "(" + strings.Join(parts, "|") + ")"
|
||||
re := regexp.MustCompile(pattern)
|
||||
|
||||
splits := re.Split(text, -1)
|
||||
matches := re.FindAllString(text, -1)
|
||||
|
||||
var result []string
|
||||
for i, s := range splits {
|
||||
if s != "" {
|
||||
result = append(result, s)
|
||||
}
|
||||
if i < len(matches) && matches[i] != "" {
|
||||
result = append(result, matches[i])
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// runeLen returns the number of runes in s.
|
||||
func runeLen(s string) int {
|
||||
return utf8.RuneCountInString(s)
|
||||
}
|
||||
|
||||
// SplitText splits text into chunks with overlap, respecting protected patterns.
|
||||
func SplitText(text string, cfg SplitterConfig) []Chunk {
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
chunkSize := cfg.ChunkSize
|
||||
chunkOverlap := cfg.ChunkOverlap
|
||||
separators := cfg.Separators
|
||||
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = 512
|
||||
}
|
||||
if chunkOverlap < 0 {
|
||||
chunkOverlap = 0
|
||||
}
|
||||
|
||||
// Step 1: Find protected spans
|
||||
protected := protectedSpans(text)
|
||||
|
||||
// Step 2: Split non-protected regions by separators, keep protected as atomic units
|
||||
units := buildUnitsWithProtection(text, protected, separators)
|
||||
|
||||
// Step 3: Merge units into chunks with overlap
|
||||
return mergeUnits(units, chunkSize, chunkOverlap)
|
||||
}
|
||||
|
||||
// buildUnitsWithProtection splits text into units, preserving protected spans as atomic.
|
||||
// Start/End positions in the returned units are rune offsets (not byte offsets),
|
||||
// because downstream merge logic indexes content via []rune slicing.
|
||||
func buildUnitsWithProtection(text string, protected []span, separators []string) []splitUnit {
|
||||
var units []splitUnit
|
||||
bytePos := 0
|
||||
runePos := 0
|
||||
|
||||
for _, p := range protected {
|
||||
if p.start > bytePos {
|
||||
pre := text[bytePos:p.start]
|
||||
parts := splitBySeparators(pre, separators)
|
||||
runeOffset := runePos
|
||||
for _, part := range parts {
|
||||
partRuneLen := runeLen(part)
|
||||
units = append(units, splitUnit{
|
||||
text: part,
|
||||
start: runeOffset,
|
||||
end: runeOffset + partRuneLen,
|
||||
})
|
||||
runeOffset += partRuneLen
|
||||
}
|
||||
runePos += runeLen(pre)
|
||||
}
|
||||
|
||||
protText := text[p.start:p.end]
|
||||
protRuneLen := runeLen(protText)
|
||||
units = append(units, splitUnit{
|
||||
text: protText,
|
||||
start: runePos,
|
||||
end: runePos + protRuneLen,
|
||||
})
|
||||
runePos += protRuneLen
|
||||
bytePos = p.end
|
||||
}
|
||||
|
||||
if bytePos < len(text) {
|
||||
remaining := text[bytePos:]
|
||||
parts := splitBySeparators(remaining, separators)
|
||||
runeOffset := runePos
|
||||
for _, part := range parts {
|
||||
partRuneLen := runeLen(part)
|
||||
units = append(units, splitUnit{
|
||||
text: part,
|
||||
start: runeOffset,
|
||||
end: runeOffset + partRuneLen,
|
||||
})
|
||||
runeOffset += partRuneLen
|
||||
}
|
||||
}
|
||||
|
||||
return units
|
||||
}
|
||||
|
||||
// mergeUnits combines split units into chunks with overlap tracking.
|
||||
func mergeUnits(units []splitUnit, chunkSize, chunkOverlap int) []Chunk {
|
||||
if len(units) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var chunks []Chunk
|
||||
var current []splitUnit
|
||||
curLen := 0
|
||||
|
||||
for _, u := range units {
|
||||
uLen := runeLen(u.text)
|
||||
|
||||
// If adding this unit exceeds chunk size and we have content, flush
|
||||
if curLen+uLen > chunkSize && len(current) > 0 {
|
||||
chunks = append(chunks, buildChunk(current, len(chunks)))
|
||||
|
||||
// Keep overlap from the end of current
|
||||
current, curLen = computeOverlap(current, chunkOverlap, chunkSize, uLen)
|
||||
}
|
||||
|
||||
current = append(current, u)
|
||||
curLen += uLen
|
||||
}
|
||||
|
||||
// Flush remaining
|
||||
if len(current) > 0 {
|
||||
chunks = append(chunks, buildChunk(current, len(chunks)))
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
func buildChunk(units []splitUnit, seq int) Chunk {
|
||||
var sb strings.Builder
|
||||
for _, u := range units {
|
||||
sb.WriteString(u.text)
|
||||
}
|
||||
return Chunk{
|
||||
Content: sb.String(),
|
||||
Seq: seq,
|
||||
Start: units[0].start,
|
||||
End: units[len(units)-1].end,
|
||||
}
|
||||
}
|
||||
|
||||
// computeOverlap returns the units to keep for overlap and their total rune length.
|
||||
func computeOverlap(current []splitUnit, chunkOverlap, chunkSize, nextLen int) ([]splitUnit, int) {
|
||||
if chunkOverlap <= 0 {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// Walk backward from end, accumulating overlap
|
||||
overlapLen := 0
|
||||
startIdx := len(current)
|
||||
for i := len(current) - 1; i >= 0; i-- {
|
||||
uLen := runeLen(current[i].text)
|
||||
if overlapLen+uLen > chunkOverlap {
|
||||
break
|
||||
}
|
||||
// Check that overlap + next unit fits in chunk
|
||||
if overlapLen+uLen+nextLen > chunkSize {
|
||||
break
|
||||
}
|
||||
overlapLen += uLen
|
||||
startIdx = i
|
||||
}
|
||||
|
||||
// Skip leading separators-only units in the overlap
|
||||
for startIdx < len(current) {
|
||||
u := current[startIdx]
|
||||
trimmed := strings.TrimSpace(u.text)
|
||||
if trimmed == "" || isSeparatorOnly(u.text) {
|
||||
overlapLen -= runeLen(u.text)
|
||||
startIdx++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if startIdx >= len(current) {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
overlap := make([]splitUnit, len(current)-startIdx)
|
||||
copy(overlap, current[startIdx:])
|
||||
return overlap, overlapLen
|
||||
}
|
||||
|
||||
func isSeparatorOnly(s string) bool {
|
||||
for _, r := range s {
|
||||
if r != '\n' && r != '\r' && r != ' ' && r != '\t' && r != '。' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ExtractImageRefs extracts markdown image references from text.
|
||||
var imageRefPattern = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
|
||||
|
||||
func ExtractImageRefs(text string) []ImageRef {
|
||||
matches := imageRefPattern.FindAllStringSubmatchIndex(text, -1)
|
||||
var refs []ImageRef
|
||||
for _, m := range matches {
|
||||
refs = append(refs, ImageRef{
|
||||
OriginalRef: text[m[4]:m[5]], // group 2: URL
|
||||
AltText: text[m[2]:m[3]], // group 1: alt text
|
||||
Start: m[0],
|
||||
End: m[1],
|
||||
})
|
||||
}
|
||||
return refs
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package chunker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestSplitText_BasicASCII(t *testing.T) {
|
||||
text := "Hello world. This is a test."
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{". "}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) == 0 {
|
||||
t.Fatal("expected at least one chunk")
|
||||
}
|
||||
combined := ""
|
||||
for _, c := range chunks {
|
||||
combined += c.Content
|
||||
}
|
||||
if combined != text {
|
||||
t.Errorf("combined content mismatch:\n got: %q\n want: %q", combined, text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ChineseText_StartEndAreRuneOffsets(t *testing.T) {
|
||||
// Each Chinese character is 3 bytes in UTF-8 but 1 rune.
|
||||
// This test ensures Start/End are rune offsets, not byte offsets.
|
||||
text := "你好世界这是一个测试文本用于检验分割位置"
|
||||
runeCount := utf8.RuneCountInString(text)
|
||||
byteCount := len(text)
|
||||
if runeCount == byteCount {
|
||||
t.Fatal("test requires multi-byte characters")
|
||||
}
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
|
||||
c := chunks[0]
|
||||
if c.Start != 0 {
|
||||
t.Errorf("Start: got %d, want 0", c.Start)
|
||||
}
|
||||
if c.End != runeCount {
|
||||
t.Errorf("End: got %d, want %d (runeCount); byteCount would be %d",
|
||||
c.End, runeCount, byteCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ChineseMultiChunk_StartEndConsistency(t *testing.T) {
|
||||
// Build a long Chinese text that will be split into multiple chunks.
|
||||
line := "这是一段中文内容用于测试分割功能是否正确。"
|
||||
text := strings.Repeat(line+"\n\n", 20)
|
||||
text = strings.TrimRight(text, "\n")
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 30, ChunkOverlap: 5, Separators: []string{"\n\n", "\n", "。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) < 2 {
|
||||
t.Fatalf("expected multiple chunks, got %d", len(chunks))
|
||||
}
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
contentRunes := []rune(c.Content)
|
||||
contentRuneLen := len(contentRunes)
|
||||
|
||||
// End - Start must equal the rune length of the content
|
||||
spanLen := c.End - c.Start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: End(%d) - Start(%d) = %d, but rune len of content = %d",
|
||||
i, c.End, c.Start, spanLen, contentRuneLen)
|
||||
}
|
||||
|
||||
// Start must be non-negative and End must not exceed total rune count
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: Start is negative: %d", i, c.Start)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d exceeds total rune count %d", i, c.End, len(textRunes))
|
||||
}
|
||||
|
||||
// Content from rune slice must match the chunk content
|
||||
if c.Start >= 0 && c.End <= len(textRunes) {
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: content mismatch via rune slice:\n got: %q\n want: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_MixedChineseAndASCII(t *testing.T) {
|
||||
text := "Hello你好World世界Test测试"
|
||||
cfg := SplitterConfig{ChunkSize: 100, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
c := chunks[0]
|
||||
expectedRuneLen := utf8.RuneCountInString(text)
|
||||
if c.End-c.Start != expectedRuneLen {
|
||||
t.Errorf("End(%d) - Start(%d) = %d, want rune len %d (byte len would be %d)",
|
||||
c.End, c.Start, c.End-c.Start, expectedRuneLen, len(text))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_ProtectedPattern_ChineseContext(t *testing.T) {
|
||||
// Test protected markdown images in Chinese context.
|
||||
text := "这是前面的中文内容。这是后面的中文内容。"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 || c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: out of rune range [%d, %d), total runes %d",
|
||||
i, c.Start, c.End, len(textRunes))
|
||||
continue
|
||||
}
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: rune-slice mismatch:\n sliced: %q\n content: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_SimulateMergeSlicing(t *testing.T) {
|
||||
// Simulate what merge.go:104-106 does to ensure it won't panic.
|
||||
// This is the exact pattern that caused the production crash.
|
||||
line := "这是第一段内容用于模拟知识库问答的文本"
|
||||
text := line + "\n\n" + line + "\n\n" + line
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 25, ChunkOverlap: 5, Separators: []string{"\n\n", "\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) < 2 {
|
||||
t.Fatalf("need at least 2 chunks for overlap test, got %d", len(chunks))
|
||||
}
|
||||
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
prev := chunks[i-1]
|
||||
curr := chunks[i]
|
||||
|
||||
if curr.Start > prev.End {
|
||||
continue // non-overlapping, no merge needed
|
||||
}
|
||||
|
||||
// This is the exact merge.go logic:
|
||||
contentRunes := []rune(curr.Content)
|
||||
offset := len(contentRunes) - (curr.End - prev.End)
|
||||
|
||||
if offset < 0 {
|
||||
t.Fatalf("chunk[%d] merge panic: offset=%d < 0 (contentRunes=%d, curr.End=%d, prev.End=%d)",
|
||||
i, offset, len(contentRunes), curr.End, prev.End)
|
||||
}
|
||||
if offset > len(contentRunes) {
|
||||
t.Fatalf("chunk[%d] merge panic: offset=%d > len(contentRunes)=%d",
|
||||
i, offset, len(contentRunes))
|
||||
}
|
||||
|
||||
_ = string(contentRunes[offset:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_Empty(t *testing.T) {
|
||||
chunks := SplitText("", DefaultConfig())
|
||||
if len(chunks) != 0 {
|
||||
t.Errorf("expected 0 chunks for empty text, got %d", len(chunks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_SingleCharChinese(t *testing.T) {
|
||||
text := "你"
|
||||
cfg := SplitterConfig{ChunkSize: 10, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("expected 1 chunk, got %d", len(chunks))
|
||||
}
|
||||
if chunks[0].Start != 0 || chunks[0].End != 1 {
|
||||
t.Errorf("expected [0,1), got [%d,%d)", chunks[0].Start, chunks[0].End)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_LaTeXBlockInChinese(t *testing.T) {
|
||||
text := "前面的文字$$E=mc^2$$后面的文字"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
spanLen := c.End - c.Start
|
||||
contentRuneLen := utf8.RuneCountInString(c.Content)
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: span %d != rune len %d", i, spanLen, contentRuneLen)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d > total runes %d", i, c.End, len(textRunes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_CodeBlockInChinese(t *testing.T) {
|
||||
text := "中文描述\n```python\nprint('hello')\n```\n继续中文"
|
||||
cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 0, Separators: []string{"\n\n", "\n"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 || c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: out of range [%d,%d), total %d", i, c.Start, c.End, len(textRunes))
|
||||
continue
|
||||
}
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: rune-slice mismatch:\n sliced: %q\n content: %q",
|
||||
i, sliced, c.Content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_OverlapChunks_NonNegativeStart(t *testing.T) {
|
||||
// When overlap is used, start of the next chunk could go before 0 if broken.
|
||||
text := strings.Repeat("中文测试内容,", 50)
|
||||
cfg := SplitterConfig{ChunkSize: 20, ChunkOverlap: 5, Separators: []string{","}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
for i, c := range chunks {
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: negative Start %d", i, c.Start)
|
||||
}
|
||||
if c.End < c.Start {
|
||||
t.Errorf("chunk[%d]: End %d < Start %d", i, c.End, c.Start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUnitsWithProtection_RuneOffsets(t *testing.T) {
|
||||
text := "你好世界"
|
||||
units := buildUnitsWithProtection(text, nil, []string{"\n"})
|
||||
|
||||
if len(units) != 1 {
|
||||
t.Fatalf("expected 1 unit, got %d", len(units))
|
||||
}
|
||||
|
||||
u := units[0]
|
||||
expectedRuneLen := 4 // 4 Chinese characters
|
||||
byteLen := len(text) // 12 bytes
|
||||
|
||||
if u.start != 0 {
|
||||
t.Errorf("start: got %d, want 0", u.start)
|
||||
}
|
||||
if u.end != expectedRuneLen {
|
||||
t.Errorf("end: got %d, want %d (rune len); byte len is %d", u.end, expectedRuneLen, byteLen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUnitsWithProtection_WithProtectedSpan(t *testing.T) {
|
||||
text := "前面后面"
|
||||
protected := protectedSpans(text)
|
||||
units := buildUnitsWithProtection(text, protected, []string{"\n"})
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, u := range units {
|
||||
contentRuneLen := utf8.RuneCountInString(u.text)
|
||||
spanLen := u.end - u.start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("unit[%d] %q: span %d != rune len %d (byte len %d)",
|
||||
i, u.text, spanLen, contentRuneLen, len(u.text))
|
||||
}
|
||||
if u.start < 0 || u.end > len(textRunes) {
|
||||
t.Errorf("unit[%d]: out of range [%d,%d), total runes %d",
|
||||
i, u.start, u.end, len(textRunes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitBySeparators(t *testing.T) {
|
||||
tests := []struct {
|
||||
text string
|
||||
separators []string
|
||||
wantParts int
|
||||
}{
|
||||
{"a\n\nb\n\nc", []string{"\n\n"}, 5},
|
||||
{"abc", []string{"\n"}, 1},
|
||||
{"a\nb\nc", []string{"\n"}, 5},
|
||||
{"", []string{"\n"}, 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
parts := splitBySeparators(tt.text, tt.separators)
|
||||
if len(parts) != tt.wantParts {
|
||||
t.Errorf("splitBySeparators(%q, %v): got %d parts %v, want %d",
|
||||
tt.text, tt.separators, len(parts), parts, tt.wantParts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractImageRefs(t *testing.T) {
|
||||
text := "hello  world  end"
|
||||
refs := ExtractImageRefs(text)
|
||||
if len(refs) != 2 {
|
||||
t.Fatalf("expected 2 refs, got %d", len(refs))
|
||||
}
|
||||
if refs[0].OriginalRef != "url1" || refs[0].AltText != "alt1" {
|
||||
t.Errorf("ref[0] mismatch: %+v", refs[0])
|
||||
}
|
||||
if refs[1].OriginalRef != "url2" || refs[1].AltText != "alt2" {
|
||||
t.Errorf("ref[1] mismatch: %+v", refs[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitText_LargeChineseDocument(t *testing.T) {
|
||||
// Simulate a real document with paragraphs of Chinese text.
|
||||
var sb strings.Builder
|
||||
for i := 0; i < 100; i++ {
|
||||
sb.WriteString(fmt.Sprintf("第%d段:这是一段用于测试的中文内容,包含各种常见的汉字和标点符号。", i))
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
text := sb.String()
|
||||
|
||||
cfg := SplitterConfig{ChunkSize: 50, ChunkOverlap: 10, Separators: []string{"\n\n", "\n", "。"}}
|
||||
chunks := SplitText(text, cfg)
|
||||
|
||||
textRunes := []rune(text)
|
||||
for i, c := range chunks {
|
||||
contentRuneLen := utf8.RuneCountInString(c.Content)
|
||||
spanLen := c.End - c.Start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk[%d]: End(%d)-Start(%d)=%d != runeLen(%d)",
|
||||
i, c.End, c.Start, spanLen, contentRuneLen)
|
||||
}
|
||||
if c.Start < 0 {
|
||||
t.Errorf("chunk[%d]: negative Start %d", i, c.Start)
|
||||
}
|
||||
if c.End > len(textRunes) {
|
||||
t.Errorf("chunk[%d]: End %d > total runes %d", i, c.End, len(textRunes))
|
||||
}
|
||||
if c.Start >= 0 && c.End <= len(textRunes) {
|
||||
sliced := string(textRunes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk[%d]: content mismatch via rune-slice", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate merge.go logic on all overlapping chunk pairs
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
prev := chunks[i-1]
|
||||
curr := chunks[i]
|
||||
if curr.Start > prev.End {
|
||||
continue
|
||||
}
|
||||
contentRunes := []rune(curr.Content)
|
||||
offset := len(contentRunes) - (curr.End - prev.End)
|
||||
if offset < 0 || offset > len(contentRunes) {
|
||||
t.Fatalf("chunk[%d] merge would panic: offset=%d, contentRunes=%d, curr.End=%d, prev.End=%d",
|
||||
i, offset, len(contentRunes), curr.End, prev.End)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// simpleFormats lists file extensions that Go can handle without the Python service.
|
||||
var simpleFormats = map[string]bool{
|
||||
"md": true, "markdown": true,
|
||||
"txt": true, "text": true,
|
||||
"csv": true,
|
||||
}
|
||||
|
||||
var imageFormats = map[string]bool{
|
||||
"jpg": true, "jpeg": true, "png": true, "gif": true,
|
||||
"bmp": true, "tiff": true, "webp": true,
|
||||
}
|
||||
|
||||
func init() {
|
||||
for k := range imageFormats {
|
||||
simpleFormats[k] = true
|
||||
}
|
||||
}
|
||||
|
||||
// IsSimpleFormat returns true if the file type can be handled by the Go SimpleFormatReader.
|
||||
func IsSimpleFormat(fileType string) bool {
|
||||
return simpleFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
|
||||
}
|
||||
|
||||
// SimpleFormatReader handles simple file formats and images directly in Go,
|
||||
// bypassing the Python docreader service.
|
||||
type SimpleFormatReader struct{}
|
||||
|
||||
// Read reads simple format files and returns markdown.
|
||||
func (b *SimpleFormatReader) Read(_ context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
|
||||
if ft == "" {
|
||||
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
|
||||
}
|
||||
|
||||
switch {
|
||||
case ft == "md" || ft == "markdown":
|
||||
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
|
||||
case ft == "txt" || ft == "text":
|
||||
return &types.ReadResult{MarkdownContent: string(req.FileContent)}, nil
|
||||
case ft == "csv":
|
||||
md, err := csvToMarkdown(req.FileContent)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("csv conversion failed: %w", err)
|
||||
}
|
||||
return &types.ReadResult{MarkdownContent: md}, nil
|
||||
case imageFormats[ft]:
|
||||
return imageToResult(req.FileName, req.FileContent), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported simple format: %s", ft)
|
||||
}
|
||||
}
|
||||
|
||||
// imageToResult wraps a standalone image as a markdown image reference with
|
||||
// the raw bytes in ImageRefs, matching Python ImageParser behaviour.
|
||||
func imageToResult(fileName string, data []byte) *types.ReadResult {
|
||||
if fileName == "" {
|
||||
fileName = "image.png"
|
||||
}
|
||||
refPath := "images/" + fileName
|
||||
mime := http.DetectContentType(data)
|
||||
|
||||
return &types.ReadResult{
|
||||
MarkdownContent: fmt.Sprintf("", fileName, refPath),
|
||||
ImageRefs: []types.ImageRef{
|
||||
{
|
||||
Filename: fileName,
|
||||
OriginalRef: refPath,
|
||||
MimeType: mime,
|
||||
ImageData: data,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// IsImageFormat returns true if the file type is a recognized image format.
|
||||
func IsImageFormat(fileType string) bool {
|
||||
return imageFormats[strings.ToLower(strings.TrimPrefix(fileType, "."))]
|
||||
}
|
||||
|
||||
// ensureOriginalImageRef checks whether the input file is an image and, if the
|
||||
// returned markdown does not already contain a markdown image reference for it,
|
||||
// prepends one and appends the raw bytes to imageRefs. This guarantees that
|
||||
// when MinerU OCRs a standalone image, the downstream chunks still carry the
|
||||
// original image link for retrieval display.
|
||||
func ensureOriginalImageRef(req *types.ReadRequest, mdContent string, imageRefs []types.ImageRef) (string, []types.ImageRef) {
|
||||
ft := strings.ToLower(strings.TrimPrefix(req.FileType, "."))
|
||||
if ft == "" {
|
||||
ft = strings.TrimPrefix(strings.ToLower(filepath.Ext(req.FileName)), ".")
|
||||
}
|
||||
if !imageFormats[ft] {
|
||||
return mdContent, imageRefs
|
||||
}
|
||||
if len(req.FileContent) == 0 {
|
||||
return mdContent, imageRefs
|
||||
}
|
||||
|
||||
fileName := req.FileName
|
||||
if fileName == "" {
|
||||
fileName = "image." + ft
|
||||
}
|
||||
refPath := "images/" + fileName
|
||||
|
||||
if strings.Contains(mdContent, refPath) {
|
||||
return mdContent, imageRefs
|
||||
}
|
||||
|
||||
imgLine := fmt.Sprintf("", fileName, refPath)
|
||||
if strings.TrimSpace(mdContent) == "" {
|
||||
mdContent = imgLine
|
||||
} else {
|
||||
mdContent = imgLine + "\n\n" + mdContent
|
||||
}
|
||||
|
||||
mime := http.DetectContentType(req.FileContent)
|
||||
imageRefs = append(imageRefs, types.ImageRef{
|
||||
Filename: fileName,
|
||||
OriginalRef: refPath,
|
||||
MimeType: mime,
|
||||
ImageData: req.FileContent,
|
||||
})
|
||||
|
||||
return mdContent, imageRefs
|
||||
}
|
||||
|
||||
func csvToMarkdown(data []byte) (string, error) {
|
||||
reader := csv.NewReader(strings.NewReader(string(data)))
|
||||
reader.LazyQuotes = true
|
||||
reader.TrimLeadingSpace = true
|
||||
|
||||
records, err := reader.ReadAll()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
|
||||
// Header row
|
||||
header := records[0]
|
||||
sb.WriteString("| ")
|
||||
sb.WriteString(strings.Join(header, " | "))
|
||||
sb.WriteString(" |\n")
|
||||
|
||||
// Separator
|
||||
sb.WriteString("|")
|
||||
for range header {
|
||||
sb.WriteString(" --- |")
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
|
||||
// Data rows
|
||||
for _, row := range records[1:] {
|
||||
sb.WriteString("| ")
|
||||
// Pad row if shorter than header
|
||||
cells := make([]string, len(header))
|
||||
for i := range cells {
|
||||
if i < len(row) {
|
||||
cells[i] = row[i]
|
||||
}
|
||||
}
|
||||
sb.WriteString(strings.Join(cells, " | "))
|
||||
sb.WriteString(" |\n")
|
||||
}
|
||||
|
||||
return sb.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// EngineRegistration is the interface every locally registered parser engine
|
||||
// must implement. Remote-only engines (e.g. markitdown) are discovered via
|
||||
// the docreader ListEngines RPC and do not need a local registration.
|
||||
type EngineRegistration interface {
|
||||
Name() string
|
||||
Description() string
|
||||
FileTypes(docreaderConnected bool) []string
|
||||
CheckAvailable(docreaderConnected bool, overrides map[string]string) (available bool, reason string)
|
||||
}
|
||||
|
||||
// localEngines holds all locally registered parser engines.
|
||||
var localEngines []EngineRegistration
|
||||
|
||||
// RegisterEngine adds an engine to the local registry. Called in init().
|
||||
func RegisterEngine(e EngineRegistration) {
|
||||
localEngines = append(localEngines, e)
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterEngine(&simpleEngine{})
|
||||
RegisterEngine(&mineruEngine{})
|
||||
RegisterEngine(&mineruCloudEngine{})
|
||||
}
|
||||
|
||||
// SimpleEngineName is the engine name for Go-native simple format handling.
|
||||
const SimpleEngineName = "simple"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// simple — Go handles md/txt/csv natively, no external service needed.
|
||||
// Distinct from docreader's "builtin" which uses Python libraries for
|
||||
// complex formats (docx, pdf, etc.).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type simpleEngine struct{}
|
||||
|
||||
func (e *simpleEngine) Name() string { return SimpleEngineName }
|
||||
func (e *simpleEngine) Description() string { return "简单格式 & 图片解析(无需外部服务)" }
|
||||
func (e *simpleEngine) FileTypes(_ bool) []string {
|
||||
return []string{"md", "markdown", "txt", "csv", "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp"}
|
||||
}
|
||||
func (e *simpleEngine) CheckAvailable(_ bool, _ map[string]string) (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// mineru — Go-native, calls self-hosted MinerU API directly
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type mineruEngine struct{}
|
||||
|
||||
func (e *mineruEngine) Name() string { return "mineru" }
|
||||
func (e *mineruEngine) Description() string { return "MinerU 自部署服务" }
|
||||
func (e *mineruEngine) FileTypes(_ bool) []string {
|
||||
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
|
||||
}
|
||||
func (e *mineruEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
|
||||
endpoint := strings.TrimSpace(overrides["mineru_endpoint"])
|
||||
if endpoint == "" {
|
||||
return false, "未配置 MinerU 服务"
|
||||
}
|
||||
return PingMinerU(endpoint)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// mineru_cloud — Go-native, calls MinerU Cloud API directly
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type mineruCloudEngine struct{}
|
||||
|
||||
func (e *mineruCloudEngine) Name() string { return "mineru_cloud" }
|
||||
func (e *mineruCloudEngine) Description() string { return "MinerU Cloud API" }
|
||||
func (e *mineruCloudEngine) FileTypes(_ bool) []string {
|
||||
return []string{"pdf", "jpg", "jpeg", "png", "bmp", "tiff", "doc", "docx", "ppt", "pptx"}
|
||||
}
|
||||
func (e *mineruCloudEngine) CheckAvailable(_ bool, overrides map[string]string) (bool, string) {
|
||||
apiKey := strings.TrimSpace(overrides["mineru_api_key"])
|
||||
if apiKey == "" {
|
||||
return false, "未配置 MinerU API Key"
|
||||
}
|
||||
return PingMinerUCloud(apiKey, overrides["mineru_api_base_url"])
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ListAllEngines — merge local + remote
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ListAllEngines returns the merged engine list: locally registered engines
|
||||
// plus engines discovered from the remote docreader via ListEngines RPC.
|
||||
//
|
||||
// Merge rules:
|
||||
// - Local engines are always included, with Go-side availability checks.
|
||||
// - For a remote engine whose name matches a local one, the remote's
|
||||
// file_types and description take precedence (the remote service is
|
||||
// authoritative for its own capabilities).
|
||||
// - Remote engines not present locally are appended as-is, enabling
|
||||
// auto-discovery of newly added docreader engines without Go changes.
|
||||
func ListAllEngines(docreaderConnected bool, overrides map[string]string, remoteEngines []types.ParserEngineInfo) []types.ParserEngineInfo {
|
||||
remoteMap := make(map[string]types.ParserEngineInfo, len(remoteEngines))
|
||||
for _, re := range remoteEngines {
|
||||
remoteMap[re.Name] = re
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, len(localEngines))
|
||||
result := make([]types.ParserEngineInfo, 0, len(localEngines)+len(remoteEngines))
|
||||
|
||||
for _, e := range localEngines {
|
||||
name := e.Name()
|
||||
seen[name] = true
|
||||
|
||||
fileTypes := e.FileTypes(docreaderConnected)
|
||||
description := e.Description()
|
||||
|
||||
if re, ok := remoteMap[name]; ok {
|
||||
if len(re.FileTypes) > 0 {
|
||||
fileTypes = re.FileTypes
|
||||
}
|
||||
if re.Description != "" {
|
||||
description = re.Description
|
||||
}
|
||||
}
|
||||
|
||||
available, reason := e.CheckAvailable(docreaderConnected, overrides)
|
||||
result = append(result, types.ParserEngineInfo{
|
||||
Name: name,
|
||||
Description: description,
|
||||
FileTypes: fileTypes,
|
||||
Available: available,
|
||||
UnavailableReason: reason,
|
||||
})
|
||||
}
|
||||
|
||||
for _, re := range remoteEngines {
|
||||
if seen[re.Name] {
|
||||
continue
|
||||
}
|
||||
result = append(result, re)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/docreader/proto"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/resolver"
|
||||
)
|
||||
|
||||
var logger = log.New(os.Stdout, "[DocParser] ", log.LstdFlags|log.Lmicroseconds)
|
||||
|
||||
func getMaxMessageSize() int {
|
||||
if sizeStr := os.Getenv("MAX_FILE_SIZE_MB"); sizeStr != "" {
|
||||
if size, err := strconv.Atoi(sizeStr); err == nil && size > 0 {
|
||||
return size * 1024 * 1024
|
||||
}
|
||||
}
|
||||
return 50 * 1024 * 1024
|
||||
}
|
||||
|
||||
// GRPCDocumentReader implements DocumentReader over gRPC.
|
||||
type GRPCDocumentReader struct {
|
||||
mu sync.RWMutex
|
||||
conn *grpc.ClientConn
|
||||
client proto.DocReaderClient
|
||||
addr string
|
||||
}
|
||||
|
||||
func NewGRPCDocumentReader(addr string) (*GRPCDocumentReader, error) {
|
||||
p := &GRPCDocumentReader{}
|
||||
if addr != "" {
|
||||
if err := p.connect(addr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *GRPCDocumentReader) connect(addr string) error {
|
||||
logger.Printf("INFO: Connecting to docreader at %s", addr)
|
||||
|
||||
maxMsgSize := getMaxMessageSize()
|
||||
opts := []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.MaxCallRecvMsgSize(maxMsgSize),
|
||||
grpc.MaxCallSendMsgSize(maxMsgSize),
|
||||
),
|
||||
}
|
||||
resolver.SetDefaultScheme("dns")
|
||||
|
||||
start := time.Now()
|
||||
conn, err := grpc.Dial("dns:///"+addr, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to docreader: %w", err)
|
||||
}
|
||||
logger.Printf("INFO: Connected to docreader in %v", time.Since(start))
|
||||
|
||||
p.conn = conn
|
||||
p.client = proto.NewDocReaderClient(conn)
|
||||
p.addr = addr
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *GRPCDocumentReader) Reconnect(addr string) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.conn != nil {
|
||||
_ = p.conn.Close()
|
||||
p.conn = nil
|
||||
p.client = nil
|
||||
p.addr = ""
|
||||
}
|
||||
return p.connect(addr)
|
||||
}
|
||||
|
||||
func (p *GRPCDocumentReader) IsConnected() bool {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
return p.conn != nil
|
||||
}
|
||||
|
||||
func (p *GRPCDocumentReader) Close() error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.conn != nil {
|
||||
return p.conn.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var errNotConnected = fmt.Errorf("docreader service not connected")
|
||||
|
||||
func (p *GRPCDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
p.mu.RLock()
|
||||
client := p.client
|
||||
p.mu.RUnlock()
|
||||
if client == nil {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
|
||||
protoReq := &proto.ReadRequest{
|
||||
FileContent: req.FileContent,
|
||||
FileName: req.FileName,
|
||||
FileType: req.FileType,
|
||||
Url: req.URL,
|
||||
Title: req.Title,
|
||||
RequestId: req.RequestID,
|
||||
Config: &proto.ReadConfig{
|
||||
ParserEngine: req.ParserEngine,
|
||||
ParserEngineOverrides: req.ParserEngineOverrides,
|
||||
ImageStorage: req.ImageStorage,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := client.Read(ctx, protoReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gRPC Read failed: %w", err)
|
||||
}
|
||||
return fromProtoReadResponse(resp), nil
|
||||
}
|
||||
|
||||
func (p *GRPCDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
|
||||
p.mu.RLock()
|
||||
client := p.client
|
||||
p.mu.RUnlock()
|
||||
if client == nil {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
|
||||
resp, err := client.ListEngines(ctx, &proto.ListEnginesRequest{ConfigOverrides: overrides})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gRPC ListEngines failed: %w", err)
|
||||
}
|
||||
|
||||
result := make([]types.ParserEngineInfo, 0, len(resp.GetEngines()))
|
||||
for _, e := range resp.GetEngines() {
|
||||
result = append(result, types.ParserEngineInfo{
|
||||
Name: e.GetName(),
|
||||
Description: e.GetDescription(),
|
||||
FileTypes: e.GetFileTypes(),
|
||||
Available: e.GetAvailable(),
|
||||
UnavailableReason: e.GetUnavailableReason(),
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func fromProtoReadResponse(resp *proto.ReadResponse) *types.ReadResult {
|
||||
result := &types.ReadResult{
|
||||
MarkdownContent: resp.GetMarkdownContent(),
|
||||
ImageDirPath: resp.GetImageDirPath(),
|
||||
Metadata: resp.GetMetadata(),
|
||||
Error: resp.GetError(),
|
||||
}
|
||||
|
||||
for _, ref := range resp.GetImageRefs() {
|
||||
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
|
||||
Filename: ref.GetFilename(),
|
||||
OriginalRef: ref.GetOriginalRef(),
|
||||
MimeType: ref.GetMimeType(),
|
||||
StorageKey: ref.GetStorageKey(),
|
||||
ImageData: ref.GetImageData(),
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
PathRead = "/read"
|
||||
PathListEngines = "/list-engines"
|
||||
)
|
||||
|
||||
// --- JSON DTOs ---
|
||||
|
||||
type httpReadConfig struct {
|
||||
ParserEngine string `json:"parser_engine,omitempty"`
|
||||
ParserEngineOverrides map[string]string `json:"parser_engine_overrides,omitempty"`
|
||||
ImageStorage map[string]string `json:"image_storage,omitempty"`
|
||||
}
|
||||
|
||||
type httpReadRequest struct {
|
||||
FileContent string `json:"file_content,omitempty"` // base64
|
||||
FileName string `json:"file_name,omitempty"`
|
||||
FileType string `json:"file_type,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Config *httpReadConfig `json:"config,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
}
|
||||
|
||||
type httpImageRef struct {
|
||||
Filename string `json:"filename"`
|
||||
OriginalRef string `json:"original_ref"`
|
||||
MimeType string `json:"mime_type"`
|
||||
StorageKey string `json:"storage_key,omitempty"`
|
||||
ImageData []byte `json:"image_data,omitempty"`
|
||||
}
|
||||
|
||||
type httpReadResponse struct {
|
||||
MarkdownContent string `json:"markdown_content"`
|
||||
ImageRefs []httpImageRef `json:"image_refs,omitempty"`
|
||||
ImageDirPath string `json:"image_dir_path,omitempty"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// HTTPDocumentReader implements DocumentReader over HTTP/JSON.
|
||||
type HTTPDocumentReader struct {
|
||||
mu sync.RWMutex
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewHTTPDocumentReader(baseURL string) (*HTTPDocumentReader, error) {
|
||||
p := &HTTPDocumentReader{
|
||||
baseURL: strings.TrimSuffix(baseURL, "/"),
|
||||
client: &http.Client{
|
||||
Timeout: 5 * time.Minute,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
MaxIdleConnsPerHost: 5,
|
||||
},
|
||||
},
|
||||
}
|
||||
if p.baseURL != "" {
|
||||
logger.Printf("INFO: HTTP docreader base URL: %s", p.baseURL)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) base() string {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
return p.baseURL
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) Reconnect(addr string) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.baseURL = strings.TrimSuffix(addr, "/")
|
||||
logger.Printf("INFO: HTTP docreader base URL set to %s", p.baseURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) IsConnected() bool {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
return p.baseURL != ""
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) Close() error { return nil }
|
||||
|
||||
type httpListEnginesRequest struct {
|
||||
ConfigOverrides map[string]string `json:"config_overrides,omitempty"`
|
||||
}
|
||||
|
||||
type httpParserEngineInfo struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
FileTypes []string `json:"file_types"`
|
||||
Available bool `json:"available"`
|
||||
UnavailableReason string `json:"unavailable_reason,omitempty"`
|
||||
}
|
||||
|
||||
type httpListEnginesResponse struct {
|
||||
Engines []httpParserEngineInfo `json:"engines"`
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error) {
|
||||
base := p.base()
|
||||
if base == "" {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
|
||||
body := httpListEnginesRequest{ConfigOverrides: overrides}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http marshal list-engines request: %w", err)
|
||||
}
|
||||
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathListEngines, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http new request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := p.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http list-engines failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBytes, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("http list-engines status %d: %s", resp.StatusCode, string(respBytes))
|
||||
}
|
||||
|
||||
var out httpListEnginesResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return nil, fmt.Errorf("http decode list-engines response: %w", err)
|
||||
}
|
||||
|
||||
result := make([]types.ParserEngineInfo, 0, len(out.Engines))
|
||||
for _, e := range out.Engines {
|
||||
result = append(result, types.ParserEngineInfo{
|
||||
Name: e.Name,
|
||||
Description: e.Description,
|
||||
FileTypes: e.FileTypes,
|
||||
Available: e.Available,
|
||||
UnavailableReason: e.UnavailableReason,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func fromHTTPReadResponse(resp *httpReadResponse) *types.ReadResult {
|
||||
result := &types.ReadResult{
|
||||
MarkdownContent: resp.MarkdownContent,
|
||||
ImageDirPath: resp.ImageDirPath,
|
||||
Metadata: resp.Metadata,
|
||||
Error: resp.Error,
|
||||
}
|
||||
for _, ref := range resp.ImageRefs {
|
||||
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
|
||||
Filename: ref.Filename,
|
||||
OriginalRef: ref.OriginalRef,
|
||||
MimeType: ref.MimeType,
|
||||
StorageKey: ref.StorageKey,
|
||||
ImageData: ref.ImageData,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (p *HTTPDocumentReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
base := p.base()
|
||||
if base == "" {
|
||||
return nil, errNotConnected
|
||||
}
|
||||
|
||||
body := httpReadRequest{
|
||||
FileName: req.FileName,
|
||||
FileType: req.FileType,
|
||||
URL: req.URL,
|
||||
Title: req.Title,
|
||||
RequestID: req.RequestID,
|
||||
Config: &httpReadConfig{
|
||||
ParserEngine: req.ParserEngine,
|
||||
ParserEngineOverrides: req.ParserEngineOverrides,
|
||||
ImageStorage: req.ImageStorage,
|
||||
},
|
||||
}
|
||||
if len(req.FileContent) > 0 {
|
||||
body.FileContent = base64.StdEncoding.EncodeToString(req.FileContent)
|
||||
}
|
||||
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http marshal read request: %w", err)
|
||||
}
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, base+PathRead, bytes.NewReader(jsonBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http new request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.ContentLength = int64(len(jsonBody))
|
||||
|
||||
resp, err := p.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http read failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("http read status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
var out httpReadResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return nil, fmt.Errorf("http decode read response: %w", err)
|
||||
}
|
||||
return fromHTTPReadResponse(&out), nil
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var httpImageClient = &http.Client{Timeout: 60 * time.Second}
|
||||
|
||||
// StoredImage describes an image that has been saved to local storage.
|
||||
type StoredImage struct {
|
||||
OriginalRef string // reference in the original markdown
|
||||
LocalPath string // absolute path on disk (/data/files/images/xxx.png)
|
||||
ServingURL string // URL for frontend access (/files/images/xxx.png)
|
||||
MimeType string
|
||||
}
|
||||
|
||||
// ImageResolver reads images from a DocReader ReadResult (temp dir or shared storage)
|
||||
// and saves them to the local file-serving directory, replacing markdown references.
|
||||
type ImageResolver struct {
|
||||
// LocalStorageDir is where images are persisted (e.g. /data/files)
|
||||
LocalStorageDir string
|
||||
// URLPrefix is the HTTP path prefix for serving (e.g. /files)
|
||||
URLPrefix string
|
||||
}
|
||||
|
||||
// NewImageResolver creates a resolver with defaults from environment.
|
||||
func NewImageResolver(localStorageDir, urlPrefix string) *ImageResolver {
|
||||
if localStorageDir == "" {
|
||||
localStorageDir = "/data/files"
|
||||
}
|
||||
if urlPrefix == "" {
|
||||
urlPrefix = "/files"
|
||||
}
|
||||
return &ImageResolver{
|
||||
LocalStorageDir: localStorageDir,
|
||||
URLPrefix: urlPrefix,
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveAndStore reads images from the convert result and persists them.
|
||||
// It returns the updated markdown with replaced image refs and a list of stored images.
|
||||
func (r *ImageResolver) ResolveAndStore(
|
||||
result *types.ReadResult,
|
||||
) (updatedMarkdown string, images []StoredImage, err error) {
|
||||
markdown := result.MarkdownContent
|
||||
if len(result.ImageRefs) == 0 && result.ImageDirPath == "" {
|
||||
return markdown, nil, nil
|
||||
}
|
||||
|
||||
imageDir := filepath.Join(r.LocalStorageDir, "images")
|
||||
if err := os.MkdirAll(imageDir, 0o755); err != nil {
|
||||
return markdown, nil, fmt.Errorf("create image dir: %w", err)
|
||||
}
|
||||
|
||||
// Build a map of original_ref -> image ref for fast lookup
|
||||
refMap := make(map[string]types.ImageRef)
|
||||
for _, ref := range result.ImageRefs {
|
||||
refMap[ref.OriginalRef] = ref
|
||||
}
|
||||
|
||||
// Process each image reference found in the markdown
|
||||
imgPattern := regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
|
||||
matches := imgPattern.FindAllStringSubmatchIndex(markdown, -1)
|
||||
|
||||
// Process in reverse order to preserve positions when replacing
|
||||
for i := len(matches) - 1; i >= 0; i-- {
|
||||
m := matches[i]
|
||||
refPath := markdown[m[4]:m[5]] // group 2: the URL/path
|
||||
|
||||
// Skip already-resolved URLs
|
||||
if strings.HasPrefix(refPath, "http://") || strings.HasPrefix(refPath, "https://") || strings.HasPrefix(refPath, "/files/") {
|
||||
continue
|
||||
}
|
||||
|
||||
// Try to find the image data
|
||||
imgBytes, mimeType, err := r.readImageBytes(result, refPath, refMap)
|
||||
if err != nil || imgBytes == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Determine extension
|
||||
ext := extFromMime(mimeType)
|
||||
if ext == "" {
|
||||
ext = filepath.Ext(refPath)
|
||||
}
|
||||
if ext == "" {
|
||||
ext = ".png"
|
||||
}
|
||||
|
||||
// Save to local storage
|
||||
newName := uuid.New().String() + ext
|
||||
destPath := filepath.Join(imageDir, newName)
|
||||
if writeErr := os.WriteFile(destPath, imgBytes, 0o644); writeErr != nil {
|
||||
logger.Printf("WARN: failed to save image %s: %v", refPath, writeErr)
|
||||
continue
|
||||
}
|
||||
|
||||
servingURL := r.URLPrefix + "/images/" + newName
|
||||
|
||||
images = append(images, StoredImage{
|
||||
OriginalRef: refPath,
|
||||
LocalPath: destPath,
|
||||
ServingURL: servingURL,
|
||||
MimeType: mimeType,
|
||||
})
|
||||
|
||||
// Replace in markdown
|
||||
markdown = markdown[:m[4]] + servingURL + markdown[m[5]:]
|
||||
}
|
||||
|
||||
return markdown, images, nil
|
||||
}
|
||||
|
||||
// readImageBytes resolves image data with cascading fallback:
|
||||
// - Mode A: shared temp directory (same-machine / Docker volume)
|
||||
// - Mode C: inline bytes carried in gRPC response (universal, cross-machine)
|
||||
// - Mode B: shared object storage via storage_key (future)
|
||||
func (r *ImageResolver) readImageBytes(
|
||||
result *types.ReadResult,
|
||||
refPath string,
|
||||
refMap map[string]types.ImageRef,
|
||||
) ([]byte, string, error) {
|
||||
ref, found := refMap[refPath]
|
||||
|
||||
// Mode A: read from shared temp directory
|
||||
if result.ImageDirPath != "" {
|
||||
candidates := []string{
|
||||
filepath.Join(result.ImageDirPath, "images", filepath.Base(refPath)),
|
||||
filepath.Join(result.ImageDirPath, refPath),
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
data, err := os.ReadFile(candidate)
|
||||
if err == nil {
|
||||
mime := "application/octet-stream"
|
||||
if found {
|
||||
mime = ref.MimeType
|
||||
}
|
||||
if mime == "" {
|
||||
mime = mimeFromExt(filepath.Ext(candidate))
|
||||
}
|
||||
return data, mime, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mode C: inline image bytes from gRPC/HTTP response
|
||||
if found && len(ref.ImageData) > 0 {
|
||||
mime := ref.MimeType
|
||||
if mime == "" {
|
||||
mime = mimeFromExt(filepath.Ext(ref.Filename))
|
||||
}
|
||||
return ref.ImageData, mime, nil
|
||||
}
|
||||
|
||||
// Mode B: shared object storage — storage_key is a download URL returned by storage.upload_bytes()
|
||||
if found && ref.StorageKey != "" {
|
||||
data, err := downloadImage(ref.StorageKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("download image from storage %s: %w", ref.StorageKey, err)
|
||||
}
|
||||
mime := ref.MimeType
|
||||
if mime == "" {
|
||||
mime = mimeFromExt(filepath.Ext(ref.Filename))
|
||||
}
|
||||
return data, mime, nil
|
||||
}
|
||||
|
||||
return nil, "", fmt.Errorf("image not found: %s", refPath)
|
||||
}
|
||||
|
||||
func downloadImage(url string) ([]byte, error) {
|
||||
resp, err := httpImageClient.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("HTTP GET: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP %d for %s", resp.StatusCode, url)
|
||||
}
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read body: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func extFromMime(mime string) string {
|
||||
switch mime {
|
||||
case "image/png":
|
||||
return ".png"
|
||||
case "image/jpeg":
|
||||
return ".jpg"
|
||||
case "image/gif":
|
||||
return ".gif"
|
||||
case "image/webp":
|
||||
return ".webp"
|
||||
case "image/bmp":
|
||||
return ".bmp"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func mimeFromExt(ext string) string {
|
||||
switch strings.ToLower(ext) {
|
||||
case ".png":
|
||||
return "image/png"
|
||||
case ".jpg", ".jpeg":
|
||||
return "image/jpeg"
|
||||
case ".gif":
|
||||
return "image/gif"
|
||||
case ".webp":
|
||||
return "image/webp"
|
||||
case ".bmp":
|
||||
return "image/bmp"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPollInterval = 3 * time.Second
|
||||
defaultCloudTimeout = 600 * time.Second
|
||||
defaultBaseURL = "https://mineru.net/api/v4"
|
||||
)
|
||||
|
||||
// MinerUCloudReader calls the MinerU Cloud API (mineru.net) to read/convert documents.
|
||||
// Flow: POST /file-urls/batch → PUT file → poll GET /extract-results/batch/{batch_id}.
|
||||
type MinerUCloudReader struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
model string
|
||||
formulaEnable bool
|
||||
tableEnable bool
|
||||
ocrEnable bool
|
||||
language string
|
||||
}
|
||||
|
||||
// NewMinerUCloudReader creates a reader from ParserEngineOverrides.
|
||||
func NewMinerUCloudReader(overrides map[string]string) *MinerUCloudReader {
|
||||
return &MinerUCloudReader{
|
||||
apiKey: strings.TrimSpace(overrides["mineru_api_key"]),
|
||||
baseURL: strings.TrimRight(stringOr(overrides["mineru_api_base_url"], defaultBaseURL), "/"),
|
||||
model: stringOr(overrides["mineru_cloud_model"], "pipeline"),
|
||||
formulaEnable: parseBoolOr(overrides["mineru_cloud_enable_formula"], true),
|
||||
tableEnable: parseBoolOr(overrides["mineru_cloud_enable_table"], true),
|
||||
ocrEnable: parseBoolOr(overrides["mineru_cloud_enable_ocr"], true),
|
||||
language: stringOr(overrides["mineru_cloud_language"], "ch"),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *MinerUCloudReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
if c.apiKey == "" {
|
||||
return &types.ReadResult{Error: "MinerU Cloud API key is not configured"}, nil
|
||||
}
|
||||
|
||||
content := req.FileContent
|
||||
if len(content) == 0 {
|
||||
return &types.ReadResult{Error: "no file content provided"}, nil
|
||||
}
|
||||
|
||||
logger.Printf("INFO: [MinerUCloud] Parsing file=%s size=%d via %s", req.FileName, len(content), c.baseURL)
|
||||
|
||||
ext := filepath.Ext(req.FileName)
|
||||
if ext == "" && req.FileType != "" {
|
||||
ext = "." + req.FileType
|
||||
}
|
||||
if ext == "" {
|
||||
ext = ".pdf"
|
||||
}
|
||||
fileName := strings.TrimSuffix(req.FileName, ext) + ext
|
||||
if fileName == ext {
|
||||
fileName = "document" + ext
|
||||
}
|
||||
|
||||
batchID, uploadURL, err := c.applyUploadURLs(ctx, fileName, ext)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MinerU Cloud apply upload URLs: %w", err)
|
||||
}
|
||||
|
||||
if err := c.uploadFile(ctx, uploadURL, content); err != nil {
|
||||
return nil, fmt.Errorf("MinerU Cloud file upload: %w", err)
|
||||
}
|
||||
|
||||
mdContent, imageRefs, err := c.pollBatchResult(ctx, batchID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MinerU Cloud poll: %w", err)
|
||||
}
|
||||
|
||||
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
|
||||
|
||||
return &types.ReadResult{
|
||||
MarkdownContent: mdContent,
|
||||
ImageRefs: imageRefs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// --- batch upload API ---
|
||||
|
||||
type batchApplyResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
BatchID string `json:"batch_id"`
|
||||
FileURLs []string `json:"file_urls"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (c *MinerUCloudReader) applyUploadURLs(ctx context.Context, fileName, ext string) (string, string, error) {
|
||||
modelVersion := c.model
|
||||
if strings.ToLower(ext) == ".html" {
|
||||
modelVersion = "MinerU-HTML"
|
||||
}
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"files": []map[string]string{{"name": fileName, "data_id": uuid.New().String()}},
|
||||
"model_version": modelVersion,
|
||||
"is_ocr": c.ocrEnable,
|
||||
"enable_formula": c.formulaEnable,
|
||||
"enable_table": c.tableEnable,
|
||||
"language": c.language,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("marshal payload: %w", err)
|
||||
}
|
||||
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/file-urls/batch", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("HTTP request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return "", "", fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result batchApplyResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return "", "", fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if result.Code != 0 {
|
||||
return "", "", fmt.Errorf("API error: %s", result.Msg)
|
||||
}
|
||||
if len(result.Data.FileURLs) == 0 {
|
||||
return "", "", fmt.Errorf("API returned no file_urls")
|
||||
}
|
||||
|
||||
logger.Printf("INFO: [MinerUCloud] batch apply ok: batch_id=%s, urls=%d", result.Data.BatchID, len(result.Data.FileURLs))
|
||||
return result.Data.BatchID, result.Data.FileURLs[0], nil
|
||||
}
|
||||
|
||||
func (c *MinerUCloudReader) uploadFile(ctx context.Context, uploadURL string, content []byte) error {
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(content))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create PUT request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 120 * time.Second}
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("PUT upload: %w", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("PUT upload status %d", resp.StatusCode)
|
||||
}
|
||||
logger.Printf("INFO: [MinerUCloud] file uploaded, status=%d", resp.StatusCode)
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- polling ---
|
||||
|
||||
type batchPollResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
ExtractResult json.RawMessage `json:"extract_result"` // can be object or array
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type extractResultItem struct {
|
||||
State string `json:"state"`
|
||||
FileName string `json:"file_name"`
|
||||
Markdown string `json:"markdown"`
|
||||
Content string `json:"content"`
|
||||
Text string `json:"text"`
|
||||
ErrMsg string `json:"err_msg"`
|
||||
Progress struct {
|
||||
ExtractedPages int `json:"extracted_pages"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
} `json:"extract_progress"`
|
||||
FullZipURL string `json:"full_zip_url"`
|
||||
}
|
||||
|
||||
func (c *MinerUCloudReader) pollBatchResult(ctx context.Context, batchID string) (string, []types.ImageRef, error) {
|
||||
deadline := time.Now().Add(defaultCloudTimeout)
|
||||
pollCount := 0
|
||||
headers := map[string]string{
|
||||
"Authorization": "Bearer " + c.apiKey,
|
||||
}
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
pollCount++
|
||||
|
||||
items, err := c.fetchBatchStatus(ctx, batchID, headers)
|
||||
if err != nil {
|
||||
logger.Printf("WARN: [MinerUCloud] poll #%d failed: %v", pollCount, err)
|
||||
sleepCtx(ctx, defaultPollInterval)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
if pollCount <= 3 || pollCount%10 == 0 {
|
||||
logger.Printf("INFO: [MinerUCloud] poll #%d: extract_result empty, retrying", pollCount)
|
||||
}
|
||||
sleepCtx(ctx, defaultPollInterval)
|
||||
continue
|
||||
}
|
||||
|
||||
item := items[0]
|
||||
state := strings.ToLower(item.State)
|
||||
|
||||
if pollCount == 1 || pollCount%10 == 0 || state == "done" || state == "failed" {
|
||||
logger.Printf("INFO: [MinerUCloud] poll #%d: file=%s state=%s pages=%d/%d",
|
||||
pollCount, item.FileName, state, item.Progress.ExtractedPages, item.Progress.TotalPages)
|
||||
}
|
||||
|
||||
if state == "failed" {
|
||||
return "", nil, fmt.Errorf("MinerU Cloud task failed: %s", item.ErrMsg)
|
||||
}
|
||||
|
||||
if state == "done" {
|
||||
return c.extractDoneResult(ctx, &item)
|
||||
}
|
||||
|
||||
sleepCtx(ctx, defaultPollInterval)
|
||||
}
|
||||
|
||||
return "", nil, fmt.Errorf("MinerU Cloud task timed out after %d polls", pollCount)
|
||||
}
|
||||
|
||||
func (c *MinerUCloudReader) fetchBatchStatus(ctx context.Context, batchID string, headers map[string]string) ([]extractResultItem, error) {
|
||||
url := fmt.Sprintf("%s/extract-results/batch/%s", c.baseURL, batchID)
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range headers {
|
||||
httpReq.Header.Set(k, v)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read poll response body: %w", err)
|
||||
}
|
||||
|
||||
var pollResp batchPollResponse
|
||||
if err := json.Unmarshal(respBody, &pollResp); err != nil {
|
||||
return nil, fmt.Errorf("decode poll response: %w", err)
|
||||
}
|
||||
if pollResp.Code != 0 {
|
||||
return nil, fmt.Errorf("poll error code=%d msg=%s", pollResp.Code, pollResp.Msg)
|
||||
}
|
||||
|
||||
if len(pollResp.Data.ExtractResult) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Dump the raw extract_result JSON for debugging
|
||||
rawExtract := string(pollResp.Data.ExtractResult)
|
||||
if len(rawExtract) > 4000 {
|
||||
logger.Printf("DEBUG: [MinerUCloud] Raw extract_result (truncated to 4000 chars): %s ...", rawExtract[:4000])
|
||||
} else {
|
||||
logger.Printf("DEBUG: [MinerUCloud] Raw extract_result: %s", rawExtract)
|
||||
}
|
||||
|
||||
// Pretty-print the structure to reveal all available fields
|
||||
var rawObj interface{}
|
||||
if err := json.Unmarshal(pollResp.Data.ExtractResult, &rawObj); err == nil {
|
||||
logCloudResponseStructure(rawObj, "extract_result")
|
||||
}
|
||||
|
||||
// The extract_result can be either a single object or an array
|
||||
var items []extractResultItem
|
||||
if pollResp.Data.ExtractResult[0] == '[' {
|
||||
if err := json.Unmarshal(pollResp.Data.ExtractResult, &items); err != nil {
|
||||
return nil, fmt.Errorf("decode extract_result array: %w", err)
|
||||
}
|
||||
} else {
|
||||
var single extractResultItem
|
||||
if err := json.Unmarshal(pollResp.Data.ExtractResult, &single); err != nil {
|
||||
return nil, fmt.Errorf("decode extract_result object: %w", err)
|
||||
}
|
||||
items = []extractResultItem{single}
|
||||
}
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// extractDoneResult extracts markdown and images from a completed batch item.
|
||||
// Prefers inline markdown/content fields; falls back to downloading full_zip_url.
|
||||
func (c *MinerUCloudReader) extractDoneResult(_ context.Context, item *extractResultItem) (string, []types.ImageRef, error) {
|
||||
text := firstNonEmpty(item.Markdown, item.Content, item.Text)
|
||||
if text != "" {
|
||||
logger.Printf("INFO: [MinerUCloud] parsed (inline), length=%d", len(text))
|
||||
return text, nil, nil
|
||||
}
|
||||
|
||||
if item.FullZipURL == "" {
|
||||
return "", nil, fmt.Errorf("MinerU Cloud state=done but no markdown/content or full_zip_url")
|
||||
}
|
||||
|
||||
md, imageRefs, err := downloadAndExtractZip(item.FullZipURL)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("extract zip: %w", err)
|
||||
}
|
||||
|
||||
logger.Printf("INFO: [MinerUCloud] parsed (zip), markdown=%d chars, images=%d", len(md), len(imageRefs))
|
||||
return md, imageRefs, nil
|
||||
}
|
||||
|
||||
// --- ZIP handling ---
|
||||
|
||||
var imgRefPattern = regexp.MustCompile(`!\[[^\]]*\]\(([^)]+)\)`)
|
||||
|
||||
func downloadAndExtractZip(zipURL string) (string, []types.ImageRef, error) {
|
||||
client := &http.Client{Timeout: 120 * time.Second}
|
||||
resp, err := client.Get(zipURL)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("download zip: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", nil, fmt.Errorf("download zip status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
zipData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("read zip body: %w", err)
|
||||
}
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("open zip: %w", err)
|
||||
}
|
||||
|
||||
// Find .md files
|
||||
var mdFiles []string
|
||||
entries := make(map[string]*zip.File)
|
||||
for _, f := range zr.File {
|
||||
entries[f.Name] = f
|
||||
if strings.HasSuffix(f.Name, ".md") {
|
||||
mdFiles = append(mdFiles, f.Name)
|
||||
}
|
||||
}
|
||||
if len(mdFiles) == 0 {
|
||||
return "", nil, fmt.Errorf("no .md file found in zip")
|
||||
}
|
||||
sort.Slice(mdFiles, func(i, j int) bool {
|
||||
di, dj := strings.Count(mdFiles[i], "/"), strings.Count(mdFiles[j], "/")
|
||||
if di != dj {
|
||||
return di < dj
|
||||
}
|
||||
return mdFiles[i] < mdFiles[j]
|
||||
})
|
||||
|
||||
mdText, err := readZipEntry(entries[mdFiles[0]])
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("read md file: %w", err)
|
||||
}
|
||||
|
||||
mdDir := filepath.Dir(mdFiles[0])
|
||||
|
||||
// Extract referenced images
|
||||
var imageRefs []types.ImageRef
|
||||
seen := map[string]bool{}
|
||||
for _, match := range imgRefPattern.FindAllStringSubmatch(mdText, -1) {
|
||||
imgPath := match[1]
|
||||
if strings.HasPrefix(imgPath, "http://") || strings.HasPrefix(imgPath, "https://") || strings.HasPrefix(imgPath, "data:") {
|
||||
continue
|
||||
}
|
||||
if seen[imgPath] {
|
||||
continue
|
||||
}
|
||||
seen[imgPath] = true
|
||||
|
||||
resolved := resolveInZip(imgPath, mdDir, entries)
|
||||
if resolved == nil {
|
||||
logger.Printf("WARN: [MinerUCloud] image not found in zip: %s", imgPath)
|
||||
continue
|
||||
}
|
||||
|
||||
imgData, err := readZipEntryBytes(resolved)
|
||||
if err != nil {
|
||||
logger.Printf("WARN: [MinerUCloud] failed to read zip image %s: %v", imgPath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(resolved.Name))
|
||||
if ext == "" {
|
||||
ext = ".png"
|
||||
}
|
||||
mimeType := mime.TypeByExtension(ext)
|
||||
if mimeType == "" {
|
||||
mimeType = "image/png"
|
||||
}
|
||||
|
||||
imageRefs = append(imageRefs, types.ImageRef{
|
||||
Filename: filepath.Base(resolved.Name),
|
||||
OriginalRef: imgPath,
|
||||
MimeType: mimeType,
|
||||
ImageData: imgData,
|
||||
})
|
||||
}
|
||||
|
||||
return mdText, imageRefs, nil
|
||||
}
|
||||
|
||||
func resolveInZip(imgPath, mdDir string, entries map[string]*zip.File) *zip.File {
|
||||
normalized := strings.ReplaceAll(imgPath, "\\", "/")
|
||||
if f, ok := entries[normalized]; ok {
|
||||
return f
|
||||
}
|
||||
if mdDir != "" && mdDir != "." {
|
||||
joined := mdDir + "/" + normalized
|
||||
if f, ok := entries[joined]; ok {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readZipEntry(f *zip.File) (string, error) {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rc.Close()
|
||||
data, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func readZipEntryBytes(f *zip.File) ([]byte, error) {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return io.ReadAll(rc)
|
||||
}
|
||||
|
||||
// logCloudResponseStructure recursively logs the structure of the Cloud API response,
|
||||
// truncating large string values to reveal all available fields (e.g. caption, bbox, etc.).
|
||||
func logCloudResponseStructure(obj interface{}, prefix string) {
|
||||
switch v := obj.(type) {
|
||||
case map[string]interface{}:
|
||||
keys := make([]string, 0, len(v))
|
||||
for k := range v {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = {object with %d keys: %s}", prefix, len(v), strings.Join(keys, ", "))
|
||||
for _, key := range keys {
|
||||
val := v[key]
|
||||
path := prefix + "." + key
|
||||
switch inner := val.(type) {
|
||||
case map[string]interface{}:
|
||||
logCloudResponseStructure(inner, path)
|
||||
case []interface{}:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = [array with %d items]", path, len(inner))
|
||||
if len(inner) > 0 {
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s[0] type=%T", path, inner[0])
|
||||
if len(inner) <= 3 {
|
||||
for i, item := range inner {
|
||||
logCloudResponseStructure(item, fmt.Sprintf("%s[%d]", path, i))
|
||||
}
|
||||
} else {
|
||||
logCloudResponseStructure(inner[0], path+"[0]")
|
||||
logger.Printf("DEBUG: [MinerUCloud] ... and %d more items in %s", len(inner)-1, path)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
if len(inner) > 200 {
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = string(%d chars): %.200s...", path, len(inner), inner)
|
||||
} else {
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = %q", path, inner)
|
||||
}
|
||||
case float64:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = %v (number)", path, inner)
|
||||
case bool:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = %v (bool)", path, inner)
|
||||
case nil:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = null", path)
|
||||
default:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = %v (%T)", path, val, val)
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = [array with %d items]", prefix, len(v))
|
||||
if len(v) > 0 {
|
||||
if len(v) <= 3 {
|
||||
for i, item := range v {
|
||||
logCloudResponseStructure(item, fmt.Sprintf("%s[%d]", prefix, i))
|
||||
}
|
||||
} else {
|
||||
logCloudResponseStructure(v[0], prefix+"[0]")
|
||||
logger.Printf("DEBUG: [MinerUCloud] ... and %d more items in %s", len(v)-1, prefix)
|
||||
}
|
||||
}
|
||||
default:
|
||||
logger.Printf("DEBUG: [MinerUCloud] %s = %v (%T)", prefix, v, v)
|
||||
}
|
||||
}
|
||||
|
||||
// PingMinerUCloud checks if the MinerU Cloud API is reachable with the given API key.
|
||||
func PingMinerUCloud(apiKey, baseURL string) (bool, string) {
|
||||
apiKey = strings.TrimSpace(apiKey)
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if apiKey == "" {
|
||||
return false, "未配置 MinerU Cloud API Key"
|
||||
}
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBaseURL
|
||||
}
|
||||
|
||||
// Light probe: request an empty batch to verify credentials
|
||||
payload := []byte(`{"files":[],"model_version":"pipeline"}`)
|
||||
req, err := http.NewRequest(http.MethodPost, baseURL+"/file-urls/batch", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("构建请求失败: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("MinerU Cloud 不可达: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == 401 || resp.StatusCode == 403 {
|
||||
return false, "MinerU Cloud API Key 无效"
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package docparser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
htmltomd "github.com/JohannesKaufmann/html-to-markdown/v2"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const mineruTimeout = 1000 * time.Second // large docs can take a while
|
||||
|
||||
var b64DataURIPattern = regexp.MustCompile(`^data:image/(\w+);base64,(.+)$`)
|
||||
|
||||
// MinerUReader calls a self-hosted MinerU API to read/convert documents.
|
||||
type MinerUReader struct {
|
||||
endpoint string
|
||||
backend string // "pipeline", "vlm-*", "hybrid-*"
|
||||
formulaEnable bool
|
||||
tableEnable bool
|
||||
ocrEnable bool
|
||||
language string
|
||||
}
|
||||
|
||||
// NewMinerUReader creates a reader from ParserEngineOverrides.
|
||||
func NewMinerUReader(overrides map[string]string) *MinerUReader {
|
||||
c := &MinerUReader{
|
||||
endpoint: strings.TrimRight(overrides["mineru_endpoint"], "/"),
|
||||
backend: stringOr(overrides["mineru_model"], "pipeline"),
|
||||
formulaEnable: parseBoolOr(overrides["mineru_enable_formula"], true),
|
||||
tableEnable: parseBoolOr(overrides["mineru_enable_table"], true),
|
||||
ocrEnable: parseBoolOr(overrides["mineru_enable_ocr"], true),
|
||||
language: stringOr(overrides["mineru_language"], "ch"),
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *MinerUReader) Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error) {
|
||||
if c.endpoint == "" {
|
||||
return &types.ReadResult{Error: "MinerU endpoint is not configured"}, nil
|
||||
}
|
||||
|
||||
content := req.FileContent
|
||||
if len(content) == 0 {
|
||||
return &types.ReadResult{Error: "no file content provided"}, nil
|
||||
}
|
||||
|
||||
logger.Printf("INFO: [MinerU] Parsing file=%s size=%d via %s", req.FileName, len(content), c.endpoint)
|
||||
|
||||
mdContent, imagesB64, err := c.callFileParse(ctx, content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MinerU file_parse: %w", err)
|
||||
}
|
||||
|
||||
// HTML -> Markdown conversion (equivalent to Python markdownify)
|
||||
mdContent = htmlToMarkdown(mdContent)
|
||||
|
||||
// Process images: decode base64, build ImageRef list, replace refs in markdown
|
||||
imageRefs, mdContent := c.processImages(mdContent, imagesB64)
|
||||
|
||||
mdContent, imageRefs = ensureOriginalImageRef(req, mdContent, imageRefs)
|
||||
|
||||
logger.Printf("INFO: [MinerU] Parsed successfully, markdown=%d chars, images=%d", len(mdContent), len(imageRefs))
|
||||
|
||||
return &types.ReadResult{
|
||||
MarkdownContent: mdContent,
|
||||
ImageRefs: imageRefs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mineruFileParseResponse mirrors the relevant fields from the MinerU API response.
|
||||
type mineruFileParseResponse struct {
|
||||
Results struct {
|
||||
Files struct {
|
||||
MDContent string `json:"md_content"`
|
||||
Images map[string]string `json:"images"` // path -> "data:image/png;base64,..." or raw base64
|
||||
} `json:"files"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
func (c *MinerUReader) callFileParse(ctx context.Context, content []byte) (string, map[string]string, error) {
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
// Form fields
|
||||
fields := map[string]string{
|
||||
"return_md": "true",
|
||||
"return_images": "true",
|
||||
"table_enable": fmt.Sprintf("%v", c.tableEnable),
|
||||
"formula_enable": fmt.Sprintf("%v", c.formulaEnable),
|
||||
"parse_method": "ocr",
|
||||
"start_page_id": "0",
|
||||
"end_page_id": "99999",
|
||||
"backend": c.backend,
|
||||
"response_format_zip": "false",
|
||||
"return_middle_json": "false",
|
||||
"return_model_output": "false",
|
||||
"return_content_list": "true",
|
||||
}
|
||||
if !c.ocrEnable {
|
||||
fields["parse_method"] = "txt"
|
||||
}
|
||||
if c.language != "" {
|
||||
fields["lang_list"] = c.language
|
||||
}
|
||||
for k, v := range fields {
|
||||
_ = writer.WriteField(k, v)
|
||||
}
|
||||
|
||||
// File part
|
||||
part, err := writer.CreateFormFile("files", "document")
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("create form file: %w", err)
|
||||
}
|
||||
if _, err := part.Write(content); err != nil {
|
||||
return "", nil, fmt.Errorf("write file content: %w", err)
|
||||
}
|
||||
writer.Close()
|
||||
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint+"/file_parse", &body)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
client := &http.Client{Timeout: mineruTimeout}
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("HTTP request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return "", nil, fmt.Errorf("MinerU API status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("read response body: %w", err)
|
||||
}
|
||||
|
||||
// Dump raw response for debugging (truncate if too large)
|
||||
rawStr := string(respBody)
|
||||
if len(rawStr) > 4000 {
|
||||
logger.Printf("DEBUG: [MinerU] Raw response (truncated to 4000 chars): %s ...", rawStr[:4000])
|
||||
} else {
|
||||
logger.Printf("DEBUG: [MinerU] Raw response: %s", rawStr)
|
||||
}
|
||||
|
||||
// Also pretty-print the top-level structure (without large base64 blobs)
|
||||
var rawMap map[string]interface{}
|
||||
if err := json.Unmarshal(respBody, &rawMap); err == nil {
|
||||
c.logResponseStructure(rawMap, "")
|
||||
}
|
||||
|
||||
var result mineruFileParseResponse
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return "", nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
|
||||
return result.Results.Files.MDContent, result.Results.Files.Images, nil
|
||||
}
|
||||
|
||||
// processImages decodes base64 images from MinerU response and returns ImageRef list.
|
||||
// It also replaces image references in the markdown content.
|
||||
func (c *MinerUReader) processImages(mdContent string, imagesB64 map[string]string) ([]types.ImageRef, string) {
|
||||
var refs []types.ImageRef
|
||||
|
||||
for ipath, b64Str := range imagesB64 {
|
||||
originalRef := "images/" + ipath
|
||||
if !strings.Contains(mdContent, originalRef) {
|
||||
continue
|
||||
}
|
||||
|
||||
var imgBytes []byte
|
||||
var ext string
|
||||
|
||||
if m := b64DataURIPattern.FindStringSubmatch(b64Str); len(m) == 3 {
|
||||
ext = m[1]
|
||||
decoded, err := base64.StdEncoding.DecodeString(m[2])
|
||||
if err != nil {
|
||||
logger.Printf("WARN: [MinerU] Failed to decode base64 image %s: %v", ipath, err)
|
||||
continue
|
||||
}
|
||||
imgBytes = decoded
|
||||
} else {
|
||||
// raw base64 without data URI prefix
|
||||
decoded, err := base64.StdEncoding.DecodeString(b64Str)
|
||||
if err != nil {
|
||||
logger.Printf("WARN: [MinerU] Failed to decode raw base64 image %s: %v", ipath, err)
|
||||
continue
|
||||
}
|
||||
imgBytes = decoded
|
||||
ext = strings.TrimPrefix(filepath.Ext(ipath), ".")
|
||||
if ext == "" {
|
||||
ext = "png"
|
||||
}
|
||||
}
|
||||
|
||||
mimeType := mime.TypeByExtension("." + ext)
|
||||
if mimeType == "" {
|
||||
mimeType = "image/png"
|
||||
}
|
||||
|
||||
refs = append(refs, types.ImageRef{
|
||||
Filename: ipath,
|
||||
OriginalRef: originalRef,
|
||||
MimeType: mimeType,
|
||||
ImageData: imgBytes,
|
||||
})
|
||||
}
|
||||
|
||||
return refs, mdContent
|
||||
}
|
||||
|
||||
// logResponseStructure recursively logs the structure of the API response,
|
||||
// truncating large string values to reveal all available fields.
|
||||
func (c *MinerUReader) logResponseStructure(obj interface{}, prefix string) {
|
||||
switch v := obj.(type) {
|
||||
case map[string]interface{}:
|
||||
for key, val := range v {
|
||||
path := prefix + "." + key
|
||||
if path[0] == '.' {
|
||||
path = path[1:]
|
||||
}
|
||||
switch inner := val.(type) {
|
||||
case map[string]interface{}:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = {object with %d keys: %s}", path, len(inner), mapKeys(inner))
|
||||
c.logResponseStructure(inner, path)
|
||||
case []interface{}:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = [array with %d items]", path, len(inner))
|
||||
if len(inner) > 0 {
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s[0] type=%T", path, inner[0])
|
||||
if len(inner) <= 3 {
|
||||
for i, item := range inner {
|
||||
c.logResponseStructure(item, fmt.Sprintf("%s[%d]", path, i))
|
||||
}
|
||||
} else {
|
||||
c.logResponseStructure(inner[0], path+"[0]")
|
||||
logger.Printf("DEBUG: [MinerU] ... and %d more items in %s", len(inner)-1, path)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
if len(inner) > 200 {
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = string(%d chars): %.200s...", path, len(inner), inner)
|
||||
} else {
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = %q", path, inner)
|
||||
}
|
||||
case float64:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = %v (number)", path, inner)
|
||||
case bool:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = %v (bool)", path, inner)
|
||||
case nil:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = null", path)
|
||||
default:
|
||||
logger.Printf("DEBUG: [MinerU] Response field: %s = %v (%T)", path, inner, inner)
|
||||
}
|
||||
}
|
||||
default:
|
||||
logger.Printf("DEBUG: [MinerU] Value at %s: %v (%T)", prefix, v, v)
|
||||
}
|
||||
}
|
||||
|
||||
func mapKeys(m map[string]interface{}) string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
return strings.Join(keys, ", ")
|
||||
}
|
||||
|
||||
// PingMinerU checks if the self-hosted MinerU service is reachable.
|
||||
func PingMinerU(endpoint string) (bool, string) {
|
||||
endpoint = strings.TrimRight(endpoint, "/")
|
||||
if endpoint == "" {
|
||||
return false, "未配置 MinerU 端点"
|
||||
}
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
resp, err := client.Get(endpoint + "/docs")
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("MinerU 服务不可达: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return false, fmt.Sprintf("MinerU 服务返回状态 %d", resp.StatusCode)
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// htmlToMarkdown converts HTML content to markdown.
|
||||
// Falls back to the original content if conversion fails.
|
||||
func htmlToMarkdown(content string) string {
|
||||
md, err := htmltomd.ConvertString(content)
|
||||
if err != nil {
|
||||
logger.Printf("WARN: [MinerU] html-to-markdown conversion failed, using raw content: %v", err)
|
||||
return content
|
||||
}
|
||||
return md
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
func stringOr(val, fallback string) string {
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" {
|
||||
return fallback
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
func parseBoolOr(val string, fallback bool) bool {
|
||||
val = strings.ToLower(strings.TrimSpace(val))
|
||||
if val == "" {
|
||||
return fallback
|
||||
}
|
||||
return val == "true" || val == "1" || val == "yes"
|
||||
}
|
||||
@@ -135,6 +135,10 @@ func Logger() gin.HandlerFunc {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
raw := c.Request.URL.RawQuery
|
||||
if strings.HasPrefix(path, "/assets/") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 读取请求体(在Next之前读取,因为Next会消费body)
|
||||
var requestBody string
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
ollamaapi "github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaVLM implements VLM via the local Ollama service.
|
||||
type OllamaVLM struct {
|
||||
modelName string
|
||||
modelID string
|
||||
ollamaService *ollama.OllamaService
|
||||
}
|
||||
|
||||
// NewOllamaVLM creates an Ollama-backed VLM instance.
|
||||
func NewOllamaVLM(config *Config, ollamaService *ollama.OllamaService) (*OllamaVLM, error) {
|
||||
if ollamaService == nil {
|
||||
return nil, fmt.Errorf("ollama service is required for local VLM model")
|
||||
}
|
||||
return &OllamaVLM{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
ollamaService: ollamaService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Predict sends an image with a text prompt to the Ollama vision model.
|
||||
func (v *OllamaVLM) Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error) {
|
||||
streamFlag := false
|
||||
chatReq := &ollamaapi.ChatRequest{
|
||||
Model: v.modelName,
|
||||
Messages: []ollamaapi.Message{
|
||||
{
|
||||
Role: "user",
|
||||
Content: prompt,
|
||||
Images: []ollamaapi.ImageData{imgBytes},
|
||||
},
|
||||
},
|
||||
Stream: &streamFlag,
|
||||
Options: map[string]interface{}{"temperature": 0.1},
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[VLM] Calling Ollama API, model=%s, imageSize=%d", v.modelName, len(imgBytes))
|
||||
|
||||
var result string
|
||||
err := v.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
result = resp.Message.Content
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Ollama VLM request: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[VLM] Ollama response received, len=%d", len(result))
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (v *OllamaVLM) GetModelName() string { return v.modelName }
|
||||
func (v *OllamaVLM) GetModelID() string { return v.modelID }
|
||||
@@ -0,0 +1,101 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 30 * time.Second
|
||||
defaultMaxToks = 5000
|
||||
defaultTemp = float32(0.1)
|
||||
)
|
||||
|
||||
// RemoteAPIVLM implements VLM via an OpenAI-compatible chat completions API.
|
||||
type RemoteAPIVLM struct {
|
||||
modelName string
|
||||
modelID string
|
||||
client *openai.Client
|
||||
baseURL string
|
||||
}
|
||||
|
||||
// NewRemoteAPIVLM creates a remote-API backed VLM instance.
|
||||
func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) {
|
||||
apiCfg := openai.DefaultConfig(config.APIKey)
|
||||
if config.BaseURL != "" {
|
||||
apiCfg.BaseURL = config.BaseURL
|
||||
}
|
||||
apiCfg.HTTPClient = &http.Client{Timeout: defaultTimeout}
|
||||
|
||||
return &RemoteAPIVLM{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
client: openai.NewClientWithConfig(apiCfg),
|
||||
baseURL: config.BaseURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Predict sends an image with a text prompt to the OpenAI-compatible API.
|
||||
func (v *RemoteAPIVLM) Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error) {
|
||||
mimeType := detectImageMIME(imgBytes)
|
||||
b64 := base64.StdEncoding.EncodeToString(imgBytes)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", mimeType, b64)
|
||||
|
||||
req := openai.ChatCompletionRequest{
|
||||
Model: v.modelName,
|
||||
Messages: []openai.ChatCompletionMessage{
|
||||
{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
MultiContent: []openai.ChatMessagePart{
|
||||
{
|
||||
Type: openai.ChatMessagePartTypeImageURL,
|
||||
ImageURL: &openai.ChatMessageImageURL{
|
||||
URL: dataURI,
|
||||
Detail: openai.ImageURLDetailAuto,
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: openai.ChatMessagePartTypeText,
|
||||
Text: prompt,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
MaxTokens: defaultMaxToks,
|
||||
Temperature: defaultTemp,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[VLM] Calling OpenAI-compatible API, model=%s, baseURL=%s, imageSize=%d",
|
||||
v.modelName, v.baseURL, len(imgBytes))
|
||||
|
||||
resp, err := v.client.CreateChatCompletion(ctx, req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("OpenAI VLM request: %w", err)
|
||||
}
|
||||
if len(resp.Choices) == 0 {
|
||||
return "", fmt.Errorf("OpenAI VLM returned no choices")
|
||||
}
|
||||
|
||||
content := resp.Choices[0].Message.Content
|
||||
logger.Infof(ctx, "[VLM] OpenAI response received, len=%d", len(content))
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func (v *RemoteAPIVLM) GetModelName() string { return v.modelName }
|
||||
func (v *RemoteAPIVLM) GetModelID() string { return v.modelID }
|
||||
|
||||
// detectImageMIME returns the MIME type for the given image bytes.
|
||||
func detectImageMIME(data []byte) string {
|
||||
ct := http.DetectContentType(data)
|
||||
if strings.HasPrefix(ct, "image/") {
|
||||
return ct
|
||||
}
|
||||
return "image/png"
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// VLM defines the interface for Vision Language Model operations.
|
||||
type VLM interface {
|
||||
// Predict sends an image with a text prompt to the VLM and returns the generated text.
|
||||
Predict(ctx context.Context, imgBytes []byte, prompt string) (string, error)
|
||||
|
||||
GetModelName() string
|
||||
GetModelID() string
|
||||
}
|
||||
|
||||
// Config holds the configuration needed to create a VLM instance.
|
||||
type Config struct {
|
||||
Source types.ModelSource
|
||||
BaseURL string
|
||||
ModelName string
|
||||
APIKey string
|
||||
ModelID string
|
||||
InterfaceType string // "ollama" or "openai" (default)
|
||||
}
|
||||
|
||||
// NewVLM creates a VLM instance based on the provided configuration.
|
||||
func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
|
||||
ifType := strings.ToLower(config.InterfaceType)
|
||||
|
||||
if ifType == "ollama" || config.Source == types.ModelSourceLocal {
|
||||
return NewOllamaVLM(config, ollamaService)
|
||||
}
|
||||
return NewRemoteAPIVLM(config)
|
||||
}
|
||||
|
||||
// NewVLMFromLegacyConfig creates a VLM from a legacy VLMConfig (inline BaseURL/APIKey/ModelName).
|
||||
func NewVLMFromLegacyConfig(vlmCfg types.VLMConfig, ollamaService *ollama.OllamaService) (VLM, error) {
|
||||
if !vlmCfg.IsEnabled() {
|
||||
return nil, fmt.Errorf("VLM config is not enabled")
|
||||
}
|
||||
|
||||
ifType := vlmCfg.InterfaceType
|
||||
if ifType == "" {
|
||||
ifType = "openai"
|
||||
}
|
||||
|
||||
source := types.ModelSourceRemote
|
||||
if strings.EqualFold(ifType, "ollama") {
|
||||
source = types.ModelSourceLocal
|
||||
}
|
||||
|
||||
return NewVLM(&Config{
|
||||
Source: source,
|
||||
BaseURL: vlmCfg.BaseURL,
|
||||
ModelName: vlmCfg.ModelName,
|
||||
APIKey: vlmCfg.APIKey,
|
||||
InterfaceType: ifType,
|
||||
}, ollamaService)
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
@@ -12,6 +17,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/handler"
|
||||
"github.com/Tencent/WeKnora/internal/handler/session"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
|
||||
@@ -88,11 +94,19 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
))
|
||||
}
|
||||
|
||||
// 本地存储文件服务(无需认证,用于 <img> 等标签访问图片)
|
||||
serveLocalFiles(r)
|
||||
|
||||
// 前端静态文件(仅 Lite 版本内嵌前端)
|
||||
if handler.Edition == "lite" {
|
||||
serveFrontendStatic(r)
|
||||
}
|
||||
|
||||
// 认证中间件
|
||||
r.Use(middleware.Auth(params.TenantService, params.UserService, params.Config))
|
||||
|
||||
// 添加OpenTelemetry追踪中间件
|
||||
r.Use(middleware.TracingMiddleware())
|
||||
// r.Use(middleware.TracingMiddleware())
|
||||
|
||||
// 需要认证的API路由
|
||||
v1 := r.Group("/api/v1")
|
||||
@@ -173,6 +187,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
|
||||
k.POST("/:id/reparse", handler.ReparseKnowledge)
|
||||
// 获取知识文件
|
||||
k.GET("/:id/download", handler.DownloadKnowledgeFile)
|
||||
// 预览知识文件(内联显示,返回正确 Content-Type)
|
||||
k.GET("/:id/preview", handler.PreviewKnowledgeFile)
|
||||
// 更新图像分块信息
|
||||
k.PUT("/image/:id/:chunk_id", handler.UpdateImageInfo)
|
||||
// 批量更新知识标签
|
||||
@@ -389,6 +405,11 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) {
|
||||
systemRoutes := r.Group("/system")
|
||||
{
|
||||
systemRoutes.GET("/info", handler.GetSystemInfo)
|
||||
systemRoutes.GET("/parser-engines", handler.ListParserEngines)
|
||||
systemRoutes.POST("/parser-engines/check", handler.CheckParserEngines)
|
||||
systemRoutes.POST("/docreader/reconnect", handler.ReconnectDocReader)
|
||||
systemRoutes.GET("/storage-engine-status", handler.GetStorageEngineStatus)
|
||||
systemRoutes.POST("/storage-engine-check", handler.CheckStorageEngine)
|
||||
systemRoutes.GET("/minio/buckets", handler.ListMinioBuckets)
|
||||
}
|
||||
}
|
||||
@@ -538,3 +559,78 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
||||
r.GET("/shared-agents", orgHandler.ListSharedAgents)
|
||||
r.POST("/shared-agents/disabled", orgHandler.SetSharedAgentDisabledByMe)
|
||||
}
|
||||
|
||||
// serveFrontendStatic registers a middleware that serves the frontend SPA
|
||||
// from the ./web directory if it exists. Must be called BEFORE auth middleware
|
||||
// so static files are served without authentication.
|
||||
func serveFrontendStatic(r *gin.Engine) {
|
||||
webDir := os.Getenv("WEKNORA_WEB_DIR")
|
||||
if webDir == "" {
|
||||
webDir = "./web"
|
||||
}
|
||||
absDir, _ := filepath.Abs(webDir)
|
||||
indexPath := filepath.Join(absDir, "index.html")
|
||||
if _, err := os.Stat(indexPath); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(context.Background(), "[Router] Serving frontend static files from %s", absDir)
|
||||
|
||||
fs := http.Dir(absDir)
|
||||
fileServer := http.FileServer(fs)
|
||||
|
||||
r.Use(func(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
path := c.Request.URL.Path
|
||||
if strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/health") || strings.HasPrefix(path, "/swagger/") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
fullPath := filepath.Join(absDir, path)
|
||||
if info, err := os.Stat(fullPath); err == nil && !info.IsDir() {
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.File(indexPath)
|
||||
c.Abort()
|
||||
})
|
||||
}
|
||||
|
||||
// serveLocalFiles serves files from the local storage directory (e.g. /data/files)
|
||||
// at the /files/ URL path. Registered before auth middleware so that <img> tags
|
||||
// in rendered markdown can load images without authentication tokens.
|
||||
func serveLocalFiles(r *gin.Engine) {
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
baseDir = "/data/files"
|
||||
}
|
||||
absDir, _ := filepath.Abs(baseDir)
|
||||
if info, err := os.Stat(absDir); err != nil || !info.IsDir() {
|
||||
if err := os.MkdirAll(absDir, 0o755); err != nil {
|
||||
logger.Warnf(context.Background(), "[Router] Cannot create local storage dir %s: %v", absDir, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(context.Background(), "[Router] Serving local storage files from %s at /files/", absDir)
|
||||
|
||||
r.GET("/files/*filepath", func(c *gin.Context) {
|
||||
reqPath := c.Param("filepath")
|
||||
fullPath := filepath.Join(absDir, filepath.Clean(reqPath))
|
||||
|
||||
if !strings.HasPrefix(fullPath, absDir) {
|
||||
c.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(fullPath)
|
||||
if err != nil || info.IsDir() {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
c.File(fullPath)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
// SyncTaskExecutor executes tasks synchronously (in a goroutine) without Redis.
|
||||
// Used in Lite mode as a drop-in replacement for *asynq.Client.
|
||||
type SyncTaskExecutor struct {
|
||||
mu sync.RWMutex
|
||||
handlers map[string]func(context.Context, *asynq.Task) error
|
||||
}
|
||||
|
||||
func NewSyncTaskExecutor() *SyncTaskExecutor {
|
||||
return &SyncTaskExecutor{
|
||||
handlers: make(map[string]func(context.Context, *asynq.Task) error),
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler registers a handler for a given task type pattern.
|
||||
func (e *SyncTaskExecutor) RegisterHandler(pattern string, handler func(context.Context, *asynq.Task) error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.handlers[pattern] = handler
|
||||
}
|
||||
|
||||
// Enqueue satisfies interfaces.TaskEnqueuer.
|
||||
// Instead of queuing to Redis, it dispatches the task to a goroutine.
|
||||
func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) {
|
||||
e.mu.RLock()
|
||||
handler, ok := e.handlers[task.Type()]
|
||||
e.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("sync task executor: no handler registered for type %q", task.Type())
|
||||
}
|
||||
|
||||
taskID := uuid.New().String()
|
||||
info := &asynq.TaskInfo{
|
||||
ID: taskID,
|
||||
Queue: "sync",
|
||||
Type: task.Type(),
|
||||
}
|
||||
|
||||
go func() {
|
||||
ctx := context.Background()
|
||||
start := time.Now()
|
||||
logger.Infof(ctx, "[SyncTask] Executing task type=%s id=%s", task.Type(), taskID)
|
||||
if err := handler(ctx, task); err != nil {
|
||||
logger.Errorf(ctx, "[SyncTask] Task failed type=%s id=%s elapsed=%v err=%v",
|
||||
task.Type(), taskID, time.Since(start), err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v",
|
||||
task.Type(), taskID, time.Since(start))
|
||||
}
|
||||
}()
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
type SyncTaskParams struct {
|
||||
dig.In
|
||||
|
||||
Executor *SyncTaskExecutor
|
||||
KnowledgeService interfaces.KnowledgeService
|
||||
KnowledgeBaseService interfaces.KnowledgeBaseService
|
||||
TagService interfaces.KnowledgeTagService
|
||||
ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"`
|
||||
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
|
||||
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
|
||||
}
|
||||
|
||||
// RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor.
|
||||
// Used in Lite mode instead of RunAsynqServer.
|
||||
func RegisterSyncHandlers(params SyncTaskParams) {
|
||||
params.Executor.RegisterHandler(types.TypeChunkExtract, params.ChunkExtractor.Handle)
|
||||
params.Executor.RegisterHandler(types.TypeDataTableSummary, params.DataTableSummary.Handle)
|
||||
params.Executor.RegisterHandler(types.TypeDocumentProcess, params.KnowledgeService.ProcessDocument)
|
||||
params.Executor.RegisterHandler(types.TypeFAQImport, params.KnowledgeService.ProcessFAQImport)
|
||||
params.Executor.RegisterHandler(types.TypeQuestionGeneration, params.KnowledgeService.ProcessQuestionGeneration)
|
||||
params.Executor.RegisterHandler(types.TypeSummaryGeneration, params.KnowledgeService.ProcessSummaryGeneration)
|
||||
params.Executor.RegisterHandler(types.TypeKBClone, params.KnowledgeService.ProcessKBClone)
|
||||
params.Executor.RegisterHandler(types.TypeKnowledgeListDelete, params.KnowledgeService.ProcessKnowledgeListDelete)
|
||||
params.Executor.RegisterHandler(types.TypeIndexDelete, params.TagService.ProcessIndexDelete)
|
||||
params.Executor.RegisterHandler(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete)
|
||||
params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle)
|
||||
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
|
||||
}
|
||||
@@ -21,6 +21,7 @@ type AsynqTaskParams struct {
|
||||
TagService interfaces.KnowledgeTagService
|
||||
ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"`
|
||||
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
|
||||
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
|
||||
}
|
||||
|
||||
func getAsynqRedisClientOpt() *asynq.RedisClientOpt {
|
||||
@@ -98,6 +99,9 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
|
||||
// Register KB delete handler
|
||||
mux.HandleFunc(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete)
|
||||
|
||||
// Register image multimodal handler
|
||||
mux.HandleFunc(types.TypeImageMultimodal, params.ImageMultimodal.Handle)
|
||||
|
||||
go func() {
|
||||
// Start the server
|
||||
if err := params.Server.Run(mux); err != nil {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package types
|
||||
|
||||
// ReadRequest is the unified transport-agnostic request for document reading.
|
||||
// Set FileContent for file mode, URL for URL mode.
|
||||
type ReadRequest struct {
|
||||
FileContent []byte
|
||||
FileName string
|
||||
FileType string
|
||||
URL string
|
||||
Title string
|
||||
ParserEngine string
|
||||
RequestID string
|
||||
ParserEngineOverrides map[string]string
|
||||
ImageStorage map[string]string // storage provider config (provider, endpoint, bucket, ...)
|
||||
}
|
||||
|
||||
// ReadResult is the transport-agnostic result of document reading.
|
||||
type ReadResult struct {
|
||||
MarkdownContent string
|
||||
ImageRefs []ImageRef
|
||||
ImageDirPath string
|
||||
Metadata map[string]string
|
||||
Error string
|
||||
}
|
||||
|
||||
// ImageRef represents an image reference extracted from the document.
|
||||
type ImageRef struct {
|
||||
Filename string
|
||||
OriginalRef string
|
||||
MimeType string
|
||||
StorageKey string
|
||||
ImageData []byte // inline image bytes (universal fallback for cross-machine deployments)
|
||||
}
|
||||
|
||||
// ParserEngineInfo describes a registered parser engine.
|
||||
type ParserEngineInfo struct {
|
||||
Name string
|
||||
Description string
|
||||
FileTypes []string
|
||||
Available bool
|
||||
UnavailableReason string
|
||||
}
|
||||
|
||||
// --- Internal types used by chunking pipeline ---
|
||||
|
||||
type DocParserStorageConfig struct {
|
||||
Provider string
|
||||
Region string
|
||||
BucketName string
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
AppID string
|
||||
PathPrefix string
|
||||
Endpoint string
|
||||
}
|
||||
|
||||
type DocParserVLMConfig struct {
|
||||
ModelName string
|
||||
BaseURL string
|
||||
APIKey string
|
||||
InterfaceType string
|
||||
}
|
||||
|
||||
type ParsedChunk struct {
|
||||
Content string
|
||||
Seq int
|
||||
Start int
|
||||
End int
|
||||
Images []ParsedImage
|
||||
ChunkID string // populated by processChunks with the actual DB UUID
|
||||
}
|
||||
|
||||
type ParsedImage struct {
|
||||
URL string
|
||||
Caption string
|
||||
OCRText string
|
||||
OriginalURL string
|
||||
Start int
|
||||
End int
|
||||
}
|
||||
@@ -11,6 +11,7 @@ const (
|
||||
TypeKBDelete = "kb:delete" // 知识库删除任务
|
||||
TypeKnowledgeListDelete = "knowledge:list_delete" // 批量删除知识任务
|
||||
TypeDataTableSummary = "datatable:summary" // 表格摘要任务
|
||||
TypeImageMultimodal = "image:multimodal" // 图片多模态处理任务(OCR + VLM Caption)
|
||||
)
|
||||
|
||||
// ExtractChunkPayload represents the extract chunk task payload
|
||||
@@ -97,6 +98,18 @@ type KnowledgeListDeletePayload struct {
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
}
|
||||
|
||||
// ImageMultimodalPayload represents the image multimodal processing task payload.
|
||||
type ImageMultimodalPayload struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
ChunkID string `json:"chunk_id"` // parent text chunk
|
||||
ImageURL string `json:"image_url"` // serving URL (/files/images/xxx.png)
|
||||
ImageLocalPath string `json:"image_local_path"` // absolute path on disk
|
||||
EnableOCR bool `json:"enable_ocr"`
|
||||
EnableCaption bool `json:"enable_caption"`
|
||||
}
|
||||
|
||||
// KBCloneTaskStatus represents the status of a knowledge base clone task
|
||||
type KBCloneTaskStatus string
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// DocReader is the core interface for reading documents into markdown.
|
||||
type DocReader interface {
|
||||
Read(ctx context.Context, req *types.ReadRequest) (*types.ReadResult, error)
|
||||
}
|
||||
|
||||
// DocumentReader extends DocReader with transport lifecycle management
|
||||
// and remote engine discovery. Used by gRPC/HTTP clients that talk to
|
||||
// the Python docreader service.
|
||||
type DocumentReader interface {
|
||||
DocReader
|
||||
Reconnect(addr string) error
|
||||
IsConnected() bool
|
||||
// ListEngines queries the remote docreader for its registered parser engines.
|
||||
// Returns engines the remote service supports, allowing auto-discovery of
|
||||
// newly added engines without Go code changes.
|
||||
ListEngines(ctx context.Context, overrides map[string]string) ([]types.ParserEngineInfo, error)
|
||||
}
|
||||
@@ -9,6 +9,9 @@ import (
|
||||
// FileService is the interface for file services.
|
||||
// FileService provides methods to save, retrieve, and delete files.
|
||||
type FileService interface {
|
||||
// CheckConnectivity verifies that the storage backend is reachable and
|
||||
// properly configured (e.g. bucket exists, credentials valid).
|
||||
CheckConnectivity(ctx context.Context) error
|
||||
// SaveFile saves a file.
|
||||
SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error)
|
||||
// SaveBytes saves bytes data to a file and returns the file path.
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/models/vlm"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
@@ -29,6 +30,8 @@ type ModelService interface {
|
||||
GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error)
|
||||
// GetChatModel gets a chat model
|
||||
GetChatModel(ctx context.Context, modelId string) (chat.Chat, error)
|
||||
// GetVLMModel gets a vision language model
|
||||
GetVLMModel(ctx context.Context, modelId string) (vlm.VLM, error)
|
||||
}
|
||||
|
||||
// ModelRepository defines the model repository interface
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package interfaces
|
||||
|
||||
import "github.com/hibiken/asynq"
|
||||
|
||||
// TaskEnqueuer abstracts task enqueueing. *asynq.Client satisfies this interface.
|
||||
// For Lite mode (no Redis), a synchronous implementation dispatches tasks inline.
|
||||
type TaskEnqueuer interface {
|
||||
Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error)
|
||||
}
|
||||
@@ -95,6 +95,12 @@ type KnowledgeBaseConfig struct {
|
||||
FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"`
|
||||
}
|
||||
|
||||
// ParserEngineRule maps a set of file types to a specific parser engine.
|
||||
type ParserEngineRule struct {
|
||||
FileTypes []string `yaml:"file_types" json:"file_types"`
|
||||
Engine string `yaml:"engine" json:"engine"`
|
||||
}
|
||||
|
||||
// ChunkingConfig represents the document splitting configuration
|
||||
type ChunkingConfig struct {
|
||||
// Chunk size
|
||||
@@ -105,6 +111,23 @@ type ChunkingConfig struct {
|
||||
Separators []string `yaml:"separators" json:"separators"`
|
||||
// EnableMultimodal (deprecated, kept for backward compatibility with old data)
|
||||
EnableMultimodal bool `yaml:"enable_multimodal,omitempty" json:"enable_multimodal,omitempty"`
|
||||
// ParserEngineRules configures which parser engine to use for each file type.
|
||||
// When empty, the builtin engine is used for all types.
|
||||
ParserEngineRules []ParserEngineRule `yaml:"parser_engine_rules,omitempty" json:"parser_engine_rules,omitempty"`
|
||||
}
|
||||
|
||||
// ResolveParserEngine returns the engine name for the given file type
|
||||
// based on the configured rules. Returns empty string (builtin) when
|
||||
// no rule matches.
|
||||
func (c ChunkingConfig) ResolveParserEngine(fileType string) string {
|
||||
for _, rule := range c.ParserEngineRules {
|
||||
for _, ft := range rule.FileTypes {
|
||||
if ft == fileType {
|
||||
return rule.Engine
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// COSConfig represents the COS configuration
|
||||
|
||||
@@ -11,6 +11,7 @@ const (
|
||||
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss"
|
||||
QdrantRetrieverEngineType RetrieverEngineType = "qdrant"
|
||||
MilvusRetrieverEngineType RetrieverEngineType = "milvus"
|
||||
SQLiteRetrieverEngineType RetrieverEngineType = "sqlite"
|
||||
)
|
||||
|
||||
// RetrieverType represents the type of retriever
|
||||
|
||||
@@ -126,6 +126,9 @@ type SearchResult struct {
|
||||
// MatchedContent is the actual content that was matched in vector search
|
||||
// For FAQ: this is the matched question text (standard or similar question)
|
||||
MatchedContent string `json:"matched_content,omitempty"`
|
||||
|
||||
// KnowledgeBaseID is the ID of the knowledge base this result belongs to
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
}
|
||||
|
||||
// SearchParams represents the search parameters
|
||||
|
||||
@@ -3,6 +3,7 @@ package types
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -31,6 +32,10 @@ var retrieverEngineMapping = map[string][]RetrieverEngineParams{
|
||||
{RetrieverType: VectorRetrieverType, RetrieverEngineType: MilvusRetrieverEngineType},
|
||||
{RetrieverType: KeywordsRetrieverType, RetrieverEngineType: MilvusRetrieverEngineType},
|
||||
},
|
||||
"sqlite": {
|
||||
{RetrieverType: KeywordsRetrieverType, RetrieverEngineType: SQLiteRetrieverEngineType},
|
||||
{RetrieverType: VectorRetrieverType, RetrieverEngineType: SQLiteRetrieverEngineType},
|
||||
},
|
||||
}
|
||||
|
||||
// GetRetrieverEngineMapping returns the retriever engine mapping
|
||||
@@ -89,6 +94,10 @@ type Tenant struct {
|
||||
// Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.
|
||||
// This field is kept for backward compatibility and will be removed in future versions.
|
||||
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
|
||||
// Parser engine config overrides (MinerU endpoint, API key, etc.). Used when parsing documents; overrides env.
|
||||
ParserEngineConfig *ParserEngineConfig `yaml:"parser_engine_config" json:"parser_engine_config" gorm:"type:jsonb"`
|
||||
// Storage engine config: parameters for Local, MinIO, COS. Used for document/file storage and docreader.
|
||||
StorageEngineConfig *StorageEngineConfig `yaml:"storage_engine_config" json:"storage_engine_config" gorm:"type:jsonb"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
// Last updated time
|
||||
@@ -189,3 +198,154 @@ func (c *ConversationConfig) Scan(value interface{}) error {
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// ParserEngineConfig holds tenant-level overrides for document parser engines (e.g. MinerU endpoint, API key).
|
||||
// These values take precedence over environment variables when parsing documents.
|
||||
type ParserEngineConfig struct {
|
||||
DocReaderAddr string `json:"docreader_addr"` // 文档解析服务地址
|
||||
MinerUEndpoint string `json:"mineru_endpoint"` // MinerU 自建服务端点
|
||||
MinerUAPIKey string `json:"mineru_api_key"` // MinerU 云 API Key
|
||||
MinerUAPIBaseURL string `json:"mineru_api_base_url"` // MinerU 云 API Base URL(可选)
|
||||
|
||||
// MinerU 自建解析参数
|
||||
MinerUModel string `json:"mineru_model,omitempty"` // backend: pipeline, vlm-*, hybrid-*
|
||||
MinerUEnableFormula *bool `json:"mineru_enable_formula,omitempty"`
|
||||
MinerUEnableTable *bool `json:"mineru_enable_table,omitempty"`
|
||||
MinerUEnableOCR *bool `json:"mineru_enable_ocr,omitempty"`
|
||||
MinerULanguage string `json:"mineru_language,omitempty"`
|
||||
|
||||
// MinerU 云 API 解析参数
|
||||
MinerUCloudModel string `json:"mineru_cloud_model,omitempty"` // model_version: pipeline, vlm, MinerU-HTML
|
||||
MinerUCloudEnableFormula *bool `json:"mineru_cloud_enable_formula,omitempty"`
|
||||
MinerUCloudEnableTable *bool `json:"mineru_cloud_enable_table,omitempty"`
|
||||
MinerUCloudEnableOCR *bool `json:"mineru_cloud_enable_ocr,omitempty"`
|
||||
MinerUCloudLanguage string `json:"mineru_cloud_language,omitempty"`
|
||||
}
|
||||
|
||||
// ToOverridesMap returns a map suitable for ParserEngineOverrides in parse requests.
|
||||
// Keys are snake_case (mineru_endpoint, mineru_api_key, mineru_api_base_url).
|
||||
func (c *ParserEngineConfig) ToOverridesMap() map[string]string {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]string)
|
||||
if c.MinerUEndpoint != "" {
|
||||
m["mineru_endpoint"] = c.MinerUEndpoint
|
||||
}
|
||||
if c.MinerUAPIKey != "" {
|
||||
m["mineru_api_key"] = c.MinerUAPIKey
|
||||
}
|
||||
if c.MinerUAPIBaseURL != "" {
|
||||
m["mineru_api_base_url"] = c.MinerUAPIBaseURL
|
||||
}
|
||||
if c.MinerUModel != "" {
|
||||
m["mineru_model"] = c.MinerUModel
|
||||
}
|
||||
if c.MinerUEnableFormula != nil {
|
||||
m["mineru_enable_formula"] = fmt.Sprintf("%v", *c.MinerUEnableFormula)
|
||||
}
|
||||
if c.MinerUEnableTable != nil {
|
||||
m["mineru_enable_table"] = fmt.Sprintf("%v", *c.MinerUEnableTable)
|
||||
}
|
||||
if c.MinerUEnableOCR != nil {
|
||||
m["mineru_enable_ocr"] = fmt.Sprintf("%v", *c.MinerUEnableOCR)
|
||||
}
|
||||
if c.MinerULanguage != "" {
|
||||
m["mineru_language"] = c.MinerULanguage
|
||||
}
|
||||
if c.MinerUCloudModel != "" {
|
||||
m["mineru_cloud_model"] = c.MinerUCloudModel
|
||||
}
|
||||
if c.MinerUCloudEnableFormula != nil {
|
||||
m["mineru_cloud_enable_formula"] = fmt.Sprintf("%v", *c.MinerUCloudEnableFormula)
|
||||
}
|
||||
if c.MinerUCloudEnableTable != nil {
|
||||
m["mineru_cloud_enable_table"] = fmt.Sprintf("%v", *c.MinerUCloudEnableTable)
|
||||
}
|
||||
if c.MinerUCloudEnableOCR != nil {
|
||||
m["mineru_cloud_enable_ocr"] = fmt.Sprintf("%v", *c.MinerUCloudEnableOCR)
|
||||
}
|
||||
if c.MinerUCloudLanguage != "" {
|
||||
m["mineru_cloud_language"] = c.MinerUCloudLanguage
|
||||
}
|
||||
if len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for ParserEngineConfig
|
||||
func (c *ParserEngineConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface for ParserEngineConfig
|
||||
func (c *ParserEngineConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, and COS.
|
||||
// Knowledge bases select which provider to use; parameters are read from here.
|
||||
type StorageEngineConfig struct {
|
||||
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos"
|
||||
Local *LocalEngineConfig `json:"local,omitempty"`
|
||||
MinIO *MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *COSEngineConfig `json:"cos,omitempty"`
|
||||
}
|
||||
|
||||
// LocalEngineConfig is for local file system storage (single-machine deployment only).
|
||||
type LocalEngineConfig struct {
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// MinIOEngineConfig is for MinIO/S3-compatible object storage.
|
||||
// Mode "docker" uses env vars for endpoint/credentials; "remote" uses the fields below.
|
||||
type MinIOEngineConfig struct {
|
||||
Mode string `json:"mode"` // "docker" or "remote"
|
||||
Endpoint string `json:"endpoint"`
|
||||
AccessKeyID string `json:"access_key_id"`
|
||||
SecretAccessKey string `json:"secret_access_key"`
|
||||
BucketName string `json:"bucket_name"`
|
||||
UseSSL bool `json:"use_ssl"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// COSEngineConfig is for Tencent Cloud COS.
|
||||
type COSEngineConfig struct {
|
||||
SecretID string `json:"secret_id"`
|
||||
SecretKey string `json:"secret_key"`
|
||||
Region string `json:"region"`
|
||||
BucketName string `json:"bucket_name"`
|
||||
AppID string `json:"app_id"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for StorageEngineConfig
|
||||
func (c *StorageEngineConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface for StorageEngineConfig
|
||||
func (c *StorageEngineConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user