Skip to content

Instantly share code, notes, and snippets.

@ficapy
Created April 26, 2021 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/d93b5b979d89ae9cdc5479bcd069dd53 to your computer and use it in GitHub Desktop.
Save ficapy/d93b5b979d89ae9cdc5479bcd069dd53 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"runtime"
"github.com/go-vgo/robotgo"
"github.com/go-vgo/robotgo/clipboard"
"github.com/martinlindhe/notify"
"github.com/otiai10/gosseract/v2"
hook "github.com/robotn/gohook"
)
var ScreenshotBin = "/usr/sbin/screencapture"
func checkOS() {
if runtime.GOOS != "darwin" {
panic("Only support osx!")
}
if _, err := os.Stat(ScreenshotBin); os.IsNotExist(err) {
panic("Not found screencapture")
}
}
func ocr(path string) string {
client := gosseract.NewClient()
defer client.Close()
client.SetImage(path)
text, _ := client.Text()
return text
}
func screenshot() string {
f, err := ioutil.TempFile(os.TempDir(), "*.png")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
c := exec.Command(ScreenshotBin, "-s", f.Name())
err = c.Run()
if err != nil {
panic(err)
}
fi, err := os.Stat(f.Name())
if err != nil {
panic(err)
}
if fi.Size() > 1024 {
return ocr(f.Name())
}
return ""
}
// https://github.com/otiai10/gosseract/issues/200#issuecomment-817511288
// pkg/mod/github.com/otiai10/gosseract/v2@v2.3.1/tessbridge.cpp
// based on the feedback,I modified the original file,otherwise the compilation would report a header file error
func main() {
checkOS()
fmt.Println("--- Please press command + option + i to stop hook ---")
robotgo.EventHook(hook.KeyDown, []string{"command", "option", "i"}, func(e hook.Event) {
fmt.Println("Start screenshot")
ocr := screenshot()
if len(ocr) > 0 {
message := ""
clipboard.WriteAll(ocr)
if len(ocr) > 10 {
message = ocr[:10]
} else {
message = ocr
}
notify.Notify("MYOCR", "MYOCR", message, "")
}
})
s := robotgo.EventStart()
<-robotgo.EventProcess(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment