Files
homeagent-sdk/example/ocr/plugin.go
JianFeeeee b6a6168e65 chore(module)!: module 路径随托管地迁移 gitcode → github
SDK 仓已迁到 GitHub 作为权威源,go module 路径同步:
`gitcode.com/JianFeeeee/homeagent-sdk` → `github.com/JianFeeeee/homeagentsdk`

## 范围

74 个文件:71 个 Go 源码 + go.mod/go.sum + hmapdev 模板 + CI 与打包脚本。

主仓(HomeAgent)侧对应改动是 6d38a164。本仓这些文件当时**不在工作树上**
(见下),所以那次的批量替换扫不到它们——这里是补偿。

## 为何这批文件当时不在工作树上(事故与恢复)

10-08 07:58 主仓做 checkout/cherry-pick 序列时,把本仓工作树的 20 个文件
误清理了(`example/*/plugin.go` + `plg.json`,10 个示例)。

根因是**结构误判**:本仓是「一目录两仓库」结构下主仓 `third_party/` 里的
**独立 git 仓库**,而主仓 .gitignore 忽略了 `example/`,于是它在主仓
`git status` 里不可见 —— 看着像「不受跟踪的构建产物」,实际是本仓受跟踪的源码。

已全部恢复(`git checkout -- <D 文件>`,只恢复删除、不动迁移改动),
20 个文件与 HEAD 逐字节一致。

**破坏的连锁后果**:恢复出来的 `plugin.go` 仍写着旧 module 路径,
因为迁移时它们已不在工作树上。所以这次补偿是必须的,不是可选优化。

## 保留 gitcode 引用

以下位置的 `gitcode` **有意保留**,不要"顺手清掉":
- README.md / docs 里「二进制实际分发地址目前是 gitcode」的说明
- mkdocs.yml 的 gitcode 镜像链接(国内直连更快)
- `tools/hmapdev/templates.go` 里「SDK 已从 gitcode 迁到 GitHub」的注释

gitcode 仍是**只读镜像**(源码同步;release 附件暂时仍在那边)。

## 验证

- 本仓根 module:`go build ./...` + `go test ./...` 全通过
- 全部 20 个 example:`go vet` 通过(补偿前 10 个因旧 module 路径失败)
- example/qq:`go test` 通过,且能从源码 build 出可用 plugin 产物
2026-10-09 07:25:25 +08:00

145 lines
4.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/JianFeeeee/homeagentsdk/sdk"
)
type Plugin struct {
name string
sdk *sdk.PluginSDK
}
func (p *Plugin) Name() string { return p.name }
func (p *Plugin) Start(s *sdk.PluginSDK) error {
s.SetAutoRestart(true)
p.sdk = s
tp := p.name + "_"
s.RegisterTool(tp+"ocr_image", sdk.ToolDef{
Name: tp + "ocr_image",
Description: "对图片进行OCR文字识别,支持中文和英文。可传入图片URL或base64编码。返回识别出的文本内容。",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"image_url": map[string]interface{}{"type": "string", "description": "图片的HTTP/HTTPS URL,与 image_data 二选一"},
"image_data": map[string]interface{}{"type": "string", "description": "图片的base64编码数据(不含 data:image/... 前缀),与 image_url 二选一"},
"language": map[string]interface{}{"type": "string", "description": "识别语言,默认 chi_sim+eng(中文简体+英文),可选 chi_sim / eng / chi_sim+eng"},
},
},
Cleaner: func(output string) string {
var r struct{ Text string }
if json.Unmarshal([]byte(output), &r) == nil && r.Text != "" {
return r.Text
}
var r2 struct{ Content string }
if json.Unmarshal([]byte(output), &r2) == nil && r2.Content != "" {
return r2.Content
}
return output
},
}, p.handleOcrImage)
log.Printf("[%s] plugin started", p.name)
return nil
}
func (p *Plugin) Stop() error {
return nil
}
func (p *Plugin) handleOcrImage(args map[string]interface{}) (interface{}, error) {
imageURL, _ := args["image_url"].(string)
imageData, _ := args["image_data"].(string)
language, _ := args["language"].(string)
if imageURL == "" && imageData == "" {
return map[string]interface{}{"error": "请提供 image_url 或 image_data"}, nil
}
tmpDir, err := os.MkdirTemp("", "ocr-*")
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("创建临时目录失败: %v", err)}, nil
}
defer os.RemoveAll(tmpDir)
inputPath := filepath.Join(tmpDir, "input.png")
if imageData != "" {
data := strings.TrimSpace(imageData)
if idx := strings.Index(data, "base64,"); idx >= 0 {
data = data[idx+7:]
}
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("base64解码失败: %v", err)}, nil
}
if err := os.WriteFile(inputPath, decoded, 0644); err != nil {
return map[string]interface{}{"error": fmt.Sprintf("写入临时文件失败: %v", err)}, nil
}
} else {
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(imageURL)
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("下载图片失败: %v", err)}, nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return map[string]interface{}{"error": fmt.Sprintf("下载图片返回状态码 %d", resp.StatusCode)}, nil
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("读取图片数据失败: %v", err)}, nil
}
if err := os.WriteFile(inputPath, data, 0644); err != nil {
return map[string]interface{}{"error": fmt.Sprintf("写入临时文件失败: %v", err)}, nil
}
}
if language == "" {
language = "chi_sim+eng"
}
outputPath := filepath.Join(tmpDir, "output")
argsList := []string{inputPath, outputPath, "-l", language, "--psm", "3"}
cmd := exec.Command("tesseract", argsList...)
var stderr strings.Builder
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return map[string]interface{}{"error": fmt.Sprintf("OCR识别失败: %v (stderr: %s)", err, stderr.String())}, nil
}
resultFile := outputPath + ".txt"
text, err := os.ReadFile(resultFile)
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("读取OCR结果失败: %v", err)}, nil
}
recognized := strings.TrimSpace(string(text))
if recognized == "" {
return map[string]interface{}{"text": "", "message": "未识别出文字内容"}, nil
}
return map[string]interface{}{
"text": recognized,
"length": len(recognized),
"language": language,
}, nil
}
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
return &Plugin{name: name}, nil
}