@uploadista/flow-documents-replicate 0.0.16-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +16 -0
- package/LICENSE +21 -0
- package/README.md +71 -0
- package/dist/index.d.mts +47 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +125 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +32 -0
- package/src/document-ai-plugin.ts +265 -0
- package/src/index.ts +5 -0
- package/tsconfig.json +14 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
> @uploadista/flow-documents-replicate@0.0.1 build /Users/denislaboureyras/Documents/uploadista/dev/uploadista-workspace/uploadista-sdk/packages/flow/documents/replicate
|
|
4
|
+
> tsdown
|
|
5
|
+
|
|
6
|
+
[34mℹ[39m tsdown [2mv0.16.5[22m powered by rolldown [2mv1.0.0-beta.50[22m
|
|
7
|
+
[34mℹ[39m entry: [34msrc/index.ts[39m
|
|
8
|
+
[34mℹ[39m tsconfig: [34mtsconfig.json[39m
|
|
9
|
+
[34mℹ[39m Build start
|
|
10
|
+
[34mℹ[39m Cleaning 4 files
|
|
11
|
+
[34mℹ[39m [2mdist/[22m[1mindex.mjs[22m [2m 5.24 kB[22m [2m│ gzip: 1.75 kB[22m
|
|
12
|
+
[34mℹ[39m [2mdist/[22mindex.mjs.map [2m10.59 kB[22m [2m│ gzip: 3.31 kB[22m
|
|
13
|
+
[34mℹ[39m [2mdist/[22mindex.d.mts.map [2m 0.55 kB[22m [2m│ gzip: 0.32 kB[22m
|
|
14
|
+
[34mℹ[39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m 1.72 kB[22m [2m│ gzip: 0.62 kB[22m
|
|
15
|
+
[34mℹ[39m 4 files, total: 18.11 kB
|
|
16
|
+
[32m✔[39m Build complete in [32m8136ms[39m
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 uploadista
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# @uploadista/flow-documents-replicate
|
|
2
|
+
|
|
3
|
+
Replicate AI-powered OCR plugin for Uploadista Flow.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **DeepSeek-OCR**: State-of-the-art OCR accuracy
|
|
8
|
+
- **Multiple task modes**: Markdown conversion, free OCR, figure parsing, object location
|
|
9
|
+
- **Configurable resolution**: Speed/accuracy tradeoff options
|
|
10
|
+
- **Cost-effective**: ~$0.005 per request (median)
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @uploadista/flow-documents-replicate
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { ReplicateDocumentAiPluginLive } from "@uploadista/flow-documents-replicate";
|
|
22
|
+
import { Effect } from "effect";
|
|
23
|
+
|
|
24
|
+
// Provide the plugin to your flow execution
|
|
25
|
+
const program = Effect.gen(function* () {
|
|
26
|
+
// Your flow logic here
|
|
27
|
+
}).pipe(Effect.provide(ReplicateDocumentAiPluginLive));
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## OCR Task Types
|
|
31
|
+
|
|
32
|
+
### Convert to Markdown
|
|
33
|
+
Extracts text with structure (headings, lists, paragraphs) in Markdown format.
|
|
34
|
+
|
|
35
|
+
**Best for**: Documents, reports, articles
|
|
36
|
+
|
|
37
|
+
### Free OCR
|
|
38
|
+
Extracts all visible text without structure.
|
|
39
|
+
|
|
40
|
+
**Best for**: Simple text extraction, receipts, forms
|
|
41
|
+
|
|
42
|
+
### Parse Figure
|
|
43
|
+
Analyzes charts, diagrams, and visual elements.
|
|
44
|
+
|
|
45
|
+
**Best for**: Technical documents, presentations, infographics
|
|
46
|
+
|
|
47
|
+
### Locate Object
|
|
48
|
+
Finds specific content using reference text.
|
|
49
|
+
|
|
50
|
+
**Best for**: Searching for specific information in documents
|
|
51
|
+
|
|
52
|
+
## Resolution Options
|
|
53
|
+
|
|
54
|
+
- **tiny**: Fastest, lowest accuracy
|
|
55
|
+
- **small**: Fast, moderate accuracy
|
|
56
|
+
- **base**: Balanced speed/accuracy
|
|
57
|
+
- **gundam**: Recommended (default)
|
|
58
|
+
- **large**: Slowest, highest accuracy
|
|
59
|
+
|
|
60
|
+
## Requirements
|
|
61
|
+
|
|
62
|
+
- Replicate API key (credential required)
|
|
63
|
+
- Internet connection for API calls
|
|
64
|
+
|
|
65
|
+
## Pricing
|
|
66
|
+
|
|
67
|
+
Approximately $0.005 per document (median cost). Actual cost depends on document complexity and resolution.
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { UploadistaError } from "@uploadista/core/errors";
|
|
2
|
+
import { DocumentAiContext, DocumentAiPlugin } from "@uploadista/core/flow";
|
|
3
|
+
import { Effect, Layer } from "effect";
|
|
4
|
+
|
|
5
|
+
//#region src/document-ai-plugin.d.ts
|
|
6
|
+
type ModelId = `${string}/${string}` | `${string}/${string}:${string}`;
|
|
7
|
+
type ReplicateCredentials = {
|
|
8
|
+
apiKey: string;
|
|
9
|
+
};
|
|
10
|
+
type CredentialProvider$1 = (context: DocumentAiContext & {
|
|
11
|
+
serviceType: "replicate";
|
|
12
|
+
}) => Effect.Effect<ReplicateCredentials, UploadistaError>;
|
|
13
|
+
type PluginConfig = string | {
|
|
14
|
+
credentialProvider?: CredentialProvider$1;
|
|
15
|
+
useCredentialProviderService?: boolean;
|
|
16
|
+
ocrModelId?: ModelId;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Create the Replicate DocumentAI plugin
|
|
20
|
+
* Supports both static credentials (OSS) and dynamic credential providers (UploadistaCloud)
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // Static credentials (OSS)
|
|
24
|
+
* documentAiPlugin(process.env.REPLICATE_API_TOKEN)
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* // Dynamic credentials with function (UploadistaCloud)
|
|
28
|
+
* documentAiPlugin({
|
|
29
|
+
* credentialProvider: (context) => Effect.succeed({ apiKey: "..." })
|
|
30
|
+
* })
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* // Dynamic credentials with Effect service (UploadistaCloud)
|
|
34
|
+
* documentAiPlugin({
|
|
35
|
+
* useCredentialProviderService: true
|
|
36
|
+
* })
|
|
37
|
+
*/
|
|
38
|
+
declare const documentAiPlugin: (config: PluginConfig, options?: {
|
|
39
|
+
ocrModelId?: ModelId;
|
|
40
|
+
}) => Layer.Layer<DocumentAiPlugin, never, never>;
|
|
41
|
+
declare const ReplicateDocumentAiPluginLive: Layer.Layer<DocumentAiPlugin, never, never>;
|
|
42
|
+
declare const createReplicateDocumentAiPlugin: (config: PluginConfig, options?: {
|
|
43
|
+
ocrModelId?: ModelId;
|
|
44
|
+
}) => Layer.Layer<DocumentAiPlugin, never, never>;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { ReplicateDocumentAiPluginLive, createReplicateDocumentAiPlugin, documentAiPlugin };
|
|
47
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/document-ai-plugin.ts"],"sourcesContent":[],"mappings":";;;;;KAUK,OAAA;KAEA,oBAAA;EAFA,MAAA,EAAA,MAAO;AAAA,CAAA;AAEa,KAKpB,oBAAA,GAAA,CAAkB,OAAA,EACZ,iBADY,GAAA;EACZ,WAAA,EAAA,WAAA;CACQ,EAAA,GAAd,MAAA,CAAO,MAAO,CAAA,oBAAA,EAAsB,eAAtB,CAAA;KAGd,YAAA,GAHoC,MAAA,GAAA;EAApC,kBAAO,CAAA,EAMe,oBANf;EAAM,4BAAA,CAAA,EAAA,OAAA;EAGb,UAAA,CAAA,EAKc,OALF;AAgFjB,CAAA;;;;;;AA6JA;AAKA;;;;;;;;;;;;;;cAlKa,2BACH;eAEO;MACd,KAAA,CAAA,MAAA;cAyJU,+BAA6B,KAAA,CAAA,MAAA;cAK7B,0CAjKH;eAEO;MACd,KAAA,CAAA,MAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { UploadistaError } from "@uploadista/core/errors";
|
|
2
|
+
import { CredentialProvider, DocumentAiPlugin } from "@uploadista/core/flow";
|
|
3
|
+
import { Effect, Layer, Option } from "effect";
|
|
4
|
+
import Replicate from "replicate";
|
|
5
|
+
|
|
6
|
+
//#region src/document-ai-plugin.ts
|
|
7
|
+
/**
|
|
8
|
+
* Map OcrTaskType to Replicate model task type
|
|
9
|
+
*/
|
|
10
|
+
function mapTaskType(taskType) {
|
|
11
|
+
switch (taskType) {
|
|
12
|
+
case "convertToMarkdown": return "Convert to Markdown";
|
|
13
|
+
case "freeOcr": return "Free OCR";
|
|
14
|
+
case "parseFigure": return "Parse Figure";
|
|
15
|
+
case "locateObject": return "Locate Object by Reference";
|
|
16
|
+
default: return "Convert to Markdown";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Map OcrResolution to Replicate resolution parameter
|
|
21
|
+
*/
|
|
22
|
+
function mapResolution(resolution) {
|
|
23
|
+
switch (resolution) {
|
|
24
|
+
case "tiny": return "Tiny";
|
|
25
|
+
case "small": return "Small";
|
|
26
|
+
case "base": return "Base";
|
|
27
|
+
case "gundam": return "Gundam (Recommended)";
|
|
28
|
+
case "large": return "Large";
|
|
29
|
+
default: return "Gundam (Recommended)";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Determine format based on task type
|
|
34
|
+
*/
|
|
35
|
+
function getFormatFromTaskType(taskType) {
|
|
36
|
+
switch (taskType) {
|
|
37
|
+
case "convertToMarkdown": return "markdown";
|
|
38
|
+
case "parseFigure": return "structured";
|
|
39
|
+
default: return "plain";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Create the Replicate DocumentAI plugin
|
|
44
|
+
* Supports both static credentials (OSS) and dynamic credential providers (UploadistaCloud)
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* // Static credentials (OSS)
|
|
48
|
+
* documentAiPlugin(process.env.REPLICATE_API_TOKEN)
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* // Dynamic credentials with function (UploadistaCloud)
|
|
52
|
+
* documentAiPlugin({
|
|
53
|
+
* credentialProvider: (context) => Effect.succeed({ apiKey: "..." })
|
|
54
|
+
* })
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* // Dynamic credentials with Effect service (UploadistaCloud)
|
|
58
|
+
* documentAiPlugin({
|
|
59
|
+
* useCredentialProviderService: true
|
|
60
|
+
* })
|
|
61
|
+
*/
|
|
62
|
+
const documentAiPlugin = (config, options) => {
|
|
63
|
+
const isStatic = typeof config === "string";
|
|
64
|
+
const staticApiKey = isStatic ? config : null;
|
|
65
|
+
const credentialProvider = isStatic ? null : config.credentialProvider;
|
|
66
|
+
const useCredentialProviderService = isStatic ? false : config.useCredentialProviderService;
|
|
67
|
+
const ocrModelId = (isStatic ? options?.ocrModelId : config.ocrModelId) || "lucataco/deepseek-ocr:0080ec8faf4da6a14afb8502e96f5bb53afbc28b40e2d4a5e17945b8f69eb863";
|
|
68
|
+
const getApiToken = (context) => {
|
|
69
|
+
if (staticApiKey) return Effect.succeed(staticApiKey);
|
|
70
|
+
if (useCredentialProviderService) return Effect.gen(function* () {
|
|
71
|
+
const credentialProviderService = yield* Effect.serviceOption(CredentialProvider);
|
|
72
|
+
if (Option.isNone(credentialProviderService)) return yield* Effect.fail(UploadistaError.fromCode("UNKNOWN_ERROR", { cause: /* @__PURE__ */ new Error("Credential provider service not found") }));
|
|
73
|
+
const credentials = yield* credentialProviderService.value.getCredential({
|
|
74
|
+
clientId: context.clientId,
|
|
75
|
+
serviceType: "replicate"
|
|
76
|
+
});
|
|
77
|
+
if (typeof credentials === "object" && credentials !== null && "apiKey" in credentials && typeof credentials.apiKey === "string") return credentials.apiKey;
|
|
78
|
+
return yield* Effect.fail(UploadistaError.fromCode("UNKNOWN_ERROR", { cause: /* @__PURE__ */ new Error("Invalid credential format from service") }));
|
|
79
|
+
});
|
|
80
|
+
if (credentialProvider) return Effect.gen(function* () {
|
|
81
|
+
return (yield* credentialProvider({
|
|
82
|
+
...context,
|
|
83
|
+
serviceType: "replicate"
|
|
84
|
+
})).apiKey;
|
|
85
|
+
});
|
|
86
|
+
return Effect.fail(UploadistaError.fromCode("UNKNOWN_ERROR", { cause: /* @__PURE__ */ new Error("No API credentials configured") }));
|
|
87
|
+
};
|
|
88
|
+
return Layer.succeed(DocumentAiPlugin, DocumentAiPlugin.of({ performOCR: (inputUrl, params, context) => {
|
|
89
|
+
return Effect.gen(function* () {
|
|
90
|
+
const apiToken = yield* getApiToken(context);
|
|
91
|
+
yield* Effect.logInfo(`Starting OCR for document with task type: ${params.taskType}`);
|
|
92
|
+
const output = yield* Effect.tryPromise({
|
|
93
|
+
try: async () => {
|
|
94
|
+
const replicate = new Replicate({ auth: apiToken });
|
|
95
|
+
const input = {
|
|
96
|
+
image: inputUrl,
|
|
97
|
+
task_type: mapTaskType(params.taskType),
|
|
98
|
+
resolution_size: mapResolution(params.resolution)
|
|
99
|
+
};
|
|
100
|
+
if (params.taskType === "locateObject" && params.referenceText) input.reference_text = params.referenceText;
|
|
101
|
+
return await replicate.run(ocrModelId, { input });
|
|
102
|
+
},
|
|
103
|
+
catch: (error) => {
|
|
104
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
105
|
+
return UploadistaError.fromCode("OCR_FAILED", { cause: errorMessage });
|
|
106
|
+
}
|
|
107
|
+
}).pipe(Effect.tapError((error) => Effect.logError(`OCR failed: ${error instanceof UploadistaError ? error.cause : String(error)}`)));
|
|
108
|
+
let extractedText;
|
|
109
|
+
if (typeof output === "string") extractedText = output;
|
|
110
|
+
else if (typeof output === "object" && output !== null && "text" in output && typeof output.text === "string") extractedText = output.text;
|
|
111
|
+
else extractedText = JSON.stringify(output);
|
|
112
|
+
yield* Effect.logInfo(`OCR completed, extracted ${extractedText.length} characters`);
|
|
113
|
+
return {
|
|
114
|
+
extractedText,
|
|
115
|
+
format: getFormatFromTaskType(params.taskType)
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
} }));
|
|
119
|
+
};
|
|
120
|
+
const ReplicateDocumentAiPluginLive = documentAiPlugin({ useCredentialProviderService: true });
|
|
121
|
+
const createReplicateDocumentAiPlugin = documentAiPlugin;
|
|
122
|
+
|
|
123
|
+
//#endregion
|
|
124
|
+
export { ReplicateDocumentAiPluginLive, createReplicateDocumentAiPlugin, documentAiPlugin };
|
|
125
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["CredentialProviderService","input: Record<string, unknown>","extractedText: string"],"sources":["../src/document-ai-plugin.ts"],"sourcesContent":["import { UploadistaError } from \"@uploadista/core/errors\";\nimport {\n CredentialProvider as CredentialProviderService,\n type DocumentAiContext,\n DocumentAiPlugin,\n type OcrResult,\n} from \"@uploadista/core/flow\";\nimport { Effect, Layer, Option } from \"effect\";\nimport Replicate from \"replicate\";\n\ntype ModelId = `${string}/${string}` | `${string}/${string}:${string}`;\n\ntype ReplicateCredentials = {\n apiKey: string;\n};\n\n// Credential provider function type\ntype CredentialProvider = (\n context: DocumentAiContext & { serviceType: \"replicate\" },\n) => Effect.Effect<ReplicateCredentials, UploadistaError>;\n\n// Plugin configuration can be either a static API key or options with credential provider or service\ntype PluginConfig =\n | string\n | {\n credentialProvider?: CredentialProvider;\n useCredentialProviderService?: boolean;\n ocrModelId?: ModelId;\n };\n\n/**\n * Map OcrTaskType to Replicate model task type\n */\nfunction mapTaskType(taskType: string): string {\n switch (taskType) {\n case \"convertToMarkdown\":\n return \"Convert to Markdown\";\n case \"freeOcr\":\n return \"Free OCR\";\n case \"parseFigure\":\n return \"Parse Figure\";\n case \"locateObject\":\n return \"Locate Object by Reference\";\n default:\n return \"Convert to Markdown\";\n }\n}\n\n/**\n * Map OcrResolution to Replicate resolution parameter\n */\nfunction mapResolution(resolution?: string): string {\n switch (resolution) {\n case \"tiny\":\n return \"Tiny\";\n case \"small\":\n return \"Small\";\n case \"base\":\n return \"Base\";\n case \"gundam\":\n return \"Gundam (Recommended)\";\n case \"large\":\n return \"Large\";\n default:\n return \"Gundam (Recommended)\";\n }\n}\n\n/**\n * Determine format based on task type\n */\nfunction getFormatFromTaskType(taskType: string): \"markdown\" | \"plain\" | \"structured\" {\n switch (taskType) {\n case \"convertToMarkdown\":\n return \"markdown\";\n case \"parseFigure\":\n return \"structured\";\n default:\n return \"plain\";\n }\n}\n\n/**\n * Create the Replicate DocumentAI plugin\n * Supports both static credentials (OSS) and dynamic credential providers (UploadistaCloud)\n *\n * @example\n * // Static credentials (OSS)\n * documentAiPlugin(process.env.REPLICATE_API_TOKEN)\n *\n * @example\n * // Dynamic credentials with function (UploadistaCloud)\n * documentAiPlugin({\n * credentialProvider: (context) => Effect.succeed({ apiKey: \"...\" })\n * })\n *\n * @example\n * // Dynamic credentials with Effect service (UploadistaCloud)\n * documentAiPlugin({\n * useCredentialProviderService: true\n * })\n */\nexport const documentAiPlugin = (\n config: PluginConfig,\n options?: {\n ocrModelId?: ModelId;\n },\n) => {\n // Parse configuration\n const isStatic = typeof config === \"string\";\n const staticApiKey = isStatic ? config : null;\n const credentialProvider = isStatic ? null : config.credentialProvider;\n const useCredentialProviderService = isStatic\n ? false\n : config.useCredentialProviderService;\n\n // Model ID for DeepSeek-OCR\n const ocrModelId =\n (isStatic ? options?.ocrModelId : config.ocrModelId) ||\n \"lucataco/deepseek-ocr:0080ec8faf4da6a14afb8502e96f5bb53afbc28b40e2d4a5e17945b8f69eb863\";\n\n // Helper to get API token (either static, from provider function, or from service)\n const getApiToken = (context: DocumentAiContext) => {\n if (staticApiKey) {\n return Effect.succeed(staticApiKey);\n }\n if (useCredentialProviderService) {\n return Effect.gen(function* () {\n const credentialProviderService = yield* Effect.serviceOption(\n CredentialProviderService,\n );\n\n if (Option.isNone(credentialProviderService)) {\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: new Error(\"Credential provider service not found\"),\n }),\n );\n }\n\n const credentials =\n yield* credentialProviderService.value.getCredential({\n clientId: context.clientId,\n serviceType: \"replicate\",\n });\n\n if (\n typeof credentials === \"object\" &&\n credentials !== null &&\n \"apiKey\" in credentials &&\n typeof credentials.apiKey === \"string\"\n ) {\n return credentials.apiKey;\n }\n\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: new Error(\"Invalid credential format from service\"),\n }),\n );\n });\n }\n if (credentialProvider) {\n return Effect.gen(function* () {\n const credentials = yield* credentialProvider({\n ...context,\n serviceType: \"replicate\",\n });\n return credentials.apiKey;\n });\n }\n return Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: new Error(\"No API credentials configured\"),\n }),\n );\n };\n\n return Layer.succeed(\n DocumentAiPlugin,\n DocumentAiPlugin.of({\n performOCR: (inputUrl, params, context) => {\n return Effect.gen(function* () {\n // Get API token (static or from credential provider)\n const apiToken = yield* getApiToken(context);\n\n yield* Effect.logInfo(\n `Starting OCR for document with task type: ${params.taskType}`\n );\n\n const output = yield* Effect.tryPromise({\n try: async () => {\n const replicate = new Replicate({\n auth: apiToken,\n });\n\n const input: Record<string, unknown> = {\n image: inputUrl,\n task_type: mapTaskType(params.taskType),\n resolution_size: mapResolution(params.resolution),\n };\n\n // Add reference text if provided and task type is locateObject\n if (params.taskType === \"locateObject\" && params.referenceText) {\n input.reference_text = params.referenceText;\n }\n\n const result = await replicate.run(ocrModelId, {\n input,\n });\n\n return result;\n },\n catch: (error) => {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n return UploadistaError.fromCode(\"OCR_FAILED\", {\n cause: errorMessage,\n });\n },\n }).pipe(\n Effect.tapError((error) =>\n Effect.logError(`OCR failed: ${error instanceof UploadistaError ? error.cause : String(error)}`)\n )\n );\n\n // Extract text from the result\n // Replicate OCR typically returns a string or an object with text\n let extractedText: string;\n\n if (typeof output === \"string\") {\n extractedText = output;\n } else if (\n typeof output === \"object\" &&\n output !== null &&\n \"text\" in output &&\n typeof output.text === \"string\"\n ) {\n extractedText = output.text;\n } else {\n // Try to stringify if it's a different format\n extractedText = JSON.stringify(output);\n }\n\n yield* Effect.logInfo(`OCR completed, extracted ${extractedText.length} characters`);\n\n const result: OcrResult = {\n extractedText,\n format: getFormatFromTaskType(params.taskType),\n };\n\n return result;\n });\n },\n })\n );\n};\n\n// Export live layer with credential provider service\nexport const ReplicateDocumentAiPluginLive = documentAiPlugin({\n useCredentialProviderService: true,\n});\n\n// Export factory function for custom configuration\nexport const createReplicateDocumentAiPlugin = documentAiPlugin;\n"],"mappings":"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"}
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@uploadista/flow-documents-replicate",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.16-beta.2",
|
|
5
|
+
"description": "Replicate OCR plugin for Uploadista document processing",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Uploadista",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.mts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.cjs",
|
|
13
|
+
"default": "./dist/index.mjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"effect": "3.19.4",
|
|
18
|
+
"replicate": "1.4.0",
|
|
19
|
+
"@uploadista/core": "0.0.16-beta.2"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/node": "24.10.1",
|
|
23
|
+
"tsdown": "0.16.5",
|
|
24
|
+
"@uploadista/typescript-config": "0.0.16-beta.2"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsdown",
|
|
28
|
+
"format": "biome format --write ./src",
|
|
29
|
+
"lint": "biome lint --write ./src",
|
|
30
|
+
"check": "biome check --write ./src"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { UploadistaError } from "@uploadista/core/errors";
|
|
2
|
+
import {
|
|
3
|
+
CredentialProvider as CredentialProviderService,
|
|
4
|
+
type DocumentAiContext,
|
|
5
|
+
DocumentAiPlugin,
|
|
6
|
+
type OcrResult,
|
|
7
|
+
} from "@uploadista/core/flow";
|
|
8
|
+
import { Effect, Layer, Option } from "effect";
|
|
9
|
+
import Replicate from "replicate";
|
|
10
|
+
|
|
11
|
+
type ModelId = `${string}/${string}` | `${string}/${string}:${string}`;
|
|
12
|
+
|
|
13
|
+
type ReplicateCredentials = {
|
|
14
|
+
apiKey: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Credential provider function type
|
|
18
|
+
type CredentialProvider = (
|
|
19
|
+
context: DocumentAiContext & { serviceType: "replicate" },
|
|
20
|
+
) => Effect.Effect<ReplicateCredentials, UploadistaError>;
|
|
21
|
+
|
|
22
|
+
// Plugin configuration can be either a static API key or options with credential provider or service
|
|
23
|
+
type PluginConfig =
|
|
24
|
+
| string
|
|
25
|
+
| {
|
|
26
|
+
credentialProvider?: CredentialProvider;
|
|
27
|
+
useCredentialProviderService?: boolean;
|
|
28
|
+
ocrModelId?: ModelId;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Map OcrTaskType to Replicate model task type
|
|
33
|
+
*/
|
|
34
|
+
function mapTaskType(taskType: string): string {
|
|
35
|
+
switch (taskType) {
|
|
36
|
+
case "convertToMarkdown":
|
|
37
|
+
return "Convert to Markdown";
|
|
38
|
+
case "freeOcr":
|
|
39
|
+
return "Free OCR";
|
|
40
|
+
case "parseFigure":
|
|
41
|
+
return "Parse Figure";
|
|
42
|
+
case "locateObject":
|
|
43
|
+
return "Locate Object by Reference";
|
|
44
|
+
default:
|
|
45
|
+
return "Convert to Markdown";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Map OcrResolution to Replicate resolution parameter
|
|
51
|
+
*/
|
|
52
|
+
function mapResolution(resolution?: string): string {
|
|
53
|
+
switch (resolution) {
|
|
54
|
+
case "tiny":
|
|
55
|
+
return "Tiny";
|
|
56
|
+
case "small":
|
|
57
|
+
return "Small";
|
|
58
|
+
case "base":
|
|
59
|
+
return "Base";
|
|
60
|
+
case "gundam":
|
|
61
|
+
return "Gundam (Recommended)";
|
|
62
|
+
case "large":
|
|
63
|
+
return "Large";
|
|
64
|
+
default:
|
|
65
|
+
return "Gundam (Recommended)";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Determine format based on task type
|
|
71
|
+
*/
|
|
72
|
+
function getFormatFromTaskType(taskType: string): "markdown" | "plain" | "structured" {
|
|
73
|
+
switch (taskType) {
|
|
74
|
+
case "convertToMarkdown":
|
|
75
|
+
return "markdown";
|
|
76
|
+
case "parseFigure":
|
|
77
|
+
return "structured";
|
|
78
|
+
default:
|
|
79
|
+
return "plain";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Create the Replicate DocumentAI plugin
|
|
85
|
+
* Supports both static credentials (OSS) and dynamic credential providers (UploadistaCloud)
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* // Static credentials (OSS)
|
|
89
|
+
* documentAiPlugin(process.env.REPLICATE_API_TOKEN)
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* // Dynamic credentials with function (UploadistaCloud)
|
|
93
|
+
* documentAiPlugin({
|
|
94
|
+
* credentialProvider: (context) => Effect.succeed({ apiKey: "..." })
|
|
95
|
+
* })
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* // Dynamic credentials with Effect service (UploadistaCloud)
|
|
99
|
+
* documentAiPlugin({
|
|
100
|
+
* useCredentialProviderService: true
|
|
101
|
+
* })
|
|
102
|
+
*/
|
|
103
|
+
export const documentAiPlugin = (
|
|
104
|
+
config: PluginConfig,
|
|
105
|
+
options?: {
|
|
106
|
+
ocrModelId?: ModelId;
|
|
107
|
+
},
|
|
108
|
+
) => {
|
|
109
|
+
// Parse configuration
|
|
110
|
+
const isStatic = typeof config === "string";
|
|
111
|
+
const staticApiKey = isStatic ? config : null;
|
|
112
|
+
const credentialProvider = isStatic ? null : config.credentialProvider;
|
|
113
|
+
const useCredentialProviderService = isStatic
|
|
114
|
+
? false
|
|
115
|
+
: config.useCredentialProviderService;
|
|
116
|
+
|
|
117
|
+
// Model ID for DeepSeek-OCR
|
|
118
|
+
const ocrModelId =
|
|
119
|
+
(isStatic ? options?.ocrModelId : config.ocrModelId) ||
|
|
120
|
+
"lucataco/deepseek-ocr:0080ec8faf4da6a14afb8502e96f5bb53afbc28b40e2d4a5e17945b8f69eb863";
|
|
121
|
+
|
|
122
|
+
// Helper to get API token (either static, from provider function, or from service)
|
|
123
|
+
const getApiToken = (context: DocumentAiContext) => {
|
|
124
|
+
if (staticApiKey) {
|
|
125
|
+
return Effect.succeed(staticApiKey);
|
|
126
|
+
}
|
|
127
|
+
if (useCredentialProviderService) {
|
|
128
|
+
return Effect.gen(function* () {
|
|
129
|
+
const credentialProviderService = yield* Effect.serviceOption(
|
|
130
|
+
CredentialProviderService,
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
if (Option.isNone(credentialProviderService)) {
|
|
134
|
+
return yield* Effect.fail(
|
|
135
|
+
UploadistaError.fromCode("UNKNOWN_ERROR", {
|
|
136
|
+
cause: new Error("Credential provider service not found"),
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const credentials =
|
|
142
|
+
yield* credentialProviderService.value.getCredential({
|
|
143
|
+
clientId: context.clientId,
|
|
144
|
+
serviceType: "replicate",
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
if (
|
|
148
|
+
typeof credentials === "object" &&
|
|
149
|
+
credentials !== null &&
|
|
150
|
+
"apiKey" in credentials &&
|
|
151
|
+
typeof credentials.apiKey === "string"
|
|
152
|
+
) {
|
|
153
|
+
return credentials.apiKey;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return yield* Effect.fail(
|
|
157
|
+
UploadistaError.fromCode("UNKNOWN_ERROR", {
|
|
158
|
+
cause: new Error("Invalid credential format from service"),
|
|
159
|
+
}),
|
|
160
|
+
);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
if (credentialProvider) {
|
|
164
|
+
return Effect.gen(function* () {
|
|
165
|
+
const credentials = yield* credentialProvider({
|
|
166
|
+
...context,
|
|
167
|
+
serviceType: "replicate",
|
|
168
|
+
});
|
|
169
|
+
return credentials.apiKey;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return Effect.fail(
|
|
173
|
+
UploadistaError.fromCode("UNKNOWN_ERROR", {
|
|
174
|
+
cause: new Error("No API credentials configured"),
|
|
175
|
+
}),
|
|
176
|
+
);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
return Layer.succeed(
|
|
180
|
+
DocumentAiPlugin,
|
|
181
|
+
DocumentAiPlugin.of({
|
|
182
|
+
performOCR: (inputUrl, params, context) => {
|
|
183
|
+
return Effect.gen(function* () {
|
|
184
|
+
// Get API token (static or from credential provider)
|
|
185
|
+
const apiToken = yield* getApiToken(context);
|
|
186
|
+
|
|
187
|
+
yield* Effect.logInfo(
|
|
188
|
+
`Starting OCR for document with task type: ${params.taskType}`
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const output = yield* Effect.tryPromise({
|
|
192
|
+
try: async () => {
|
|
193
|
+
const replicate = new Replicate({
|
|
194
|
+
auth: apiToken,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
const input: Record<string, unknown> = {
|
|
198
|
+
image: inputUrl,
|
|
199
|
+
task_type: mapTaskType(params.taskType),
|
|
200
|
+
resolution_size: mapResolution(params.resolution),
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// Add reference text if provided and task type is locateObject
|
|
204
|
+
if (params.taskType === "locateObject" && params.referenceText) {
|
|
205
|
+
input.reference_text = params.referenceText;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const result = await replicate.run(ocrModelId, {
|
|
209
|
+
input,
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
return result;
|
|
213
|
+
},
|
|
214
|
+
catch: (error) => {
|
|
215
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
216
|
+
|
|
217
|
+
return UploadistaError.fromCode("OCR_FAILED", {
|
|
218
|
+
cause: errorMessage,
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
}).pipe(
|
|
222
|
+
Effect.tapError((error) =>
|
|
223
|
+
Effect.logError(`OCR failed: ${error instanceof UploadistaError ? error.cause : String(error)}`)
|
|
224
|
+
)
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
// Extract text from the result
|
|
228
|
+
// Replicate OCR typically returns a string or an object with text
|
|
229
|
+
let extractedText: string;
|
|
230
|
+
|
|
231
|
+
if (typeof output === "string") {
|
|
232
|
+
extractedText = output;
|
|
233
|
+
} else if (
|
|
234
|
+
typeof output === "object" &&
|
|
235
|
+
output !== null &&
|
|
236
|
+
"text" in output &&
|
|
237
|
+
typeof output.text === "string"
|
|
238
|
+
) {
|
|
239
|
+
extractedText = output.text;
|
|
240
|
+
} else {
|
|
241
|
+
// Try to stringify if it's a different format
|
|
242
|
+
extractedText = JSON.stringify(output);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
yield* Effect.logInfo(`OCR completed, extracted ${extractedText.length} characters`);
|
|
246
|
+
|
|
247
|
+
const result: OcrResult = {
|
|
248
|
+
extractedText,
|
|
249
|
+
format: getFormatFromTaskType(params.taskType),
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
return result;
|
|
253
|
+
});
|
|
254
|
+
},
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// Export live layer with credential provider service
|
|
260
|
+
export const ReplicateDocumentAiPluginLive = documentAiPlugin({
|
|
261
|
+
useCredentialProviderService: true,
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
// Export factory function for custom configuration
|
|
265
|
+
export const createReplicateDocumentAiPlugin = documentAiPlugin;
|
package/src/index.ts
ADDED
package/tsconfig.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "@uploadista/typescript-config/server.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"baseUrl": "./",
|
|
5
|
+
"paths": {
|
|
6
|
+
"@/*": ["./src/*"]
|
|
7
|
+
},
|
|
8
|
+
"outDir": "./dist",
|
|
9
|
+
"rootDir": "./src",
|
|
10
|
+
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
|
11
|
+
"types": []
|
|
12
|
+
},
|
|
13
|
+
"include": ["src"]
|
|
14
|
+
}
|