60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package tesseract
|
|
|
|
import (
|
|
"git.giftfish.de/ston1th/docstore/pkg/core"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"time"
|
|
)
|
|
|
|
type Tesseract struct {
|
|
cmd string
|
|
args []string
|
|
dir string
|
|
timeout time.Duration
|
|
}
|
|
|
|
func NewTesseract(dir string, langs []string, timeout time.Duration) (t *Tesseract, err error) {
|
|
var (
|
|
cmd string
|
|
lang string
|
|
)
|
|
cmd, err = exec.LookPath("tesseract")
|
|
if err != nil {
|
|
return
|
|
}
|
|
for i, l := range langs {
|
|
lang += l
|
|
if i < len(langs) {
|
|
lang += "+"
|
|
}
|
|
}
|
|
args := []string{"-l", lang, "--oem", "2"}
|
|
t = &Tesseract{cmd, args, dir, timeout}
|
|
return
|
|
}
|
|
|
|
func (t *Tesseract) Scan(file string) (filename, text string, err error) {
|
|
filename = core.FileName() + ".pdf"
|
|
txt, err := core.Timeout(exec.Command(t.cmd, append(t.args, []string{file, "stdout", "txt"}...)...), t.timeout)
|
|
if err != nil {
|
|
return
|
|
}
|
|
text = string(txt)
|
|
pdf, err := core.Timeout(exec.Command(t.cmd, append(t.args, []string{file, "stdout", "pdf"}...)...), t.timeout)
|
|
if err != nil {
|
|
return
|
|
}
|
|
f, err := os.OpenFile(filepath.Join(t.dir, filename), os.O_RDWR|os.O_CREATE, 0640)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
_, err = f.Write(pdf)
|
|
if err != nil {
|
|
return
|
|
}
|
|
err = os.Remove(file)
|
|
return
|
|
}
|