Skip to content

Fast, accurate OCR with correctness assessment.

webdemo: show pages filling in while they are recognized.

caowanxia6882cc669128
diff --git a/docs/webdemo_deploy.md b/docs/webdemo_deploy.md
index 975e369..5133c6e 100644
--- a/docs/webdemo_deploy.md
+++ b/docs/webdemo_deploy.md
@@ -78,6 +78,8 @@ VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --str
Open **`http://localhost:5173/playground/document-parse`** to try the local Web Demo.
+While a document is being parsed the page shows the pages still being recognized: finished blocks appear at once, blocks being decoded grow as their text arrives, and the first pages of a PDF start first. For that order, start the backend with `OCR_SHARED_CROP_POOL=0` (`start_local_worker.sh` defaults to `1`; with one recognition queue shared by all jobs, blocks are not ordered by page).
+
## 5. API
The backend also provides an API. The endpoints are listed below.
@@ -85,7 +87,7 @@ The backend also provides an API. The endpoints are listed below.
| Endpoint | Purpose |
|---|---|
| `POST /api/document-parse/jobs` | Async image or PDF. HTTP 200 returns a job |
-| `GET /api/document-parse/jobs/{id}` | HTTP 200 returns progress and results |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 returns progress and results; while the job runs, `pages` also lists, after the finished pages, the pages still being recognized (`"partial": true`) with the blocks done so far and the current text of the blocks being decoded |
| `DELETE /api/document-parse/jobs/{id}` | Cancel the job. HTTP 200 returns the job status |
| `POST /api/kie` | Sync single image. HTTP 200 returns one page |
diff --git a/docs/webdemo_deploy_zh.md b/docs/webdemo_deploy_zh.md
index 3760cce..14b9d7d 100644
--- a/docs/webdemo_deploy_zh.md
+++ b/docs/webdemo_deploy_zh.md
@@ -78,6 +78,8 @@ VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --str
打开 **`http://localhost:5173/playground/document-parse`**,即可开始体验本地的 WebDemo!
+解析过程中页面会实时显示正在识别的页:识别完的块直接出现,正在解码的块逐字增长,PDF 的前面几页最先开始。要得到这个顺序,后端需以 `OCR_SHARED_CROP_POOL=0` 启动(`start_local_worker.sh` 默认为 `1`,多个任务共用一个识别队列时不按页排序)。
+
## 5. 接口
后端同样也提供了 API 服务,以下是相关的 API 接口。
@@ -85,7 +87,7 @@ VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --str
| 接口 | 用途 |
|---|---|
| `POST /api/document-parse/jobs` | 异步图片或 PDF,HTTP 200 返回任务 |
-| `GET /api/document-parse/jobs/{id}` | HTTP 200 返回进度与结果 |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 返回进度与结果;任务运行中,`pages` 在已完成的页之后还带有正在识别的页(`"partial": true`),内容是已识别完的块和正在解码的块的当前文本 |
| `DELETE /api/document-parse/jobs/{id}` | 取消任务,HTTP 200 返回任务状态 |
| `POST /api/kie` | 同步单图,HTTP 200 返回单页响应 |
diff --git a/webdemo/backend/document_jobs.py b/webdemo/backend/document_jobs.py
index 7d225bf..457c114 100644
--- a/webdemo/backend/document_jobs.py
+++ b/webdemo/backend/document_jobs.py
@@ -1,7 +1,10 @@
"""Hand an uploaded image or PDF to the local page worker.
-The frontend polls page by page. A detector is held only while that page is
-being cut. Rotation adaptation and recognition each have their own queue.
+The frontend polls the job. Besides the pages that are finished, a running job
+reports the pages still being recognized: the blocks done so far and the text
+of the blocks that are being decoded right now, so the page fills in as it is
+read. A detector is borrowed for the job and returned loaded, so the next job
+does not wait for the layout model.
"""
from __future__ import annotations
@@ -60,6 +63,12 @@ def _layout_page_index(layout: Dict, stem: str) -> int:
return 0
+def _page_index(state: Dict, layout: Dict, stem: str) -> int:
+ if state.get("only_page") is not None:
+ return int(state["only_page"])
+ return _layout_page_index(layout, stem)
+
+
def _collect_pages(state: Dict) -> list:
import server
@@ -67,23 +76,114 @@ def _collect_pages(state: Dict) -> list:
layouts = job_dir / "runtime" / "intermediate" / "layouts"
if not layouts.is_dir():
return []
+ # While the job runs it is polled several times a second: a finished page is read once.
+ running = state["status"] == "Running"
+ done: Dict = state.setdefault("finished_pages", {}) if running else {}
pages = []
for path in sorted(layouts.glob("*.json")):
- layout = server._read_json(path)
- result = server._read_json(job_dir / "results_json" / f"{path.stem}.json")
- if not layout or not result:
- continue
- page_index = _layout_page_index(layout, path.stem)
- if state.get("only_page") is not None:
- page_index = int(state["only_page"])
- pages.append(server._build_page_response(
- path.stem, layout, result, state["id"], "standard",
- bool(state["upright"]), int(state["created_at"]), state["id"], page_index,
- ))
+ page = done.get(path.stem)
+ if page is None:
+ layout = server._read_json(path)
+ result = server._read_json(job_dir / "results_json" / f"{path.stem}.json")
+ if not layout or not result:
+ continue
+ page = server._build_page_response(
+ path.stem, layout, result, state["id"], "standard",
+ bool(state["upright"]), int(state["created_at"]), state["id"],
+ _page_index(state, layout, path.stem),
+ )
+ page["image_id"] = path.stem
+ done[path.stem] = page
+ pages.append(page)
pages.sort(key=lambda item: int(item.get("metadata", {}).get("page_index") or 0))
return pages
+def _hear(state: Dict, event: Dict) -> None:
+ """Keep what the run says about pages that are not finished yet.
+
+ Called by the run for every layout, piece of decoded text, block and page.
+ """
+ kind = event["event"]
+ with state["live_lock"]:
+ live = state["live"]
+ if kind == "layout":
+ live[event["image_id"]] = {}
+ elif kind == "page":
+ live.pop(event["image_id"], None)
+ elif kind == "block":
+ live.setdefault(event["image_id"], {})[event["order"]] = {
+ "text": event["content"], "done": True}
+ elif kind == "delta":
+ block = live.setdefault(event["image_id"], {}).setdefault(
+ event["order"], {"text": "", "done": False})
+ # A request that was sent again starts its text over.
+ block["text"] = event["text"] if event.get("restart") else block["text"] + event["text"]
+
+
+def _preview(label: str, raw: str) -> str:
+ 'The text of a block that is still being decoded, tidied the way its final content will be.'
+ from minicpmvocr.pipeline._text import _normalize_and_dedupe_blocks
+ from minicpmvocr.postprocess.markdown import postprocess_content
+ from minicpmvocr.prompts import DEFAULT_PROMPT_MAP, get_element_cfg
+
+ try:
+ elem = get_element_cfg(DEFAULT_PROMPT_MAP, label)
+ content = postprocess_content(raw, elem["output_format"], label=label) if elem else raw
+ tidy = _normalize_and_dedupe_blocks([{"label": label, "order": 0, "content": content}])
+ return tidy[0]["content"] or raw
+ except Exception:
+ return raw
+
+
+def _partial_pages(state: Dict, finished: set) -> list:
+ """Pages still being recognized, in the shape of a finished page.
+
+ Only blocks that have text so far are listed, and the page body is left
+ empty: the frontend then builds the preview from the blocks.
+ """
+ import server
+
+ with state["live_lock"]:
+ live = {image_id: {order: dict(block) for order, block in blocks.items()}
+ for image_id, blocks in state["live"].items()}
+ layouts = Path(state["job_dir"]) / "runtime" / "intermediate" / "layouts"
+ cache = state.setdefault("layouts", {})
+ pages = []
+ for image_id, heard in live.items():
+ if image_id in finished or not heard:
+ continue
+ layout = cache.get(image_id)
+ if layout is None:
+ layout = server._read_json(layouts / f"{image_id}.json")
+ if not layout:
+ continue
+ cache[image_id] = layout
+ blocks = []
+ for layout_block in layout.get("blocks", []):
+ block = heard.get(layout_block.get("order", 0))
+ if not block or not block["text"].strip():
+ continue
+ content = block["text"] if block["done"] else _preview(layout_block.get("label", ""), block["text"])
+ blocks.append(server._block_to_api(layout_block, {"content": content, "status": "ok"}))
+ if not blocks:
+ continue
+ pages.append({
+ "metadata": {"page_index": _page_index(state, layout, image_id)},
+ "partial": True,
+ "image_id": image_id,
+ "choices": [{"message": {"content": ""}}],
+ "minicpm_ocr": {
+ "request_id": state["id"],
+ "mode": "ocr_only",
+ "image_width": layout.get("image_width", 0),
+ "image_height": layout.get("image_height", 0),
+ "blocks": blocks,
+ },
+ })
+ return pages
+
+
def _public(state: Dict) -> Dict:
pages = _collect_pages(state)
body = {
@@ -95,13 +195,16 @@ def _public(state: Dict) -> Dict:
}
if state["status"] == "Running":
body["pages_done"] = len(pages)
+ # After the finished pages, so a client that only wants those can stop at pages_done.
+ partial = _partial_pages(state, {page.get("image_id") for page in pages})
+ partial.sort(key=lambda item: item["metadata"]["page_index"])
+ body["pages"] = pages + partial
if state.get("error"):
body["error"] = state["error"]
return body
def _run(job_id: str) -> None:
- import page_fleet
import server
with _LOCK:
@@ -109,7 +212,13 @@ def _run(job_id: str) -> None:
try:
cfg = server.RUNNER.build_cfg(job_id, upright=bool(state["upright"]), mode="ocr", save_crops=False)
cfg["input"]["file_path"] = state["path"]
- page_fleet.run_releasing_layout(server.RUNNER, cfg)
+ from minicpmvocr import pipelined_run
+
+ # Streamed: earlier pages are rendered, laid out and recognized first, and the
+ # job hears each block and its text as it is decoded.
+ with server.RUNNER.acquire(cfg) as resources:
+ pipelined_run(cfg, resources=resources,
+ on_page=lambda event: _hear(state, event), stream_detail="token")
pages = _collect_pages(state)
with _LOCK:
if state["status"] == "Running":
@@ -172,6 +281,9 @@ async def create_document_job(
"only_page": only_page,
"created_at": int(time.time()),
"error": "",
+ # image_id -> block order -> {"text", "done"}, for pages not finished yet.
+ "live": {},
+ "live_lock": threading.Lock(),
}
with _LOCK:
_JOBS[job_id] = state
diff --git a/webdemo/frontend/src/api/map/__tests__/imageParseJobs.test.ts b/webdemo/frontend/src/api/map/__tests__/imageParseJobs.test.ts
index f4f4ce7..7bce7ef 100644
--- a/webdemo/frontend/src/api/map/__tests__/imageParseJobs.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/imageParseJobs.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { QueryClient } from '@tanstack/react-query';
import { BizError } from '@map/types';
-import { runImageParseJob } from '../imageParseJobs';
+import { IMAGE_PARSE_JOB_POLL_MS, runImageParseJob } from '../imageParseJobs';
const mocks = vi.hoisted(() => ({ request: vi.fn() }));
vi.mock('../request', () => ({ mapRequest: mocks.request }));
@@ -56,14 +56,14 @@ describe('MAP OCR jobs', () => {
recognize_chart: true,
});
expect(init.signal).toBeUndefined();
- await vi.advanceTimersByTimeAsync(999);
+ await vi.advanceTimersByTimeAsync(IMAGE_PARSE_JOB_POLL_MS - 1);
expect(mocks.request).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(mocks.request).toHaveBeenLastCalledWith('/image-parse/jobs/job%2Fone', {
signal: expect.any(AbortSignal),
});
expect(progress.mock.calls.map(([job]) => job.pages_done)).toEqual([0, 1]);
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(IMAGE_PARSE_JOB_POLL_MS);
await expect(promise).resolves.toEqual(success);
await vi.advanceTimersByTimeAsync(5000);
expect(mocks.request).toHaveBeenCalledTimes(3);
@@ -137,7 +137,7 @@ describe('MAP OCR jobs', () => {
onProgress: progress,
});
const rejected = expect(promise).rejects.toMatchObject({ name: 'AbortError' });
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(IMAGE_PARSE_JOB_POLL_MS);
expect(getSignal?.aborted).toBe(false);
controller.abort();
await rejected;
@@ -192,7 +192,7 @@ describe('MAP OCR jobs', () => {
signal: new AbortController().signal,
});
const rejected = expect(promise).rejects.toThrow('imageParseRequestFailed');
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(IMAGE_PARSE_JOB_POLL_MS);
await rejected;
expect(mocks.request).toHaveBeenLastCalledWith('/image-parse/jobs/job%2Fone', {
method: 'DELETE',
@@ -239,7 +239,7 @@ describe('MAP OCR jobs', () => {
queryClient,
signal: new AbortController().signal,
});
- await vi.advanceTimersByTimeAsync(1000);
+ await vi.advanceTimersByTimeAsync(IMAGE_PARSE_JOB_POLL_MS);
await expect(promise).resolves.toMatchObject({ id: 'ocr_1234-abcd' });
expect(mocks.request).toHaveBeenLastCalledWith('/image-parse/jobs/ocr_1234-abcd', {
signal: expect.any(AbortSignal),
diff --git a/webdemo/frontend/src/api/map/imageParseJobs.ts b/webdemo/frontend/src/api/map/imageParseJobs.ts
index 0b72a77..b6fd21f 100644
--- a/webdemo/frontend/src/api/map/imageParseJobs.ts
+++ b/webdemo/frontend/src/api/map/imageParseJobs.ts
@@ -12,7 +12,13 @@ export type ImageParseJobTask = 'standard' | 'seal' | 'kie';
export type ImageParseJobStatus = 'Running' | 'Success' | 'Failed' | 'Cancelled';
export type ImageParseJobPage = Parameters<typeof adaptImageParseV2>[0];
-/** Async OCR job owned by MAP; while running, pages is the prefix of pages already finished. */
+/** How often a running job is polled; short enough that text still being decoded reads as a stream. */
+export const IMAGE_PARSE_JOB_POLL_MS = 200;
+
+/**
+ * Async OCR job owned by MAP. While running, pages holds the pages already finished and, after them,
+ * the pages still being recognized (`partial: true`): their blocks so far, with the text decoded so far.
+ */
export interface ImageParseJob {
id: string;
status: ImageParseJobStatus;
@@ -128,7 +134,7 @@ async function observeJob(
refetchOnReconnect: false,
refetchIntervalInBackground: true,
refetchInterval: (query) =>
- query.state.error || query.state.data?.status !== 'Running' ? false : 1000,
+ query.state.error || query.state.data?.status !== 'Running' ? false : IMAGE_PARSE_JOB_POLL_MS,
retry: false,
gcTime: 0,
});
@@ -171,7 +177,7 @@ async function observeJob(
}
/**
- * Create a MAP OCR job and watch progress once a second with TanStack Query; stop and clear the query at a terminal state.
+ * Create a MAP OCR job and watch progress with TanStack Query (every IMAGE_PARSE_JOB_POLL_MS); stop and clear the query at a terminal state.
* @param input Original-file fileId, execution options, QueryClient, and cancel/progress callbacks
* @returns The successful job; failure uses a stable copy key, and cancel DELETEs the job that was created
*/
diff --git a/webdemo/frontend/src/api/map/imageParsePipeline.ts b/webdemo/frontend/src/api/map/imageParsePipeline.ts
index c4870b5..8a221b1 100644
--- a/webdemo/frontend/src/api/map/imageParsePipeline.ts
+++ b/webdemo/frontend/src/api/map/imageParsePipeline.ts
@@ -8,7 +8,7 @@
import { BizError } from '@map/types';
import type { QueryClient } from '@tanstack/react-query';
import { adaptImageParseV2 } from './imageParseV2';
-import { runImageParseJob } from './imageParseJobs';
+import { runImageParseJob, type ImageParseJob } from './imageParseJobs';
import { validateImageParseSdkResult, type ImageParseSdkResult } from './imageParseSdk';
import { mapRequest } from './request';
import {
@@ -85,6 +85,8 @@ interface ImageParsePipelineBaseInput {
recognizeChart?: boolean;
signal: AbortSignal;
queryClient?: QueryClient;
+ /** Called while the job runs with the blocks and text decoded so far; the returned result replaces them. */
+ onPartial?: (result: ImageParseSdkResult) => void;
}
/**
@@ -98,6 +100,19 @@ export type ImageParsePipelineInput = ImageParsePipelineBaseInput &
| { image: string; fileId?: never; fileUrl?: never }
);
+/** Hand over the page of a running job that is still being recognized; a frame that cannot be shown is skipped. */
+function publishPartial(job: ImageParseJob, onPartial: (result: ImageParseSdkResult) => void) {
+ const page = job.pages?.find((item) => (item as { partial?: boolean }).partial === true);
+ if (!page) return;
+ try {
+ const result = adaptImageParseV2(page);
+ delete result.source;
+ onPartial(validateImageParseSdkResult(result, { allowEmptyMarkdown: true }));
+ } catch {
+ // The next frame or the finished page replaces it.
+ }
+}
+
/** A single-image fileId goes through an async job; older URL and inline calls keep the sync contract. L3 validates both. */
export async function parseImagePipeline(
input: ImageParsePipelineInput,
@@ -130,6 +145,7 @@ export async function parseImagePipeline(
...(fields ? { fields } : {}),
...(input.pageIndex !== undefined ? { pageIndex: input.pageIndex } : {}),
...(input.queryClient ? { queryClient: input.queryClient } : {}),
+ ...(input.onPartial ? { onProgress: (running) => publishPartial(running, input.onPartial!) } : {}),
});
if (job.pages?.length !== 1) throw new Error('imageParseInvalidResult');
raw = job.pages[0];
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
index d0bc672..512f3e7 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
@@ -139,6 +139,12 @@ export function useImageParseExecution(options: ImageParseExecutionOptions) {
signal,
fileId,
...(queryClient ? { queryClient } : {}),
+ // While the page is being recognized, show its blocks and the text decoded so far.
+ onPartial: (partial) => {
+ if (!isCurrent()) return;
+ setters.setMarkdown(partial.markdown);
+ setters.setLayout(partial.blocks);
+ },
});
};
setters.setLoading(true);
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
index a92ac9c..1b3d649 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
@@ -64,13 +64,18 @@ export function usePdfImageParsePresentation({
},
[setResults],
);
- usePdfImageParseCrops(valid ? source : '', page, valid ? results[page] : undefined, onCrops);
+ // A page still streaming changes several times a second; its crops are cut once it is finished.
+ const cropTarget = valid && !results[page]?.partial ? results[page] : undefined;
+ usePdfImageParseCrops(valid ? source : '', page, cropTarget, onCrops);
const snapshot = useMemo<PdfImageParseSnapshot | null>(() => {
if (!valid) return null;
if (finished) return { page, pages, results };
const partial: Record<number, PdfPageResult> = {};
- for (const [key, value] of Object.entries(results))
+ for (const [key, value] of Object.entries(results)) {
+ // A page still streaming is not a result to restore.
+ if (value.partial) continue;
partial[Number(key)] = value.result ? { result: value.result, error: value.error } : value;
+ }
return { page, pages, results: partial };
}, [valid, finished, page, pages, results]);
return { visibleResults, current: valid ? visibleResults[page] : undefined, snapshot };
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
index bda5f69..7e39957 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
@@ -18,6 +18,8 @@ export interface PdfPageResult {
result?: ImageParseSdkResult;
crops?: readonly string[];
error?: string;
+ /** The page is still being recognized: result holds the blocks and text decoded so far, and will be replaced. */
+ partial?: boolean;
}
/** PDF execution context; queries reuse the portal QueryClient, and KIE fields are handed to the task client for validation as-is. */
@@ -79,6 +81,8 @@ export async function parsePdfPages(
signal.throwIfAborted();
let total = 0;
const published = new Set<number>();
+ // What was last shown of each page still being recognized, so an unchanged poll does not re-render it.
+ const streamed = new Map<number, string>();
const publish = (job: ImageParseJob) => {
signal.throwIfAborted();
if (job.pages_total > MAX_PDF_PAGES) throw new Error('imageParsePdfTooManyPages');
@@ -99,6 +103,23 @@ export async function parsePdfPages(
const number = index + 1;
if (skipPages?.has(number) || published.has(number)) continue;
signal.throwIfAborted();
+ if ((page as { partial?: boolean }).partial === true) {
+ // Still being recognized: show what there is so far and wait for the finished page.
+ try {
+ const result = adaptImageParseV2(page);
+ delete result.source;
+ const shown = result.blocks.map((block) => `${block.order}:${block.text}`).join('\u0000');
+ if (streamed.get(number) === shown) continue;
+ streamed.set(number, shown);
+ onPage(number, {
+ result: validateImageParseSdkResult(result, { allowEmptyMarkdown: true }),
+ partial: true,
+ });
+ } catch {
+ // A frame that cannot be shown is skipped; the next one or the finished page replaces it.
+ }
+ continue;
+ }
let value: PdfPageResult;
try {
const result = adaptImageParseV2(page);
@@ -108,6 +129,7 @@ export async function parsePdfPages(
value = { error: pdfParseErrorKey(failure) };
}
published.add(number);
+ streamed.delete(number);
onPage(number, value);
}
};
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
index 9e3fe72..cb46ab4 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
@@ -11,10 +11,11 @@ export function pdfParseErrorKey(failure: unknown): string {
return 'imageParseRequestFailed';
}
-/** Count pages that already have a result or an error; a waiting placeholder does not count toward completion. */
+/** Count pages that already have a result or an error; a waiting placeholder or a page still streaming does not count toward completion. */
export function countCompletedPdfPages(results: Readonly<Record<number, PdfPageResult>>) {
- return Object.values(results).filter((page) => Boolean(page.result) || Boolean(page.error))
- .length;
+ return Object.values(results).filter(
+ (page) => !page.partial && (Boolean(page.result) || Boolean(page.error)),
+ ).length;
}
/** On restore, skip only pages that already have a successful result; failed pages can still be shown again. */
@@ -23,7 +24,7 @@ export function completedPdfPageIndexes(
): Set<number> {
return new Set(
Object.entries(results)
- .filter(([, value]) => value.result)
+ .filter(([, value]) => value.result && !value.partial)
.map(([key]) => Number(key)),
);
}