File size: 6,050 Bytes
8839278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import { Client } from "@gradio/client";
import type { GradioFileData, ModelChoice, OcrPayload, PageResult } from "../types";

const PAGES_PER_GPU_REQUEST = 4;

export function appRoot(): string {
  const { origin, pathname } = window.location;
  const trimmed = pathname.replace(/\/+$/, "");
  if (!trimmed || trimmed === "/") {
    return origin;
  }
  return `${origin}${trimmed}`;
}

export async function uploadDocument(file: File): Promise<GradioFileData> {
  const form = new FormData();
  form.append("files", file, file.name);
  const response = await fetch(new URL("gradio_api/upload", appRoot() + "/"), {
    method: "POST",
    body: form,
    credentials: "include",
  });
  if (!response.ok) {
    throw new Error(`Document upload failed (${response.status}).`);
  }
  const payload = (await response.json()) as string[] | { path?: string }[];
  const path =
    typeof payload[0] === "string"
      ? payload[0]
      : (payload[0] as { path?: string })?.path;
  if (!path) {
    throw new Error("Upload did not return a file path.");
  }
  return {
    path,
    orig_name: file.name,
    size: file.size,
    mime_type: file.type || undefined,
    meta: { _type: "gradio.FileData" },
  };
}

function mergePages(existing: PageResult[], incoming: PageResult[]): PageResult[] {
  const byNumber = new Map<number, PageResult>();
  for (const page of existing) {
    byNumber.set(page.page_number, page);
  }
  for (const page of incoming) {
    const prev = byNumber.get(page.page_number);
    if (!prev || page.status === "complete" || (page.markdown?.length ?? 0) >= (prev.markdown?.length ?? 0)) {
      byNumber.set(page.page_number, page);
    }
  }
  return [...byNumber.values()].sort((a, b) => a.page_number - b.page_number);
}

function firstIncompleteIndex(pages: PageResult[], totalPages: number): number {
  for (let i = 1; i <= totalPages; i += 1) {
    const page = pages.find((p) => p.page_number === i);
    if (!page || page.status !== "complete") {
      return i - 1;
    }
  }
  return totalPages;
}

function combineField(pages: PageResult[], field: "markdown" | "render_markdown"): string {
  if (pages.length <= 1) {
    return pages[0]?.[field] ?? "";
  }
  return pages
    .map((page) => `<!-- Page ${page.page_number} -->\n\n${page[field] ?? ""}`)
    .join("\n\n---\n\n");
}

export type RunOcrHandlers = {
  onStatus: (text: string) => void;
  onUpdate: (state: {
    pages: PageResult[];
    markdown: string;
    renderMarkdown: string;
    preview?: string | null;
    totalPages: number;
    currentPage: number;
    charCount: number;
  }) => void;
};

export async function runOcrDocument(options: {
  fileData: GradioFileData;
  modelChoice: ModelChoice;
  prompt: string;
  signal?: AbortSignal;
  handlers: RunOcrHandlers;
}): Promise<void> {
  const { fileData, modelChoice, prompt, signal, handlers } = options;
  const client = await Client.connect(appRoot());
  let pages: PageResult[] = [];
  let totalPages = 1;
  let pageIndex = 0;
  let preview: string | null | undefined;

  while (pageIndex < totalPages) {
    if (signal?.aborted) {
      throw new DOMException("Aborted", "AbortError");
    }

    handlers.onStatus(
      totalPages > 1
        ? `Running pages ${pageIndex + 1}${Math.min(totalPages, pageIndex + PAGES_PER_GPU_REQUEST)} of ${totalPages}…`
        : "Running OCR…",
    );

    const stream = client.submit("/run_ocr", {
      image_path: fileData,
      page_index: pageIndex,
      page_count: PAGES_PER_GPU_REQUEST,
      model_choice: modelChoice,
      prompt,
    });

    let batchComplete = false;
    let sawData = false;

    for await (const message of stream) {
      if (signal?.aborted) {
        throw new DOMException("Aborted", "AbortError");
      }
      if (message.type === "status") {
        const stage = (message as { stage?: string }).stage ?? "";
        if (stage === "error") {
          throw new Error("OCR job failed in the queue.");
        }
        continue;
      }
      if (message.type !== "data") {
        continue;
      }
      sawData = true;
      const raw = Array.isArray(message.data) ? message.data[0] : message.data;
      const payload = raw as OcrPayload;
      if (!payload || typeof payload !== "object") {
        continue;
      }

      totalPages = payload.total_pages || totalPages;
      if (payload.page_preview) {
        preview = payload.page_preview;
      }
      pages = mergePages(pages, payload.pages ?? []);
      batchComplete = Boolean(payload.batch_complete);

      const label =
        payload.event === "page_start"
          ? `Preparing page ${payload.current_page}/${payload.total_pages}`
          : payload.event === "stream"
            ? `Streaming page ${payload.current_page}/${payload.total_pages} · ${payload.char_count.toLocaleString()} chars`
            : payload.event === "page_complete"
              ? `Page ${payload.current_page}/${payload.total_pages} complete`
              : `Batch complete · ${payload.char_count.toLocaleString()} chars`;

      handlers.onStatus(label);
      handlers.onUpdate({
        pages,
        markdown: combineField(pages, "markdown"),
        renderMarkdown: combineField(pages, "render_markdown"),
        preview,
        totalPages,
        currentPage: payload.current_page,
        charCount: pages.reduce((sum, page) => sum + (page.markdown?.length ?? 0), 0),
      });

      if (batchComplete) {
        break;
      }
    }

    if (!sawData) {
      throw new Error("OCR stream closed without data.");
    }

    const next = firstIncompleteIndex(pages, totalPages);
    if (next >= totalPages) {
      break;
    }
    // Advance to the first unfinished page (batch complete or reconnect).
    if (!batchComplete && next === pageIndex) {
      // No progress — avoid infinite reconnect loops.
      throw new Error(`OCR stalled on page ${pageIndex + 1}.`);
    }
    pageIndex = next;
  }

  handlers.onStatus(
    `Done · ${pages.reduce((s, p) => s + (p.markdown?.length ?? 0), 0).toLocaleString()} chars`,
  );
}