Skill: datappt8/screen-capture-hub (version 1.0.0)

--- name: openclaw-screen-viewer displayName: OPENCLAW(龙虾)-屏幕查看器 description: 此技能应被用于任何需要捕获屏幕截图、分析屏幕内容或处理屏幕图像的任务。包括：使用Python PIL库捕获整个屏幕或特定区域的截图；保存截图到指定位置；分析截图中的文字内容（支持中英文OCR识别）；对截图进行基本图像处理（裁剪、旋转、调整大小）。当用户提到"屏幕截图"、"截屏"、"查看屏幕"或需要分析屏幕上的内容时，使用此技能。 version: 1.0.0 author: CodeBuddy User license: MIT keywords: - 屏幕截图 - OCR识别 - 文字提取 - 屏幕分析 - 图像处理 - 中文识别 - openclaw categories: - 图像处理 - OCR - 屏幕工具 - AI助手 --- # OPENCLAW(龙虾)-屏幕查看器 ## 概述 此技能提供了使用Python进行屏幕截图和图像处理的功能。它依赖于Pillow (PIL) 和pyautogui库来捕获屏幕内容，并可选择性地使用pytesseract进行OCR文字识别。 ## 安装依赖 ### 方法1：一键安装（推荐） ```bash python scripts/setup.py ``` ### 方法2：手动安装 **必需依赖**（基础功能）： ```bash pip install pillow pyautogui ``` **可选依赖**（OCR功能）： ```bash pip install pytesseract ``` **Tesseract OCR引擎**（OCR功能必需）： - Windows: 运行 `python scripts/install_tesseract.py` 自动安装 - Windows (手动): 从 https://github.com/UB-Mannheim/tesseract/wiki 下载安装 - macOS: `brew install tesseract` - Linux: `sudo apt-get install tesseract-ocr` **可选依赖**（高级分析功能）： ```bash pip install opencv-python numpy ``` ### 验证安装 ```bash # 检查所有依赖 python scripts/dependency_check.py # 测试截图功能 python scripts/test_screenshot.py # 测试OCR功能 python scripts/test_ocr.py # 运行所有示例 python examples/run_examples.py ``` ## 使用方法 ### 基本屏幕截图 使用`scripts/screenshot.py`脚本捕获整个屏幕： ```python python scripts/screenshot.py --output screenshot.png ``` 捕获特定区域： ```python python scripts/screenshot.py --output screenshot.png --region "100,100,500,500" ``` ### 文字识别 使用`scripts/ocr_screenshot.py`脚本捕获屏幕并识别文字： ```python python scripts/ocr_screenshot.py --output screenshot.png --text-output text.txt ``` ### 分析屏幕内容 使用`scripts/analyze_screen.py`脚本进行更复杂的分析： ```python python scripts/analyze_screen.py --task find_text --text "搜索词" ``` ## 工作流程 当用户请求屏幕相关操作时： 1. **确定需求** - 明确用户需要的是截图、文字识别还是其他分析 2. **选择脚本** - 根据需求选择合适的脚本 3. **设置参数** - 配置输出路径、区域等参数 4. **执行脚本** - 运行相应的Python脚本 5. **处理结果** - 将结果展示给用户或进行进一步分析 ## 常见任务 ### 任务1：快速截图 - 使用：`scripts/screenshot.py` - 参数：`--output` 指定输出文件路径 - 示例：捕获整个屏幕并保存为当前目录的screenshot.png ### 任务2：区域截图 - 使用：`scripts/screenshot.py` - 参数：`--region "x1,y1,x2,y2"` - 示例：捕获屏幕左上角500x500像素区域 ### 任务3：屏幕文字提取 - 使用：`scripts/ocr_screenshot.py` - 参数：`--text-output` 指定文本输出文件 - 示例：捕获屏幕并提取所有文字保存到text.txt ### 任务4：查找特定内容 - 使用：`scripts/analyze_screen.py` - 参数：`--task find_text --text "搜索内容"` - 示例：在屏幕上查找特定文字并高亮显示 ## 注意事项 1. **权限**：某些应用程序可能需要管理员权限才能捕获其窗口内容 2. **性能**：高分辨率屏幕截图可能需要较多内存 3. **OCR准确性**：文字识别准确性受字体、背景、分辨率影响 4. **多显示器**：脚本默认捕获主显示器，多显示器环境需要特殊处理 ## 故障排除 如果截图失败： 1. 检查Python库是否正确安装 2. 确认有足够的权限 3. 尝试降低分辨率或捕获特定区域 如果OCR识别不准确： 1. 确保Tesseract正确安装 2. 尝试预处理图像（二值化、去噪） 3. 指定语言参数（如`--lang chi_sim`用于简体中文）

path: CHANGELOG.md
content: # Changelog

All notable changes to the Screen Capture Hub skill will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.0.0] - 2026-03-13

### Added
- Initial release of Screen Capture Hub skill
- Basic screen capture functionality using PIL/Pillow and pyautogui
- OCR text recognition support with pytesseract
- Screen analysis tools for finding text, colors, and edges
- Comprehensive documentation and usage examples
- Test scripts for validating environment and dependencies

### Features
- **Full screen capture**: Capture entire screen with single command
- **Region capture**: Capture specific screen areas with coordinates
- **OCR integration**: Extract text from screenshots in multiple languages
- **Screen analysis**: Find specific text, colors, and detect edges
- **Cross-platform**: Works on Windows, macOS, and Linux
- **Easy installation**: Simple Python dependencies with clear installation instructions

### Technical Details
- Built with Python 3.8+
- Uses Pillow for image processing
- Integrates with pyautogui for screen interaction
- Supports Tesseract OCR for text recognition
- Includes OpenCV for advanced image analysis

### Dependencies
- Python 3.8 or higher
- Pillow >= 9.0.0
- pyautogui >= 0.9.0
- pytesseract >= 0.3.0 (optional for OCR)
- opencv-python >= 4.5.0 (optional for advanced analysis)
- numpy >= 1.20.0 (optional for advanced analysis)

## [0.1.0] - 2026-03-13

### Development Release
- Initial development and testing
- Basic functionality validation
- Documentation setup
- Package structure definition

path: INSTALL.md
content: # Installation Guide

## Prerequisites

- Python 3.8 or higher
- pip (Python package manager)

## Quick Installation

1. **Install Python dependencies:**

```bash
pip install pillow pyautogui
```

2. **For OCR functionality (optional):**

```bash
pip install pytesseract
```

3. **For advanced image analysis (optional):**

```bash
pip install opencv-python numpy
```

## Tesseract OCR Installation

### Windows
1. Download Tesseract OCR installer from: https://github.com/UB-Mannheim/tesseract/wiki
2. Run the installer
3. During installation, check "Add to PATH" or add the installation directory to your system PATH manually
4. Default installation path: `C:\Program Files\Tesseract-OCR\`

### macOS
```bash
brew install tesseract
```

### Linux (Ubuntu/Debian)
```bash
sudo apt-get install tesseract-ocr
sudo apt-get install tesseract-ocr-eng
sudo apt-get install tesseract-ocr-chi-sim  # For Chinese
```

## Verification

Run the test script to verify installation:

```bash
python scripts/test_screenshot.py
```

## Troubleshooting

### Common Issues

1. **"No module named 'pyautogui'"**
   - Make sure you have Python installed correctly
   - Try: `python -m pip install --user pyautogui`

2. **Screenshots show black screen**
   - Run as administrator (Windows)
   - Check application permissions

3. **Tesseract not found**
   - Ensure Tesseract is installed and in PATH
   - Or specify the path manually in your script:
   ```python
   import pytesseract
   pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
   ```

4. **Permission errors**
   - On macOS/Linux, you may need to grant screen recording permissions
   - On Windows, run as administrator

## Development Installation

For development, install all dependencies including development tools:

```bash
pip install -r requirements.txt
```

## Updating

To update to the latest version:

```bash
pip install --upgrade pillow pyautogui pytesseract opencv-python numpy
```

path: package.json
content: {
  "name": "openclaw-screen-viewer",
  "displayName": "OPENCLAW(龙虾)-屏幕查看器",
  "version": "1.0.0",
  "description": "A comprehensive screen capture, OCR recognition, and screen analysis skill for AI assistants",
  "longDescription": "OPENCLAW(龙虾)-屏幕查看器是一个功能强大的屏幕操作工具包，支持全屏/区域截图、OCR文字识别（中英文等多语言）、屏幕分析（文字搜索、颜色检测、边缘识别）、定时监控等功能。专为AI助手和自动化脚本设计，提供简洁的命令行界面和完整的Python API。",
  "author": "CodeBuddy User",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/your-username/openclaw-screen-viewer"
  },
  "keywords": [
    "openclaw",
    "screen-capture",
    "screenshot",
    "ocr",
    "text-recognition",
    "image-processing",
    "ai-assistant",
    "automation",
    "chinese-ocr",
    "screen-analysis"
  ],
  "categories": [
    "Automation",
    "Image Processing",
    "OCR",
    "Productivity",
    "Screen Tools",
    "Chinese Tools"
  ],
  "engines": {
    "codebuddy": ">=1.0.0"
  },
  "main": "SKILL.md",
  "files": [
    "SKILL.md",
    "README.md",
    "requirements.txt",
    "scripts/",
    "assets/",
    "references/"
  ],
  "dependencies": {
    "python": {
      "pillow": ">=9.0.0",
      "pyautogui": ">=0.9.0",
      "pytesseract": ">=0.3.0",
      "opencv-python": ">=4.5.0",
      "numpy": ">=1.20.0"
    }
  },
  "peerDependencies": {},
  "devDependencies": {},
  "scripts": {
    "test": "python scripts/test_screenshot.py"
  },
  "bugs": {
    "url": "https://github.com/your-username/openclaw-screen-viewer/issues"
  },
  "homepage": "https://github.com/your-username/openclaw-screen-viewer#readme",
  "prerequisites": {
    "python": ">=3.8",
    "system": {
      "windows": "Tesseract OCR installation required for OCR features",
      "macos": "brew install tesseract",
      "linux": "apt-get install tesseract-ocr"
    }
  },
  "features": [
    "Full screen and region capture",
    "OCR text recognition (multi-language support)",
    "Chinese text recognition support",
    "Screen analysis tools",
    "Scheduled monitoring",
    "Cross-platform compatibility",
    "Command-line interface",
    "Python API",
    "Automatic dependency checking"
  ],
  "supportedLanguages": ["en", "zh-CN"]
}

path: README.md
content: # OPENCLAW(龙虾)-屏幕查看器

一个功能强大的屏幕截图、OCR识别和屏幕分析技能包，专为AI助手设计。

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

## ✨ 功能特性

- **🎯 全屏/区域截图** - 灵活捕获屏幕内容
- **🔍 OCR文字识别** - 提取屏幕文字，支持多语言
- **📊 屏幕分析** - 查找特定文字、颜色、检测边缘
- **⚡ 快速操作** - 简化的命令行界面
- **🔄 定时监控** - 自动定时截图和变化检测
- **📁 多种格式输出** - 支持PNG、JSON、TXT等格式
- **🌍 跨平台** - Windows、macOS、Linux全支持

## 🚀 快速开始

### 一键安装（推荐）

运行一键安装脚本，自动安装所有依赖和OCR引擎：

```bash
# 运行安装脚本
python scripts/setup.py
```

### 手动安装

#### 1. 安装Python依赖库

**基础依赖（必需）** - 屏幕截图功能需要：
```bash
pip install pillow pyautogui
```

**OCR功能（可选）** - 文字识别功能需要：
```bash
pip install pytesseract
```

**图像分析（可选）** - 高级屏幕分析功能需要：
```bash
pip install opencv-python numpy
```

#### 2. 安装Tesseract OCR引擎（OCR功能必需）

**Windows（推荐方法）**：
```bash
# 自动下载和安装
python scripts/install_tesseract.py
```

**Windows（手动方法）**：
1. 访问：https://github.com/UB-Mannheim/tesseract/wiki
2. 下载最新的 `.exe` 安装程序
3. 运行安装程序，使用默认设置

**macOS**：
```bash
brew install tesseract
```

**Linux**：
```bash
sudo apt-get install tesseract-ocr tesseract-ocr-eng tesseract-ocr-chi-sim
```

### 验证安装

运行测试脚本验证所有功能：
```bash
# 测试屏幕截图功能
python scripts/test_screenshot.py

# 测试OCR功能
python scripts/test_ocr.py
```

### 基础使用

```bash
# 快速截图
python scripts/quick_capture.py

# 查看屏幕信息
python scripts/screenshot.py --list-displays

# 区域截图
python scripts/screenshot.py --region "0,0,500,500" --output region.png

# OCR文字识别
python scripts/ocr_screenshot.py --text-output screen_text.txt

