Skip to content
CMD
← Back to Blog

deskocr: Cross-Platform Screen Capture, OCR, and LLM Pipeline

•7 min read•Projects

A native C++23 desktop tool that captures the screen, extracts text with Tesseract or Apple Vision, hands the image plus OCR to an LLM, and drives the cursor to UI elements it identifies. Runs on macOS and Windows behind a single CLI.

C++23CMakeConan 2TesseractOpenCVScreenCaptureKitApple VisionOpenAIAnthropiclibcurlmacOSWindows

deskocr is a native desktop tool that captures the screen, runs local OCR over the image, and hands both the pixels and the extracted text to an LLM for analysis. It runs on macOS and Windows from a single C++23 codebase, can operate as a one-shot CLI, a hotkey-driven headless mode, or a background daemon, and includes a cursor navigation layer that can locate and click UI elements the model identifies in the screenshot.

Project Overview

The goal was a small, fast, native binary that bridges three things the desktop OS keeps in separate silos: the pixels on screen, the text inside those pixels, and an LLM's understanding of what's in front of the user. Existing screenshot-to-LLM tooling is mostly Electron wrappers or browser extensions. deskocr does it with platform-native capture APIs, local OCR, and a thin HTTP layer over the model providers.

Core Requirements

  • Native screen capture on macOS and Windows with multi-monitor support
  • Local OCR with word-level bounding boxes so detected text is spatially anchored
  • Pluggable LLM provider — OpenAI and Anthropic out of the box, swappable without recompiling
  • Combined image + OCR-text prompting so the model gets pixels and ground-truth text
  • Headless and daemon modes that survive being detached from a terminal
  • Cursor navigation: take a model's "click the Submit button" answer and actually move the mouse there
  • Runtime-editable prompt files so behaviour can be tuned without a rebuild

Technical Architecture

LayerTechnology
LanguageC++23
BuildCMake 3.31 with presets, Conan 2 for dependency management
Screen capture (mac)ScreenCaptureKit (Objective-C++ .mm bridge)
Screen capture (Win)GDI BitBlt
OCR (default)Tesseract + Leptonica with word-level bounding boxes
OCR (mac alternative)Apple Vision framework via Objective-C++ bridge
Image handlingOpenCV (pre-processing, region crops)
HTTPlibcurl with an RAII CurlSession wrapper
JSONnlohmann/json
Accessibility (mac)AXUIElement / Quartz Event Services for cursor control
Accessibility (Win)SendInput / UI Automation

Everything platform-specific sits behind an abstract interface (ScreenCapture, OCREngine, AccessibilityProvider) selected at runtime by a factory. The platform .cpp / .mm files only get compiled into the build that needs them, so the macOS binary never pulls in GDI symbols and vice versa.


Pipeline

A single capture flows through one orchestrator (Pipeline) that owns the lifecycle:

  1. Capture. ScreenCapture::capture() returns an RGBA buffer plus monitor geometry. On macOS that's a CGImageRef materialised from a SCStream; on Windows it's a HBITMAP from BitBlt(GetDC(NULL), ...).
  2. OCR. The image is handed to whichever OCREngine is configured. Tesseract returns word-level boxes (text, confidence, x/y/w/h); the Vision backend returns the same shape so the rest of the pipeline doesn't know which engine ran.
  3. LLM call. The image (base64) and the OCR text both go to the model in a single request. Sending OCR alongside the pixels gives the model ground-truth strings for anything it can't read confidently from the image, and gives the cursor-navigation layer something to match against later.
  4. Cursor navigation (optional). If the model returns instructions referencing on-screen text (e.g. "click Continue"), the text matcher resolves that to one of the OCR boxes and CursorNavigator moves the system cursor there.

The pipeline is the only place that knows the full flow; every step is replaceable at the interface boundary.


Key Design Decisions

Interface-per-platform, not #ifdef-per-function

Every platform difference is hidden behind a pure-virtual interface and a factory. There is no #ifdef __APPLE__ salted through the orchestration code. The Mac files (screenCaptureMac.mm, ocrEngineVision.mm, accessibilityProviderMac.mm) are Objective-C++; the Windows files (screenCaptureWindows.cpp, accessibilityProviderWin.cpp) are plain C++. CMake only compiles the set that matches CMAKE_SYSTEM_NAME. This keeps the cross-platform seam exactly one file deep — adding a Linux backend later is a new file, not a new sprinkling of ifdefs.

Two OCR engines behind one interface

Tesseract is the default because it ships everywhere and is predictable. On macOS, Apple's Vision framework is also wired in — it's faster on Apple Silicon and handles handwriting and rotated text better than Tesseract, but it only exists on macOS and its accuracy on small UI font sizes is uneven. Both implement the same OCREngine interface (returning OCRWord { text, confidence, bbox }), and the pipeline picks one at construction. Letting both coexist meant being able to A/B them on the same screenshot during development instead of choosing blind.

Sending image + OCR together, not OCR-only

Early on the LLM call was OCR-only — cheaper, faster, fewer tokens. It was also worse: Tesseract loses layout cues (which words are in a button, which are headings, what's near what) and small-font OCR is noisy enough that the model would hallucinate to fill gaps. Sending the screenshot alongside the OCR text was strictly better: the model uses the image for layout and the OCR for verbatim strings, and the cursor-navigation step downstream has reliable bounding boxes to anchor any "click X" instruction to.

Runtime prompt files

Prompts live in prompts/*.txt and are loaded by PromptLoader at startup, not baked into the binary. There are four — extract.txt, analyze.txt, clean_ocr.txt, screen_analyze.txt — corresponding to the pipeline stages. The active files are gitignored; an examples/ directory ships as a starting point. This makes iterating on prompt wording a text-edit + rerun cycle instead of a recompile, and keeps personal customisations out of the repo.

Provider abstraction over the model APIs

LLMProvider is an abstract base; OpenAIProvider and AnthropicProvider implement it. The factory reads LLM_PROVIDER / OPENAI_API_KEY / ANTHROPIC_API_KEY from the environment (or .env) and returns a cached singleton. Switching providers is one env-var flip — no rebuild, no code change. The HTTP layer is a single CurlSession RAII wrapper that handles curl_easy_init/cleanup, header lifetime, and WriteCallback buffering so the provider classes only deal with request bodies and response parsing.

Daemon mode

--daemon double-forks, redirects stdio, writes a PID file under the user's runtime dir, and detaches. --status reads the PID file and signals 0 to check liveness; --stop-daemon sends SIGTERM. In daemon mode the process registers global hotkeys (Cmd+Opt+S on macOS, equivalent on Windows) so a capture can fire from any application without focus shifting. The hotkey handler funnels into the same Pipeline::run() the CLI uses — there's one code path, just different triggers.

Text matching for cursor targeting

When the LLM says "click Continue", the cursor navigator can't just do a substring match against OCR — OCR has typos, casing differences, and split words. textMatcher.cpp does fuzzy matching (Levenshtein-distance scoring with length-normalised thresholds), line grouping (vertical proximity to reconstruct multi-word labels Tesseract split), and a small "labeled option" detector that recognises radio-button / multiple-choice layouts so the model can answer with "option B" and have it resolved to the right bounding box.


CLI

deskocr               # one-shot: capture + OCR + analyse, print to stdout
deskocr --test        # capture only, exit (used to verify permissions)
deskocr --headless    # foreground, hotkey-driven, runs until quit
deskocr --daemon      # background, hotkey-driven, detached
deskocr --status      # is the daemon running?
deskocr --stop-daemon # SIGTERM the daemon

Headless and daemon modes share the same hotkey table; the only difference is whether the process owns a terminal.


Build

The build is CMake + Conan 2. Conan resolves OpenCV, nlohmann/json, libcurl, and Leptonica; Tesseract comes from Homebrew / system packages because Conan's Tesseract recipe is flakier than pkg-config tesseract. The presets in CMakePresets.json wire the Conan toolchain in automatically, so a clean build is:

conan install . --output-folder=build/Release --build=missing -s build_type=Release
cmake --preset conan-release
cmake --build --preset release

C++23 was chosen for std::expected, std::print, and ranges — the error-handling story in the pipeline reads much better with std::expected<Result, Error> returns than with exceptions or out-parameters, and the OCR-word filtering pipelines are mostly views::filter / views::transform chains.


Permissions

macOS gates screen capture behind Screen Recording permission and cursor / accessibility actions behind Accessibility permission. Both are first-launch prompts (and re-prompt after binary signature changes); the --test flag exists specifically to trigger and verify these without running the full pipeline. Windows requires no special permission for GDI capture, but UI Automation needs the process not to be running as a different integrity level than the target window.


Summary

deskocr is the kind of project that's only interesting because it's native: a browser extension could OCR a screenshot, but it can't capture the system-wide screen, it can't move the cursor outside its tab, and it can't run as a daemon. Putting all three in one small C++23 binary with a clean interface-per-platform seam meant the macOS and Windows builds share roughly 80% of their code, the LLM provider is a swap-an-env-var decision rather than a fork, and the prompt files are editable without touching the compiler. The result is a tool that captures, reads, and acts on the screen with the same latency budget as a native screenshot utility.

What's Next

A few directions I'd take this further:

  • Linux backend. A screenCaptureLinux.cpp using PipeWire (Wayland) or XShm (X11) is the obvious gap. The interface is already there; it's a file, not a refactor.
  • Local LLM provider. A third LLMProvider implementation talking to a local llama.cpp / Ollama server would remove the network round-trip and the API-key requirement for offline use.
  • Streaming responses. The current LLM call is request/response; streaming tokens to stdout would make --headless feel a lot more responsive.
  • Window-scoped capture. Capturing only the foreground window (or a user-selected region) would cut OCR cost on large displays and reduce the prompt size sent to the model.
  • Structured action output. Right now the cursor navigator parses free-text answers. Forcing the model into a JSON action schema ({ "action": "click", "target": "Continue" }) would make the navigation step more reliable and unlock multi-step workflows.