Skip to content

Instantly share code, notes, and snippets.

@reverie

reverie/read-screenshot.py

Last active Jan 27, 2019
Embed
What would you like to do?
OCR your latest screenshot on MacOS and copy its contents to the clipboard
#!/usr/bin/env python3
# Give this +x and put it on your $PATH
import subprocess
import os.path
import glob
from pathlib import Path
def get_latest_file(path, *paths):
"""
Returns the name of the latest (most recent) file
of the joined path(s)
From
https://codereview.stackexchange.com/questions/120494/finding-the-latest-file-in-a-folder
"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath)
if not list_of_files:
return None
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
def get_latest_screenshot():
home = str(Path.home())
return get_latest_file(home, 'Desktop', 'Screen*')
def get_image_text(path):
args = ['tesseract', path, '-']
p = subprocess.run(args, capture_output=True, check=True)
return p.stdout.rstrip().decode('utf8')
def main():
ss_path = get_latest_screenshot()
result = get_image_text(ss_path)
subprocess.run(['pbcopy'], input=result.encode('utf8'), check=True)
print("Copied to clipboard:")
print(result)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.