Files
ragflow/internal/ingestion/component/media_dispatch.go
Jack 554925b583 Fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain + Chunker) (#17349)
## Summary
Aligns the Go ingestion pipeline with the Python implementation, closing
several behavioral gaps found during the Python→Go migration (tracked in
`docs/migration_python_go_diff.md`). Covers parser/media dispatch
alignment, the PDF coordinate-chain (preview images, outline→title,
chunk coordinate finalization), and the Chunker Token/QA batches below.

Commits are grouped as follows.

### 1. Fix parser params (c524f450e)
Fixes parser/media wiring and several dispatch gaps:
- **docx/pdf vision dispatch**: correct parameter handling and VLM
invocation.
- **markdown vision (diff 2.5)**: also enhance items whose
`doc_type_kwd` is `table`, not only `image` (parser/utils.py:181).
- **media audio (diff 2.11)**: when `output_format` is `json`, carry the
ASR transcription as a JSON item instead of only the `Text` field (the
Invoke switch had no `json` branch and dropped it).
- **email (diff 2.2)**: default `output_format` is `json`
(parser.py:212), not `text`.
- **tokenizer**: handle empty/whitespace-only names; trim before
embedding.
- **extractor**: tag-matching parameter wiring.
- **split**: keyword-split regex now covers CJK/English separators.
- **parser.go**: parser-param plumbing.

### 2. fix parser gap (373537da1)
Image dispatch now mirrors `rag/app/picture.py:chunk()`:
- Always OCR the image (PaddleOCR or local ONNX).
- When OCR text is short, also call VLM (`describe`) and combine `OCR +
VLM` text.
- Emits a **structured JSON item** carrying the image data-URI and
`doc_type_kwd:"image"`, instead of a bare `Text` string. This fixes the
payload being rejected downstream by OneChunker/TokenChunker (JSON=nil).

### 3. PDF coordinate-chain fixes (55367a820, 727f8167c)
Closes three items from the migration tracker in the
chunker/tokenizer/task layer:

- **(Chunker-1.3) `restore_pdf_text_previews`** — `needsCrop` now also
returns true for `text` chunks that carry PDF positions
(`pdfcrop_cgo.go`), so text blocks get a rendered preview image uploaded
to storage via `imageUploadDecorator`/`ChunkImageUploader`, matching
Python `restore_pdf_text_previews` + `image2id`.

- **(Chunker-1.5) PDF outline → title levels** — `title.go` adds
`outlineSimilarity` (rune-bigram Jaccard, mirroring
`common.py:_outline_similarity`), `resolveOutlineLevels` (matches text
lines to outline entries at similarity > 0.8, with a sparse guard
`len(outline)/len(records) <= 0.03`), and `outlineFromInputs` (reads
`file.outline`). Wired into `newLevelContext` in both `group.go` and
`hierarchy.go`; falls back to the title-shape heuristic when no outline
is present.

- **(Tokenizer-(T)1) `finalize_pdf_chunk`** — the coordinate →
`position_int`/`page_num_int`/`top_int` conversion is owned by the task
layer (`processChunkPositions`→`AddPositions`), which runs *after* the
tokenizer and consumes the tokenizer-owned fields. The tokenizer only
preserves the raw `positions`/`_pdf_positions` (no duplicate
conversion), pinned by `TestChunkDocsToMaps_PreservesPDFPositions`.

### 4. Integration test made environment-free
(`internal/ingestion/task/pipeline_real_integration_test.go`)
- Removed the `//go:build integration` tag so the contract tests run
under the default `build.sh --test` (which does not pass `-tags
integration`).
- External dependencies replaced with in-memory substitutes so no
MySQL/MinIO/ES is required:
- MySQL → on-disk sqlite (`glebarez/sqlite`) with the needed tables
auto-migrated.
  - MinIO → `storage.NewMemoryStorage()`.
- Elasticsearch → chunks captured via `WithInsertFunc` instead of
`engine.InsertChunks`/`Search`.
- `requireTokenizerPool` still skips gracefully when the native
tokenizer pool is unavailable; `WithLogCreateFunc(noop)` avoids
depending on the operation-log table.
- Added `taskChunkFieldEqualsStr` to tolerate `kb_id` being a
`[]string`/`[]any` in the raw chunk payload (the search engine flattens
it to a string on read).

### 5. TokenChunker alignment — Batch 1
(`internal/ingestion/component/chunker/token.go`)
Closes four Chunker items from the migration tracker:
- **(Chunker-2.1) sentence delimiter** — the boundary regex now also
breaks on ASCII `!`/`?`. Extracted to a package-level `var
sentenceDelimiter` and used in `mergeByTokenSize`, matching Python's
full delimiter set.
- **(Chunker-2.2) overlap tag leakage** — when a new chunk starts, its
overlap prefix is taken from the previous chunk *after* `removeTag`, in
both the text path (`mergeByTokenSize`) and the JSON path
(`mergeByTokenSizeFromJSON`). Parser tags (`@@…##`) no longer leak into
the overlap region (mirrors `nlp/__init__.py:1181`).
- **(Chunker-2.11) empty-text merge** — merging a non-empty chunk into
an empty previous chunk now assigns the text directly instead of being
skipped (`mergeByTokenSizeFromJSON`), mirroring
`token_chunker.py:236-239`.
- **(Chunker-2.4) overlap token counting** —
`takeFromEnd`/`takeFromStart` now count tokens exactly via `tokenizeStr`
instead of the 4-bytes/token heuristic, fixing over-counting for CJK
text.

### 6. QA Chunker alignment — Batch 2
(`internal/ingestion/component/chunker/qa.go` + `schema`)
Closes three Chunker items from the migration tracker:
- **(Chunker-2.13) default language** — an empty `lang` now defaults to
Chinese prefixes (`问题:`/`回答:`) instead of English, matching `qa.py:299`.
- **(Chunker-2.12) `rmQAPrefix` regex** — the separator is changed to
`[\t:: ]+` (one-or-more), matching `qa.py:241`, so multiple separators
(e.g. `Q:: answer`) are fully stripped.
- **(Chunker-1.8 QA) missing chunk fields** — QA chunks now preserve:
- `top_int` — the source row/record index, threaded through the
tab/csv/markdown extractors (mirrors `qa.py` `beAdoc(..., row_num=i)`);
  - `image` + `doc_type_kwd:"image"`;
  - `_pdf_positions` / `positions` carried from the upstream JSON item.
`schema.ChunkDoc` gains a `TopInt []int` field (serialized as `top_int`,
registered in `UnmarshalJSON`). Note: the Tag/Table/Presentation/One
chunker field gaps under 1.8 remain pending.

## Test plan
- Added/updated unit tests: `pdfcrop_cgo_test.go` (`TestNeedsCrop`,
`TestRestorePDFTextPreview`), `title_test.go`
(`TestResolveOutlineLevels`, `TestResolveOutlineLevels_SparseGuard`,
`TestNewLevelContext_OutlineBranch`, `TestOutlineFromInputs`),
`tokenizer_unit_test.go` (`TestChunkDocsToMaps_PreservesPDFPositions`),
`token_pdfpos_test.go`.
- **Batch 1** — `token_batch1_test.go`:
`TestSentenceDelimiterMatchesBangAndQuestion`,
`TestMergeByTokenSizeFromJSON_OverlapStripsTags`,
`TestMergeByTokenSizeFromJSON_EmptyPrevKeepsChunk`,
`TestTakeFromEndRespectsTokenCount`,
`TestTakeFromStartRespectsTokenCount`.
- **Batch 2** — `qa_batch2_test.go`:
`TestQAChunker_DefaultLangIsChinese`,
`TestRmQAPrefixStripsMultipleSeparators`, `TestQAChunker_SetsTopInt`,
`TestQAChunker_CarriesImageAndPositions`. Existing `qa_test.go`
expectations were updated to the corrected language default / separator
behavior.
- `pipeline_real_integration_test.go`
(`TestPipelineExecutor_Run_RealCanvasDSL_UsesGeneralPipeline`,
`TestPipelineExecutor_Run_RealPDF_ProducesIndexedChunks`,
`TestRunPipeline_RealPipelineOutput_ProducesIndexFields`) now runs
without any external service.
- `bash build.sh --test ./internal/ingestion/...` passes.
- No files deleted.
2026-07-24 21:06:38 +08:00

626 lines
18 KiB
Go

//
// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Media dispatch: image, audio, video parser branches that require
// model access (OCR, IMAGE2TEXT, SPEECH2TEXT) at the component
// layer. Mirrors Python's _image / _audio / _video methods in
// rag/flow/parser/parser.py and rag/app/picture.py.
//
// These follow the maybeDispatchPDFVision pattern: they bypass
// dispatchParse and call the model directly from the component
// layer, returning a parserDispatchResult.
package component
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"image"
// Import image decoders for common formats.
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"os"
"path/filepath"
"sort"
"strings"
"ragflow/internal/common"
inference "ragflow/internal/deepdoc/parser/pdf/inference"
"ragflow/internal/entity"
modelModule "ragflow/internal/entity/models"
"ragflow/internal/ingestion/component/schema"
"ragflow/internal/parser/parser"
"ragflow/internal/utility"
)
// Video dispatch: IMAGE2TEXT vision chat ---
func maybeDispatchVideo(
ctx context.Context,
fileType utility.FileType,
filename string,
binary []byte,
inputs map[string]any,
setups map[string]schema.ParserSetup,
) (parserDispatchResult, bool, error) {
if fileType != utility.FileTypeVIDEO {
return parserDispatchResult{}, false, nil
}
setup, ok := setups["video"]
if !ok {
return parserDispatchResult{}, false, nil
}
tenantID := getStringOr(inputs, "tenant_id", "")
if tenantID == "" {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: video requires tenant_id")
}
// Resolve the tenant's IMAGE2TEXT model.
driver, modelName, apiConfig, _, err := resolveTenantModelByType(tenantID, entity.ModelTypeImage2Text)
if err != nil {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: video image2text model: %w", err)
}
videoPrompt, _ := setup["prompt"].(string)
videoB64 := base64.StdEncoding.EncodeToString(binary)
// Build a multimodal message with the video payload.
// Python uses cv_mdl.async_chat(video_bytes=blob, ...);
// Go ChatWithMessages is synchronous and uses a data URI.
mimeType := videoMIME(filename)
dataURI := "data:" + mimeType + ";base64," + videoB64
messages := []modelModule.Message{{
Role: "user",
Content: []interface{}{
map[string]any{"type": "text", "text": videoPrompt},
map[string]any{"type": "video_url", "video_url": map[string]any{"url": dataURI}},
},
}}
vision := true
resp, err := driver.ChatWithMessages(ctx, modelName, messages, apiConfig, &modelModule.ChatConfig{Vision: &vision}, nil)
if err != nil {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: video describe: %w", err)
}
txt := ""
if resp != nil && resp.Answer != nil {
txt = strings.TrimSpace(*resp.Answer)
}
outputFormat, _ := setup["output_format"].(string)
if outputFormat == "" {
outputFormat = "text"
}
return parserDispatchResult{
OutputFormat: outputFormat,
DocType: "video",
Text: txt,
}, true, nil
}
// Image dispatch: OCR + IMAGE2TEXT vision describe ---
// Mirrors Python's rag/app/picture.py:chunk() image branch:
// 1. Try PaddleOCR if layout_recognize is "@PaddleOCR"
// 2. Fallback to local ONNX OCR (DeepDoc /predict/ocr endpoint)
// 3. If OCR text is short (≤32 chars or ≤32 English words),
// also call IMAGE2TEXT VLM describe()
// 4. Returns combined text
func maybeDispatchImage(
ctx context.Context,
fileType utility.FileType,
filename string,
binary []byte,
inputs map[string]any,
setups map[string]schema.ParserSetup,
) (parserDispatchResult, bool, error) {
if fileType != utility.FileTypeVISUAL {
return parserDispatchResult{}, false, nil
}
setup, ok := setups["image"]
if !ok {
return parserDispatchResult{}, false, nil
}
tenantID := getStringOr(inputs, "tenant_id", "")
if tenantID == "" {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: image requires tenant_id")
}
// --- Phase 1: OCR ---
var ocrText string
// Step 1a: Try PaddleOCR if layout_recognize is set to PaddleOCR.
// Mirrors Python's picture.py:_try_paddleocr_image().
layoutRecognize := getStringOr(setup, "layout_recognize", "")
if layoutRecognize != "" {
recognizer, _ := normalizeLayoutRecognizer(layoutRecognize)
if recognizer == "PaddleOCR" {
if txt, err := runPaddleOCRImage(binary, filename); err == nil && txt != "" {
ocrText = txt
}
}
}
// Step 1b: Fallback to local ONNX OCR (DeepDoc /predict/ocr).
// Mirrors Python's picture.py:ocr(np.array(img)) from deepdoc.vision.
if ocrText == "" {
if txt, err := runLocalImageOCR(binary); err == nil && txt != "" {
ocrText = txt
}
}
// The image family always emits a structured JSON item carrying the
// image attachment (data URI) and doc_type_kwd, mirroring Python
// rag/app/picture.py:71-72 (doc["image"]=img, doc["doc_type_kwd"]=
// "image"). picture.py has no "text" output mode — it always returns
// a structured doc — so output_format is hardcoded to "json" and any
// setup override is ignored. The former behavior returned a bare Text
// string, which dropped the image attachment, set doc_type to "text",
// and on the default json path produced JSON=nil so downstream
// Chunkers rejected the payload with errRequiredField{"json"}.
imageB64 := base64.StdEncoding.EncodeToString(binary)
dataURI := "data:" + imageMIME(filename) + ";base64," + imageB64
// --- Phase 2: VLM description (when OCR text is short) ---
// Mirrors Python's check: if (eng and len(txt.split()) > 32) or len(txt) > 32
// then use OCR text only; otherwise call cv_mdl.describe().
lang := getStringOr(setup, "lang", "")
eng := strings.EqualFold(lang, "english")
if ocrText != "" {
wordCount := len(strings.Fields(ocrText))
charCount := len(ocrText)
if (eng && wordCount > 32) || charCount > 32 {
// OCR returned substantial text — skip VLM.
return imageDispatchResult(ocrText, dataURI), true, nil
}
}
// Short OCR text (or no text): supplement with VLM describe.
driver, modelName, apiConfig, _, err := resolveTenantModelByType(tenantID, entity.ModelTypeImage2Text)
if err != nil {
// If VLM is unavailable but we have OCR text, return it.
if ocrText != "" {
return imageDispatchResult(ocrText, dataURI), true, nil
}
return parserDispatchResult{}, true,
fmt.Errorf("Parser: picture image2text model: %w", err)
}
prompt := "Describe this image in detail."
// image family's contract key is system_prompt (parser.go:295),
// mirroring Python parser.py:1119. Do NOT read setup["prompt"]
// here — that key is for the video family, not image.
if v, ok := setup["system_prompt"].(string); ok && v != "" {
prompt = v
}
messages := []modelModule.Message{{
Role: "user",
Content: []interface{}{
map[string]any{"type": "text", "text": prompt},
map[string]any{"type": "image_url", "image_url": map[string]any{"url": dataURI}},
},
}}
vision := true
resp, err := driver.ChatWithMessages(ctx, modelName, messages, apiConfig, &modelModule.ChatConfig{Vision: &vision}, nil)
if err != nil {
if ocrText != "" {
return imageDispatchResult(ocrText, dataURI), true, nil
}
return parserDispatchResult{}, true,
fmt.Errorf("Parser: picture describe: %w", err)
}
vlmText := ""
if resp != nil && resp.Answer != nil {
vlmText = strings.TrimSpace(*resp.Answer)
}
// Combine OCR + VLM text.
// Mirrors Python: txt += "\n" + ans
combined := ocrText
if vlmText != "" {
if combined != "" {
combined += "\n" + vlmText
} else {
combined = vlmText
}
}
return imageDispatchResult(combined, dataURI), true, nil
}
// imageDispatchResult builds the structured JSON payload for the image
// family: a single item carrying the combined text, the image attachment
// (data URI), and doc_type_kwd "image". Mirrors Python
// rag/app/picture.py:71-72.
func imageDispatchResult(text, dataURI string) parserDispatchResult {
return parserDispatchResult{
OutputFormat: "json",
DocType: "image",
JSON: []map[string]any{{
"text": text,
"image": dataURI,
"doc_type_kwd": "image",
}},
}
}
// Audio dispatch: SPEECH2TEXT transcription ---
// Mirrors Python's rag/app/audio.py:chunk():
// - Writes the audio binary to a temp file (extension-preserving)
// - Calls the tenant's SPEECH2TEXT model via TranscribeAudio()
// - Returns the transcription as text
func maybeDispatchAudio(
ctx context.Context,
fileType utility.FileType,
filename string,
binary []byte,
inputs map[string]any,
setups map[string]schema.ParserSetup,
) (parserDispatchResult, bool, error) {
if fileType != utility.FileTypeAURAL {
return parserDispatchResult{}, false, nil
}
setup, ok := setups["audio"]
if !ok {
return parserDispatchResult{}, false, nil
}
tenantID := getStringOr(inputs, "tenant_id", "")
if tenantID == "" {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: audio requires tenant_id")
}
driver, modelName, apiConfig, _, err := resolveTenantModelByType(tenantID, entity.ModelTypeSpeech2Text)
if err != nil {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: audio speech2text model: %w", err)
}
tmpFile, err := writeTempAudioFile(filename, binary)
if err != nil {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: audio temp file: %w", err)
}
defer os.Remove(tmpFile)
resp, err := driver.TranscribeAudio(ctx, &modelName, &tmpFile, apiConfig, nil, nil)
if err != nil {
return parserDispatchResult{}, true,
fmt.Errorf("Parser: audio transcription: %w", err)
}
transcription := ""
if resp != nil {
transcription = resp.Text
}
outputFormat, _ := setup["output_format"].(string)
if outputFormat == "" {
outputFormat = "text"
}
// Diff 2.11: when output_format is "json" the transcription must be
// carried as a JSON item. Returning it only in Text made the Invoke
// switch silently drop it (the switch has no "json" branch and the
// JSON slice was empty). Mirror the JSON-item shape used by the
// other parser branches.
if outputFormat == "json" {
return parserDispatchResult{
OutputFormat: "json",
DocType: "audio",
JSON: []map[string]any{{
"text": transcription,
"doc_type_kwd": "audio",
}},
}, true, nil
}
return parserDispatchResult{
OutputFormat: outputFormat,
DocType: "audio",
Text: transcription,
}, true, nil
}
// writeTempAudioFile writes binary to a temp file preserving the
// original extension so the ASR provider can detect the format.
func writeTempAudioFile(filename string, binary []byte) (string, error) {
ext := filepath.Ext(filename)
tmp, err := os.CreateTemp("", "ragflow_audio_*"+ext)
if err != nil {
return "", err
}
defer tmp.Close()
if _, err := tmp.Write(binary); err != nil {
os.Remove(tmp.Name())
return "", err
}
return tmp.Name(), nil
}
// normalizeLayoutRecognizer parses layout_recognize strings like
// "model@PaddleOCR" → ("PaddleOCR", "model@PaddleOCR").
// Mirrors Python's common/parser_config_utils.py:normalize_layout_recognizer().
func normalizeLayoutRecognizer(raw string) (recognizer, modelName string) {
lowered := strings.ToLower(raw)
if strings.HasSuffix(lowered, "@paddleocr") {
return "PaddleOCR", raw
}
if strings.HasSuffix(lowered, "@mineru") {
return "MinerU", raw
}
if strings.HasSuffix(lowered, "@somark") {
return "SoMark", raw
}
if strings.HasSuffix(lowered, "@opendataloader") {
return "OpenDataLoader", raw
}
return raw, ""
}
// imageMIME maps common image filename extensions to MIME types
// for constructing base64 data URIs.
func imageMIME(filename string) string {
dot := strings.LastIndex(filename, ".")
if dot == -1 {
return "image/png"
}
switch strings.ToLower(filename[dot+1:]) {
case "jpg", "jpeg":
return "image/jpeg"
case "png":
return "image/png"
case "gif":
return "image/gif"
case "bmp":
return "image/bmp"
case "webp":
return "image/webp"
case "svg":
return "image/svg+xml"
case "tiff", "tif":
return "image/tiff"
case "ico":
return "image/x-icon"
case "avif":
return "image/avif"
case "heic":
return "image/heic"
default:
return "image/png"
}
}
// videoMIME maps common video filename extensions to MIME types
// for constructing base64 data URIs.
func videoMIME(filename string) string {
dot := strings.LastIndex(filename, ".")
if dot == -1 {
return "video/mp4"
}
switch strings.ToLower(filename[dot+1:]) {
case "mp4":
return "video/mp4"
case "avi":
return "video/x-msvideo"
case "mkv":
return "video/x-matroska"
case "mov":
return "video/quicktime"
case "wmv":
return "video/x-ms-wmv"
case "flv":
return "video/x-flv"
case "webm":
return "video/webm"
case "mpeg", "mpg":
return "video/mpeg"
case "3gp":
return "video/3gpp"
default:
return "video/mp4"
}
}
// --- OCR helpers for picture dispatch ---
// runPaddleOCRImage tries PaddleOCR remote API for image text extraction.
// Mirrors Python's picture.py:_try_paddleocr_image() which creates a
// PaddleOCRParser and calls parse_image().
func runPaddleOCRImage(binary []byte, filename string) (string, error) {
client := parser.NewPaddleOCRClientFromEnv()
if !client.Enabled() {
return "", fmt.Errorf("paddleocr: not configured (set PADDLEOCR_ACCESS_TOKEN)")
}
return client.ParseImage(binary, filename)
}
// runLocalImageOCR uses the DeepDoc inference service (/predict/ocr) to
// detect and recognize text in an image. Mirrors Python's
// deepdoc.vision.OCR (local ONNX pipeline), but routed through the
// DeepDoc HTTP service which wraps the same ONNX models.
//
// Pipeline:
// 1. Decode image bytes → image.Image
// 2. OCRDetect → find text region boxes
// 3. For each box: crop → OCRRecognize → text
// 4. Sort boxes by Y, then X (reading order)
// 5. Join all recognized text with newlines
func runLocalImageOCR(binary []byte) (string, error) {
deepdocURL := common.GetEnv(common.EnvDeepDocURL)
if deepdocURL == "" {
deepdocURL = common.GetEnv(common.EnvTensorrtDLAServer)
}
if deepdocURL == "" {
return "", fmt.Errorf("local OCR: DEEPDOC_URL not configured")
}
client, err := inference.NewClient(deepdocURL)
if err != nil {
return "", fmt.Errorf("local OCR: %w", err)
}
img, _, err := image.Decode(bytes.NewReader(binary))
if err != nil {
return "", fmt.Errorf("local OCR: decode image: %w", err)
}
// Step 1: Detect text regions.
ctx := context.Background()
boxes, err := client.OCRDetect(ctx, img)
if err != nil {
return "", fmt.Errorf("local OCR: detect: %w", err)
}
if len(boxes) == 0 {
return "", nil
}
// Step 2: Sort boxes by Y (top to bottom), then X (left to right)
// for reading-order text assembly.
sort.Slice(boxes, func(i, j int) bool {
yi := (boxes[i].Y0 + boxes[i].Y2) / 2
yj := (boxes[j].Y0 + boxes[j].Y2) / 2
if yi < yj {
return true
}
if yi > yj {
return false
}
return boxes[i].X0 < boxes[j].X0
})
// Step 3: Recognize text per box.
var texts []string
bounds := img.Bounds()
for _, box := range boxes {
// Convert quad box to axis-aligned crop rect.
x0 := int(min4(box.X0, box.X1, box.X2, box.X3))
y0 := int(min4(box.Y0, box.Y1, box.Y2, box.Y3))
x1 := int(max4(box.X0, box.X1, box.X2, box.X3))
y1 := int(max4(box.Y0, box.Y1, box.Y2, box.Y3))
// Clamp to image bounds.
if x0 < bounds.Min.X {
x0 = bounds.Min.X
}
if y0 < bounds.Min.Y {
y0 = bounds.Min.Y
}
if x1 > bounds.Max.X {
x1 = bounds.Max.X
}
if y1 > bounds.Max.Y {
y1 = bounds.Max.Y
}
if x1 <= x0 || y1 <= y0 {
continue
}
// Crop the region. This requires an image type that supports
// cropping; for simplicity we recode through a sub-image.
crop := cropImage(img, x0, y0, x1, y1)
if crop == nil {
continue
}
recTexts, err := client.OCRRecognize(ctx, crop)
if err != nil {
continue // skip boxes that fail recognition
}
for _, t := range recTexts {
s := strings.TrimSpace(t.Text)
if s != "" {
texts = append(texts, s)
}
}
}
if len(texts) == 0 {
return "", nil
}
return strings.Join(texts, "\n"), nil
}
// cropImage extracts a sub-rectangle from img. Works with any image.Image
// by converting to RGBA if needed, then cropping.
func cropImage(img image.Image, x0, y0, x1, y1 int) image.Image {
bounds := img.Bounds()
cropRect := image.Rect(
bounds.Min.X+x0, bounds.Min.Y+y0,
bounds.Min.X+x1, bounds.Min.Y+y1,
)
switch src := img.(type) {
case *image.RGBA:
return src.SubImage(cropRect)
case *image.NRGBA:
return src.SubImage(cropRect)
case *image.RGBA64:
return src.SubImage(cropRect)
case *image.NRGBA64:
return src.SubImage(cropRect)
case *image.Gray:
return src.SubImage(cropRect)
case *image.Gray16:
return src.SubImage(cropRect)
case *image.YCbCr:
return src.SubImage(cropRect)
case *image.Paletted:
return src.SubImage(cropRect)
default:
// Convert to RGBA for cropping.
rgba := image.NewRGBA(cropRect)
for y := cropRect.Min.Y; y < cropRect.Max.Y; y++ {
for x := cropRect.Min.X; x < cropRect.Max.X; x++ {
rgba.Set(x, y, img.At(x, y))
}
}
return rgba
}
}
func min4(a, b, c, d float64) float64 {
m := a
if b < m {
m = b
}
if c < m {
m = c
}
if d < m {
m = d
}
return m
}
func max4(a, b, c, d float64) float64 {
m := a
if b > m {
m = b
}
if c > m {
m = c
}
if d > m {
m = d
}
return m
}