Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add tesseract image loader #76

Merged
merged 1 commit into from Jun 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/loader/tesseract/main.go
@@ -0,0 +1,21 @@
package main

import (
"context"
"fmt"

"github.com/henomis/lingoose/loader"
)

func main() {

l := loader.NewTesseractLoader("/tmp/image.png")

docs, err := l.Load(context.Background())
if err != nil {
panic(err)
}

fmt.Println(docs[0].Content)

}
91 changes: 91 additions & 0 deletions loader/tesseract.go
@@ -0,0 +1,91 @@
package loader

import (
"context"
"fmt"
"os/exec"

"github.com/henomis/lingoose/document"
"github.com/henomis/lingoose/types"
)

var (
ErrTesseractNotFound = fmt.Errorf("pdftotext not found")
defaultTesseractPath = "/usr/bin/tesseract"
)

type tesseractLoader struct {
loader loader

tesseractPath string
tesseractArgs []string
filename string
}

func NewTesseractLoader(filename string) *tesseractLoader {
return &tesseractLoader{
tesseractPath: defaultTesseractPath,
tesseractArgs: []string{},
filename: filename,
}
}

func (l *tesseractLoader) WithTesseractPath(tesseractPath string) *tesseractLoader {
l.tesseractPath = tesseractPath
return l
}

func (l *tesseractLoader) WithTextSplitter(textSplitter TextSplitter) *tesseractLoader {
l.loader.textSplitter = textSplitter
return l
}

func (l *tesseractLoader) WithArgs(tesseractArgs []string) *tesseractLoader {
l.tesseractArgs = tesseractArgs
return l
}

func (l *tesseractLoader) Load(ctx context.Context) ([]document.Document, error) {

err := isFile(l.tesseractPath)
if err != nil {
return nil, ErrTesseractNotFound
}

err = isFile(l.filename)
if err != nil {
return nil, err
}

documents, err := l.loadFile(ctx)
if err != nil {
return nil, err
}

if l.loader.textSplitter != nil {
documents = l.loader.textSplitter.SplitDocuments(documents)
}

return documents, nil
}

func (l *tesseractLoader) loadFile(ctx context.Context) ([]document.Document, error) {

tesseractArgs := []string{l.filename, "stdout"}
tesseractArgs = append(tesseractArgs, l.tesseractArgs...)

out, err := exec.CommandContext(ctx, l.tesseractPath, tesseractArgs...).Output()
if err != nil {
return nil, err
}

metadata := make(types.Meta)
metadata[SourceMetadataKey] = l.filename

return []document.Document{
{
Content: string(out),
Metadata: metadata,
},
}, nil
}