textract

package
v1.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 26 Imported by: 0

README

Textract

Parity grade: A · SDK aws-sdk-go-v2/service/textract@v1.43.4 · last audited 2026-08-07 (8c56f4eb9)

Coverage

Metric Value
Operations audited 25 (25 ok)
Feature families 6 (6 ok)
Known gaps 1
Structural gaps (can't be emulated) 1
Deferred items 1
Resource leaks clean
Known gaps
  • Geometry.RotationAngle (types.Geometry) was added to the Geometry struct (*float64, omitempty) for wire-shape completeness but nothing in synthetic_blocks.go ever populates it -- always nil/omitted. Harmless (matches real AWS behavior when a document has no detected rotation), flagging only so a future auditor doesn't assume it's untested/forgotten.
Structural gaps

These do not block an A grade — no implementation could produce real data here because the underlying data source cannot exist in an emulator.

  • AnalyzeDocument/StartDocumentAnalysis's HumanLoopConfig-triggered activation decision (AnalyzeDocumentOutput.HumanLoopActivationOutput) cannot be computed: real AWS evaluates the referenced FlowDefinition's HumanLoopActivationConditionsConfig, a JsonPath-based rules engine over per-block confidence scores that lives in SageMaker Augmented AI, a service gopherstack does not model the condition-evaluation semantics of anywhere (SageMaker's own FlowDefinition resource is tracked, but only as a CRUD record, not as an executable condition set). Approximating activation (e.g. a fixed probability, or a made-up confidence threshold) would fabricate a business decision, not derive one from held state -- exactly the failure mode this campaign removes. What IS buildable and built this pass (gopherstack-n1bo): HumanLoopConfig's two required members (FlowDefinitionArn, HumanLoopName) are validated, InvalidParameterException on either missing; HumanLoopActivationOutput is correctly omitted (nil) rather than fabricated. (bd: gopherstack-n1bo)
Deferred
  • Full byte-for-byte Block field audit beyond the fields cross-checked this pass (BlockType, ColumnIndex, ColumnSpan, Confidence, EntityTypes, Geometry, Id, Page, Query, Relationships, RowIndex, RowSpan, SelectionStatus, Text, TextType) — spot-checked per BlockType variant (WORD/LINE/PAGE/TABLE/CELL/KEY_VALUE_SET/QUERY/QUERY_RESULT/SIGNATURE/LAYOUT_*), not exhaustively fuzzed.

More

Documentation

Index

Constants

View Source
const MaxJobHistory = maxJobHistory

MaxJobHistory is the exported value for testing.

Variables

View Source
var (
	// ErrJobNotFound is returned when a document job is not found.
	ErrJobNotFound = awserr.New("InvalidJobIdException", awserr.ErrNotFound)
	// ErrAdapterNotFound is returned when an adapter is not found. Real AWS
	// returns ResourceNotFoundException (not InvalidParameterException) for
	// GetAdapter/UpdateAdapter/DeleteAdapter/CreateAdapterVersion/
	// ListAdapterVersions/Tag*Resource on a nonexistent adapter -- verified
	// against every deserializeOpError<Op> switch in the SDK.
	ErrAdapterNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)
	// ErrAdapterVersionNotFound is returned when an adapter version is not
	// found. See ErrAdapterNotFound's doc comment for the error-code source.
	ErrAdapterVersionNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)
	// ErrValidation is returned when request parameters fail validation.
	ErrValidation = awserr.New("ValidationException", awserr.ErrInvalidParameter)
)
View Source
var ErrNilAppContext = errors.New("textract: nil AppContext")

ErrNilAppContext is returned when Init receives a nil AppContext.

Functions

This section is empty.

Types

type Adapter

type Adapter struct {
	CreationTime time.Time         `json:"creationTime"`
	Tags         map[string]string `json:"tags"`
	AdapterID    string            `json:"adapterId"`
	// Region is the store.Table[Adapter] key material -- see the
	// DocumentJob.Region doc comment above for why this field exists and is
	// excluded from persisted JSON.
	Region             string   `json:"-"`
	AdapterName        string   `json:"adapterName"`
	AutoUpdate         string   `json:"autoUpdate"`
	Description        string   `json:"description"`
	ClientRequestToken string   `json:"clientRequestToken,omitempty"`
	FeatureTypes       []string `json:"featureTypes"`
}

Adapter represents a Textract Adapter.

type AdapterUsage added in v1.3.1

type AdapterUsage struct {
	AdapterID string   `json:"AdapterId"`
	Version   string   `json:"Version"`
	Pages     []string `json:"Pages,omitempty"`
}

AdapterUsage references one adapter (and version) to apply, and which pages of the document it applies to. See AdaptersConfig's doc comment for why this isn't named Adapter.

type AdapterVersion

type AdapterVersion struct {
	CreationTime      time.Time                        `json:"creationTime"`
	Tags              map[string]string                `json:"tags"`
	DatasetConfig     *DatasetConfig                   `json:"datasetConfig,omitempty"`
	OutputConfig      *OutputConfig                    `json:"outputConfig,omitempty"`
	EvaluationMetrics []AdapterVersionEvaluationMetric `json:"evaluationMetrics,omitempty"`
	AdapterVersion    string                           `json:"adapterVersion"`
	AdapterID         string                           `json:"adapterId"`
	Status            string                           `json:"status"`
	StatusMessage     string                           `json:"statusMessage"`
	//nolint:revive,staticcheck // KMSKeyId: AWS SDK field name convention
	KMSKeyId           string   `json:"kmsKeyId,omitempty"`
	ClientRequestToken string   `json:"clientRequestToken,omitempty"`
	Region             string   `json:"-"`
	FeatureTypes       []string `json:"featureTypes"`
}

AdapterVersion represents a version of a Textract Adapter.

type AdapterVersionEvaluationMetric added in v1.2.0

type AdapterVersionEvaluationMetric struct {
	Baseline       *EvaluationMetric `json:"Baseline,omitempty"`
	AdapterVersion *EvaluationMetric `json:"AdapterVersion,omitempty"`
	FeatureType    string            `json:"FeatureType,omitempty"`
}

AdapterVersionEvaluationMetric pairs baseline and adapter-version scores for a single FeatureType. AdapterVersion.EvaluationMetrics is a list of these -- one per FeatureType the adapter version was trained for -- not a single flat metrics struct.

type AdaptersConfig added in v1.3.1

type AdaptersConfig struct {
	Adapters []AdapterUsage `json:"Adapters"`
}

AdaptersConfig holds the adapters to apply during AnalyzeDocument. Real AWS's AdaptersConfig.Adapters element type is itself named types.Adapter -- gopherstack names it AdapterUsage instead to avoid colliding with the unrelated Adapter management-resource type (CreateAdapter/GetAdapter/...).

type AnalyzeIDDetections

type AnalyzeIDDetections struct {
	Geometry        *Geometry        `json:"Geometry,omitempty"`
	NormalizedValue *NormalizedValue `json:"NormalizedValue,omitempty"`
	Text            string           `json:"Text"`
	Confidence      float64          `json:"Confidence"`
}

AnalyzeIDDetections holds a detected ID field.

type Block

type Block struct {
	RowIndex        *int           `json:"RowIndex,omitempty"`
	ColumnIndex     *int           `json:"ColumnIndex,omitempty"`
	Query           *QueryBlock    `json:"Query,omitempty"`
	Page            *int           `json:"Page,omitempty"`
	Geometry        *Geometry      `json:"Geometry,omitempty"`
	ColumnSpan      *int           `json:"ColumnSpan,omitempty"`
	RowSpan         *int           `json:"RowSpan,omitempty"`
	BlockType       string         `json:"BlockType"`
	SelectionStatus string         `json:"SelectionStatus,omitempty"`
	Text            string         `json:"Text"`
	ID              string         `json:"Id"`
	TextType        string         `json:"TextType,omitempty"`
	EntityTypes     []string       `json:"EntityTypes,omitempty"`
	Relationships   []Relationship `json:"Relationships,omitempty"`
	Confidence      float64        `json:"Confidence"`
}

Block represents a detected text element returned by Textract.

func PaginateBlocks

func PaginateBlocks(blocks []Block, maxResults int, nextToken string) ([]Block, string)

PaginateBlocks applies pagination to blocks (exported for handler use).

type BoundingBox

type BoundingBox struct {
	Width  float64 `json:"Width"`
	Height float64 `json:"Height"`
	Left   float64 `json:"Left"`
	Top    float64 `json:"Top"`
}

BoundingBox represents the bounding box of a detected element.

type DatasetConfig

type DatasetConfig struct {
	ManifestS3Object *S3ObjectRef `json:"ManifestS3Object,omitempty"`
}

DatasetConfig holds dataset configuration for an adapter version.

type DetectedSignature

type DetectedSignature struct {
	Page int `json:"Page"`
}

DetectedSignature describes a detected signature page.

type DocumentGroup

type DocumentGroup struct {
	Type                 string              `json:"Type"`
	SplitDocuments       []SplitDocument     `json:"SplitDocuments,omitempty"`
	DetectedSignatures   []DetectedSignature `json:"DetectedSignatures,omitempty"`
	UndetectedSignatures []DetectedSignature `json:"UndetectedSignatures,omitempty"`
}

DocumentGroup groups documents of the same type in a lending summary.

type DocumentJob

type DocumentJob struct {
	CreationTime time.Time `json:"creationTime"`
	JobID        string    `json:"jobId"`
	// Region is the store.Table[DocumentJob] key material (see jobKey in
	// store_setup.go): this backend nests jobs by region, and DocumentJob
	// otherwise carries no field recording which region bucket it lives in.
	// Excluded from persisted JSON -- persistence.go's DTO-based
	// Snapshot/Restore captures Region as a real field instead (Phase 3.3).
	Region              string               `json:"-"`
	JobStatus           string               `json:"jobStatus"`
	JobType             string               `json:"jobType"` // "DocumentAnalysis" or "TextDetection"
	Blocks              []Block              `json:"blocks"`
	OutputConfig        *OutputConfig        `json:"outputConfig,omitempty"`
	NotificationChannel *NotificationChannel `json:"notificationChannel,omitempty"`
	JobTag              string               `json:"jobTag,omitempty"`
	ClientRequestToken  string               `json:"clientRequestToken,omitempty"`
	StatusMessage       string               `json:"statusMessage,omitempty"`
	Warnings            []WarningBlock       `json:"warnings,omitempty"`
}

DocumentJob represents an asynchronous Textract document job.

type EvaluationMetric added in v1.2.0

type EvaluationMetric struct {
	F1Score   float64 `json:"F1Score"`
	Precision float64 `json:"Precision"`
	Recall    float64 `json:"Recall"`
}

EvaluationMetric holds F1/Precision/Recall scores for either the baseline Textract model or a specific adapter version, scoped to one FeatureType.

type ExpenseCurrency added in v1.2.0

type ExpenseCurrency struct {
	Code       string  `json:"Code"`
	Confidence float64 `json:"Confidence"`
}

ExpenseCurrency holds the currency code detected for a monetary expense field. Distinct from ExpenseDetection: the real SDK's ExpenseCurrency has Code instead of Text/Geometry.

type ExpenseDetection

type ExpenseDetection struct {
	Geometry   *Geometry `json:"Geometry,omitempty"`
	Text       string    `json:"Text"`
	Confidence float64   `json:"Confidence"`
}

ExpenseDetection holds a detected expense field value.

type ExpenseDocument

type ExpenseDocument struct {
	Blocks         []Block         `json:"Blocks"`
	SummaryFields  []ExpenseField  `json:"SummaryFields,omitempty"`
	LineItemGroups []LineItemGroup `json:"LineItemGroups,omitempty"`
	ExpenseIndex   int             `json:"ExpenseIndex"`
}

ExpenseDocument represents a single expense document result.

type ExpenseField

type ExpenseField struct {
	Type            *ExpenseType           `json:"Type,omitempty"`
	LabelDetection  *ExpenseDetection      `json:"LabelDetection,omitempty"`
	ValueDetection  *ExpenseDetection      `json:"ValueDetection,omitempty"`
	Currency        *ExpenseCurrency       `json:"Currency,omitempty"`
	GroupProperties []ExpenseGroupProperty `json:"GroupProperties,omitempty"`
	PageNumber      int                    `json:"PageNumber"`
}

ExpenseField represents a single field in an expense document.

type ExpenseGroupProperty

type ExpenseGroupProperty struct {
	Id    string   `json:"Id"` //nolint:revive,staticcheck // AWS SDK field name convention
	Types []string `json:"Types"`
}

ExpenseGroupProperty describes an expense group membership.

type ExpenseJob

type ExpenseJob struct {
	CreationTime time.Time `json:"creationTime"`
	JobID        string    `json:"jobId"`
	// Region is the store.Table[ExpenseJob] key material -- see the
	// DocumentJob.Region doc comment above for why this field exists and is
	// excluded from persisted JSON.
	Region              string               `json:"-"`
	JobStatus           string               `json:"jobStatus"`
	ExpenseDocuments    []ExpenseDocument    `json:"expenseDocuments"`
	OutputConfig        *OutputConfig        `json:"outputConfig,omitempty"`
	NotificationChannel *NotificationChannel `json:"notificationChannel,omitempty"`
	JobTag              string               `json:"jobTag,omitempty"`
	ClientRequestToken  string               `json:"clientRequestToken,omitempty"`
	StatusMessage       string               `json:"statusMessage,omitempty"`
	Warnings            []WarningBlock       `json:"warnings,omitempty"`
}

ExpenseJob represents an asynchronous Textract expense analysis job.

type ExpenseType added in v1.2.0

type ExpenseType struct {
	Text       string  `json:"Text"`
	Confidence float64 `json:"Confidence"`
}

ExpenseType holds the classification of an expense field (e.g. "TOTAL", "VENDOR_NAME"). Distinct from ExpenseDetection: the real SDK's ExpenseType has no Geometry member.

type Extraction

type Extraction struct {
	LendingDocument *LendingDocument `json:"LendingDocument,omitempty"`
	ExpenseDocument *ExpenseDocument `json:"ExpenseDocument,omitempty"`
}

Extraction holds the extraction results for a single lending page.

type Geometry

type Geometry struct {
	BoundingBox   *BoundingBox `json:"BoundingBox"`
	RotationAngle *float64     `json:"RotationAngle,omitempty"`
	Polygon       []Point      `json:"Polygon"`
}

Geometry contains bounding box and polygon for a block.

type Handler

type Handler struct {
	Backend StorageBackend
	// contains filtered or unexported fields
}

Handler is the Echo HTTP handler for Amazon Textract operations.

func NewHandler

func NewHandler(backend StorageBackend) *Handler

NewHandler creates a new Textract handler.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns all operations that can be fault-injected.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns all regions this Textract instance handles.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns the lowercase AWS service name for fault rule matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the Textract action from the X-Amz-Target header.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource extracts the S3 document URI from the request body.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns the list of supported Textract operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all backend state. Implements service.Resettable.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher returns a function that matches Textract requests.

func (*Handler) Shutdown

func (h *Handler) Shutdown(ctx context.Context)

Shutdown implements service.Shutdowner. It cancels any in-flight delayed async-job completion goroutines and waits for them to exit (bounded by ctx) so they cannot mutate backend state after the process begins shutting down.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend.

type HumanLoopActivationOutput added in v1.3.1

type HumanLoopActivationOutput struct {
	HumanLoopActivationConditionsEvaluationResults string   `json:"HumanLoopActivationConditionsEvaluationResults,omitempty"` //nolint:lll // real SDK field name
	HumanLoopArn                                   string   `json:"HumanLoopArn,omitempty"`
	HumanLoopActivationReasons                     []string `json:"HumanLoopActivationReasons,omitempty"`
}

HumanLoopActivationOutput reports whether a human review loop activated.

type HumanLoopConfig added in v1.3.1

type HumanLoopConfig struct {
	DataAttributes    *HumanLoopDataAttributes `json:"DataAttributes,omitempty"`
	FlowDefinitionArn string                   `json:"FlowDefinitionArn"`
	HumanLoopName     string                   `json:"HumanLoopName"`
}

HumanLoopConfig sets up the human-in-the-loop review workflow for AnalyzeDocument.

type HumanLoopDataAttributes added in v1.3.1

type HumanLoopDataAttributes struct {
	ContentClassifiers []string `json:"ContentClassifiers,omitempty"`
}

HumanLoopDataAttributes declares content classifiers for the input image.

type IdentityDocument

type IdentityDocument struct {
	Blocks                 []Block                 `json:"Blocks"`
	IdentityDocumentFields []IdentityDocumentField `json:"IdentityDocumentFields,omitempty"`
	DocumentIndex          int                     `json:"DocumentIndex"`
}

IdentityDocument represents a single identity document result.

type IdentityDocumentField

type IdentityDocumentField struct {
	Type           *AnalyzeIDDetections `json:"Type,omitempty"`
	ValueDetection *AnalyzeIDDetections `json:"ValueDetection,omitempty"`
}

IdentityDocumentField holds a single field from an ID document.

type InMemoryBackend

type InMemoryBackend struct {
	// contains filtered or unexported fields
}

InMemoryBackend is the in-memory store for Textract jobs.

jobs/expenseJobs/lendingJobs/adapters/adapterVersions were formerly nested by region (outer key = region) so that same-named resources in different regions are fully isolated; each is now a store.Table[T] keyed by a region+id composite (see regionKey in store_setup.go) providing the same isolation. clientTokenToJobID/adapterClientTokenToID remain plain region-nested maps: their values are strings, not *T, so they do not fit store.Table's keyed-by-identity-value shape.

func NewInMemoryBackend

func NewInMemoryBackend(accountID, region string) *InMemoryBackend

NewInMemoryBackend creates a new InMemoryBackend with a background lifecycle context. Prefer NewInMemoryBackendWithContext when a service context is available so delayed job completions are cancelled on shutdown.

func NewInMemoryBackendWithContext

func NewInMemoryBackendWithContext(svcCtx context.Context, accountID, region string) *InMemoryBackend

NewInMemoryBackendWithContext creates a new InMemoryBackend whose delayed job-completion goroutines are tied to svcCtx, so they are cancelled when the service shuts down. If svcCtx is nil, context.Background is used.

func (*InMemoryBackend) AccountID

func (b *InMemoryBackend) AccountID() string

AccountID returns the AWS account ID for this backend.

func (*InMemoryBackend) AnalyzeDocument

func (b *InMemoryBackend) AnalyzeDocument(_ context.Context, documentURI string) []Block

AnalyzeDocument performs a synchronous document analysis and returns blocks based on the requested feature types.

func (*InMemoryBackend) AnalyzeDocumentWithFeatures

func (b *InMemoryBackend) AnalyzeDocumentWithFeatures(
	_ context.Context,
	documentURI string,
	featureTypes []string,
	queries *QueriesConfig,
) []Block

AnalyzeDocumentWithFeatures performs synchronous document analysis using feature types.

func (*InMemoryBackend) AnalyzeExpense

