Skip to content

Instantly share code, notes, and snippets.

@noprompt
Created February 22, 2018 18:57
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 noprompt/d3be53ba0c3129d99f127bcc959a9918 to your computer and use it in GitHub Desktop.
Save noprompt/d3be53ba0c3129d99f127bcc959a9918 to your computer and use it in GitHub Desktop.
#! /usr/local/bin/lumo
(ns app.core
"This application watches the a directory <DIR> for screen shots
and applies an OCR to them (`tesseract`). The resulting text file is
saved to a directory called '<DIR>/OCR Screen Shots`.")
(def fs
(js/require "fs"))
(def child-process
(js/require "child_process"))
(def
^{:doc "The directory to watch for changes."}
watch-directory "")
(def
^{:doc "The directory to where results are stored."}
output-path
(str watch-directory "/OCR Screen Shots"))
(defn tesseract! [input-file output-file]
(let [command "tesseract"
args #js [input-file output-file]]
(prn {:child-process/spawn [command args]})
(let [tesseract (. child-process spawn command args)
pid (. tesseract -pid)]
(prn {:child-process/pid pid})
(. (. tesseract -stderr) on "data"
(fn [buffer]
(let [message (. buffer toString)]
(when (re-find (new js/RegExp "\\berror\\b" "i") message)
(prn {:child-process/error message
:child-process/pid pid})))))
(. tesseract on "close"
(fn [code]
(prn {:child-process/exit code
:child-process/pid pid}))))))
(defn ensure-output-path
[callback]
(. fs stat output-path
(fn [error stats]
(when (and error
(= (. error -code)
"ENOENT"))
(. fs mkdir output-path
(fn [error]
(if error
(do
(prn {:app.error/message (str "Could not create " output-path)})
(. js/process exit))
;; Created directory successfully.
(callback)))))
;; Assume directory exists.
(when stats
(callback)))))
(defn start! []
(ensure-output-path
(fn []
(. fs watch watch-directory
(fn [event-type file-name]
(prn {:fs.watch/event-type event-type})
(prn {:fs.watch/file-name (or file-name "<none>")})
(if file-name
(let [input-file (str watch-directory "/" file-name)]
(. fs stat input-file
(fn [error stats]
;; ENONENT indicates the file was removed.
(when (and error
(not (= (. error -code) "ENOENT")))
(prn {:fs.stats.error/message (.-Error error)
:fs.stats.error/code (. error -code)}))
(when (and stats
(. stats isFile)
(re-find #"Screen Shot" file-name))
(let [output-file (str output-path "/" file-name)]
(tesseract! input-file output-file))))))))))))
(start!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment