返回首页

Wayland 无 AI 截屏搜索:脚本

Bash 脚本在 Wayland 中实现无 AI 的 OCR 截屏捕获。screen.sh 保存 PNG 和 .txt,ssearch.sh 通过 tofi 提供模糊搜索。Hyprland/Sway 带热键设置。

Wayland:无神经网络的 OCR 截屏搜索
Advertisement 728x90

Wayland下无需AI的本地屏幕截图搜索

通过Bash脚本实现屏幕截图自动OCR文字提取与内容检索——无需神经网络或云端服务。专为Wayland环境设计,使用grim、slurp、tesseract和tofi工具。每张截图均配套保存一个包含提取文本的.txt文件,便于索引与快速查找。

所需工具:

  • grim:屏幕捕获
  • slurp:区域选择
  • tesseract:OCR引擎
  • tofi:搜索界面
  • wl-clipboard 和 cliphist:剪贴板管理
  • notify-send:桌面通知

screen.sh:捕获与OCR脚本

此脚本捕获选定屏幕区域,以PNG格式保存,并异步运行tesseract生成文本侧车文件。支持俄语和英语双语言识别。

Google AdInline article slot
#!/bin/bash
set -euo pipefail

SCREENSHOT_DIR="${SCREENSHOT_DIR:-$HOME/Pictures/screens}"
OCR_LANG="${OCR_LANG:-rus+eng}"
SLURP_ARGS=(-d -b 1B1F2866 -c 89b4faff -w 1)
GRIM_ARGS=(-t png -l 3)

die()  { notify-send "screen.sh" "$1" -i dialog-error -t 4000; exit 1; }
need() { for cmd in " $@"; do command -v "$cmd" &>/dev/null || die "missing: $cmd"; done; }

OCR函数并清理结果:

run_ocr() {
    tesseract "$1" - -l "$OCR_LANG" --psm 3 2>/dev/null \
        | grep -v '^[[:space:]]*$' \
        | sed 's/[[:space:]]\+/ /g; s/^ //; s/ $//'
}

save_sidecar() {
    run_ocr "$1" > "${1%.png}.txt" 2>/dev/null || true
}

OCR在后台运行:command -v tesseract &>/dev/null && { save_sidecar "$FILEPATH" & disown; }。通知可交互——提供打开文件夹、用swappy编辑或复制文本到剪贴板等选项。

--ocr模式直接复制提取文本,不保存文件。

Google AdInline article slot

ssearch.sh:索引与搜索脚本

支持三种模式:

  • --index:处理缺少.txt侧车文件的现有PNG文件
  • --list:输出包含路径、时间戳和文本片段的TSV格式
  • 主模式:通过tofi进行模糊搜索

索引逻辑:

if [[ "${1:-}" == "--index" ]]; then
    while IFS= read -r png; do
        txt="${png%.png}.txt"
        [[ -f "$txt" ]] && continue
        run_ocr "$png" > "$txt" 2>/dev/null || true
    done < <(find "$SCREENSHOT_DIR" -name "screenshot-*.png" -type f | sort)
fi

列表生成:

Google AdInline article slot
if [[ "${1:-}" == "--list" ]]; then
    while IFS= read -r txt; do
        png="${txt%.txt}.png"
        [[ -f "$png" ]] || continue
        base=$(basename "$txt" .txt)
        dt="${base#screenshot-}"
        stamp="${dt:0:10} ${dt:11:2}:${dt:13:2}:${dt:15:2}"
        snippet=$(head -3 "$txt" | tr '\n' ' ' | cut -c1-120)
        printf '%s\t%s\t%s\n' "$png" "$stamp" "$snippet"
    done < <(find "$SCREENSHOT_DIR" -name "screenshot-*.txt" -type f | sort -r)
fi

搜索通过管道传入tofi,支持模糊匹配,宽度设为1100px。选中结果将文本复制到wl-clipboard,并通过xdg-open打开图像。

安装与集成

在Arch系统上安装:

sudo pacman -S grim slurp tesseract tesseract-data-rus wl-clipboard libnotify swappy

使脚本可执行,并在Hyprland中绑定快捷键:

bind = , Print, exec, ~/wayland/scripts/screen.sh
bind = SHIFT, Print, exec, ~/wayland/scripts/screen.sh --ocr
bind = SUPER, F, exec, ~/wayland/scripts/ssearch.sh

对于旧截图:./ssearch.sh --index

核心优势

  • OCR异步运行——从不阻塞UI;PSM 3适合混合内容屏幕。
  • tofi的模糊匹配能优雅处理OCR识别误差。
  • 侧车文件始终创建——即使为空——确保索引可靠。
  • 无AI或云依赖;仅使用纯Unix工具链。
  • 专为Wayland + tofi优化;适配GNOME/KDE需替换启动器。

局限与改进方向

Tesseract在深色主题中小字体识别困难——建议测试PSM/OEM参数。搜索基于字符串匹配,无语义理解能力。对于旋转截图,可设置cron或systemd-timer定期清理超过N天的文件。

— Editorial Team

Advertisement 728x90

继续阅读