func (b *InMemoryBackend) AnalyzeExpense(_ context.Context, documentURI string) []ExpenseDocument

AnalyzeExpense performs a synchronous expense analysis and returns expense documents.

func (*InMemoryBackend) AnalyzeID

func (b *InMemoryBackend) AnalyzeID(_ context.Context, documentURIs []string) []IdentityDocument

AnalyzeID performs a synchronous ID analysis and returns identity documents.

func (*InMemoryBackend) BuildAdapterARN

func (b *InMemoryBackend) BuildAdapterARN(adapterID string) string

BuildAdapterARN returns the ARN for an adapter (exported for handler use).

func (*InMemoryBackend) BuildAdapterVersionARN

func (b *InMemoryBackend) BuildAdapterVersionARN(adapterID, version string) string

BuildAdapterVersionARN returns the ARN for an adapter version (exported for handler use).

func (*InMemoryBackend) CreateAdapter

func (b *InMemoryBackend) CreateAdapter(
	ctx context.Context,
	name, description, autoUpdate string,
	featureTypes []string,
	tags map[string]string,
) (*Adapter, error)

CreateAdapter creates a new Textract adapter and returns it.

func (*InMemoryBackend) CreateAdapterVersion

func (b *InMemoryBackend) CreateAdapterVersion(
	ctx context.Context, adapterID string, tags map[string]string,
) (*AdapterVersion, error)

CreateAdapterVersion creates a new version for an existing adapter.

func (*InMemoryBackend) CreateAdapterVersionWithOptions

func (b *InMemoryBackend) CreateAdapterVersionWithOptions(
	ctx context.Context,
	adapterID string,
	tags map[string]string,
	datasetConfig *DatasetConfig,
	outputConfig *OutputConfig,
	kmsKeyID, clientRequestToken string,
) (*AdapterVersion, error)

CreateAdapterVersionWithOptions creates an adapter version with full options.

func (*InMemoryBackend) CreateAdapterWithToken

func (b *InMemoryBackend) CreateAdapterWithToken(
	ctx context.Context,
	name, description, autoUpdate string,
	featureTypes []string,
	tags map[string]string,
	clientRequestToken string,
) (*Adapter, error)

CreateAdapterWithToken creates an adapter with ClientRequestToken dedup.

func (*InMemoryBackend) DeleteAdapter

func (b *InMemoryBackend) DeleteAdapter(ctx context.Context, adapterID string) error

DeleteAdapter removes an adapter and all its versions by ID.

func (*InMemoryBackend) DeleteAdapterVersion

func (b *InMemoryBackend) DeleteAdapterVersion(ctx context.Context, adapterID, version string) error

DeleteAdapterVersion removes a specific adapter version.

func (*InMemoryBackend) DetectDocumentText

func (b *InMemoryBackend) DetectDocumentText(_ context.Context, documentURI string) []Block

DetectDocumentText performs synchronous text detection and returns proper blocks.

func (*InMemoryBackend) GetAdapter

func (b *InMemoryBackend) GetAdapter(ctx context.Context, adapterID string) (*Adapter, error)

GetAdapter retrieves an adapter by ID.

func (*InMemoryBackend) GetAdapterVersion

func (b *InMemoryBackend) GetAdapterVersion(ctx context.Context, adapterID, version string) (*AdapterVersion, error)

GetAdapterVersion retrieves a specific adapter version.

func (*InMemoryBackend) GetDocumentAnalysis

func (b *InMemoryBackend) GetDocumentAnalysis(ctx context.Context, jobID string) (*DocumentJob, error)

GetDocumentAnalysis retrieves the results of a document analysis job. Returns a clone of the stored job.

func (*InMemoryBackend) GetDocumentTextDetection

func (b *InMemoryBackend) GetDocumentTextDetection(ctx context.Context, jobID string) (*DocumentJob, error)

GetDocumentTextDetection retrieves the results of a text detection job. Returns a clone of the stored job.

func (*InMemoryBackend) GetExpenseAnalysis

func (b *InMemoryBackend) GetExpenseAnalysis(ctx context.Context, jobID string) (*ExpenseJob, error)

GetExpenseAnalysis retrieves the results of an expense analysis job. Returns a deep clone so callers may safely mutate the returned value.

func (*InMemoryBackend) GetLendingAnalysis

func (b *InMemoryBackend) GetLendingAnalysis(ctx context.Context, jobID string) (*LendingJob, error)

GetLendingAnalysis retrieves the results of a lending analysis job. Returns a clone of the stored job.

func (*InMemoryBackend) GetLendingAnalysisSummary

func (b *InMemoryBackend) GetLendingAnalysisSummary(ctx context.Context, jobID string) (*LendingJob, error)

GetLendingAnalysisSummary returns a summary of a lending analysis job.

func (*InMemoryBackend) ListAdapterVersions

func (b *InMemoryBackend) ListAdapterVersions(ctx context.Context, adapterID string) ([]AdapterVersion, error)

