2026-02-28 05:22:07 +00:00
|
|
|
package docparser
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
2026-06-02 01:50:09 +00:00
|
|
|
"io"
|
2026-02-28 05:22:07 +00:00
|
|
|
"os"
|
|
|
|
|
"strconv"
|
|
|
|
|
"sync"
|
|
|
|
|
"time"
|
|
|
|
|
|
2026-05-16 13:39:10 +00:00
|
|
|
docclient "github.com/Tencent/WeKnora/docreader/client"
|
2026-02-28 05:22:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/docreader/proto"
|
2026-04-14 09:13:16 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2026-02-28 05:22:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"google.golang.org/grpc"
|
2026-06-03 04:26:16 +00:00
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
|
"google.golang.org/grpc/status"
|
2026-02-28 05:22:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
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 {
|
2026-05-16 13:39:10 +00:00
|
|
|
authConfig := docclient.LoadAuthConfigFromEnv()
|
|
|
|
|
opts, err := authConfig.BuildDialOptions(getMaxMessageSize())
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to build docreader dial options: %w", err)
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
2026-05-16 13:39:10 +00:00
|
|
|
if authConfig.TLSEnabled {
|
2026-05-16 09:49:31 +00:00
|
|
|
logger.Infof(context.Background(), "TLS enabled for docreader gRPC client")
|
|
|
|
|
}
|
2026-05-16 13:39:10 +00:00
|
|
|
if authConfig.AuthToken != "" {
|
|
|
|
|
logger.Infof(context.Background(),
|
|
|
|
|
"Token authentication enabled for docreader gRPC client (TLS=%v)",
|
|
|
|
|
authConfig.TLSEnabled,
|
|
|
|
|
)
|
2026-05-16 09:49:31 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-28 05:22:07 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
conn, err := grpc.Dial("dns:///"+addr, opts...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to connect to docreader: %w", err)
|
|
|
|
|
}
|
2026-04-14 09:13:16 +00:00
|
|
|
logger.Infof(context.Background(), "Connected to docreader in %v", time.Since(start))
|
2026-02-28 05:22:07 +00:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-27 12:32:26 +00:00
|
|
|
var errNotConnected = status.Error(codes.Unavailable, "docreader service not connected")
|
2026-02-28 05:22:07 +00:00
|
|
|
|
|
|
|
|
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,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-02 01:50:09 +00:00
|
|
|
// Use the streaming RPC so documents with many page images (large scanned
|
|
|
|
|
// PDFs) are not capped by the unary message-size limit. The meta frame
|
|
|
|
|
// arrives first, followed by one frame per image.
|
2026-06-03 04:26:16 +00:00
|
|
|
result, err := p.readStream(ctx, client, protoReq)
|
|
|
|
|
if err != nil {
|
|
|
|
|
// An older docreader build may not implement ReadStream. Fall back to
|
|
|
|
|
// the unary Read RPC so a version-skewed deployment still parses
|
|
|
|
|
// documents (small/medium docs only — the unary path remains capped by
|
|
|
|
|
// the gRPC message-size limit, which is exactly what streaming avoids).
|
|
|
|
|
if status.Code(err) == codes.Unimplemented {
|
|
|
|
|
logger.Warnf(ctx, "docreader ReadStream unimplemented, falling back to unary Read: %v", err)
|
|
|
|
|
return p.readUnary(ctx, client, protoReq)
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// readStream consumes the server-streaming ReadStream RPC: one meta frame
|
|
|
|
|
// followed by one frame per image. Errors are returned verbatim so the caller
|
|
|
|
|
// can inspect the gRPC status code (e.g. Unimplemented) for fallback.
|
|
|
|
|
func (p *GRPCDocumentReader) readStream(
|
|
|
|
|
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
|
|
|
|
|
) (*types.ReadResult, error) {
|
2026-06-02 01:50:09 +00:00
|
|
|
stream, err := client.ReadStream(ctx, protoReq)
|
2026-02-28 05:22:07 +00:00
|
|
|
if err != nil {
|
2026-06-02 01:50:09 +00:00
|
|
|
return nil, fmt.Errorf("gRPC ReadStream failed: %w", err)
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
2026-06-02 01:50:09 +00:00
|
|
|
|
|
|
|
|
result := &types.ReadResult{}
|
|
|
|
|
gotMeta := false
|
|
|
|
|
for {
|
|
|
|
|
frame, recvErr := stream.Recv()
|
|
|
|
|
if recvErr == io.EOF {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
if recvErr != nil {
|
|
|
|
|
return nil, fmt.Errorf("gRPC ReadStream recv failed: %w", recvErr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if meta := frame.GetMeta(); meta != nil {
|
|
|
|
|
gotMeta = true
|
|
|
|
|
result.MarkdownContent = meta.GetMarkdownContent()
|
|
|
|
|
result.ImageDirPath = meta.GetImageDirPath()
|
|
|
|
|
result.Metadata = meta.GetMetadata()
|
|
|
|
|
result.Error = meta.GetError()
|
feat(chat): open cited documents at the cited passage (#3700)
* feat(chat): open cited documents at the cited passage
Clicking a citation used to show only the parsed chunk. It now opens the
original file in the references panel, jumps to the cited place and
highlights it, narrowed to the sentence the citation supports.
Parsing records where each chunk sits in the original file
(chunks.source_locators): PDF page and paragraph boxes from the docreader,
MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and
EPUB chapters aligned in Go against any parser engine's Markdown; text
offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites
are followed with a line-diff remapper. Scanned PDF pages get their OCR
text as quotes at search time so a sentence can pick its page.
The frontend renders PDFs with pdf.js and every other previewable type
with the existing preview, then highlights with the CSS Custom Highlight
API in a highlighter yellow that stays visible against the brand green.
* fix(docreader): serialize source blocks outside main so tests import it
test_docx_tables stubs docreader.parser in sys.modules, so importing
docreader.main from a later test failed in the full unittest discover run.
The wire conversion now lives in docreader.source_wire, which needs only
the proto.
* fix(chat): tighten source locators from review
- Remap rewritten-line-for-line stretches by line so scanned PDF pages
no longer drift onto the wrong page.
- Keep the source preview mounted for citations in the file already open.
- Wait for in-flight PDF page renders before looking for the text layer.
- Count image rune offsets in one pass; stream xlsx rows up to maxUnits.
- Start text locators after a UTF-8 BOM, as viewers decode without it.
- Only re-query image children for scanned-page results.
- Seek audio citations without autoplay and drop stale seek listeners.
- Fix the SQLite migration's cross-reference to versioned/000113.
* fix(migrations): renumber chunk source locators after main's chunk_images
main took versioned 000113 and sqlite 000032 for chunk_images, so the
source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
|
|
|
result.SourceBlocks = sourceBlocksFromProto(meta.GetSourceBlocks())
|
2026-06-02 01:50:09 +00:00
|
|
|
if n := meta.GetImageCount(); n > 0 {
|
|
|
|
|
result.ImageRefs = make([]types.ImageRef, 0, n)
|
|
|
|
|
}
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if img := frame.GetImage(); img != nil {
|
|
|
|
|
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
|
|
|
|
|
Filename: img.GetFilename(),
|
|
|
|
|
OriginalRef: img.GetOriginalRef(),
|
|
|
|
|
MimeType: img.GetMimeType(),
|
|
|
|
|
StorageKey: img.GetStorageKey(),
|
|
|
|
|
ImageData: img.GetImageData(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if !gotMeta {
|
|
|
|
|
return nil, fmt.Errorf("gRPC ReadStream returned no metadata frame")
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
2026-06-03 04:26:16 +00:00
|
|
|
// readUnary calls the legacy unary Read RPC. Used only as a compatibility
|
|
|
|
|
// fallback when the connected docreader does not implement ReadStream.
|
|
|
|
|
func (p *GRPCDocumentReader) readUnary(
|
|
|
|
|
ctx context.Context, client proto.DocReaderClient, protoReq *proto.ReadRequest,
|
|
|
|
|
) (*types.ReadResult, error) {
|
|
|
|
|
resp, err := client.Read(ctx, protoReq)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("gRPC Read failed: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
result := &types.ReadResult{
|
|
|
|
|
MarkdownContent: resp.GetMarkdownContent(),
|
|
|
|
|
ImageDirPath: resp.GetImageDirPath(),
|
|
|
|
|
Metadata: resp.GetMetadata(),
|
|
|
|
|
Error: resp.GetError(),
|
feat(chat): open cited documents at the cited passage (#3700)
* feat(chat): open cited documents at the cited passage
Clicking a citation used to show only the parsed chunk. It now opens the
original file in the references panel, jumps to the cited place and
highlights it, narrowed to the sentence the citation supports.
Parsing records where each chunk sits in the original file
(chunks.source_locators): PDF page and paragraph boxes from the docreader,
MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and
EPUB chapters aligned in Go against any parser engine's Markdown; text
offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites
are followed with a line-diff remapper. Scanned PDF pages get their OCR
text as quotes at search time so a sentence can pick its page.
The frontend renders PDFs with pdf.js and every other previewable type
with the existing preview, then highlights with the CSS Custom Highlight
API in a highlighter yellow that stays visible against the brand green.
* fix(docreader): serialize source blocks outside main so tests import it
test_docx_tables stubs docreader.parser in sys.modules, so importing
docreader.main from a later test failed in the full unittest discover run.
The wire conversion now lives in docreader.source_wire, which needs only
the proto.
* fix(chat): tighten source locators from review
- Remap rewritten-line-for-line stretches by line so scanned PDF pages
no longer drift onto the wrong page.
- Keep the source preview mounted for citations in the file already open.
- Wait for in-flight PDF page renders before looking for the text layer.
- Count image rune offsets in one pass; stream xlsx rows up to maxUnits.
- Start text locators after a UTF-8 BOM, as viewers decode without it.
- Only re-query image children for scanned-page results.
- Seek audio citations without autoplay and drop stale seek listeners.
- Fix the SQLite migration's cross-reference to versioned/000113.
* fix(migrations): renumber chunk source locators after main's chunk_images
main took versioned 000113 and sqlite 000032 for chunk_images, so the
source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
|
|
|
SourceBlocks: sourceBlocksFromProto(resp.GetSourceBlocks()),
|
2026-06-03 04:26:16 +00:00
|
|
|
}
|
|
|
|
|
if refs := resp.GetImageRefs(); len(refs) > 0 {
|
|
|
|
|
result.ImageRefs = make([]types.ImageRef, 0, len(refs))
|
|
|
|
|
for _, img := range refs {
|
|
|
|
|
result.ImageRefs = append(result.ImageRefs, types.ImageRef{
|
|
|
|
|
Filename: img.GetFilename(),
|
|
|
|
|
OriginalRef: img.GetOriginalRef(),
|
|
|
|
|
MimeType: img.GetMimeType(),
|
|
|
|
|
StorageKey: img.GetStorageKey(),
|
|
|
|
|
ImageData: img.GetImageData(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-28 05:22:07 +00:00
|
|
|
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
|
|
|
|
|
}
|