# 屏幕分析
python scripts/analyze_screen.py --task screen_info
```

## 📖 详细文档

### 脚本说明

| 脚本 | 功能 | 示例 |
|------|------|------|
| `quick_capture.py` | 快速截图工具 | `python quick_capture.py -o screenshot.png` |
| `screenshot.py` | 完整截图工具 | `python screenshot.py --region "100,100,500,500"` |
| `ocr_screenshot.py` | OCR文字识别 | `python ocr_screenshot.py --lang chi_sim` |
| `analyze_screen.py` | 屏幕分析 | `python analyze_screen.py --task find_text --text "搜索词"` |
| `test_screenshot.py` | 环境测试 | `python test_screenshot.py` |
| `setup.py` | 安装脚本 | `python setup.py` |

### 参数说明

#### 截图参数
- `--output, -o`: 输出文件路径
- `--region, -r`: 截图区域 (x1,y1,x2,y2)
- `--list-displays, -l`: 显示屏幕信息

#### OCR参数
- `--text-output, -t`: 文字输出文件
- `--lang, -l`: OCR语言 (默认: eng+chi_sim)
- `--list-langs`: 显示支持的语言

#### 分析参数
- `--task, -t`: 分析任务 (screen_info, find_text, find_color, detect_edges)
- `--text`: 要搜索的文字
- `--color`: 要搜索的颜色 (#RRGGBB)
- `--tolerance`: 颜色匹配容差 (0-255)

## 🎯 使用示例

### 1. 基本截图
```bash
# 全屏截图
python scripts/quick_capture.py

# 指定区域截图
python scripts/screenshot.py --region "100,100,600,400" --output window.png

# 带时间戳的截图
python scripts/quick_capture.py -o screenshot_$(date +%Y%m%d_%H%M%S).png
```

### 2. OCR文字提取
```bash
# 提取全屏文字
python scripts/ocr_screenshot.py --text-output full_text.txt

# 提取中文文字
python scripts/ocr_screenshot.py --lang chi_sim --text-output chinese.txt

# 提取特定区域文字
python scripts/ocr_screenshot.py --region "200,200,800,600" --text-output region_text.txt
```

### 3. 屏幕分析
```bash
# 获取屏幕信息
python scripts/analyze_screen.py --task screen_info --output info.json

# 查找特定文字
python scripts/analyze_screen.py --task find_text --text "错误" --output errors.json

# 查找特定颜色
python scripts/analyze_screen.py --task find_color --color "#FF0000" --output red_items.json

# 检测屏幕边缘
python scripts/analyze_screen.py --task detect_edges --output edges.png
```

### 4. 高级应用
```python
# 定时截图监控
import time
from datetime import datetime
from PIL import ImageGrab

for i in range(10):  # 每5秒截图一次，共10次
    screenshot = ImageGrab.grab()
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    screenshot.save(f"monitor_{timestamp}.png")
    time.sleep(5)
```

## 🔧 API参考

### Python API
```python
from PIL import ImageGrab
import pyautogui

# 获取屏幕信息
screen_width, screen_height = pyautogui.size()
mouse_x, mouse_y = pyautogui.position()

# 截图
screenshot = ImageGrab.grab()  # 全屏
region_screenshot = ImageGrab.grab(bbox=(100, 100, 500, 500))  # 区域

# OCR识别
import pytesseract
text = pytesseract.image_to_string(screenshot, lang='eng+chi_sim')
```

## 📁 项目结构

```
screen-capture-hub/
├── SKILL.md              # 技能定义文件
├── README.md             # 项目文档
├── package.json          # 包元数据
├── LICENSE               # MIT许可证
├── CHANGELOG.md          # 版本日志
├── requirements.txt      # Python依赖
├── INSTALL.md            # 安装指南
├── scripts/              # Python脚本
│   ├── quick_capture.py
│   ├── screenshot.py
│   ├── ocr_screenshot.py
│   ├── analyze_screen.py
│   ├── test_screenshot.py
│   ├── setup.py
│   └── __init__.py
├── references/           # 参考文档
│   └── usage_examples.md
└── assets/              # 静态资源
    └── (图标、模板等)
```

## 🤝 贡献指南

欢迎贡献！请遵循以下步骤：

1. Fork 本仓库
2. 创建功能分支 (`git checkout -b feature/amazing-feature`)
3. 提交更改 (`git commit -m 'Add some amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 开启 Pull Request

### 开发设置
```bash
# 克隆仓库
git clone https://github.com/your-username/screen-capture-hub.git

# 安装开发依赖
pip install -r requirements.txt

# 运行测试
python scripts/test_screenshot.py
```

## 📄 许可证

本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。

## 🙏 致谢

- [Pillow (PIL Fork)](https://python-pillow.org/) - Python图像处理库
- [PyAutoGUI](https://pyautogui.readthedocs.io/) - 跨平台GUI自动化
- [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) - OCR引擎
- [OpenCV](https://opencv.org/) - 计算机视觉库

## 📞 支持

- **问题反馈**: [GitHub Issues](https://github.com/your-username/screen-capture-hub/issues)
- **功能请求**: 开启新的Issue
- **文档**: 查看 [references/](references/) 目录

## 🔗 相关链接

- [OpenClaw Hub](https://hub.openclaw.org/) - AI技能市场
- [Python官方文档](https://docs.python.org/3/)
- [Pillow文档](https://pillow.readthedocs.io/)
- [PyAutoGUI文档](https://pyautogui.readthedocs.io/)

---

**Screen Capture Hub** - 让屏幕操作更智能！ 🚀

path: requirements.txt
content: # 屏幕截图技能依赖
pillow>=9.0.0
pyautogui>=0.9.0
pytesseract>=0.3.0
opencv-python>=4.5.0
numpy>=1.20.0

# Tesseract OCR 引擎需要单独安装
# Windows: 从 https://github.com/UB-Mannheim/tesseract/wiki 下载安装
# 安装后需要将Tesseract添加到系统PATH

path: docs/OCR_SETUP_GUIDE.md
content: # Tesseract OCR 安装和配置指南

## 📝 概述

**OPENCLAW(龙虾)-屏幕查看器** 的OCR功能依赖于Tesseract OCR引擎。Tesseract是一个开源的OCR引擎，支持100多种语言，包括中文、英文等。

## 🚀 快速安装（Windows）

### 方法1：自动安装脚本（推荐）

运行以下脚本自动下载和安装Tesseract OCR：

```bash
python scripts/install_tesseract.py
```

### 方法2：手动下载安装

1. **下载Tesseract OCR**
   - 访问：https://github.com/UB-Mannheim/tesseract/wiki
   - 下载最新版本的安装程序（如 `tesseract-ocr-w64-setup-5.4.0.20241124.exe`）

2. **安装步骤**
   - 运行下载的安装程序
   - 选择安装语言（建议选择英文）
   - 接受许可证协议
   - 选择安装路径（建议使用默认路径）
   - 等待安装完成

3. **配置环境变量**
   - 安装程序通常会自动添加环境变量
   - 如果没有，请手动将Tesseract安装目录添加到PATH
     - 默认路径：`C:\Program Files\Tesseract-OCR\`

## 🌍 语言包安装

### 中文支持（简体中文）

Tesseract安装时可以选择安装语言包。如果安装时未选择中文包，请按以下步骤安装：

1. **手动下载语言包**
   - 中文（简体）：https://github.com/tesseract-ocr/tessdata/blob/main/chi_sim.traineddata
   - 英文：https://github.com/tesseract-ocr/tessdata/blob/main/eng.traineddata

2. **安装语言包**
   - 下载的文件放置在Tesseract的`tessdata`目录下
   - 默认路径：`C:\Program Files\Tesseract-OCR\tessdata\`

## 🔧 验证安装

### 命令行验证

```bash
# 检查Tesseract版本
tesseract --version

# 列出支持的语言
tesseract --list-langs
```

### Python验证

```python
import pytesseract

# 设置Tesseract路径（如果需要）
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# 测试OCR功能
print(pytesseract.get_tesseract_version())
print(pytesseract.get_languages(config=''))
```

## 🛠️ 常见问题解决

### 问题1：找不到tesseract

**错误信息**：
```
TesseractNotFoundError: tesseract is not installed or it's not in your PATH
```

**解决方案**：
1. 检查Tesseract是否已安装
2. 检查环境变量是否配置正确
3. 或者在Python代码中指定路径：
   ```python
   pytesseract.pytesseract.tesseract_cmd = r'完整路径\tesseract.exe'
   ```

### 问题2：不支持的语言

**错误信息**：
```
Error opening data file \tessdata\chi_sim.traineddata
```

**解决方案**：
1. 下载对应的语言包
2. 放置到正确的`tessdata`目录中

### 问题3：OCR识别效果差

**优化建议**：
1. **预处理图像**
   ```python
   # 转换为灰度图
   image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
   
   # 二值化
   _, image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
   ```

2. **调整参数**
   ```python
   # 使用更好的配置
   text = pytesseract.image_to_string(
       image,
       lang='chi_sim+eng',  # 中英文混合
       config='--psm 6 --oem 3'
   )
   ```

## 📚 语言代码参考

| 语言 | 代码 | 用途 |
|------|------|------|
| 英语 | `eng` | 英文文本识别 |
| 简体中文 | `chi_sim` | 简体中文识别 |
| 繁体中文 | `chi_tra` | 繁体中文识别 |
| 日语 | `jpn` | 日文识别 |
| 韩语 | `kor` | 韩文识别 |
| 多语言 | `eng+chi_sim` | 中英文混合识别 |

## 🎯 高级配置

### Tesseract配置参数

```python
# 常用的配置参数
config_params = {
    '--psm': '页面分割模式 (0-13)',
    '--oem': 'OCR引擎模式 (0-3)',
    '--dpi': '图像DPI设置',
    '--user-words': '用户词典文件',
    '--user-patterns': '用户模式文件'
}
```

### 推荐的PSM模式

- `3`：自动页面分割，但无方向检测
- `6`：假设为一个统一文本块
- `11`：尽量识别为单行文本

### 性能优化

1. **限制识别区域**
   ```python
   # 只识别特定区域
   region = image[y1:y2, x1:x2]
   text = pytesseract.image_to_string(region, lang='chi_sim')
   ```

2. **批量处理优化**
   ```python
   # 预加载模型
   import pytesseract
   from PIL import Image
   
   # 一次加载，多次使用
   def init_ocr():
       config = r'--oem 3 --psm 6'
       return lambda img: pytesseract.image_to_string(img, lang='chi_sim', config=config)
   
   ocr_engine = init_ocr()
   ```

## 🔗 资源链接

- **官方项目**: https://github.com/tesseract-ocr/tesseract
- **Windows安装**: https://github.com/UB-Mannheim/tesseract/wiki
- **语言包**: https://github.com/tesseract-ocr/tessdata
- **文档**: https://tesseract-ocr.github.io/

## 📊 支持的平台

| 平台 | 安装方法 | 备注 |
|------|----------|------|
| Windows | 自动安装脚本 | 支持64位系统 |
| macOS | `brew install tesseract` | 需要Homebrew |
| Linux | `apt-get install tesseract-ocr` | 根据发行版选择 |

## 🤝 社区支持

如果遇到问题，请：
1. 查看本项目的问题反馈区
2. 参考Tesseract官方文档
3. 加入相关技术社区讨论

---

**注意**: Tesseract OCR是独立的开源项目，安装和配置可能需要管理员权限。

path: examples/run_examples.py
content: #!/usr/bin/env python3
"""
OPENCLAW(龙虾)-屏幕查看器 使用示例
运行此脚本演示所有功能
"""

import os
import sys
import subprocess
from pathlib import Path

def print_header():
    """打印标题"""
    print("=" * 70)
    print("OPENCLAW(龙虾)-屏幕查看器 - 功能演示")
    print("=" * 70)
    print("此脚本将演示屏幕查看器的各种功能")
    print("请确保已安装所有依赖")
    print("=" * 70)

def check_dependencies():
    """检查依赖"""
    print("\n1. 检查系统依赖...")
    
    # 检查Python版本
    version = sys.version_info
    print(f"   Python版本: {sys.version.split()[0]}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("   [失败] 需要Python 3.8或更高版本")
        return False
    else:
        print("   [成功] Python版本符合要求")
    
    # 检查脚本目录
    script_dir = Path(__file__).parent.parent / "scripts"
    if not script_dir.exists():
        print(f"   [失败] 脚本目录不存在: {script_dir}")
        return False
    
    print("   [成功] 脚本目录检查通过")
    return True

def run_basic_screenshot():
    """运行基本截图示例"""
    print("\n2. 基本截图演示...")
    
    try:
        # 使用快速截图工具
        cmd = ["python", "scripts/quick_capture.py", "-o", "example_basic.png"]
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("   基本截图测试完成")
            if Path("example_basic.png").exists():
                file_size = Path("example_basic.png").stat().st_size
                print(f"   截图文件已保存: example_basic.png ({file_size/1024:.1f}KB)")
                return True
            else:
                print("   警告: 截图文件未生成")
                return False
        else:
            print(f"   错误: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"   异常: {e}")
        return False

def run_screen_info():
    """运行屏幕信息获取"""
    print("\n3. 屏幕信息获取演示...")
    
    try:
        cmd = ["python", "scripts/screenshot.py", "--list-displays"]
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("   屏幕信息获取完成")
            lines = result.stdout.strip().split('\n')
            for line in lines:
                if line.strip():
                    print(f"   {line.strip()}")
            return True
        else:
            print(f"   错误: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"   异常: {e}")
        return False

def run_region_capture():
    """运行区域截图演示"""
    print("\n4. 区域截图演示...")
    
    try:
        cmd = [
            "python", "scripts/screenshot.py",
            "--region", "100,100,500,400",
            "--output", "example_region.png"
        ]
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("   区域截图测试完成")
            if Path("example_region.png").exists():
                file_size = Path("example_region.png").stat().st_size
                print(f"   区域截图已保存: example_region.png ({file_size/1024:.1f}KB)")
                return True
            else:
                print("   警告: 区域截图文件未生成")
                return False
        else:
            print(f"   错误: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"   异常: {e}")
        return False

def run_ocr_test():
    """运行OCR测试"""
    print("\n5. OCR文字识别演示...")
    
    try:
        cmd = ["python", "scripts/test_ocr.py"]
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("   OCR功能测试完成")
            return True
        else:
            print("   OCR功能测试失败")
            print(f"   错误信息: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"   异常: {e}")
        return False

def run_analysis_test():
    """运行分析功能测试"""
    print("\n6. 屏幕分析演示...")
    
    try:
        cmd = ["python", "scripts/analyze_screen.py", "--task", "screen_info"]
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("   屏幕分析测试完成")
            return True
        else:
            print("   屏幕分析测试失败")
            if result.stdout:
                print(f"   输出: {result.stdout[:200]}...")
            return False
            
    except Exception as e:
        print(f"   异常: {e}")
        return False

def cleanup_example_files():
    """清理示例文件"""
    print("\n7. 清理示例文件...")
    
    files_to_clean = [
        "example_basic.png",
        "example_region.png",
        "ocr_test_image.png"
    ]
    
    cleaned = 0
    for file_name in files_to_clean:
        if Path(file_name).exists():
            Path(file_name).unlink()
            cleaned += 1
    
    if cleaned > 0:
        print(f"   已清理 {cleaned} 个示例文件")
    else:
        print("   没有需要清理的文件")

def main():
    """主函数"""
    print_header()
    
    # 检查依赖
    if not check_dependencies():
        print("\n[失败] 系统依赖检查失败")
        print("请先安装必要的依赖:")
        print("  1. Python 3.8或更高版本")
        print("  2. 运行依赖检查: python scripts/dependency_check.py")
        sys.exit(1)
    
    results = {
        'basic': run_basic_screenshot(),
        'info': run_screen_info(),
        'region': run_region_capture(),
        'ocr': run_ocr_test(),
        'analysis': run_analysis_test()
    }
    
    # 显示结果
    print("\n" + "=" * 70)
    print("功能演示结果:")
    print("=" * 70)
    
    test_names = {
        'basic': '基本截图',
        'info': '屏幕信息',
        'region': '区域截图',
        'ocr': 'OCR识别',
        'analysis': '屏幕分析'
    }
    
    all_passed = True
    for test_key, passed in results.items():
        status = "[成功]" if passed else "[失败]"
        print(f"  {test_names[test_key]:10} {status}")
        if not passed:
            all_passed = False
    
    print("\n" + "=" * 70)
    
    if all_passed:
        print("[成功] 所有功能测试通过!")
        print("您的OPENCLAW(龙虾)-屏幕查看器已成功安装并配置完成")
        
        print("\n下一步操作建议:")
        print("  1. 查看详细文档: cat README.md")
        print("  2. 测试更多功能: python scripts/test_screenshot.py")
        print("  3. 查看使用示例: examples/目录")
        print("  4. 获取帮助: python scripts/screenshot.py --help")
        
        # 清理示例文件
        cleanup_example_files()
        
        return True
    else:
        print("[警告] 部分功能测试失败")
        
        print("\n问题解决建议:")
        print("  1. 检查依赖: python scripts/dependency_check.py")
        print("  2. 安装缺少的依赖:")
        print("     pip install pillow pyautogui")
        print("  3. 安装OCR功能:")
        print("     pip install pytesseract")
        print("     并从 https://github.com/UB-Mannheim/tesseract/wiki 下载Tesseract")
        print("  4. 查看详细错误日志")
        
        return False

if __name__ == "__main__":
    try:
        success = main()
        if success:
            sys.exit(0)
        else:
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n[信息] 用户中断演示")
        sys.exit(1)

path: references/usage_examples.md
content: # 使用示例

## 基本截图示例

### 示例1: 快速全屏截图
```bash
# 使用快速截图工具
python scripts/quick_capture.py

# 使用完整截图工具
python scripts/screenshot.py --output my_screen.png
```

### 示例2: 区域截图
```bash
# 截取屏幕左上角500x500区域
python scripts/screenshot.py --region "0,0,500,500" --output top_left.png

# 截取屏幕中心区域
python scripts/screenshot.py --region "710,290,1210,790" --output center.png
```

### 示例3: 带时间戳的截图
```bash
# 自动添加时间戳
python scripts/quick_capture.py -o screenshot_$(date +%Y%m%d_%H%M%S).png
```

## OCR文字识别示例

### 示例4: 提取屏幕文字
```bash
# 提取全屏文字
python scripts/ocr_screenshot.py --text-output screen_text.txt

# 提取特定区域文字
python scripts/ocr_screenshot.py --region "100,100,800,600" --text-output region_text.txt

# 使用中文识别
python scripts/ocr_screenshot.py --lang chi_sim --text-output chinese_text.txt
```

### 示例5: 批量处理截图
```bash
# 创建批处理脚本 process_screenshots.bat (Windows)
@echo off
python scripts/ocr_screenshot.py --text-output screenshot1.txt
python scripts/ocr_screenshot.py --region "0,0,500,500" --text-output region1.txt
python scripts/ocr_screenshot.py --lang eng+chi_sim --text-output bilingual.txt
```

## 屏幕分析示例

### 示例6: 查找特定文字
```bash
# 查找屏幕上的"错误"文字
python scripts/analyze_screen.py --task find_text --text "错误" --output error_positions.json

# 查找多个关键词
python scripts/analyze_screen.py --task find_text --text "成功|完成|OK" --output results.json
```

### 示例7: 颜色检测
```bash
# 查找红色元素 (#FF0000)
python scripts/analyze_screen.py --task find_color --color "#FF0000" --output red_elements.json

# 查找蓝色元素，增加容差
python scripts/analyze_screen.py --task find_color --color "#0000FF" --tolerance 20 --output blue_elements.json
```

### 示例8: 屏幕边缘检测
```bash
# 检测屏幕边缘
python scripts/analyze_screen.py --task detect_edges --output edges.png

# 分析边缘密度
python scripts/analyze_screen.py --task detect_edges --output analysis.json
```

## 高级使用示例

### 示例9: 定时截图监控
```python
# 创建定时截图脚本 monitor.py
import time
from datetime import datetime
from PIL import ImageGrab

interval = 5  # 秒
duration = 60  # 秒

for i in range(duration // interval):
    # 截图
    screenshot = ImageGrab.grab()
    
    # 生成文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"monitor_{timestamp}.png"
    
    # 保存
    screenshot.save(filename)
    print(f"已保存: {filename}")
    
    # 等待
    time.sleep(interval)
```

### 示例10: 变化检测
```python
# 创建变化检测脚本 change_detector.py
import cv2
import numpy as np
from PIL import ImageGrab
import time

prev_screen = None
threshold = 0.01  # 1%的变化阈值

while True:
    current_screen = ImageGrab.grab()
    
    if prev_screen is not None:
        # 转换为灰度图
        prev_gray = cv2.cvtColor(np.array(prev_screen), cv2.COLOR_RGB2GRAY)
        curr_gray = cv2.cvtColor(np.array(current_screen), cv2.COLOR_RGB2GRAY)
        
        # 计算差异
        diff = cv2.absdiff(prev_gray, curr_gray)
        change_percentage = np.sum(diff > 25) / diff.size
        
        if change_percentage > threshold:
            print(f"检测到变化: {change_percentage*100:.2f}%")
            # 保存变化截图
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            current_screen.save(f"change_{timestamp}.png")
    
    prev_screen = current_screen
    time.sleep(1)
```

### 示例11: 自动化报告生成
```python
# 创建报告生成脚本 report_generator.py
import json
from datetime import datetime
from PIL import ImageGrab
import pyautogui

def generate_screen_report():
    """生成屏幕报告"""
    report = {
        "timestamp": datetime.now().isoformat(),
        "screen_info": {},
        "screenshot": None
    }
    
    # 获取屏幕信息
    screen_width, screen_height = pyautogui.size()
    mouse_x, mouse_y = pyautogui.position()
    
    report["screen_info"] = {
        "resolution": f"{screen_width}x{screen_height}",
        "mouse_position": [mouse_x, mouse_y]
    }
    
    # 截图
    screenshot = ImageGrab.grab()
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    screenshot_file = f"report_screenshot_{timestamp}.png"
    screenshot.save(screenshot_file)
    
    report["screenshot"] = screenshot_file
    report["screenshot_size"] = f"{screenshot.size[0]}x{screenshot.size[1]}"
    
    # 保存报告
    report_file = f"screen_report_{timestamp}.json"
    with open(report_file, 'w', encoding='utf-8') as f:
        json.dump(report, f, indent=2, ensure_ascii=False)
    
    print(f"报告已生成: {report_file}")
    return report_file

if __name__ == "__main__":
    generate_screen_report()
```

## 集成示例

### 示例12: 与CodeBuddy集成
```python
# 在CodeBuddy技能中集成屏幕截图功能
def capture_and_analyze():
    """捕获并分析屏幕"""
    from scripts.screenshot import capture_full_screen
    from scripts.ocr_screenshot import capture_and_ocr
    from scripts.analyze_screen import find_text_on_screen
    
    # 1. 截图
    screenshot_file = "analysis_screenshot.png"
    capture_full_screen(screenshot_file)
    
    # 2. OCR识别
    text_file = "analysis_text.txt"
    capture_and_ocr(output_image=screenshot_file, output_text=text_file)
    
    # 3. 分析特定内容
    search_results = find_text_on_screen("错误", lang='chi_sim')
    
    return {
        "screenshot": screenshot_file,
        "text": text_file,
        "errors_found": len(search_results) if search_results else 0
    }
```

### 示例13: 错误监控系统
```python
# 错误监控脚本 error_monitor.py
import time
import json
from datetime import datetime
from scripts.analyze_screen import find_text_on_screen

def monitor_errors(interval=30, duration=3600):
    """监控屏幕错误"""
    error_log = []
    start_time = time.time()
    
    while time.time() - start_time < duration:
        # 搜索错误关键词
        errors = find_text_on_screen("错误|失败|异常|Error|Failed|Exception")
        
        if errors:
            error_entry = {
                "timestamp": datetime.now().isoformat(),
                "errors": errors,
                "count": len(errors)
            }
            error_log.append(error_entry)
            
            # 保存错误日志
            with open("error_log.json", "w", encoding="utf-8") as f:
                json.dump(error_log, f, indent=2, ensure_ascii=False)
            
            print(f"发现 {len(errors)} 个错误")
        
        time.sleep(interval)
    
    return error_log
```

## 故障排除示例

### 示例14: 诊断脚本
```bash
# 运行诊断测试
python scripts/test_screenshot.py

# 检查依赖
python -c "from PIL import ImageGrab; import pyautogui; print('依赖检查通过')"

# 测试OCR
python -c "import pytesseract; print('Tesseract版本:', pytesseract.get_tesseract_version())"
```

这些示例展示了Screen Capture Hub技能的各种用法，您可以根据需要修改和扩展。

path: scripts/analyze_screen.py
content: #!/usr/bin/env python3
"""
屏幕分析工具
提供多种屏幕分析功能
"""

import argparse
import sys
import os
import json
from datetime import datetime

try:
    from PIL import ImageGrab, Image, ImageDraw, ImageFont
    import pyautogui
    import cv2
    import numpy as np
except ImportError as e:
    print(f"错误：缺少必要的库。请安装：pip install pillow pyautogui opencv-python numpy")
    print(f"导入错误：{e}")
    sys.exit(1)

def capture_screenshot(output_path=None, region=None):
    """捕获屏幕截图"""
    try:
        if region:
            coords = region.split(',')
            if len(coords) != 4:
                print("区域格式错误，应为 'x1,y1,x2,y2'")
                return None
            x1, y1, x2, y2 = map(int, coords)
            bbox = (x1, y1, x2, y2)
            screenshot = ImageGrab.grab(bbox=bbox)
        else:
            screenshot = ImageGrab.grab()
        
        if output_path:
            screenshot.save(output_path)
            print(f"截图已保存：{output_path}")
        
        return screenshot
    except Exception as e:
        print(f"截图失败：{e}")
        return None

def find_text_on_screen(search_text, screenshot=None, lang='eng+chi_sim'):
    """在屏幕上查找特定文字"""
    try:
        import pytesseract
        
        # 如果没有提供截图，先捕获屏幕
        if screenshot is None:
            screenshot = capture_screenshot()
            if screenshot is None:
                return None
        
        # 转换为灰度图
        gray = screenshot.convert('L')
        
        # 使用Tesseract获取文字和位置信息
        data = pytesseract.image_to_data(gray, lang=lang, output_type=pytesseract.Output.DICT)
        
        found_positions = []
        
        # 搜索匹配的文字
        for i in range(len(data['text'])):
            text = data['text'][i].strip()
            if search_text.lower() in text.lower():
                x = data['left'][i]
                y = data['top'][i]
                w = data['width'][i]
                h = data['height'][i]
                conf = data['conf'][i]
                
                found_positions.append({
                    'text': text,
                    'position': (x, y, w, h),
                    'confidence': conf,
                    'index': i
                })
        
        return found_positions
        
    except ImportError:
        print("错误：未找到pytesseract。请安装：pip install pytesseract")
        return None
    except Exception as e:
        print(f"文字搜索失败：{e}")
        return None

def find_color_on_screen(target_color, screenshot=None, tolerance=10):
    """在屏幕上查找特定颜色"""
    try:
        # 如果没有提供截图，先捕获屏幕
        if screenshot is None:
            screenshot = capture_screenshot()
            if screenshot is None:
                return None
        
        # 转换为RGB
        rgb_img = screenshot.convert('RGB')
        width, height = rgb_img.size
        
        # 将目标颜色转换为RGB元组
        if isinstance(target_color, str):
            # 解析十六进制颜色
            if target_color.startswith('#'):
                target_color = target_color[1:]
            r = int(target_color[0:2], 16)
            g = int(target_color[2:4], 16)
            b = int(target_color[4:6], 16)
            target_rgb = (r, g, b)
        else:
            target_rgb = target_color
        
        # 查找匹配颜色的像素
        matches = []
        
        # 为了性能，可以采样检查
        for y in range(0, height, 5):  # 每5个像素采样一次
            for x in range(0, width, 5):
                pixel = rgb_img.getpixel((x, y))
                
                # 计算颜色差异
                diff = sum(abs(p - t) for p, t in zip(pixel, target_rgb))
                if diff <= tolerance:
                    matches.append((x, y))
        
        return matches
        
    except Exception as e:
        print(f"颜色搜索失败：{e}")
        return None

def detect_edges_on_screen(screenshot=None):
    """检测屏幕边缘"""
    try:
        # 如果没有提供截图，先捕获屏幕
        if screenshot is None:
            screenshot = capture_screenshot()
            if screenshot is None:
                return None
        
        # 转换为OpenCV格式
        cv_img = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
        
        # 转换为灰度图
        gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
        
        # 应用Canny边缘检测
        edges = cv2.Canny(gray, 50, 150)
        
        # 计算边缘数量
        edge_pixels = np.sum(edges > 0)
        total_pixels = edges.size
        edge_percentage = (edge_pixels / total_pixels) * 100
        
        return {
            'edge_image': edges,
            'edge_pixels': edge_pixels,
            'total_pixels': total_pixels,
            'edge_percentage': edge_percentage
        }
        
    except Exception as e:
        print(f"边缘检测失败：{e}")
        return None

def get_screen_info():
    """获取屏幕信息"""
    try:
        screen_width, screen_height = pyautogui.size()
        mouse_x, mouse_y = pyautogui.position()
        
        info = {
            'resolution': f"{screen_width}x{screen_height}",
            'mouse_position': (mouse_x, mouse_y),
            'timestamp': datetime.now().isoformat()
        }
        
        return info
        
    except Exception as e:
        print(f"获取屏幕信息失败：{e}")
        return None

def main():
    parser = argparse.ArgumentParser(description='屏幕分析工具')
    parser.add_argument('--task', '-t', required=True,
                       choices=['find_text', 'find_color', 'detect_edges', 'screen_info'],
                       help='分析任务类型')
    parser.add_argument('--text', default='',
                       help='要搜索的文字（用于find_text任务）')
    parser.add_argument('--color', default='#FF0000',
                       help='要搜索的颜色（十六进制，用于find_color任务）')
    parser.add_argument('--tolerance', type=int, default=10,
                       help='颜色匹配容差（0-255，用于find_color任务）')
    parser.add_argument('--output', '-o', default=None,
                       help='输出文件路径')
    parser.add_argument('--region', '-r', default=None,
                       help='捕获区域，格式：x1,y1,x2,y2')
    parser.add_argument('--lang', '-l', default='eng+chi_sim',
                       help='OCR语言（用于find_text任务）')
    
    args = parser.parse_args()
    
    # 根据任务类型执行不同的分析
    if args.task == 'screen_info':
        # 获取屏幕信息
        info = get_screen_info()
        if info:
            print("屏幕信息：")
            print(f"  分辨率：{info['resolution']}")
            print(f"  鼠标位置：{info['mouse_position']}")
            print(f"  时间：{info['timestamp']}")
            
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(info, f, indent=2)
                print(f"信息已保存到：{args.output}")
    
    elif args.task == 'find_text':
        # 搜索文字
        if not args.text:
            print("错误：--text 参数是必需的")
            sys.exit(1)
        
        print(f"正在搜索文字：'{args.text}'")
        positions = find_text_on_screen(args.text, lang=args.lang)
        
        if positions:
            print(f"找到 {len(positions)} 个匹配：")
            for i, pos in enumerate(positions):
                x, y, w, h = pos['position']
                print(f"  {i+1}: '{pos['text']}' 位置: ({x}, {y}, {w}, {h}) 置信度: {pos['confidence']}")
            
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(positions, f, indent=2, default=str)
                print(f"结果已保存到：{args.output}")
        else:
            print("未找到匹配的文字")
    
    elif args.task == 'find_color':
        # 搜索颜色
        print(f"正在搜索颜色：{args.color}")
        matches = find_color_on_screen(args.color, tolerance=args.tolerance)
        
        if matches:
            print(f"找到 {len(matches)} 个匹配颜色的像素")
            
            # 显示前几个匹配位置
            print("前10个匹配位置：")
            for i, (x, y) in enumerate(matches[:10]):
                print(f"  {i+1}: ({x}, {y})")
            
            if args.output:
                with open(args.output, 'w') as f:
                    json.dump(matches, f, indent=2)
                print(f"结果已保存到：{args.output}")
        else:
            print("未找到匹配的颜色")
    
    elif args.task == 'detect_edges':
        # 检测边缘
        print("正在检测屏幕边缘...")
        result = detect_edges_on_screen()
        
        if result:
            print(f"边缘检测结果：")
            print(f"  边缘像素数：{result['edge_pixels']}")
            print(f"  总像素数：{result['total_pixels']}")
            print(f"  边缘比例：{result['edge_percentage']:.2f}%")
            
            if args.output:
                # 保存边缘图像
                edge_img = Image.fromarray(result['edge_image'])
                edge_img.save(args.output)
                print(f"边缘图像已保存到：{args.output}")
    
    else:
        print(f"未知任务：{args.task}")
        sys.exit(1)

if __name__ == "__main__":
    main()

path: scripts/dependency_check.py
content: #!/usr/bin/env python3
"""
依赖检查工具
自动检测并提示缺少的依赖
"""

import sys
import subprocess
import importlib.util
from pathlib import Path

class DependencyChecker:
    """依赖检查器"""
    
    def __init__(self):
        self.dependencies = {
            'basic': {
                'pillow': {
                    'name': 'Pillow',
                    'import_name': 'PIL',
                    'pip_name': 'pillow',
                    'required': True,
                    'purpose': '图像处理库，用于屏幕截图'
                },
                'pyautogui': {
                    'name': 'PyAutoGUI',
                    'import_name': 'pyautogui',
                    'pip_name': 'pyautogui',
                    'required': True,
                    'purpose': '屏幕自动化库，用于获取屏幕信息'
                }
            },
            'ocr': {
                'pytesseract': {
                    'name': 'pytesseract',
                    'import_name': 'pytesseract',
                    'pip_name': 'pytesseract',
                    'required': False,
                    'purpose': 'OCR文字识别库'
                }
            },
            'analysis': {
                'opencv': {
                    'name': 'OpenCV',
                    'import_name': 'cv2',
                    'pip_name': 'opencv-python',
                    'required': False,
                    'purpose': '计算机视觉库，用于图像分析'
                },
                'numpy': {
                    'name': 'NumPy',
                    'import_name': 'numpy',
                    'pip_name': 'numpy',
                    'required': False,
                    'purpose': '数值计算库，用于图像处理'
                }
            }
        }
        
        self.missing_deps = []
        self.available_deps = []
        self.tesseract_path = None
        
    def check_import(self, module_name):
        """检查模块是否可以导入"""
        try:
            spec = importlib.util.find_spec(module_name)
            return spec is not None
        except:
            return False
    
    def check_tesseract(self):
        """检查Tesseract OCR是否安装"""
        print("\n检查Tesseract OCR...")
        
        # 常见Tesseract路径
        common_paths = [
            r"C:\Program Files\Tesseract-OCR\tesseract.exe",
            r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
            r"C:\Program Files\Tesseract\tesseract.exe",
        ]
        
        # 检查环境变量
        try:
            result = subprocess.run(
                "tesseract --version",
                shell=True,
                capture_output=True,
                text=True,
                encoding='utf-8',
                errors='ignore'
            )
            if result.returncode == 0:
                print("  [成功] Tesseract在环境变量中可用")
                # 获取版本
                version_line = result.stdout.strip().split('\n')[0]
                print(f"   版本: {version_line}")
                return True
        except:
            pass
        
        # 检查常见路径
        for path in common_paths:
            if Path(path).exists():
                print(f"  [成功] 找到Tesseract: {path}")
                self.tesseract_path = path
                
                # 检查版本
                try:
                    result = subprocess.run(
                        [path, "--version"],
                        capture_output=True,
                        text=True,
                        encoding='utf-8',
                        errors='ignore'
                    )
                    if result.returncode == 0:
                        version_line = result.stdout.strip().split('\n')[0]
                        print(f"   版本: {version_line}")
                except:
                    pass
                    
                return True
        
        print("  [失败] 未找到Tesseract OCR")
        print("  OCR功能将不可用")
        return False
    
    def check_category(self, category_name, category_deps):
        """检查一个类别的依赖"""
        print(f"\n检查{category_name}依赖...")
        
        for dep_key, dep_info in category_deps.items():
            is_available = self.check_import(dep_info['import_name'])
            
            if is_available:
                print(f"  [成功] {dep_info['name']}: 已安装")
                self.available_deps.append(dep_info['name'])
            else:
                print(f"  [失败] {dep_info['name']}: 未安装")
                print(f"    用途: {dep_info['purpose']}")
                if dep_info['required']:
                    self.missing_deps.append(dep_info)
    
    def run_checks(self):
        """运行所有检查"""
        print("=" * 60)
        print("OPENCLAW(龙虾)-屏幕查看器 - 依赖检查")
        print("=" * 60)
        
        # 检查基础依赖
        self.check_category('基础', self.dependencies['basic'])
        
        # 检查OCR依赖
        self.check_category('OCR', self.dependencies['ocr'])
        
        # 检查分析依赖
        self.check_category('分析', self.dependencies['analysis'])
        
        # 检查Tesseract OCR
        tesseract_installed = self.check_tesseract()
        
        # 显示结果
        print("\n" + "=" * 60)
        print("依赖检查结果:")
        print("=" * 60)
        
        if not self.missing_deps:
            print("\n[成功] 所有必需依赖已安装!")
        else:
            print("\n[警告] 缺少以下必需依赖:")
            for dep in self.missing_deps:
                print(f"  • {dep['name']} ({dep['pip_name']})")
                print(f"    用途: {dep['purpose']}")
        
        # 显示可选依赖状态
        if self.available_deps:
            print(f"\n[信息] 已安装的可选依赖: {', '.join(self.available_deps)}")
        
        # Tesseract状态
        if tesseract_installed:
            print("\n[成功] Tesseract OCR已安装，OCR功能可用")
        else:
            print("\n[警告] Tesseract OCR未安装，OCR功能将不可用")
        
        # 提供安装建议
        if self.missing_deps or not tesseract_installed:
            print("\n" + "=" * 60)
            print("安装建议:")
            print("=" * 60)
            
            if self.missing_deps:
                print("\n安装Python依赖:")
                pip_commands = []
                for dep in self.missing_deps:
                    pip_commands.append(f"pip install {dep['pip_name']}")
                
                print("或运行以下命令:")
                for cmd in pip_commands:
                    print(f"  {cmd}")
                
                print("\n或运行一键安装脚本:")
                print("  python scripts/setup.py")
            
            if not tesseract_installed:
                print("\n安装Tesseract OCR:")
                print("Windows:")
                print("  自动安装: python scripts/install_tesseract.py")
                print("  手动安装: 从 https://github.com/UB-Mannheim/tesseract/wiki 下载")
                print("macOS:")
                print("  brew install tesseract")
                print("Linux:")
                print("  sudo apt-get install tesseract-ocr")
        
        print("\n" + "=" * 60)
        
        # 返回结果
        has_all_required = len(self.missing_deps) == 0
        return has_all_required, tesseract_installed
    
    def get_installation_commands(self):
        """获取安装命令"""
        commands = []
        
        if self.missing_deps:
            commands.append("# 安装Python依赖")
            for dep in self.missing_deps:
                commands.append(f"pip install {dep['pip_name']}")
        
        if not self.tesseract_path:
            commands.append("\n# 安装Tesseract OCR")
            commands.append("# Windows:")
            commands.append("python scripts/install_tesseract.py")
            commands.append("# 或手动下载: https://github.com/UB-Mannheim/tesseract/wiki")
        
        return "\n".join(commands)

def main():
    """主函数"""
    checker = DependencyChecker()
    has_all_required, tesseract_installed = checker.run_checks()
    
    # 导出到环境变量
    if checker.tesseract_path:
        print(f"\nTesseract路径: {checker.tesseract_path}")
        print("建议在Python代码中设置:")
        print(f'pytesseract.pytesseract.tesseract_cmd = r"{checker.tesseract_path}"')
    
    # 返回退出码
    if has_all_required:
        print("\n[成功] 系统准备就绪，可以运行屏幕查看器")
        sys.exit(0)
    else:
        print("\n[失败] 缺少必需依赖，请先安装")
        sys.exit(1)

if __name__ == "__main__":
    main()

path: scripts/install_tesseract.py
content: #!/usr/bin/env python3
"""
Tesseract OCR 自动安装脚本
适用于Windows系统
"""

import os
import sys
import subprocess
import requests
import tempfile
import shutil
from pathlib import Path
import time

def print_header():
    """打印标题"""
    print("=" * 60)
    print("OPENCLAW(龙虾)-屏幕查看器 - Tesseract OCR安装程序")
    print("=" * 60)
    print("此脚本将自动下载和安装Tesseract OCR引擎")
    print("用于屏幕文字识别功能")
    print("=" * 60)

def check_os():
    """检查操作系统"""
    print("\n检查操作系统...")
    if sys.platform != "win32":
        print(f"[警告] 当前系统: {sys.platform}")
        print("此脚本仅支持Windows系统")
        print("其他系统请手动安装:")
        print("  macOS: brew install tesseract")
        print("  Linux: sudo apt-get install tesseract-ocr")
        return False
    print("[成功] Windows系统检测通过")
    return True

def check_existing_tesseract():
    """检查是否已安装Tesseract"""
    print("\n检查Tesseract OCR...")
    
    paths_to_check = [
        r"C:\Program Files\Tesseract-OCR\tesseract.exe",
        r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
        os.path.join(os.environ.get("ProgramFiles", ""), "Tesseract-OCR", "tesseract.exe"),
    ]
    
    for tesseract_path in paths_to_check:
        if os.path.exists(tesseract_path):
            print(f"[成功] 发现Tesseract: {tesseract_path}")
            # 测试版本
            try:
                result = subprocess.run([tesseract_path, "--version"], 
                                      capture_output=True, text=True, encoding='utf-8')
                if result.returncode == 0:
                    version_info = result.stdout.strip().split('\n')[0]
                    print(f"[成功] 版本: {version_info}")
                    return tesseract_path
            except:
                pass
            return tesseract_path
    
    print("[信息] 未发现已安装的Tesseract OCR")
    return None

def download_tesseract_installer():
    """下载Tesseract安装程序"""
    print("\n下载Tesseract OCR安装程序...")
    
    # Tesseract下载URL（使用UB-Mannheim的最新版本）
    # 注意：这里使用一个稳定的版本URL
    tesseract_version = "5.4.0.20241124"
    download_url = f"https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-{tesseract_version}.exe"
    
    # 备用下载链接
    backup_url = "https://github.com/UB-Mannheim/tesseract/releases/latest/download/tesseract-ocr-w64-setup.exe"
    
    temp_dir = tempfile.gettempdir()
    installer_path = os.path.join(temp_dir, "tesseract_installer.exe")
    
    try:
        print(f"下载URL: {download_url}")
        print(f"保存到: {installer_path}")
        
        # 使用requests下载
        response = requests.get(download_url, stream=True, timeout=30)
        
        if response.status_code == 200:
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            
            with open(installer_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        
                        # 显示进度
                        if total_size > 0:
                            percent = (downloaded / total_size) * 100
                            print(f"\r下载进度: {percent:.1f}% ({downloaded/1024/1024:.1f}MB/{total_size/1024/1024:.1f}MB)", end='')
            
            print(f"\n[成功] 下载完成: {os.path.getsize(installer_path)/1024/1024:.1f} MB")
            return installer_path
        else:
            print(f"[失败] 下载失败，状态码: {response.status_code}")
            return None
            
    except Exception as e:
        print(f"[失败] 下载错误: {e}")
        
        # 尝试备用链接
        print("尝试备用下载链接...")
        try:
            response = requests.get(backup_url, stream=True, timeout=30)
            if response.status_code == 200:
                with open(installer_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                print(f"[成功] 使用备用链接下载完成")
                return installer_path
        except Exception as e2:
            print(f"[失败] 备用链接下载失败: {e2}")
            
        return None

def install_tesseract(installer_path):
    """安装Tesseract"""
    print("\n安装Tesseract OCR...")
    
    if not os.path.exists(installer_path):
        print(f"[失败] 安装文件不存在: {installer_path}")
        return False
    
    # 默认安装路径
    default_install_path = r"C:\Program Files\Tesseract-OCR"
    
    try:
        # 静默安装参数
        # /S: 静默安装
        # /D=<路径>: 安装目录
        install_command = f'"{installer_path}" /S /D={default_install_path}'
        
        print(f"安装命令: {install_command}")
        print("正在安装，请稍候...")
        
        # 运行安装程序
        result = subprocess.run(
            install_command,
            shell=True,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )
        
        if result.returncode == 0:
            print(f"[成功] Tesseract安装完成")
            
            # 验证安装
            time.sleep(2)  # 等待安装完成
            tesseract_exe = os.path.join(default_install_path, "tesseract.exe")
            
            if os.path.exists(tesseract_exe):
                print(f"[成功] Tesseract可执行文件: {tesseract_exe}")
                
                # 检查版本
                version_result = subprocess.run(
                    [tesseract_exe, "--version"],
                    capture_output=True,
                    text=True,
                    encoding='utf-8'
                )
                
                if version_result.returncode == 0:
                    print(f"[成功] Tesseract版本信息:")
                    for line in version_result.stdout.strip().split('\n'):
                        if line.strip():
                            print(f"  {line}")
                
                return tesseract_exe
            else:
                print(f"[警告] 未在预期位置找到Tesseract")
                return default_install_path
        else:
            print(f"[失败] 安装失败，返回码: {result.returncode}")
            if result.stderr:
                print(f"错误信息: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"[失败] 安装过程出错: {e}")
        return False

def download_language_packs(tesseract_path):
    """下载语言包"""
    print("\n下载语言包...")
    
    # 创建tessdata目录
    tessdata_dir = os.path.join(os.path.dirname(tesseract_path), "tessdata")
    os.makedirs(tessdata_dir, exist_ok=True)
    
    language_files = {
        "eng": "英语",
        "chi_sim": "简体中文",
        "chi_tra": "繁体中文",
        "jpn": "日语",
        "kor": "韩语"
    }
    
    base_url = "https://github.com/tesseract-ocr/tessdata/raw/main/"
    
    for lang_code, lang_name in language_files.items():
        lang_file = f"{lang_code}.traineddata"
        lang_path = os.path.join(tessdata_dir, lang_file)
        
        if os.path.exists(lang_path):
            print(f"[信息] {lang_name}语言包已存在，跳过下载")
            continue
        
        download_url = f"{base_url}{lang_file}"
        
        try:
            print(f"下载{lang_name}语言包...")
            response = requests.get(download_url, stream=True, timeout=30)
            
            if response.status_code == 200:
                with open(lang_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                print(f"[成功] {lang_name}语言包下载完成")
            else:
                print(f"[警告] {lang_name}语言包下载失败，状态码: {response.status_code}")
                
        except Exception as e:
            print(f"[警告] {lang_name}语言包下载失败: {e}")

def configure_python_environment(tesseract_exe):
    """配置Python环境"""
    print("\n配置Python环境...")
    
    config_example = f'''#!/usr/bin/env python3
"""
OCR配置示例
"""

import pytesseract
import os

# 设置Tesseract路径
if os.path.exists("{tesseract_exe}"):
    pytesseract.pytesseract.tesseract_cmd = r"{tesseract_exe}"
    print("Tesseract路径已配置")
else:
    print("[警告] 未找到Tesseract，请检查安装")
    print("或者手动设置路径:")
    print('pytesseract.pytesseract.tesseract_cmd = r"C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe"')

# 测试OCR
try:
    version = pytesseract.get_tesseract_version()
    print(f"Tesseract版本: {version}")
except:
    print("无法获取Tesseract版本，请检查安装")
'''

    # 保存配置示例
    config_file = "ocr_config_example.py"
    with open(config_file, "w", encoding="utf-8") as f:
        f.write(config_example)
    
    print(f"[成功] 配置示例已保存到: {config_file}")

def test_ocr_installation(tesseract_exe):
    """测试OCR安装"""
    print("\n测试OCR安装...")
    
    try:
        # 测试Tesseract可执行文件
        result = subprocess.run(
            [tesseract_exe, "--list-langs"],
            capture_output=True,
            text=True,
            encoding='utf-8',
            errors='ignore'
        )
        
        if result.returncode == 0:
            print("[成功] Tesseract安装验证通过")
            if result.stdout.strip():
                print("支持的语言:")
                langs = [lang.strip() for lang in result.stdout.strip().split('\n') if lang.strip()]
                for lang in langs:
                    print(f"  - {lang}")
            return True
        else:
            print("[失败] Tesseract验证失败")
            return False
            
    except Exception as e:
        print(f"[失败] 测试失败: {e}")
        return False

def main():
    """主函数"""
    print_header()
    
    # 检查操作系统
    if not check_os():
        print("\n[失败] 系统不支持，请手动安装")
        return False
    
    # 检查是否已安装
    existing_tesseract = check_existing_tesseract()
    if existing_tesseract:
        print("\n[信息] Tesseract已安装，跳过下载安装")
        tesseract_exe = existing_tesseract
    else:
        # 下载安装程序
        installer_path = download_tesseract_installer()
        if not installer_path:
            print("\n[失败] 无法下载安装程序，请手动下载")
            print("请访问: https://github.com/UB-Mannheim/tesseract/wiki")
            return False
        
        # 安装Tesseract
        tesseract_exe = install_tesseract(installer_path)
        if not tesseract_exe:
            print("\n[失败] 安装失败，请手动安装")
            return False
        
        # 下载语言包
        download_language_packs(tesseract_exe)
    
    # 配置Python环境
    configure_python_environment(tesseract_exe)
    
    # 测试安装
    if test_ocr_installation(tesseract_exe):
        print("\n" + "=" * 60)
        print("[成功] Tesseract OCR安装完成!")
        print("=" * 60)
        print("\n下一步操作:")
        print("1. 安装Python OCR库: pip install pytesseract")
        print("2. 运行OCR测试: python scripts/test_ocr.py")
        print("3. 查看配置示例: cat ocr_config_example.py")
        print("\n如果遇到问题，请查看 docs/OCR_SETUP_GUIDE.md")
        return True
    else:
        print("\n[警告] Tesseract安装完成，但测试失败")
        print("请手动检查安装")
        return False

if __name__ == "__main__":
    try:
        success = main()
        if success:
            sys.exit(0)
        else:
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n[信息] 用户中断安装")
        sys.exit(1)

path: scripts/ocr_screenshot.py
content: #!/usr/bin/env python3
"""
屏幕截图OCR工具
捕获屏幕并识别文字
"""

import argparse
import sys
import os
from datetime import datetime

def check_dependencies():
    """检查并安装必要的依赖"""
    missing_deps = []
    
    # 检查基础依赖
    try:
        from PIL import ImageGrab, Image
    except ImportError:
        missing_deps.append("pillow (图像处理库)")
        print("[提示] 缺少依赖: Pillow - 用于屏幕截图")
        print("      安装命令: pip install pillow")
    
    try:
        import pyautogui
    except ImportError:
        missing_deps.append("pyautogui (屏幕自动化库)")
        print("[提示] 缺少依赖: PyAutoGUI - 用于获取屏幕信息")
        print("      安装命令: pip install pyautogui")
    
    # 检查OCR依赖
    try:
        import pytesseract
    except ImportError:
        missing_deps.append("pytesseract (OCR文字识别库)")
        print("[提示] 缺少依赖: pytesseract - 用于文字识别")
        print("      安装命令: pip install pytesseract")
    
    if missing_deps:
        print("\n[重要] 以下依赖需要安装才能使用OCR功能:")
        for dep in missing_deps:
            print(f"  • {dep}")
        
        print("\n[安装建议]")
        print("1. 安装所有Python依赖:")
        print("   pip install pillow pyautogui pytesseract")
        
        print("\n2. 安装Tesseract OCR引擎:")
        print("   Windows: 从 https://github.com/UB-Mannheim/tesseract/wiki 下载")
        print("   macOS: brew install tesseract")
        print("   Linux: sudo apt-get install tesseract-ocr")
        
        print("\n3. 或使用一键安装脚本:")
        print("   python scripts/setup.py")
        
        return False
    
    return True

# 检查依赖
if not check_dependencies():
    print("\n[提示] 依赖检查完成，部分功能可能不可用")
    print("      如果要使用全部功能，请先安装缺少的依赖")
    print("      继续运行可能会出错...")
    
    # 询问用户是否继续
    response = input("\n要继续运行吗? (y/n): ").lower().strip()
    if response not in ['y', 'yes', '是']:
        print("[信息] 用户选择退出")
        sys.exit(0)
    print("[信息] 继续运行，部分功能可能不可用")

def check_tesseract():
    """检查Tesseract OCR是否可用"""
    try:
        import pytesseract
        # 测试是否可以导入
        return True
    except ImportError:
        print("错误：未找到pytesseract。请安装：pip install pytesseract")
        return False
    except Exception as e:
        print(f"Tesseract检查失败：{e}")
        return False

def capture_and_ocr(output_image=None, output_text=None, region=None, lang='eng+chi_sim'):
    """捕获屏幕并识别文字"""
    try:
        import pytesseract
        
        # 设置输出路径
        if output_image is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_image = f"screenshot_ocr_{timestamp}.png"
            
        if output_text is None:
            base_name = os.path.splitext(output_image)[0]
            output_text = f"{base_name}.txt"
        
        # 捕获屏幕
        if region:
            coords = region.split(',')
            if len(coords) != 4:
                print("区域格式错误，应为 'x1,y1,x2,y2'")
                return False
            x1, y1, x2, y2 = map(int, coords)
            bbox = (x1, y1, x2, y2)
            screenshot = ImageGrab.grab(bbox=bbox)
            print(f"捕获区域：{bbox}")
        else:
            screenshot = ImageGrab.grab()
            screen_width, screen_height = pyautogui.size()
            print(f"捕获全屏：{screen_width}x{screen_height}")
        
        # 保存截图
        screenshot.save(output_image)
        print(f"截图已保存：{output_image}")
        
        # 图像预处理（提高OCR准确性）
        # 转换为灰度图
        gray = screenshot.convert('L')
        
        # 可选：二值化处理
        # threshold = 150
        # binary = gray.point(lambda x: 0 if x < threshold else 255, '1')
        
        # 使用处理后的图像进行OCR
        print(f"正在识别文字（语言：{lang}）...")
        text = pytesseract.image_to_string(gray, lang=lang)
        
        # 保存文字结果
        with open(output_text, 'w', encoding='utf-8') as f:
            f.write(text)
        
        print(f"文字已保存：{output_text}")
        
        # 显示统计信息
        word_count = len(text.split())
        char_count = len(text)
        line_count = len(text.split('\n'))
        
        print(f"\n识别结果统计：")
        print(f"  行数：{line_count}")
        print(f"  单词数：{word_count}")
        print(f"  字符数：{char_count}")
        
        # 显示前几行文字预览
        lines = text.strip().split('\n')
        print(f"\n文字预览（前5行）：")
        for i, line in enumerate(lines[:5]):
            if line.strip():
                print(f"  {i+1}: {line[:80]}{'...' if len(line) > 80 else ''}")
        
        return True
        
    except Exception as e:
        print(f"OCR处理失败：{e}")
        return False

def main():
    parser = argparse.ArgumentParser(description='屏幕截图OCR工具')
    parser.add_argument('--output-image', '-i', default=None,
                       help='截图输出文件路径')
    parser.add_argument('--text-output', '-t', default=None,
                       help='文字输出文件路径')
    parser.add_argument('--region', '-r', default=None,
                       help='捕获区域，格式：x1,y1,x2,y2')
    parser.add_argument('--lang', '-l', default='eng+chi_sim',
                       help='OCR语言（默认：eng+chi_sim 英文+简体中文）')
    parser.add_argument('--list-langs', action='store_true',
                       help='列出可用的OCR语言')
    
    args = parser.parse_args()
    
    # 检查Tesseract
    if not check_tesseract():
        sys.exit(1)
    
    # 列出可用的语言
    if args.list_langs:
        try:
            import pytesseract
            langs = pytesseract.get_languages(config='')
            print("可用的OCR语言：")
            for lang in sorted(langs):
                print(f"  {lang}")
            print("\n提示：使用 --lang 参数指定语言，如 --lang eng+chi_sim")
        except Exception as e:
            print(f"获取语言列表失败：{e}")
        return
    
    # 执行OCR
    success = capture_and_ocr(
        output_image=args.output_image,
        output_text=args.text_output,
        region=args.region,
        lang=args.lang
    )
    
    if not success:
        print("OCR处理失败")
        sys.exit(1)
    
    print(f"\n完成！")
    if args.output_image and os.path.exists(args.output_image):
        print(f"截图：{os.path.abspath(args.output_image)}")
    if args.text_output and os.path.exists(args.text_output):
        print(f"文字：{os.path.abspath(args.text_output)}")

if __name__ == "__main__":
    main()

path: scripts/package_skill.py
content: #!/usr/bin/env python3
"""
技能打包脚本
将技能目录打包为ZIP文件，准备发布到OpenClaw Hub
"""

import os
import sys
import json
import zipfile
import shutil
from pathlib import Path
import argparse
import yaml
from datetime import datetime

def validate_skill(skill_dir):
    """验证技能目录结构"""
    print("验证技能结构...")
    
    required_files = ["SKILL.md"]
    required_dirs = ["scripts"]
    
    skill_path = Path(skill_dir)
    
    # 检查必需文件
    for file_name in required_files:
        file_path = skill_path / file_name
        if not file_path.exists():
            print(f"[失败] 缺少必需文件: {file_name}")
            return False
    
    # 检查必需目录
    for dir_name in required_dirs:
        dir_path = skill_path / dir_name
        if not dir_path.exists():
            print(f"[失败] 缺少必需目录: {dir_name}")
            return False
    
    # 检查SKILL.md格式
    skill_md_path = skill_path / "SKILL.md"
    try:
        with open(skill_md_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 检查YAML frontmatter
        if not content.startswith('---'):
            print("[失败] SKILL.md 必须以YAML frontmatter开始 (---)")
            return False
            
        # 解析YAML
        parts = content.split('---')
        if len(parts) < 3:
            print("[失败] SKILL.md 格式错误，缺少YAML frontmatter结束标记")
            return False
            
        frontmatter = parts[1].strip()
        metadata = yaml.safe_load(frontmatter)
        
        # 检查必需字段
        if 'name' not in metadata:
            print("[失败] SKILL.md 缺少 'name' 字段")
            return False
            
        if 'description' not in metadata:
            print("[失败] SKILL.md 缺少 'description' 字段")
            return False
            
        skill_name = metadata['name']
        print(f"[成功] 技能名称: {skill_name}")
        print(f"[成功] 技能描述: {metadata['description'][:100]}...")
        
    except yaml.YAMLError as e:
        print(f"[失败] YAML解析错误: {e}")
        return False
    except Exception as e:
        print(f"[失败] 文件读取错误: {e}")
        return False
    
    # 检查package.json (可选但推荐)
    package_json_path = skill_path / "package.json"
    if package_json_path.exists():
        try:
            with open(package_json_path, 'r', encoding='utf-8') as f:
                package_data = json.load(f)
            
            if 'version' not in package_data:
                print("⚠ package.json 缺少 'version' 字段")
            else:
                print(f"[成功] 版本号: {package_data.get('version', '未指定')}")
                
        except json.JSONDecodeError as e:
            print(f"[警告] package.json JSON解析错误: {e}")
    
    print("[成功] 技能验证通过")
    return skill_name

def create_zip_file(skill_dir, output_dir, skill_name):
    """创建ZIP压缩包"""
    print(f"\n创建ZIP压缩包...")
    
    # 创建输出目录
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    
    # 生成ZIP文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    zip_filename = f"{skill_name}-{timestamp}.zip"
    zip_path = output_path / zip_filename
    
    # 创建ZIP文件
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        skill_path = Path(skill_dir)
        
        # 遍历所有文件
        for root, dirs, files in os.walk(skill_dir):
            # 跳过一些目录
            if '__pycache__' in dirs:
                dirs.remove('__pycache__')
            if '.git' in dirs:
                dirs.remove('.git')
            
            for file in files:
                # 跳过一些文件
                if file.endswith('.pyc') or file == '.DS_Store':
                    continue
                    
                file_path = Path(root) / file
                # 计算相对路径
                rel_path = file_path.relative_to(skill_path)
                
                # 添加到ZIP
                zipf.write(file_path, rel_path)
                print(f"  添加: {rel_path}")
    
    print(f"[成功] ZIP文件创建完成: {zip_path}")
    print(f"   大小: {zip_path.stat().st_size / 1024:.1f} KB")
    
    return zip_path

def create_manifest(skill_dir, output_dir, skill_name, zip_path):
    """创建发布清单"""
    print(f"\n创建发布清单...")
    
    manifest_path = Path(output_dir) / f"{skill_name}-manifest.json"
    
    # 收集技能信息
    skill_path = Path(skill_dir)
    
    # 读取SKILL.md元数据
    skill_md_path = skill_path / "SKILL.md"
    with open(skill_md_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    parts = content.split('---')
    frontmatter = parts[1].strip()
    metadata = yaml.safe_load(frontmatter)
    
    # 读取package.json (如果存在)
    package_info = {}
    package_json_path = skill_path / "package.json"
    if package_json_path.exists():
        with open(package_json_path, 'r', encoding='utf-8') as f:
            package_info = json.load(f)
    
    # 统计文件
    script_count = 0
    reference_count = 0
    asset_count = 0
    
    scripts_dir = skill_path / "scripts"
    if scripts_dir.exists():
        script_count = sum(1 for f in scripts_dir.glob('*.py') if f.is_file())
    
    references_dir = skill_path / "references"
    if references_dir.exists():
        reference_count = sum(1 for f in references_dir.glob('*') if f.is_file())
    
    assets_dir = skill_path / "assets"
    if assets_dir.exists():
        asset_count = sum(1 for f in assets_dir.glob('*') if f.is_file())
    
    # 创建清单
    manifest = {
        "skill": {
            "name": metadata['name'],
            "description": metadata['description'],
            "version": package_info.get('version', '1.0.0'),
            "author": package_info.get('author', 'Unknown'),
            "license": package_info.get('license', 'MIT'),
            "created_at": datetime.now().isoformat(),
            "stats": {
                "scripts": script_count,
                "references": reference_count,
                "assets": asset_count,
                "total_files": script_count + reference_count + asset_count + 3  # SKILL.md, README.md, requirements.txt
            }
        },
        "package": {
            "filename": zip_path.name,
            "size_bytes": zip_path.stat().st_size,
            "created_at": datetime.now().isoformat(),
            "sha256": "计算中..."  # 实际应用中需要计算
        },
        "requirements": {
            "python": ">=3.8",
            "dependencies": [
                "pillow>=9.0.0",
                "pyautogui>=0.9.0"
            ],
            "optional_dependencies": [
                "pytesseract>=0.3.0",
                "opencv-python>=4.5.0",
                "numpy>=1.20.0"
            ]
        },
        "compatibility": {
            "platforms": ["windows", "macos", "linux"],
            "codebuddy_version": ">=1.0.0"
        }
    }
    
    # 保存清单
    with open(manifest_path, 'w', encoding='utf-8') as f:
        json.dump(manifest, f, indent=2, ensure_ascii=False)
    
    print(f"[成功] 发布清单创建完成: {manifest_path}")
    
    return manifest_path

def main():
    parser = argparse.ArgumentParser(description='技能打包工具')
    parser.add_argument('skill_dir', help='技能目录路径')
    parser.add_argument('-o', '--output', default='./dist', help='输出目录 (默认: ./dist)')
    parser.add_argument('--no-validate', action='store_true', help='跳过验证')
    parser.add_argument('--no-manifest', action='store_true', help='跳过清单创建')
    
    args = parser.parse_args()
    
    print("=" * 60)
    print("Screen Capture Hub 技能打包工具")
    print("=" * 60)
    
    # 验证技能
    if not args.no_validate:
        skill_name = validate_skill(args.skill_dir)
        if not skill_name:
            print("[失败] 技能验证失败，打包中止")
            sys.exit(1)
    else:
        # 从目录名提取技能名
        skill_name = Path(args.skill_dir).name
        print(f"[警告] 跳过验证，使用目录名作为技能名: {skill_name}")
    
    # 创建ZIP文件
    zip_path = create_zip_file(args.skill_dir, args.output, skill_name)
    
    # 创建清单
    if not args.no_manifest:
        manifest_path = create_manifest(args.skill_dir, args.output, skill_name, zip_path)
    
    print("\n" + "=" * 60)
    print("[成功] 打包完成!")
    print("=" * 60)
    
    print(f"\n生成的文件:")
    print(f"  1. ZIP包: {zip_path}")
    if not args.no_manifest:
        print(f"  2. 清单: {manifest_path}")
    
    print(f"\n发布到OpenClaw Hub的步骤:")
    print(f"  1. 登录 OpenClaw Hub: https://hub.openclaw.org/")
    print(f"  2. 进入 '发布技能' 页面")
    print(f"  3. 上传: {zip_path.name}")
    print(f"  4. 填写技能信息")
    print(f"  5. 提交审核")
    
    print(f"\n技能信息:")
    print(f"  名称: {skill_name}")
    print(f"  版本: 1.0.0")
    print(f"  平台: Windows/macOS/Linux")
    print(f"  依赖: Python 3.8+, Pillow, PyAutoGUI")
    
    print(f"\n查看完整文档:")
    print(f"  {Path(args.skill_dir) / 'README.md'}")

if __name__ == "__main__":
    main()

path: scripts/quick_capture.py
content: #!/usr/bin/env python3
"""
快速截图工具 - 简化版本的屏幕截图
提供简单易用的命令行界面
"""

import argparse
import sys
import os
from datetime import datetime

try:
    from PIL import ImageGrab
    import pyautogui
except ImportError as e:
    print(f"错误: 缺少必要的库。请运行: pip install pillow pyautogui")
    print(f"错误详情: {e}")
    sys.exit(1)

def quick_capture(output=None, region=None, show_info=False):
    """
    快速截图函数
    
    Args:
        output: 输出文件路径，如果为None则自动生成
        region: 截图区域，格式为 "x1,y1,x2,y2"
        show_info: 是否显示屏幕信息
    """
    
    # 获取屏幕信息
    screen_width, screen_height = pyautogui.size()
    mouse_x, mouse_y = pyautogui.position()
    
    if show_info:
        print("=== 屏幕信息 ===")
        print(f"分辨率: {screen_width}x{screen_height}")
        print(f"鼠标位置: ({mouse_x}, {mouse_y})")
        print("================")
    
    # 设置输出文件名
    if output is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output = f"screen_capture_{timestamp}.png"
    
    # 执行截图
    try:
        if region:
            # 解析区域
            coords = region.split(',')
            if len(coords) != 4:
                print("错误: 区域格式应为 'x1,y1,x2,y2'")
                return False
            x1, y1, x2, y2 = map(int, coords)
            bbox = (x1, y1, x2, y2)
            img = ImageGrab.grab(bbox=bbox)
            print(f"区域截图: {bbox}")
        else:
            # 全屏截图
            img = ImageGrab.grab()
            print(f"全屏截图: {screen_width}x{screen_height}")
        
        # 保存图片
        img.save(output)
        file_size = os.path.getsize(output) / 1024  # KB
        
        print(f"✅ 截图成功!")
        print(f"📁 文件: {os.path.abspath(output)}")
        print(f"📏 尺寸: {img.size[0]}x{img.size[1]}")
        print(f"💾 大小: {file_size:.1f} KB")
        
        return True
        
    except Exception as e:
        print(f"❌ 截图失败: {e}")
        return False

def main():
    parser = argparse.ArgumentParser(
        description='快速截图工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s                    # 全屏截图，自动命名
  %(prog)s -o my_screen.png   # 保存为指定文件
  %(prog)s -r "0,0,500,500"   # 截取指定区域
  %(prog)s -i                 # 显示屏幕信息
  %(prog)s -r "0,0,500,500" -o region.png  # 区域截图并指定文件名
        """
    )
    
    parser.add_argument('-o', '--output', 
                       help='输出文件路径（默认: screen_capture_时间戳.png）')
    parser.add_argument('-r', '--region',
                       help='截图区域，格式: x1,y1,x2,y2')
    parser.add_argument('-i', '--info', action='store_true',
                       help='显示屏幕信息')
    
    args = parser.parse_args()
    
    # 执行截图
    success = quick_capture(
        output=args.output,
        region=args.region,
        show_info=args.info
    )
    
    if not success:
        sys.exit(1)

if __name__ == "__main__":
    main()

path: scripts/screenshot.py
content: #!/usr/bin/env python3
"""
屏幕截图工具
支持捕获整个屏幕或指定区域
"""

import argparse
import sys
import os
from datetime import datetime

try:
    from PIL import ImageGrab
    import pyautogui
except ImportError as e:
    print(f"错误：缺少必要的库。请安装：pip install pillow pyautogui")
    print(f"导入错误：{e}")
    sys.exit(1)

def capture_full_screen(output_path):
    """捕获整个屏幕"""
    try:
        # 获取屏幕尺寸
        screen_width, screen_height = pyautogui.size()
        print(f"屏幕分辨率：{screen_width}x{screen_height}")
        
        # 捕获整个屏幕
        screenshot = ImageGrab.grab()
        
        # 保存图片
        screenshot.save(output_path)
        print(f"截图已保存到：{output_path}")
        print(f"图片尺寸：{screenshot.size[0]}x{screenshot.size[1]}")
        
        return True
    except Exception as e:
        print(f"截图失败：{e}")
        return False

def capture_region(output_path, region_str):
    """捕获指定区域"""
    try:
        # 解析区域字符串 "x1,y1,x2,y2"
        coords = region_str.split(',')
        if len(coords) != 4:
            print("区域格式错误，应为 'x1,y1,x2,y2'")
            return False
            
        x1, y1, x2, y2 = map(int, coords)
        
        # 确保坐标有效
        if x1 < 0 or y1 < 0 or x2 <= x1 or y2 <= y1:
            print("区域坐标无效")
            return False
            
        region = (x1, y1, x2, y2)
        
        # 捕获指定区域
        screenshot = ImageGrab.grab(bbox=region)
        
        # 保存图片
        screenshot.save(output_path)
        print(f"区域截图已保存到：{output_path}")
        print(f"区域：{region}")
        print(f"图片尺寸：{screenshot.size[0]}x{screenshot.size[1]}")
        
        return True
    except Exception as e:
        print(f"区域截图失败：{e}")
        return False

def main():
    parser = argparse.ArgumentParser(description='屏幕截图工具')
    parser.add_argument('--output', '-o', default=None,
                       help='输出文件路径（默认：screenshot_时间戳.png）')
    parser.add_argument('--region', '-r', default=None,
                       help='捕获区域，格式：x1,y1,x2,y2')
    parser.add_argument('--list-displays', '-l', action='store_true',
                       help='列出所有显示器信息')
    
    args = parser.parse_args()
    
    # 设置默认输出路径
    if args.output is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        args.output = f"screenshot_{timestamp}.png"
    
    # 列出显示器信息
    if args.list_displays:
        try:
            screen_width, screen_height = pyautogui.size()
            print(f"主显示器：{screen_width}x{screen_height}")
            
            # 尝试获取鼠标位置
            x, y = pyautogui.position()
            print(f"当前鼠标位置：({x}, {y})")
            
            # 获取所有显示器信息（需要pyautogui的支持）
            print("\n提示：使用 --region 参数指定捕获区域")
            print("示例：--region \"100,100,500,500\"")
            
        except Exception as e:
            print(f"获取显示器信息失败：{e}")
        return
    
    # 执行截图
    success = False
    if args.region:
        success = capture_region(args.output, args.region)
    else:
        success = capture_full_screen(args.output)
    
    if success:
        print(f"\n截图完成！")
        print(f"文件：{os.path.abspath(args.output)}")
        
        # 显示文件信息
        if os.path.exists(args.output):
            file_size = os.path.getsize(args.output)
            print(f"大小：{file_size / 1024:.2f} KB")
    else:
        print("截图失败")
        sys.exit(1)

if __name__ == "__main__":
    main()

path: scripts/setup.py
content: #!/usr/bin/env python3
"""
技能安装和设置脚本
自动安装依赖并配置环境
"""

import sys
import subprocess
import os
from pathlib import Path

def run_command(cmd, description):
    """运行命令并显示结果"""
    print(f"\n{'='*60}")
    print(f"执行: {description}")
    print(f"{'='*60}")
    print(f"命令: {cmd}")
    
    try:
        result = subprocess.run(
            cmd, 
            shell=True, 
            capture_output=True, 
            text=True,
            encoding='utf-8',
            errors='replace'
        )
        
        if result.stdout:
            print(f"输出: {result.stdout}")
        
        if result.stderr:
            print(f"错误: {result.stderr}")
        
        print(f"返回码: {result.returncode}")
        
        if result.returncode == 0:
            print(f"[成功] {description} 成功")
        else:
            print(f"[失败] {description} 失败")
            
        return result.returncode == 0
        
    except Exception as e:
        print(f"[失败] 执行失败: {e}")
        return False

def check_python_version():
    """检查Python版本"""
    print("检查Python版本...")
    
    version = sys.version_info
    print(f"当前Python版本: {sys.version}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("[失败] 需要Python 3.8或更高版本")
        return False
    
    print("[成功] Python版本符合要求")
    return True

def check_pip():
    """检查pip是否可用"""
    print("\n检查pip...")
    
    success = run_command(
        "python -m pip --version",
        "检查pip版本"
    )
    
    if not success:
        print("\n[失败] pip不可用，请先安装pip")
        print("获取pip: https://pip.pypa.io/en/stable/installation/")
        return False
    
    return True

def install_dependencies():
    """安装Python依赖"""
    print("\n安装Python依赖...")
    
    # 基础依赖
    dependencies = [
        ("pillow", "图像处理库"),
        ("pyautogui", "屏幕自动化库"),
    ]
    
    all_success = True
    
    for package, description in dependencies:
        success = run_command(
            f"python -m pip install --user {package}",
            f"安装{description} ({package})"
        )
        if not success:
            all_success = False
    
    # 可选依赖提示
    print("\n" + "="*60)
    print("可选依赖安装:")
    print("如需OCR功能，请安装: python -m pip install --user pytesseract")
    print("如需图像分析功能，请安装: python -m pip install --user opencv-python numpy")
    print("Tesseract OCR引擎需要单独安装")
    print("Windows: https://github.com/UB-Mannheim/tesseract/wiki")
    print("="*60)
    
    return all_success

def create_example_scripts():
    """创建示例脚本"""
    print("\n创建示例脚本...")
    
    example_dir = Path("examples")
    example_dir.mkdir(exist_ok=True)
    
    # 创建简单示例
    example_code = '''#!/usr/bin/env python3
"""
屏幕截图示例
"""

from PIL import ImageGrab
import pyautogui
from datetime import datetime

# 获取屏幕信息
screen_width, screen_height = pyautogui.size()
print(f"屏幕分辨率: {screen_width}x{screen_height}")

# 截图
screenshot = ImageGrab.grab()
print(f"截图尺寸: {screenshot.size[0]}x{screenshot.size[1]}")

# 保存
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"example_screenshot_{timestamp}.png"
screenshot.save(filename)
print(f"截图已保存: {filename}")'''
    
    example_file = example_dir / "simple_capture.py"
    with open(example_file, "w", encoding="utf-8") as f:
        f.write(example_code)
    
    print(f"[成功] 示例脚本已创建: {example_file}")
    return True

def verify_installation():
    """验证安装"""
    print("\n验证安装...")
    
    test_code = '''
try:
    from PIL import ImageGrab
    import pyautogui
    print("[成功] 基础库导入成功")
    
    # 测试屏幕信息
    w, h = pyautogui.size()
    print(f"[成功] 屏幕分辨率: {w}x{h}")
    
    # 测试截图
    img = ImageGrab.grab()
    print(f"[成功] 截图成功: {img.size[0]}x{img.size[1]}")
    
    print("\\n🎉 所有测试通过!")
    
except ImportError as e:
    print(f"[失败] 导入错误: {e}")
    return False
except Exception as e:
    print(f"[失败] 测试失败: {e}")
    return False
'''
    
    # 运行测试代码
    try:
        exec(test_code)
        return True
    except Exception as e:
        print(f"❌ 验证失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("OPENCLAW(龙虾)-屏幕查看器 技能安装程序")
    print("=" * 60)
    
    steps = [
        ("检查Python版本", check_python_version),
        ("检查pip", check_pip),
        ("安装依赖", install_dependencies),
        ("创建示例", create_example_scripts),
        ("验证安装", verify_installation),
    ]
    
    all_success = True
    
    for step_name, step_func in steps:
        print(f"\n步骤: {step_name}")
        print("-" * 40)
        
        if not step_func():
            print(f"[失败] {step_name} 失败")
            all_success = False
            break
    
    print("\n" + "=" * 60)
    
    if all_success:
        print("[成功] 安装完成!")
        print("\n使用方法:")
        print("1. 基本截图: python scripts/quick_capture.py")
        print("2. OCR功能: python scripts/ocr_screenshot.py")
        print("3. 屏幕分析: python scripts/analyze_screen.py")
        print("\n更多信息请查看 README.md")
    else:
        print("[失败] 安装失败，请检查错误信息")
        sys.exit(1)

if __name__ == "__main__":
    m

path: scripts/test_ocr.py
content: #!/usr/bin/env python3
"""
OCR功能测试脚本
测试Tesseract OCR安装和配置
"""

import sys
import os
from pathlib import Path

def test_pytesseract_import():
    """测试pytesseract导入"""
    print("=" * 60)
    print("OCR功能测试")
    print("=" * 60)
    
    print("\n1. 测试pytesseract导入...")
    try:
        import pytesseract
        print("[成功] pytesseract导入成功")
        return pytesseract
    except ImportError as e:
        print(f"[失败] 导入错误: {e}")
        print("\n请安装pytesseract:")
        print("  pip install pytesseract")
        return None

def test_tesseract_path(pytesseract):
    """测试Tesseract路径"""
    print("\n2. 测试Tesseract路径...")
    
    # 常见Tesseract路径
    common_paths = [
        r"C:\Program Files\Tesseract-OCR\tesseract.exe",
        r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
        r"C:\Program Files\Tesseract\tesseract.exe",
        # 环境变量中的路径
        "tesseract"
    ]
    
    tesseract_found = False
    for path in common_paths:
        try:
            # 如果是相对路径或环境变量路径
            if path == "tesseract":
                result = os.system(f"{path} --version >nul 2>nul")
                if result == 0:
                    print(f"[成功] Tesseract在环境变量中可用")
                    tesseract_found = True
                    break
            else:
                if os.path.exists(path):
                    print(f"[成功] 找到Tesseract: {path}")
                    pytesseract.pytesseract.tesseract_cmd = path
                    tesseract_found = True
                    break
        except:
            continue
    
    if not tesseract_found:
        print("[失败] 未找到Tesseract")
        print("\n请检查:")
        print("1. 是否已安装Tesseract OCR")
        print("2. 是否在环境变量PATH中")
        print("3. 或者手动设置路径:")
        print('   pytesseract.pytesseract.tesseract_cmd = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe"')
        return False
    
    return True

def test_tesseract_version(pytesseract):
    """测试Tesseract版本"""
    print("\n3. 测试Tesseract版本...")
    
    try:
        version = pytesseract.get_tesseract_version()
        print(f"[成功] Tesseract版本: {version}")
        return True
    except Exception as e:
        print(f"[失败] 获取版本失败: {e}")
        return False

def test_available_languages(pytesseract):
    """测试可用语言"""
    print("\n4. 测试可用语言...")
    
    try:
        langs = pytesseract.get_languages(config='')
        print(f"[成功] 发现 {len(langs)} 种语言")
        
        # 显示语言
        if langs:
            print("支持的语言:")
            for lang in sorted(langs):
                print(f"  - {lang}")
            
            # 检查中文支持
            if 'chi_sim' in langs:
                print("[成功] 支持简体中文 (chi_sim)")
            else:
                print("[警告] 不支持简体中文，请下载语言包")
                
            if 'eng' in langs:
                print("[成功] 支持英文 (eng)")
            else:
                print("[警告] 不支持英文")
        else:
            print("[警告] 未发现语言包")
            
        return True
    except Exception as e:
        print(f"[失败] 获取语言失败: {e}")
        return False

def create_test_image():
    """创建测试图像"""
    print("\n5. 创建测试图像...")
    
    try:
        from PIL import Image, ImageDraw, ImageFont
        
        # 创建测试图像
        width, height = 400, 200
        image = Image.new('RGB', (width, height), color='white')
        draw = ImageDraw.Draw(image)
        
        # 添加文字
        text = "Hello World\n中文测试\nOCR Test"
        
        # 使用默认字体
        try:
            font = ImageFont.truetype("arial.ttf", 24)
        except:
            font = ImageFont.load_default()
        
        # 计算文字位置
        bbox = draw.multiline_textbbox((0, 0), text, font=font)
        text_x = (width - (bbox[2] - bbox[0])) // 2
        text_y = (height - (bbox[3] - bbox[1])) // 2
        
        # 绘制文字
        draw.multiline_text((text_x, text_y), text, font=font, fill='black', align='center')
        
        # 保存图像
        test_image_path = "ocr_test_image.png"
        image.save(test_image_path)
        print(f"[成功] 测试图像已创建: {test_image_path}")
        return test_image_path
        
    except ImportError as e:
        print(f"[失败] PIL导入错误: {e}")
        print("请安装Pillow: pip install pillow")
        return None
    except Exception as e:
        print(f"[失败] 创建图像失败: {e}")
        return None

def run_ocr_test(pytesseract, image_path):
    """运行OCR测试"""
    print("\n6. 运行OCR测试...")
    
    if not image_path or not os.path.exists(image_path):
        print("[失败] 测试图像不存在")
        return False
    
    try:
        from PIL import Image
        
        # 加载图像
        image = Image.open(image_path)
        
        print("测试英文识别...")
        text_eng = pytesseract.image_to_string(image, lang='eng')
        if text_eng.strip():
            print("[成功] 英文识别结果:")
            print("-" * 40)
            print(text_eng.strip())
            print("-" * 40)
        else:
            print("[失败] 英文识别无结果")
        
        # 测试中文识别
        try:
            print("\n测试中文识别...")
            text_chi = pytesseract.image_to_string(image, lang='chi_sim')
            if text_chi.strip():
                print("[成功] 中文识别结果:")
                print("-" * 40)
                print(text_chi.strip())
                print("-" * 40)
            else:
                print("[警告] 中文识别无结果，可能未安装中文语言包")
        except:
            print("[警告] 中文识别失败，请检查中文语言包")
        
        # 测试中英文混合
        try:
            print("\n测试中英文混合识别...")
            text_mixed = pytesseract.image_to_string(image, lang='eng+chi_sim')
            if text_mixed.strip():
                print("[成功] 混合识别结果:")
                print("-" * 40)
                print(text_mixed.strip())
                print("-" * 40)
            else:
                print("[警告] 混合识别无结果")
        except:
            print("[警告] 混合识别失败")
        
        return True
        
    except Exception as e:
        print(f"[失败] OCR测试失败: {e}")
        return False

def main():
    """主函数"""
    # 测试导入
    pytesseract = test_pytesseract_import()
    if not pytesseract:
        return False
    
    # 测试路径
    if not test_tesseract_path(pytesseract):
        return False
    
    # 测试版本
    if not test_tesseract_version(pytesseract):
        return False
    
    # 测试语言
    if not test_available_languages(pytesseract):
        return False
    
    # 创建测试图像
    image_path = create_test_image()
    
    # 运行OCR测试
    if image_path:
        run_ocr_test(pytesseract, image_path)
    
    print("\n" + "=" * 60)
    print("OCR测试完成")
    print("=" * 60)
    
    print("\n总结:")
    print("✓ pytesseract库已安装")
    print("✓ Tesseract OCR已配置")
    print("✓ 语言包已检查")
    print("✓ OCR功能测试完成")
    
    print("\n下一步:")
    print("1. 使用OCR功能: python scripts/ocr_screenshot.py")
    print("2. 查看详细文档: docs/OCR_SETUP_GUIDE.md")
    print("3. 获取帮助: python scripts/ocr_screenshot.py --help")
    
    return True

if __name__ == "__main__":
    try:
        success = main()
        if success:
            sys.exit(0)
        else:
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n[信息] 用户中断测试")
        sys.exit(1)

path: scripts/test_screenshot.py
content: #!/usr/bin/env python3
"""
测试屏幕截图功能
"""

import sys
import os

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_basic_capture():
    """测试基本截图功能"""
    print("测试基本截图功能...")
    try:
        # 尝试导入所需的库
        from PIL import ImageGrab
        import pyautogui
        
        print("成功：依赖库导入成功")
        
        # 获取屏幕信息
        screen_width, screen_height = pyautogui.size()
        print(f"成功：屏幕分辨率：{screen_width}x{screen_height}")
        
        # 测试截图
        print("正在测试截图...")
        screenshot = ImageGrab.grab()
        
        if screenshot:
            print(f"成功：截图成功，尺寸：{screenshot.size[0]}x{screenshot.size[1]}")
            return True
        else:
            print("失败：截图失败")
            return False
            
    except ImportError as e:
        print(f"错误：导入错误：{e}")
        print("请安装依赖：pip install pillow pyautogui")
        return False
    except Exception as e:
        print(f"错误：测试失败：{e}")
        return False

def test_ocr_capability():
    """测试OCR功能"""
    print("\n测试OCR功能...")
    try:
        import pytesseract
        print("✓ pytesseract 导入成功")
        
        # 获取可用语言
        try:
            langs = pytesseract.get_languages(config='')
            print(f"✓ 可用OCR语言：{', '.join(langs[:5])}...")
            return True
        except:
            print("⚠ 无法获取语言列表，但pytesseract可用")
            return True
            
    except ImportError:
        print("警告：pytesseract 未安装，OCR功能不可用")
        print("  安装：pip install pytesseract")
        print("  还需要安装Tesseract OCR引擎")
        return False
    except Exception as e:
        print(f"失败：OCR测试失败：{e}")
        return False

def test_opencv_capability():
    """测试OpenCV功能"""
    print("\n测试OpenCV功能...")
    try:
        import cv2
        import numpy as np
        
        print(f"✓ OpenCV版本：{cv2.__version__}")
        print(f"✓ NumPy版本：{np.__version__}")
        
        # 创建一个测试图像
        test_img = np.zeros((100, 100, 3), dtype=np.uint8)
        test_img[25:75, 25:75] = [255, 0, 0]  # 红色方块
        
        # 测试边缘检测
        gray = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY)
        edges = cv2.Canny(gray, 50, 150)
        
        print(f"✓ OpenCV功能测试通过")
        return True
        
    except ImportError as e:
        print(f"失败：导入错误：{e}")
        print("请安装依赖：pip install opencv-python numpy")
        return False
    except Exception as e:
        print(f"失败：OpenCV测试失败：{e}")
        return False

def main():
    """运行所有测试"""
    print("=" * 50)
    print("屏幕截图技能测试")
    print("=" * 50)
    
    results = []
    
    # 运行测试
    results.append(("基本截图", test_basic_capture()))
    results.append(("OCR功能", test_ocr_capability()))
    results.append(("OpenCV功能", test_opencv_capability()))
    
    # 显示测试结果
    print("\n" + "=" * 50)
    print("测试结果汇总：")
    print("=" * 50)
    
    all_passed = True
    for test_name, passed in results:
        status = "[通过]" if passed else "[失败]"
        print(f"{test_name:20} {status}")
        if not passed:
            all_passed = False
    
    print("\n" + "=" * 50)
    if all_passed:
        print("[成功] 所有测试通过！技能可以使用。")
        print("\n可用命令：")
        print("  1. python screenshot.py --output my_screenshot.png")
        print("  2. python ocr_screenshot.py --text-output text.txt")
        print("  3. python analyze_screen.py --task screen_info")
    else:
        print("[警告] 部分测试失败，请安装缺失的依赖。")
        print("\n安装所有依赖：")
        print("  pip install pillow pyautogui pytesseract opencv-python numpy")
        print("\n注意：pytesseract还需要安装Tesseract OCR引擎")
        print("Windows: 从 https://github.com/UB-Mannheim/tesseract/wiki 下载安装")
    
    return 0 if all_passed else 1

if __name__ == "__main__":
    sys.exit(main())

path: scripts/__init__.py
content: """
Screen Capture Hub Scripts Package
----------------------------------
This package contains scripts for screen capture, OCR, and screen analysis.
"""

__version__ = "1.0.0"
__author__ = "CodeBuddy User"
__description__ = "Screen capture and analysis tools for AI assistants"

Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)