ListAdapterVersions returns all versions for a given adapter, sorted by version string.

func (*InMemoryBackend) ListAdapters

func (b *InMemoryBackend) ListAdapters(ctx context.Context) []Adapter

ListAdapters returns a sorted list of all adapters for the request region.

func (*InMemoryBackend) ListJobs

func (b *InMemoryBackend) ListJobs(ctx context.Context) []DocumentJob

ListJobs returns all stored jobs for the request region, sorted by creation time (newest first).

func (*InMemoryBackend) ListTagsForResource

func (b *InMemoryBackend) ListTagsForResource(ctx context.Context, resourceARN string) (map[string]string, error)

ListTagsForResource returns a copy of the tags for an adapter or adapter version. Region is resolved from the ARN, falling back to the context region.

func (*InMemoryBackend) Region

func (b *InMemoryBackend) Region() string

Region returns the AWS region for this backend.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all stored resources, resetting the backend to its initial state.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot. It implements persistence.Persistable.

func (*InMemoryBackend) Shutdown

func (b *InMemoryBackend) Shutdown(ctx context.Context)

Shutdown cancels in-flight delayed job completions and waits for their goroutines to exit, bounded by ctx. It implements the service shutdown contract used by the handler.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON. It implements persistence.Persistable.

func (*InMemoryBackend) StartDocumentAnalysis

func (b *InMemoryBackend) StartDocumentAnalysis(ctx context.Context, documentURI string) (*DocumentJob, error)

StartDocumentAnalysis creates an async document analysis job.

func (*InMemoryBackend) StartDocumentAnalysisWithOptions

func (b *InMemoryBackend) StartDocumentAnalysisWithOptions(
	ctx context.Context,
	documentURI string,
	featureTypes []string,
	queries *QueriesConfig,
	outputConfig *OutputConfig,
	jobTag, clientRequestToken string,
) (*DocumentJob, error)

StartDocumentAnalysisWithOptions creates an async document analysis job with full options.

func (*InMemoryBackend) StartDocumentTextDetection

func (b *InMemoryBackend) StartDocumentTextDetection(ctx context.Context, documentURI string) (*DocumentJob, error)

StartDocumentTextDetection creates an async text detection job.

func (*InMemoryBackend) StartDocumentTextDetectionWithOptions

func (b *InMemoryBackend) StartDocumentTextDetectionWithOptions(
	ctx context.Context,
	documentURI string,
	outputConfig *OutputConfig,
	notificationChannel *NotificationChannel,
	jobTag, clientRequestToken string,
) (*DocumentJob, error)

StartDocumentTextDetectionWithOptions creates an async text detection job with options.

func (*InMemoryBackend) StartExpenseAnalysis

func (b *InMemoryBackend) StartExpenseAnalysis(ctx context.Context, documentURI string) (*ExpenseJob, error)

StartExpenseAnalysis creates an async expense analysis job.

func (*InMemoryBackend) StartExpenseAnalysisWithOptions

func (b *InMemoryBackend) StartExpenseAnalysisWithOptions(
	ctx context.Context,
	documentURI string,
	outputConfig *OutputConfig,
	notificationChannel *NotificationChannel,
	jobTag, clientRequestToken string,
) (*ExpenseJob, error)

StartExpenseAnalysisWithOptions creates an async expense analysis job with full options, including ClientRequestToken dedup: real AWS returns the same JobId when the same token is reused (see the docs on StartExpenseAnalysisInput.ClientRequestToken).

func (*InMemoryBackend) StartLendingAnalysis

func (b *InMemoryBackend) StartLendingAnalysis(ctx context.Context, documentURI string) (*LendingJob, error)

StartLendingAnalysis creates an async lending analysis job.

func (*InMemoryBackend) StartLendingAnalysisWithOptions

func (b *InMemoryBackend) StartLendingAnalysisWithOptions(
	ctx context.Context,
	_ string,
	outputConfig *OutputConfig,
	notificationChannel *NotificationChannel,
	jobTag, clientRequestToken string,
) (*LendingJob, error)

StartLendingAnalysisWithOptions creates an async lending analysis job with full options, including ClientRequestToken dedup: real AWS returns the same JobId when the same token is reused (see the docs on StartLendingAnalysisInput.ClientRequestToken).

func (*InMemoryBackend) TagResource

func (b *InMemoryBackend) TagResource(ctx context.Context, resourceARN string, tags map[string]string) error

TagResource adds or replaces tags on an adapter or adapter version identified by ARN. Region is resolved from the ARN, falling back to the context region.

func (*InMemoryBackend) UntagResource

func (b *InMemoryBackend) UntagResource(ctx context.Context, resourceARN string, tagKeys []string) error

UntagResource removes the specified tag keys from an adapter or adapter version. Region is resolved from the ARN, falling back to the context region.

func (*InMemoryBackend) UpdateAdapter

