Update unstructured document loaders (#2213)

* Update UnstructuredFile with missing values. Removed deprecated values.

* Update UnstructuredFolder with missing values. Removed deprecated values.

* Added suport for sourceIdKey to unstructured loaders

* Update unstructured hi_res model names

* Update S3File document loader with latest unstructured and model changes

* Update credential method for S3File document loader

* moved pnpm req to engines to avoid minor version changes

* Change unstructured skipInferTableTypes parse to JSON

* Update unstructured with new params. Also fixed list order, missing values, and support for null on multiOptions.
This commit is contained in:
Quinn
2024-04-21 11:42:28 -07:00
committed by GitHub
parent 95beaba9d9
commit 4c2ba109fd
4 changed files with 1119 additions and 245 deletions
@@ -1,5 +1,11 @@
import { ICommonObject, INode, INodeData, INodeParams } from '../../../src/Interface'
import { UnstructuredLoader, UnstructuredLoaderOptions } from 'langchain/document_loaders/fs/unstructured'
import {
UnstructuredLoader,
UnstructuredLoaderOptions,
UnstructuredLoaderStrategy,
SkipInferTableTypes,
HiResModelName
} from 'langchain/document_loaders/fs/unstructured'
import { getCredentialData, getCredentialParam } from '../../../src/utils'
class UnstructuredFile_DocumentLoaders implements INode {
@@ -17,7 +23,7 @@ class UnstructuredFile_DocumentLoaders implements INode {
constructor() {
this.label = 'Unstructured File Loader'
this.name = 'unstructuredFileLoader'
this.version = 1.0
this.version = 2.0
this.type = 'Document'
this.icon = 'unstructured-file.svg'
this.category = 'Document Loaders'
@@ -46,65 +52,340 @@ class UnstructuredFile_DocumentLoaders implements INode {
default: 'http://localhost:8000/general/v0/general'
},
{
label: 'Element Type',
name: 'elementType',
description:
'Unstructured partition document into different types, select the types to return. If not selected, all types will be returned',
label: 'Strategy',
name: 'strategy',
description: 'The strategy to use for partitioning PDF/image. Options are fast, hi_res, auto. Default: auto.',
type: 'options',
options: [
{
label: 'Hi-Res',
name: 'hi_res'
},
{
label: 'Fast',
name: 'fast'
},
{
label: 'OCR Only',
name: 'ocr_only'
},
{
label: 'Auto',
name: 'auto'
}
],
optional: true,
additionalParams: true,
default: 'auto'
},
{
label: 'Encoding',
name: 'encoding',
description: 'The encoding method used to decode the text input. Default: utf-8.',
type: 'string',
optional: true,
additionalParams: true,
default: 'utf-8'
},
{
label: 'Skip Infer Table Types',
name: 'skipInferTableTypes',
description: 'The document types that you want to skip table extraction with. Default: pdf, jpg, png.',
type: 'multiOptions',
options: [
{
label: 'FigureCaption',
name: 'FigureCaption'
label: 'doc',
name: 'doc'
},
{
label: 'NarrativeText',
name: 'NarrativeText'
label: 'docx',
name: 'docx'
},
{
label: 'ListItem',
name: 'ListItem'
label: 'eml',
name: 'eml'
},
{
label: 'Title',
name: 'Title'
label: 'epub',
name: 'epub'
},
{
label: 'Address',
name: 'Address'
label: 'heic',
name: 'heic'
},
{
label: 'Table',
name: 'Table'
label: 'htm',
name: 'htm'
},
{
label: 'PageBreak',
name: 'PageBreak'
label: 'html',
name: 'html'
},
{
label: 'Header',
name: 'Header'
label: 'jpeg',
name: 'jpeg'
},
{
label: 'Footer',
name: 'Footer'
label: 'jpg',
name: 'jpg'
},
{
label: 'UncategorizedText',
name: 'UncategorizedText'
label: 'md',
name: 'md'
},
{
label: 'Image',
name: 'Image'
label: 'msg',
name: 'msg'
},
{
label: 'Formula',
name: 'Formula'
label: 'odt',
name: 'odt'
},
{
label: 'pdf',
name: 'pdf'
},
{
label: 'png',
name: 'png'
},
{
label: 'ppt',
name: 'ppt'
},
{
label: 'pptx',
name: 'pptx'
},
{
label: 'rtf',
name: 'rtf'
},
{
label: 'text',
name: 'text'
},
{
label: 'txt',
name: 'txt'
},
{
label: 'xls',
name: 'xls'
},
{
label: 'xlsx',
name: 'xlsx'
}
],
optional: true,
additionalParams: true,
default: '["pdf", "jpg", "png"]'
},
{
label: 'Hi-Res Model Name',
name: 'hiResModelName',
description: 'The name of the inference model used when strategy is hi_res. Default: detectron2_onnx.',
type: 'options',
options: [
{
label: 'chipper',
name: 'chipper',
description:
'Exlusive to Unstructured hosted API. The Chipper model is Unstructured in-house image-to-text model based on transformer-based Visual Document Understanding (VDU) models.'
},
{
label: 'detectron2_onnx',
name: 'detectron2_onnx',
description:
'A Computer Vision model by Facebook AI that provides object detection and segmentation algorithms with ONNX Runtime. It is the fastest model with the hi_res strategy.'
},
{
label: 'yolox',
name: 'yolox',
description: 'A single-stage real-time object detector that modifies YOLOv3 with a DarkNet53 backbone.'
},
{
label: 'yolox_quantized',
name: 'yolox_quantized',
description: 'Runs faster than YoloX and its speed is closer to Detectron2.'
}
],
optional: true,
additionalParams: true,
default: 'detectron2_onnx'
},
{
label: 'Chunking Strategy',
name: 'chunkingStrategy',
description:
'Use one of the supported strategies to chunk the returned elements. When omitted, no chunking is performed and any other chunking parameters provided are ignored. Default: by_title',
type: 'options',
options: [
{
label: 'None',
name: 'None'
},
{
label: 'By Title',
name: 'by_title'
}
],
optional: true,
additionalParams: true,
default: 'by_title'
},
{
label: 'OCR Languages',
name: 'ocrLanguages',
description: 'The languages to use for OCR. Note: Being depricated as languages is the new type. Pending langchain update.',
type: 'multiOptions',
options: [
{
label: 'English',
name: 'eng'
},
{
label: 'Spanish (Español)',
name: 'spa'
},
{
label: 'Mandarin Chinese (普通话)',
name: 'cmn'
},
{
label: 'Hindi (हिन्दी)',
name: 'hin'
},
{
label: 'Arabic (اَلْعَرَبِيَّةُ)',
name: 'ara'
},
{
label: 'Portuguese (Português)',
name: 'por'
},
{
label: 'Bengali (বাংলা)',
name: 'ben'
},
{
label: 'Russian (Русский)',
name: 'rus'
},
{
label: 'Japanese (日本語)',
name: 'jpn'
},
{
label: 'Punjabi (ਪੰਜਾਬੀ)',
name: 'pan'
},
{
label: 'German (Deutsch)',
name: 'deu'
},
{
label: 'Korean (한국어)',
name: 'kor'
},
{
label: 'French (Français)',
name: 'fra'
},
{
label: 'Italian (Italiano)',
name: 'ita'
},
{
label: 'Vietnamese (Tiếng Việt)',
name: 'vie'
}
],
default: [],
optional: true,
additionalParams: true
},
{
label: 'Source ID Key',
name: 'sourceIdKey',
type: 'string',
description:
'Key used to get the true source of document, to be compared against the record. Document metadata must contain the Source ID Key.',
default: 'source',
placeholder: 'source',
optional: true,
additionalParams: true
},
{
label: 'Coordinates',
name: 'coordinates',
type: 'boolean',
description: 'If true, return coordinates for each element. Default: false.',
optional: true,
additionalParams: true,
default: false
},
{
label: 'XML Keep Tags',
name: 'xmlKeepTags',
description:
'If True, will retain the XML tags in the output. Otherwise it will simply extract the text from within the tags. Only applies to partition_xml.',
type: 'boolean',
optional: true,
additionalParams: true
},
{
label: 'Include Page Breaks',
name: 'includePageBreaks',
description: 'When true, the output will include page break elements when the filetype supports it.',
type: 'boolean',
optional: true,
additionalParams: true
},
{
label: 'XML Keep Tags',
name: 'xmlKeepTags',
description: 'Whether to keep XML tags in the output.',
type: 'boolean',
optional: true,
additionalParams: true
},
{
label: 'Multi-Page Sections',
name: 'multiPageSections',
description: 'Whether to treat multi-page documents as separate sections.',
type: 'boolean',
optional: true,
additionalParams: true
},
{
label: 'Combine Under N Chars',
name: 'combineUnderNChars',
description:
"If chunking strategy is set, combine elements until a section reaches a length of n chars. Default: value of max_characters. Can't exceed value of max_characters.",
type: 'number',
optional: true,
additionalParams: true
},
{
label: 'New After N Chars',
name: 'newAfterNChars',
description:
"If chunking strategy is set, cut off new sections after reaching a length of n chars (soft max). value of max_characters. Can't exceed value of max_characters.",
type: 'number',
optional: true,
additionalParams: true
},
{
label: 'Max Characters',
name: 'maxCharacters',
description:
'If chunking strategy is set, cut off new sections after reaching a length of n chars (hard max). Default: 500',
type: 'number',
optional: true,
additionalParams: true,
default: '500'
},
{
label: 'Metadata',
name: 'metadata',
@@ -118,44 +399,69 @@ class UnstructuredFile_DocumentLoaders implements INode {
async init(nodeData: INodeData, _: string, options: ICommonObject): Promise<any> {
const filePath = nodeData.inputs?.filePath as string
const unstructuredAPIUrl = nodeData.inputs?.unstructuredAPIUrl as string
const elementType = nodeData.inputs?.elementType as string
const strategy = nodeData.inputs?.strategy as UnstructuredLoaderStrategy
const encoding = nodeData.inputs?.encoding as string
const coordinates = nodeData.inputs?.coordinates as boolean
const skipInferTableTypes = nodeData.inputs?.skipInferTableTypes
? JSON.parse(nodeData.inputs?.skipInferTableTypes as string)
: ([] as SkipInferTableTypes[])
const hiResModelName = nodeData.inputs?.hiResModelName as HiResModelName
const includePageBreaks = nodeData.inputs?.includePageBreaks as boolean
const chunkingStrategy = nodeData.inputs?.chunkingStrategy as 'None' | 'by_title'
const metadata = nodeData.inputs?.metadata
const sourceIdKey = (nodeData.inputs?.sourceIdKey as string) || 'source'
const ocrLanguages = nodeData.inputs?.ocrLanguages ? JSON.parse(nodeData.inputs?.ocrLanguages as string) : ([] as string[])
const xmlKeepTags = nodeData.inputs?.xmlKeepTags as boolean
const multiPageSections = nodeData.inputs?.multiPageSections as boolean
const combineUnderNChars = nodeData.inputs?.combineUnderNChars as number
const newAfterNChars = nodeData.inputs?.newAfterNChars as number
const maxCharacters = nodeData.inputs?.maxCharacters as number
const obj: UnstructuredLoaderOptions = { apiUrl: unstructuredAPIUrl }
const obj: UnstructuredLoaderOptions = {
apiUrl: unstructuredAPIUrl,
strategy,
encoding,
coordinates,
skipInferTableTypes,
hiResModelName,
includePageBreaks,
chunkingStrategy,
ocrLanguages,
xmlKeepTags,
multiPageSections,
combineUnderNChars,
newAfterNChars,
maxCharacters
}
const credentialData = await getCredentialData(nodeData.credential ?? '', options)
const unstructuredAPIKey = getCredentialParam('unstructuredAPIKey', credentialData, nodeData)
if (unstructuredAPIKey) obj.apiKey = unstructuredAPIKey
const loader = new UnstructuredLoader(filePath, obj)
const docs = await loader.load()
let elementTypes: string[] = []
if (elementType) {
try {
elementTypes = JSON.parse(elementType)
} catch (e) {
elementTypes = []
}
}
let docs = await loader.load()
if (metadata) {
const parsedMetadata = typeof metadata === 'object' ? metadata : JSON.parse(metadata)
let finaldocs = []
for (const doc of docs) {
const newdoc = {
...doc,
metadata: {
...doc.metadata,
...parsedMetadata
}
docs = docs.map((doc) => ({
...doc,
metadata: {
...doc.metadata,
...parsedMetadata,
[sourceIdKey]: doc.metadata[sourceIdKey] || sourceIdKey
}
finaldocs.push(newdoc)
}
return elementTypes.length ? finaldocs.filter((doc) => elementTypes.includes(doc.metadata.category)) : finaldocs
}))
} else {
docs = docs.map((doc) => ({
...doc,
metadata: {
...doc.metadata,
[sourceIdKey]: doc.metadata[sourceIdKey] || sourceIdKey
}
}))
}
return elementTypes.length ? docs.filter((doc) => elementTypes.includes(doc.metadata.category)) : docs
return docs
}
}