func (b *InMemoryBackend) UpdateAdapter(
	ctx context.Context, adapterID, description, autoUpdate string,
) (*Adapter, error)

UpdateAdapter updates mutable fields on an existing adapter.

func (*InMemoryBackend) ValidateAdaptersConfig added in v1.3.1

func (b *InMemoryBackend) ValidateAdaptersConfig(ctx context.Context, cfg *AdaptersConfig) error

ValidateAdaptersConfig checks every adapter reference in cfg against real Adapter/AdapterVersion backend state. AnalyzeDocument's real error surface (aws-sdk-go-v2/service/textract deserializers.go's deserializeOpErrorAnalyzeDocument switch) has no ResourceNotFoundException case at all -- so an unknown adapter or version must surface as InvalidParameterException (errInvalidRequest, op-aware-mapped in handleError), never ErrAdapterNotFound/ErrAdapterVersionNotFound (which are correct only for the adapter-management ops that do declare ResourceNotFoundException).

type LendingDetection

type LendingDetection struct {
	Geometry        *Geometry `json:"Geometry,omitempty"`
	Text            string    `json:"Text,omitempty"`
	SelectionStatus string    `json:"SelectionStatus,omitempty"`
	Confidence      float64   `json:"Confidence"`
}

LendingDetection holds a detected lending field value.

type LendingDocument

type LendingDocument struct {
	LendingFields       []LendingField       `json:"LendingFields,omitempty"`
	SignatureDetections []SignatureDetection `json:"SignatureDetections,omitempty"`
}

LendingDocument holds the extracted fields for a lending page.

type LendingField

type LendingField struct {
	KeyDetection    *LendingDetection  `json:"KeyDetection,omitempty"`
	Type            string             `json:"Type,omitempty"`
	ValueDetections []LendingDetection `json:"ValueDetections,omitempty"`
}

LendingField is a single field detected in a lending document. Type is a bare string (not a LendingDetection) and ValueDetections is a list -- both diverge from the shape of the sibling Expense/AnalyzeID field types, see the real SDK's types.LendingField.

type LendingJob

type LendingJob struct {
	CreationTime time.Time `json:"creationTime"`
	JobID        string    `json:"jobId"`
	// Region is the store.Table[LendingJob] key material -- see the
	// DocumentJob.Region doc comment above for why this field exists and is
	// excluded from persisted JSON.
	Region              string               `json:"-"`
	JobStatus           string               `json:"jobStatus"`
	Results             []LendingResult      `json:"results"`
	Summary             *LendingSummary      `json:"summary,omitempty"`
	OutputConfig        *OutputConfig        `json:"outputConfig,omitempty"`
	NotificationChannel *NotificationChannel `json:"notificationChannel,omitempty"`
	JobTag              string               `json:"jobTag,omitempty"`
	ClientRequestToken  string               `json:"clientRequestToken,omitempty"`
	StatusMessage       string               `json:"statusMessage,omitempty"`
	Warnings            []WarningBlock       `json:"warnings,omitempty"`
}

LendingJob represents an asynchronous Textract lending analysis job.

type LendingResult

type LendingResult struct {
	PageClassification *PageClassification `json:"PageClassification,omitempty"`
	Extractions        []Extraction        `json:"Extractions,omitempty"`
	Page               int                 `json:"Page"`
}

LendingResult represents a single lending analysis result page.

type LendingSummary

type LendingSummary struct {
	DocumentGroups          []DocumentGroup `json:"DocumentGroups,omitempty"`
	UndetectedDocumentTypes []string        `json:"UndetectedDocumentTypes,omitempty"`
}

LendingSummary summarizes lending analysis results.

type LineItem

type LineItem struct {
	LineItemExpenseFields []ExpenseField `json:"LineItemExpenseFields"`
}

LineItem represents a single line item in an expense document.

type LineItemGroup

type LineItemGroup struct {
	LineItems          []LineItem `json:"LineItems"`
	LineItemGroupIndex int        `json:"LineItemGroupIndex"`
}

LineItemGroup represents a group of line items.

type NormalizedValue

type NormalizedValue struct {
	Value     string `json:"Value"`
	ValueType string `json:"ValueType"`
}

NormalizedValue holds a normalized field value.

type NotificationChannel

type NotificationChannel struct {
	RoleArn     string `json:"RoleArn"`
	SNSTopicArn string `json:"SNSTopicArn"`
}

NotificationChannel holds SNS topic configuration.

type OutputConfig

type OutputConfig struct {
	S3Bucket string `json:"S3Bucket"`
	S3Prefix string `json:"S3Prefix"`
}

OutputConfig holds S3 output configuration for async jobs.

type PageClassification

type PageClassification struct {
	PageType   []Prediction `json:"PageType"`
	PageNumber []Prediction `json:"PageNumber"`
}

PageClassification holds the page classification for a lending page.

type Point

type Point struct {
	X float64 `json:"X"`
	Y float64 `json:"Y"`
}

Point represents a polygon vertex.

type Prediction added in v1.2.0

type Prediction struct {
	Value      string  `json:"Value"`
	Confidence float64 `json:"Confidence"`
}

Prediction holds a classification value and its confidence. Used for PageClassification.PageType/PageNumber -- distinct from LendingDetection, which carries Geometry/SelectionStatus fields Prediction doesn't have.

type Provider

type Provider struct{}

Provider implements service.Provider for Amazon Textract.

func (*Provider) Init

Init initializes the Textract service backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name.

type QueriesConfig

type QueriesConfig struct {
	Queries []QueryEntry `json:"Queries"`
}

QueriesConfig holds query configuration for AnalyzeDocument.

type QueryBlock

type QueryBlock struct {
	Text  string   `json:"Text"`
	Alias string   `json:"Alias"`
	Pages []string `json:"Pages"`
}

QueryBlock holds query metadata for QUERY blocks.

type QueryEntry

type QueryEntry struct {
	Text  string   `json:"Text"`
	Alias string   `json:"Alias"`
	Pages []string `json:"Pages"`
}

QueryEntry is a single query with text, alias and page filters.

type Relationship

type Relationship struct {
	Type string   `json:"Type"`
	Ids  []string `json:"Ids"` //nolint:revive // AWS SDK field name convention
}

Relationship describes child/value relationships between blocks.

type S3ObjectRef

type S3ObjectRef struct {
	Bucket  string `json:"Bucket"`
	Name    string `json:"Name"`
	Version string `json:"Version,omitempty"`
}

S3ObjectRef is an S3 object reference.

type SignatureDetection

type SignatureDetection struct {
	Geometry   *Geometry `json:"Geometry,omitempty"`
	Confidence float64   `json:"Confidence"`
}

SignatureDetection represents a detected signature.

type SplitDocument

type SplitDocument struct {
	Pages []int `json:"Pages"`
	Index int   `json:"Index"`
}

SplitDocument describes a sub-document within a group.

type StorageBackend

type StorageBackend interface {
	AnalyzeDocument(ctx context.Context, documentURI string) []Block
	AnalyzeExpense(ctx context.Context, documentURI string) []ExpenseDocument
	AnalyzeID(ctx context.Context, documentURIs []string) []IdentityDocument
	CreateAdapter(
		ctx context.Context,
		name, description, autoUpdate string,
		featureTypes []string, tags map[string]string,
	) (*Adapter, error)
	CreateAdapterVersion(ctx context.Context, adapterID string, tags map[string]string) (
		*AdapterVersion, error,
	)
	DeleteAdapter(ctx context.Context, adapterID string) error
	DeleteAdapterVersion(ctx context.Context, adapterID, version string) error
	DetectDocumentText(ctx context.Context, documentURI string) []Block
	GetAdapter(ctx context.Context, adapterID string) (*Adapter, error)
	GetAdapterVersion(ctx context.Context, adapterID, version string) (*AdapterVersion, error)
	GetDocumentAnalysis(ctx context.Context, jobID string) (*DocumentJob, error)
	GetDocumentTextDetection(ctx context.Context, jobID string) (*DocumentJob, error)
	GetExpenseAnalysis(ctx context.Context, jobID string) (*ExpenseJob, error)
	GetLendingAnalysis(ctx context.Context, jobID string) (*LendingJob, error)
	GetLendingAnalysisSummary(ctx context.Context, jobID string) (*LendingJob, error)
	ListAdapterVersions(ctx context.Context, adapterID string) ([]AdapterVersion, error)
	ListAdapters(ctx context.Context) []Adapter
	ListJobs(ctx context.Context) []DocumentJob
	ListTagsForResource(ctx context.Context, resourceARN string) (map[string]string, error)
	Region() string
	Reset()
	Restore(ctx context.Context, data []byte) error
	Snapshot(ctx context.Context) []byte
	StartDocumentAnalysis(ctx context.Context, documentURI string) (*DocumentJob, error)
	StartDocumentTextDetection(ctx context.Context, documentURI string) (*DocumentJob, error)
	StartExpenseAnalysis(ctx context.Context, documentURI string) (*ExpenseJob, error)
	StartLendingAnalysis(ctx context.Context, documentURI string) (*LendingJob, error)
	TagResource(ctx context.Context, resourceARN string, tags map[string]string) error
	UntagResource(ctx context.Context, resourceARN string, tagKeys []string) error
	UpdateAdapter(ctx context.Context, adapterID, description, autoUpdate string) (
		*Adapter, error,
	)
}

StorageBackend is the interface for Textract storage operations.

type WarningBlock

type WarningBlock struct {
	ErrorCode string `json:"ErrorCode"`
	Pages     []int  `json:"Pages"`
}

WarningBlock represents a warning returned in async job responses.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL