feat: add uv support with run.sh wrapper script
This commit is contained in:
parent
09552407b5
commit
2b5c0c61d6
|
|
@ -3,3 +3,17 @@
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
*.env
|
*.env
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
*.egg-info/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Test files
|
||||||
|
test-*.xlsx
|
||||||
|
test-*.csv
|
||||||
|
|
||||||
|
# Lock file (optional, can commit if you want reproducible builds)
|
||||||
|
# uv.lock
|
||||||
|
|
|
||||||
339
SKILL.md
339
SKILL.md
|
|
@ -1,291 +1,106 @@
|
||||||
|
---
|
||||||
|
name: excel-toolkit
|
||||||
|
description: "Excel 文件智能处理工具,支持读取、合并、编辑、筛选、翻译等操作"
|
||||||
|
---
|
||||||
|
> Auth (CLIENT_KEY) is loaded automatically from `~/.openclaw/.env`.
|
||||||
|
|
||||||
# Excel Toolkit - Excel 文件智能处理
|
# Excel Toolkit - Excel 文件智能处理
|
||||||
|
|
||||||
## 技能描述
|
## 调用方式(重要!)
|
||||||
|
|
||||||
提供 Excel 文件的智能处理功能,包括读取、合并、编辑、筛选、翻译等操作。支持 .xlsx 和 .csv 格式,可批量处理多个文件。
|
**必须使用 `uv run` 或 `./run.sh` 调用,确保虚拟环境隔离:**
|
||||||
|
|
||||||
**核心特性:自扩展能力** - 遇到不支持的操作时,自动生成并执行临时脚本。
|
|
||||||
|
|
||||||
## 触发条件
|
|
||||||
|
|
||||||
当用户提及以下关键词时激活此技能:
|
|
||||||
|
|
||||||
- Excel 相关:`excel`、`xlsx`、`电子表格`、`工作簿`、`工作表`
|
|
||||||
- 文件操作:`读取 excel`、`打开 excel`、`合并 excel`、`合并工作表`
|
|
||||||
- 数据处理:`筛选数据`、`排序数据`、`去重`、`替换内容`、`翻译单元格`
|
|
||||||
- **翻译相关**:`翻译 excel`、`中文转英文`、`translate excel`、`excel translation`、`翻译表格`
|
|
||||||
- 批量操作:`批量处理 excel`、`批量合并`、`批量替换`
|
|
||||||
- CSV 相关:`csv`、`csv 转 excel`、`excel 转 csv`
|
|
||||||
- **自扩展触发**:`计算`、`转换`、`透视`、`清洗`、`货币`、`汇率`、`公式`、`合并列`、`拆分列`
|
|
||||||
|
|
||||||
## 核心功能
|
|
||||||
|
|
||||||
### 1. 基础文件操作
|
|
||||||
- 读取 Excel 文件(.xlsx, .csv)
|
|
||||||
- 创建新的 Excel 文件
|
|
||||||
- 保存和导出
|
|
||||||
|
|
||||||
### 2. 合并功能
|
|
||||||
- 按行合并多个文件
|
|
||||||
- 按列合并多个文件
|
|
||||||
- 合并同一文件中的多个 sheet
|
|
||||||
- 合并多个文件的指定 sheet
|
|
||||||
|
|
||||||
### 3. 数据处理
|
|
||||||
- 单元格内容替换
|
|
||||||
- 批量替换(支持正则表达式)
|
|
||||||
- 数据筛选(按条件筛选行)
|
|
||||||
- 数据排序(按列排序)
|
|
||||||
- 数据去重(基于指定列)
|
|
||||||
|
|
||||||
### 4. 🆕 翻译功能
|
|
||||||
- **中文→英文翻译**:使用 Google Gemini Flash Lite API 翻译 Excel/CSV 中的中文内容
|
|
||||||
- **智能检测**:自动检测包含中文字符的单元格
|
|
||||||
- **批量处理**:支持批量翻译,提高效率
|
|
||||||
- **保留格式**:保留原文件格式、样式、公式和结构
|
|
||||||
- **灵活控制**:可指定特定列或工作表进行翻译
|
|
||||||
- **预览模式**:支持 dry-run 预览,查看翻译范围
|
|
||||||
|
|
||||||
### 5. 🆕 自扩展功能
|
|
||||||
- **自动脚本生成**:根据自然语言需求自动生成处理脚本
|
|
||||||
- **模板复用**:常用操作使用预置模板,确保稳定可靠
|
|
||||||
- **智能缓存**:相同需求自动复用已生成的脚本
|
|
||||||
- **灵活扩展**:无模板时自动生成通用脚本框架
|
|
||||||
|
|
||||||
## 脚本说明
|
|
||||||
|
|
||||||
所有脚本位于 `scripts/` 目录,使用 Python 编写:
|
|
||||||
|
|
||||||
### 基础脚本
|
|
||||||
- `read_excel.py` - 读取 Excel 文件并显示内容
|
|
||||||
- `merge_excel.py` - 合并多个 Excel 文件
|
|
||||||
- `replace_cells.py` - 替换单元格内容
|
|
||||||
- `filter_data.py` - 筛选和排序数据
|
|
||||||
- `batch_process.py` - 批量处理多个文件
|
|
||||||
|
|
||||||
### 🆕 翻译脚本
|
|
||||||
- `translate_excel.py` - 翻译 Excel/CSV 中的中文内容为英文(使用 Google Gemini Flash Lite)
|
|
||||||
|
|
||||||
### 🆕 自扩展脚本
|
|
||||||
- `auto_script.py` - 核心脚本引擎,分析需求并生成/执行脚本
|
|
||||||
|
|
||||||
## 翻译功能详解
|
|
||||||
|
|
||||||
### 功能特性
|
|
||||||
|
|
||||||
- **自动检测中文**:使用正则表达式检测包含中文字符的单元格
|
|
||||||
- **批量翻译**:将多个单元格合并为一个 API 请求,提高效率
|
|
||||||
- **保留原始格式**:工作表结构、样式、公式完整保留
|
|
||||||
- **生成新文件**:不修改原文件,生成 `{原文件名}_en.xlsx` 或 `{原文件名}_en.csv`
|
|
||||||
- **灵活控制**:支持按列、按工作表指定翻译范围
|
|
||||||
- **预览模式**:`--dry-run` 参数可预览翻译范围而不实际生成文件
|
|
||||||
|
|
||||||
### 使用方法
|
|
||||||
|
|
||||||
#### 翻译整个文件
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 翻译整个 Excel 文件
|
cd ~/Documents/ai-build-app/skills/excel-toolkit
|
||||||
python scripts/translate_excel.py --file data.xlsx
|
|
||||||
|
|
||||||
# 翻译整个 CSV 文件
|
# 方式 1:使用统一入口脚本(推荐)
|
||||||
python scripts/translate_excel.py --file data.csv
|
./run.sh <script_name> [args...]
|
||||||
|
|
||||||
|
# 方式 2:直接使用 uv run
|
||||||
|
uv run python scripts/<script_name>.py [args...]
|
||||||
|
|
||||||
|
# ❌ 不要直接使用 python scripts/xxx.py(会污染系统环境)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 指定输出文件
|
## 可用脚本
|
||||||
|
|
||||||
|
| 脚本 | 功能 | 示例 |
|
||||||
|
|------|------|------|
|
||||||
|
| `read_excel` | 读取 Excel/CSV | `./run.sh read_excel --file data.xlsx` |
|
||||||
|
| `merge_excel` | 合并多个文件 | `./run.sh merge_excel --files a.xlsx b.xlsx` |
|
||||||
|
| `replace_cells` | 替换内容 | `./run.sh replace_cells --file data.xlsx --old "旧" --new "新"` |
|
||||||
|
| `filter_data` | 筛选排序 | `./run.sh filter_data --file data.xlsx --column "姓名" --value "张三"` |
|
||||||
|
| `batch_process` | 批量处理 | `./run.sh batch_process --dir ./files --replace "旧\|新"` |
|
||||||
|
| `translate_excel` | 翻译中→英 | `./run.sh translate_excel --file data.xlsx` |
|
||||||
|
| `auto_script` | 自扩展 | `./run.sh auto_script --prompt "计算每列总和"` |
|
||||||
|
|
||||||
|
## 完整命令参考
|
||||||
|
|
||||||
|
### 1. 读取 Excel/CSV
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/translate_excel.py --file data.xlsx --output translated.xlsx
|
./run.sh read_excel --file data.xlsx --rows 10
|
||||||
|
./run.sh read_excel --file data.csv --all --json
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 指定列翻译
|
### 2. 合并 Excel
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 只翻译指定列
|
./run.sh merge_excel --files file1.xlsx file2.xlsx --output merged.xlsx
|
||||||
python scripts/translate_excel.py --file data.xlsx --columns "姓名,地址,备注"
|
./run.sh merge_excel --dir ./files --output merged.xlsx
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 指定工作表(Excel)
|
### 3. 替换内容
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/translate_excel.py --file data.xlsx --sheet "Sheet1"
|
./run.sh replace_cells --file data.xlsx --old "旧值" --new "新值"
|
||||||
|
./run.sh replace_cells --file data.xlsx --regex "旧值\|新值"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 预览模式
|
### 4. 筛选数据
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 查看将要翻译的内容,不生成文件
|
./run.sh filter_data --file data.xlsx --column "姓名" --value "张三"
|
||||||
python scripts/translate_excel.py --file data.xlsx --dry-run
|
./run.sh filter_data --file data.xlsx --sort "年龄" --desc
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 使用自定义 API 密钥
|
### 5. 批量处理
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 方法 1:通过参数提供
|
./run.sh batch_process --dir ./files --replace "旧\|新"
|
||||||
python scripts/translate_excel.py --file data.xlsx --api-key "your-api-key"
|
./run.sh batch_process --dry-run --replace "旧值\|新值"
|
||||||
|
```
|
||||||
|
|
||||||
# 方法 2:通过环境变量(推荐)
|
### 6. 翻译 Excel/CSV
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 基础翻译
|
||||||
|
./run.sh translate_excel --file data.xlsx
|
||||||
|
|
||||||
|
# 指定列
|
||||||
|
./run.sh translate_excel --file data.xlsx --columns "姓名,地址,备注"
|
||||||
|
|
||||||
|
# 预览模式
|
||||||
|
./run.sh translate_excel --file data.xlsx --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
## 依赖管理
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 首次使用或添加新依赖
|
||||||
|
uv sync
|
||||||
|
|
||||||
|
# 添加新包
|
||||||
|
uv add <package-name>
|
||||||
|
|
||||||
|
# 运行任意命令(自动使用虚拟环境)
|
||||||
|
uv run python scripts/xxx.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 环境变量
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Google Gemini API Key(翻译功能需要)
|
||||||
export GEMINI_API_KEY="your-api-key"
|
export GEMINI_API_KEY="your-api-key"
|
||||||
python scripts/translate_excel.py --file data.xlsx
|
export GOOGLE_API_KEY="your-api-key"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 使用不同模型
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 使用其他 Gemini 模型
|
|
||||||
python scripts/translate_excel.py --file data.xlsx --model "gemini-2.0-flash-exp"
|
|
||||||
```
|
|
||||||
|
|
||||||
### API 密钥配置
|
|
||||||
|
|
||||||
翻译功能需要 Google Gemini API 密钥,配置方法:
|
|
||||||
|
|
||||||
1. **环境变量(推荐)**:
|
|
||||||
```bash
|
|
||||||
export GEMINI_API_KEY="your-api-key-here"
|
|
||||||
# 或
|
|
||||||
export GOOGLE_API_KEY="your-api-key-here"
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **命令行参数**:
|
|
||||||
```bash
|
|
||||||
python scripts/translate_excel.py --file data.xlsx --api-key "your-api-key"
|
|
||||||
```
|
|
||||||
|
|
||||||
获取 API 密钥:https://aistudio.google.com/app/apikey
|
|
||||||
|
|
||||||
### 翻译策略
|
|
||||||
|
|
||||||
- **保留专有名词**:人名、地名、品牌名等保持原样
|
|
||||||
- **数字格式**:保留数字、日期、时间的原始格式
|
|
||||||
- **技术术语**:使用标准英文翻译技术术语
|
|
||||||
- **空值跳过**:自动跳过空单元格、数字、公式单元格
|
|
||||||
|
|
||||||
### 输出示例
|
|
||||||
|
|
||||||
```
|
|
||||||
输入文件: data.xlsx
|
|
||||||
输出文件: data_en.xlsx
|
|
||||||
翻译列: 姓名, 地址, 职位
|
|
||||||
|
|
||||||
翻译工作表 'Sheet1' 中的 25 个单元格...
|
|
||||||
已保存翻译结果到: data_en.xlsx
|
|
||||||
|
|
||||||
翻译统计 - data.xlsx
|
|
||||||
============================================================
|
|
||||||
总单元格数: 100
|
|
||||||
包含中文: 25
|
|
||||||
已翻译: 25
|
|
||||||
跳过: 75
|
|
||||||
|
|
||||||
工作表: Sheet1
|
|
||||||
翻译列: 姓名, 地址, 职位
|
|
||||||
总数: 25, 中文: 25, 已翻译: 25
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🆕 自扩展能力详解
|
|
||||||
|
|
||||||
### 工作原理
|
|
||||||
|
|
||||||
1. **需求分析**:解析用户的自然语言描述
|
|
||||||
2. **模板匹配**:检查是否有可用的脚本模板
|
|
||||||
3. **脚本生成**:
|
|
||||||
- 有模板:使用模板 + 参数生成
|
|
||||||
- 无模板:自动生成通用脚本框架
|
|
||||||
4. **执行并缓存**:执行脚本并保存到 `temp_scripts/` 供复用
|
|
||||||
5. **结果返回**:输出执行结果和统计信息
|
|
||||||
|
|
||||||
### 可用模板
|
|
||||||
|
|
||||||
模板位于 `script_templates/` 目录:
|
|
||||||
|
|
||||||
| 模板 | 功能 | 触发关键词 |
|
|
||||||
|------|------|-----------|
|
|
||||||
| `currency_convert.py` | 货币/汇率转换 | 货币、汇率、转换、currency、convert |
|
|
||||||
| `pivot_summary.py` | 数据透视汇总 | 透视、汇总、聚合、pivot、summary |
|
|
||||||
| `data_clean.py` | 数据清洗(去空、格式化) | 清洗、去空、格式化、clean |
|
|
||||||
| `column_calc.py` | 列计算(加减乘除、公式) | 计算、加减乘除、公式、calc、calculate |
|
|
||||||
| `merge_columns.py` | 列合并/拆分 | 合并列、拆分、split、join |
|
|
||||||
|
|
||||||
### 自然语言触发示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 货币转换
|
|
||||||
python scripts/auto_script.py "把金额列从美元转换为人民币,汇率7.2" --file sales.xlsx --output converted.xlsx
|
|
||||||
|
|
||||||
# 数据透视
|
|
||||||
python scripts/auto_script.py "按地区和产品透视汇总销售额" --file sales.xlsx --output summary.xlsx --group_by "地区,产品" --agg_column "销售额" --agg_func "sum"
|
|
||||||
|
|
||||||
# 数据清洗
|
|
||||||
python scripts/auto_script.py "清洗数据,删除空行并去除空格" --file data.xlsx --output cleaned.xlsx --drop_na --strip_whitespace
|
|
||||||
|
|
||||||
# 列计算
|
|
||||||
python scripts/auto_script.py "计算总价 = 单价 * 数量" --file products.xlsx --output result.xlsx --operation multiply --column1 "单价" --column2 "数量" --result_column "总价"
|
|
||||||
|
|
||||||
# 仅生成不执行(预览)
|
|
||||||
python scripts/auto_script.py "计算利润" --dry-run
|
|
||||||
```
|
|
||||||
|
|
||||||
### 脚本缓存
|
|
||||||
|
|
||||||
相同需求会自动复用已生成的脚本,存储位置:
|
|
||||||
- `temp_scripts/script_[hash].py`
|
|
||||||
- 哈希值基于需求描述生成
|
|
||||||
- 手动清理:删除 `temp_scripts/` 目录
|
|
||||||
|
|
||||||
## 基础功能使用示例
|
|
||||||
|
|
||||||
### 读取 Excel
|
|
||||||
```bash
|
|
||||||
python scripts/read_excel.py /path/to/file.xlsx
|
|
||||||
```
|
|
||||||
|
|
||||||
### 合并文件
|
|
||||||
```bash
|
|
||||||
# 按行合并
|
|
||||||
python scripts/merge_excel.py --mode row file1.xlsx file2.xlsx output.xlsx
|
|
||||||
|
|
||||||
# 按列合并
|
|
||||||
python scripts/merge_excel.py --mode col file1.xlsx file2.xlsx output.xlsx
|
|
||||||
```
|
|
||||||
|
|
||||||
### 替换内容
|
|
||||||
```bash
|
|
||||||
python scripts/replace_cells.py input.xlsx "旧值" "新值" output.xlsx
|
|
||||||
```
|
|
||||||
|
|
||||||
### 筛选数据
|
|
||||||
```bash
|
|
||||||
python scripts/filter_data.py input.xlsx --filter "列A > 100" --sort "列B" output.xlsx
|
|
||||||
```
|
|
||||||
|
|
||||||
### 批量处理
|
|
||||||
```bash
|
|
||||||
python scripts/batch_process.py --replace "旧值|新值" *.xlsx
|
|
||||||
```
|
|
||||||
|
|
||||||
## 技术依赖
|
|
||||||
|
|
||||||
- Python 3.8+
|
|
||||||
- openpyxl (读写 .xlsx)
|
|
||||||
- pandas (数据处理)
|
|
||||||
- **google-generativeai** (翻译功能,>=0.3.0)
|
|
||||||
|
|
||||||
安装依赖:
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
## 注意事项
|
|
||||||
|
|
||||||
- 大文件处理可能需要较多内存
|
|
||||||
- 合并前请确保文件结构兼容
|
|
||||||
- 备份原始文件后再进行批量操作
|
|
||||||
- 公式可能在某些操作中丢失,建议保留原始文件
|
|
||||||
- 自扩展生成的脚本默认超时时间为 5 分钟
|
|
||||||
- 自动生成的脚本可能需要手动调整参数以适应特定需求
|
|
||||||
- **翻译功能**:
|
|
||||||
- 需要配置 Google Gemini API 密钥
|
|
||||||
- 大量翻译可能产生 API 费用
|
|
||||||
- 建议先用 `--dry-run` 预览翻译范围
|
|
||||||
- Gemini Flash Lite 有速率限制,大批量翻译建议分批处理
|
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,17 @@ dependencies = [
|
||||||
"google-generativeai>=0.8.0",
|
"google-generativeai>=0.8.0",
|
||||||
"requests>=2.28.0",
|
"requests>=2.28.0",
|
||||||
# 引用本地 auth-runtime 包
|
# 引用本地 auth-runtime 包
|
||||||
"python-auth-runtime-py @ file:///${PROJECT_ROOT}/python_auth_runtime",
|
"clawd-auth-runtime-py @ file:///${PROJECT_ROOT}/python_auth_runtime",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
excel-read = "scripts.read_excel:main"
|
||||||
|
excel-merge = "scripts.merge_excel:main"
|
||||||
|
excel-replace = "scripts.replace_cells:main"
|
||||||
|
excel-filter = "scripts.filter_data:main"
|
||||||
|
excel-batch = "scripts.batch_process:main"
|
||||||
|
excel-translate = "scripts.translate_excel:main"
|
||||||
|
excel-auto = "scripts.auto_script:main"
|
||||||
|
|
||||||
[tool.uv]
|
[tool.uv]
|
||||||
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,372 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@clawd/auth-runtime-py - Python 版本的 OpenClaw Auth Runtime
|
||||||
|
|
||||||
|
基于 ~/clawd/skills/_shared/auth-runtime 的 TypeScript 实现,
|
||||||
|
提供 Python 版本的客户端密钥认证。
|
||||||
|
|
||||||
|
配置加载优先级:
|
||||||
|
1. 环境变量(最高优先级)
|
||||||
|
2. 全局配置文件 ~/.openclaw/.env
|
||||||
|
3. 默认值
|
||||||
|
|
||||||
|
使用方式:
|
||||||
|
from python_auth_runtime import create_env_config, get_access_token, request_api_with_auto_refresh
|
||||||
|
|
||||||
|
config = create_env_config()
|
||||||
|
token = get_access_token(dry_run=False, config=config)
|
||||||
|
|
||||||
|
response = request_api_with_auto_refresh(
|
||||||
|
method="POST",
|
||||||
|
url=f"{config.auth_base}/your-endpoint",
|
||||||
|
dry_run=False,
|
||||||
|
config=config,
|
||||||
|
body={"key": "value"},
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import requests # type: ignore
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EnvConfig:
|
||||||
|
"""环境配置"""
|
||||||
|
auth_base: str = "https://api-gw-test.yuanwei-lnc.com"
|
||||||
|
client_key: str = ""
|
||||||
|
auth_cache_dir: str = "/tmp/skill-auth-cache"
|
||||||
|
auth_min_ttl_sec: int = 60
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SessionResponse:
|
||||||
|
"""会话响应"""
|
||||||
|
access_token: str
|
||||||
|
hook_url: Optional[str] = None
|
||||||
|
hook_token: Optional[str] = None
|
||||||
|
expires_in: int = 900
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CachedTokenData:
|
||||||
|
"""缓存的令牌数据"""
|
||||||
|
access_token: str
|
||||||
|
expires_at: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ApiResponse:
|
||||||
|
"""HTTP 响应"""
|
||||||
|
status: int
|
||||||
|
body: str
|
||||||
|
headers: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
# 可重试的状态码
|
||||||
|
RETRYABLE_STATUS = {401, 403}
|
||||||
|
|
||||||
|
# 可重试的响应体标记
|
||||||
|
RETRYABLE_BODY_MARKERS = [
|
||||||
|
'session not found or expired',
|
||||||
|
'invalid or expired token',
|
||||||
|
'unauthorized',
|
||||||
|
'client key expired',
|
||||||
|
'client key revoked',
|
||||||
|
]
|
||||||
|
|
||||||
|
# 全局配置文件路径
|
||||||
|
GLOBAL_ENV_PATHS = [
|
||||||
|
Path.home() / ".openclaw" / ".env",
|
||||||
|
Path.home() / ".clawd" / ".env",
|
||||||
|
Path.home() / "clawd" / ".env",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def load_global_env() -> bool:
|
||||||
|
"""
|
||||||
|
从全局配置文件加载环境变量
|
||||||
|
|
||||||
|
加载优先级:
|
||||||
|
1. ~/.openclaw/.env
|
||||||
|
2. ~/.clawd/.env
|
||||||
|
3. ~/clawd/.env
|
||||||
|
|
||||||
|
只加载尚未存在的环境变量(命令行参数优先级更高)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 是否成功加载
|
||||||
|
"""
|
||||||
|
for env_path in GLOBAL_ENV_PATHS:
|
||||||
|
if env_path.exists():
|
||||||
|
print(f"📄 加载全局配置:{env_path}")
|
||||||
|
with open(env_path, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
eq_index = line.find("=")
|
||||||
|
if eq_index > 0:
|
||||||
|
key = line[:eq_index].strip()
|
||||||
|
value = line[eq_index + 1:].strip()
|
||||||
|
# 去除引号
|
||||||
|
if (value.startswith('"') and value.endswith('"')) or \
|
||||||
|
(value.startswith("'") and value.endswith("'")):
|
||||||
|
value = value[1:-1]
|
||||||
|
# 只加载尚未存在的环境变量
|
||||||
|
if key not in os.environ:
|
||||||
|
os.environ[key] = value
|
||||||
|
print(f" ✓ {key} = {value[:10]}..." if len(str(value)) > 10 else f" ✓ {key} = {value}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def create_env_config() -> EnvConfig:
|
||||||
|
"""
|
||||||
|
从环境变量创建配置
|
||||||
|
|
||||||
|
加载优先级:
|
||||||
|
1. 环境变量(最高优先级)
|
||||||
|
2. 全局配置文件 ~/.openclaw/.env
|
||||||
|
3. 默认值
|
||||||
|
|
||||||
|
环境变量:
|
||||||
|
- AUTH_BASE: 认证基础 URL(默认:https://api-gw-test.yuanwei-lnc.com)
|
||||||
|
- CLIENT_KEY: 客户端密钥(必需)
|
||||||
|
- AUTH_CACHE_DIR: 缓存目录(默认:/tmp/skill-auth-cache)
|
||||||
|
- AUTH_MIN_TTL_SEC: 最小令牌 TTL 秒数(默认:60)
|
||||||
|
"""
|
||||||
|
# 先尝试加载全局配置
|
||||||
|
load_global_env()
|
||||||
|
|
||||||
|
auth_base = os.getenv("AUTH_BASE", "https://api-gw-test.yuanwei-lnc.com").rstrip("/")
|
||||||
|
client_key = os.getenv("CLIENT_KEY", "")
|
||||||
|
auth_cache_dir = os.getenv("AUTH_CACHE_DIR", "/tmp/skill-auth-cache")
|
||||||
|
auth_min_ttl_sec = int(os.getenv("AUTH_MIN_TTL_SEC", "60"))
|
||||||
|
|
||||||
|
return EnvConfig(
|
||||||
|
auth_base=auth_base,
|
||||||
|
client_key=client_key,
|
||||||
|
auth_cache_dir=auth_cache_dir,
|
||||||
|
auth_min_ttl_sec=auth_min_ttl_sec,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_cache_file(auth_base: str, client_key: str, cache_dir: str) -> Path:
|
||||||
|
"""获取缓存文件路径"""
|
||||||
|
cache_path = Path(cache_dir)
|
||||||
|
cache_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
key_str = f"{auth_base}:{client_key}"
|
||||||
|
hash_value = hashlib.sha256(key_str.encode()).hexdigest()[:16]
|
||||||
|
|
||||||
|
return cache_path / f"token_{hash_value}.json"
|
||||||
|
|
||||||
|
|
||||||
|
def read_cached_token(cache_file: Path, min_ttl_sec: int) -> Optional[str]:
|
||||||
|
"""读取缓存的令牌"""
|
||||||
|
if not cache_file.exists():
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(cache_file, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
cached = CachedTokenData(
|
||||||
|
access_token=data["access_token"],
|
||||||
|
expires_at=data["expires_at"],
|
||||||
|
)
|
||||||
|
|
||||||
|
if time.time() + min_ttl_sec < cached.expires_at:
|
||||||
|
return cached.access_token
|
||||||
|
else:
|
||||||
|
cache_file.unlink(missing_ok=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
except (json.JSONDecodeError, KeyError, Exception):
|
||||||
|
cache_file.unlink(missing_ok=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def write_cache(cache_file: Path, session: SessionResponse) -> None:
|
||||||
|
"""写入缓存"""
|
||||||
|
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"access_token": session.access_token,
|
||||||
|
"expires_at": time.time() + session.expires_in,
|
||||||
|
"expires_in": session.expires_in,
|
||||||
|
}
|
||||||
|
|
||||||
|
with open(cache_file, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, indent=2)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_cache(cache_file: Path) -> None:
|
||||||
|
"""删除缓存"""
|
||||||
|
cache_file.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_session_json(dry_run: bool, config: EnvConfig) -> SessionResponse:
|
||||||
|
"""从认证端点获取会话 JSON"""
|
||||||
|
if dry_run:
|
||||||
|
return SessionResponse(
|
||||||
|
access_token="<dry-run-token>",
|
||||||
|
hook_url="<dry-run-hook-url>",
|
||||||
|
hook_token="<dry-run-hook-token>",
|
||||||
|
expires_in=900,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not config.client_key:
|
||||||
|
raise ValueError("CLIENT_KEY is required. Please set it in ~/.openclaw/.env or environment variable.")
|
||||||
|
|
||||||
|
payload = {"clientKey": config.client_key}
|
||||||
|
url = f"{config.auth_base}/auth/skill-credit/session"
|
||||||
|
|
||||||
|
response = requests.post(url, json=payload, timeout=30)
|
||||||
|
|
||||||
|
if response.status_code < 200 or response.status_code >= 300:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Auth session request failed: HTTP {response.status_code} - {response.text}"
|
||||||
|
)
|
||||||
|
|
||||||
|
session_data = response.json()
|
||||||
|
|
||||||
|
if not session_data.get("accessToken"):
|
||||||
|
raise RuntimeError(f"Missing accessToken in session response: {response.text}")
|
||||||
|
|
||||||
|
return SessionResponse(
|
||||||
|
access_token=session_data["accessToken"],
|
||||||
|
hook_url=session_data.get("hookUrl"),
|
||||||
|
hook_token=session_data.get("hookToken"),
|
||||||
|
expires_in=session_data.get("expiresIn", 900),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_access_token(dry_run: bool, config: EnvConfig) -> str:
|
||||||
|
"""获取访问令牌(带缓存)"""
|
||||||
|
if dry_run:
|
||||||
|
return "<dry-run-token>"
|
||||||
|
|
||||||
|
if not config.client_key:
|
||||||
|
raise ValueError("CLIENT_KEY is required. Please set it in ~/.openclaw/.env or environment variable.")
|
||||||
|
|
||||||
|
cache_file = get_cache_file(config.auth_base, config.client_key, config.auth_cache_dir)
|
||||||
|
cached_token = read_cached_token(cache_file, config.auth_min_ttl_sec)
|
||||||
|
|
||||||
|
if cached_token:
|
||||||
|
return cached_token
|
||||||
|
|
||||||
|
session = fetch_session_json(dry_run, config)
|
||||||
|
write_cache(cache_file, session)
|
||||||
|
|
||||||
|
return session.access_token
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_access_token(dry_run: bool, config: EnvConfig) -> str:
|
||||||
|
"""刷新访问令牌(绕过缓存)"""
|
||||||
|
if dry_run:
|
||||||
|
return "<dry-run-token>"
|
||||||
|
|
||||||
|
if not config.client_key:
|
||||||
|
raise ValueError("CLIENT_KEY is required")
|
||||||
|
|
||||||
|
cache_file = get_cache_file(config.auth_base, config.client_key, config.auth_cache_dir)
|
||||||
|
delete_cache(cache_file)
|
||||||
|
|
||||||
|
return get_access_token(dry_run, config)
|
||||||
|
|
||||||
|
|
||||||
|
def is_retryable_session_error(response: ApiResponse) -> bool:
|
||||||
|
"""检查响应是否表示会话过期/无效"""
|
||||||
|
if response.status not in RETRYABLE_STATUS:
|
||||||
|
return False
|
||||||
|
|
||||||
|
body = (response.body or "").lower()
|
||||||
|
if not body:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return any(marker in body for marker in RETRYABLE_BODY_MARKERS)
|
||||||
|
|
||||||
|
|
||||||
|
def request_api(
|
||||||
|
method: str,
|
||||||
|
url: str,
|
||||||
|
auth_token: Optional[str] = None,
|
||||||
|
body: Optional[dict[str, Any]] = None,
|
||||||
|
timeout: int = 30,
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""发送 HTTP 请求"""
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
if auth_token:
|
||||||
|
headers["Authorization"] = f"Bearer {auth_token}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
if method.upper() == "GET":
|
||||||
|
response = requests.get(url, headers=headers, timeout=timeout)
|
||||||
|
elif method.upper() == "POST":
|
||||||
|
response = requests.post(url, headers=headers, json=body, timeout=timeout)
|
||||||
|
elif method.upper() == "PUT":
|
||||||
|
response = requests.put(url, headers=headers, json=body, timeout=timeout)
|
||||||
|
elif method.upper() == "DELETE":
|
||||||
|
response = requests.delete(url, headers=headers, timeout=timeout)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported HTTP method: {method}")
|
||||||
|
|
||||||
|
return ApiResponse(
|
||||||
|
status=response.status_code,
|
||||||
|
body=response.text,
|
||||||
|
headers=dict(response.headers),
|
||||||
|
)
|
||||||
|
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
return ApiResponse(
|
||||||
|
status=0,
|
||||||
|
body=str(e),
|
||||||
|
headers={},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def request_api_with_auto_refresh(
|
||||||
|
method: str,
|
||||||
|
url: str,
|
||||||
|
dry_run: bool,
|
||||||
|
config: EnvConfig,
|
||||||
|
body: Optional[dict[str, Any]] = None,
|
||||||
|
access_token: Optional[str] = None,
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""发送 API 请求并自动刷新令牌"""
|
||||||
|
token = access_token or get_access_token(dry_run, config)
|
||||||
|
|
||||||
|
first = request_api(method, url, token, body)
|
||||||
|
|
||||||
|
if not is_retryable_session_error(first):
|
||||||
|
return first
|
||||||
|
|
||||||
|
fresh_token = refresh_access_token(dry_run, config)
|
||||||
|
return request_api(method, url, fresh_token, body)
|
||||||
|
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__all__ = [
|
||||||
|
"EnvConfig",
|
||||||
|
"SessionResponse",
|
||||||
|
"ApiResponse",
|
||||||
|
"load_global_env",
|
||||||
|
"create_env_config",
|
||||||
|
"get_access_token",
|
||||||
|
"refresh_access_token",
|
||||||
|
"fetch_session_json",
|
||||||
|
"request_api",
|
||||||
|
"request_api_with_auto_refresh",
|
||||||
|
"is_retryable_session_error",
|
||||||
|
]
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
[project]
|
[project]
|
||||||
name = "@clawd/auth-runtime-py"
|
name = "clawd-auth-runtime-py"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
description = "Python 版本的 OpenClaw Auth Runtime"
|
description = "Python 版本的 OpenClaw Auth Runtime"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,245 @@
|
||||||
|
Metadata-Version: 2.4
|
||||||
|
Name: clawd-auth-runtime-py
|
||||||
|
Version: 1.0.0
|
||||||
|
Summary: Python 版本的 OpenClaw Auth Runtime
|
||||||
|
Requires-Python: >=3.9
|
||||||
|
Description-Content-Type: text/markdown
|
||||||
|
Requires-Dist: requests>=2.28.0
|
||||||
|
|
||||||
|
# @clawd/auth-runtime-py
|
||||||
|
|
||||||
|
Python 版本的 OpenClaw Auth Runtime。
|
||||||
|
|
||||||
|
## 全局配置
|
||||||
|
|
||||||
|
**所有 skill 共享同一份全局配置**,无需在每个 skill 中重复配置。
|
||||||
|
|
||||||
|
### 创建全局配置文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 复制模板
|
||||||
|
cp ~/.openclaw/.env.example ~/.openclaw/.env
|
||||||
|
|
||||||
|
# 编辑配置文件
|
||||||
|
vi ~/.openclaw/.env
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置文件内容
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# ~/.openclaw/.env
|
||||||
|
|
||||||
|
# Auth Runtime 配置
|
||||||
|
CLIENT_KEY=sk_ae28fc4e.xxx
|
||||||
|
AUTH_BASE=https://api-gw-test.yuanwei-lnc.com
|
||||||
|
|
||||||
|
# Gemini API 配置(可选)
|
||||||
|
GEMINI_API_KEY=your-gemini-api-key
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意**: `~/.openclaw/.env` 包含敏感信息,不要提交到 git。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv pip install /path/to/python_auth_runtime
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 使用方式
|
||||||
|
|
||||||
|
### 最简单的用法
|
||||||
|
|
||||||
|
```python
|
||||||
|
from python_auth_runtime import create_env_config, request_api_with_auto_refresh
|
||||||
|
|
||||||
|
# 自动从 ~/.openclaw/.env 加载配置
|
||||||
|
config = create_env_config()
|
||||||
|
|
||||||
|
# 调用 API
|
||||||
|
response = request_api_with_auto_refresh(
|
||||||
|
method="POST",
|
||||||
|
url=f"{config.auth_base}/ecom/tasks/scrape",
|
||||||
|
dry_run=False,
|
||||||
|
config=config,
|
||||||
|
body={"url": "https://detail.1688.com/offer/123.html"},
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置加载优先级
|
||||||
|
|
||||||
|
1. **环境变量**(最高优先级)
|
||||||
|
```bash
|
||||||
|
export CLIENT_KEY="override-key"
|
||||||
|
python script.py
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **全局配置文件** `~/.openclaw/.env`
|
||||||
|
```bash
|
||||||
|
CLIENT_KEY=sk_ae28fc4e.xxx
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **默认值**
|
||||||
|
- `AUTH_BASE`: `https://api-gw-test.yuanwei-lnc.com`
|
||||||
|
- `AUTH_CACHE_DIR`: `/tmp/skill-auth-cache`
|
||||||
|
- `AUTH_MIN_TTL_SEC`: `60`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
```python
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# your-skill/scripts/main.py
|
||||||
|
|
||||||
|
from python_auth_runtime import create_env_config, request_api_with_auto_refresh
|
||||||
|
import json
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# 自动从 ~/.openclaw/.env 加载配置
|
||||||
|
config = create_env_config()
|
||||||
|
|
||||||
|
# 验证配置
|
||||||
|
if not config.client_key:
|
||||||
|
print("❌ CLIENT_KEY not found!")
|
||||||
|
print("Please create ~/.openclaw/.env with your CLIENT_KEY")
|
||||||
|
print("See: ~/.openclaw/.env.example")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# 调用 1688 API
|
||||||
|
response = request_api_with_auto_refresh(
|
||||||
|
method="POST",
|
||||||
|
url=f"{config.auth_base}/ecom/tasks/scrape",
|
||||||
|
dry_run=False,
|
||||||
|
config=config,
|
||||||
|
body={"url": "https://detail.1688.com/offer/123.html"},
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status == 200:
|
||||||
|
data = json.loads(response.body)
|
||||||
|
print("商品价格:", data.get("price"))
|
||||||
|
else:
|
||||||
|
print(f"❌ 失败:{response.status}")
|
||||||
|
print(response.body)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
exit(main())
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API 参考
|
||||||
|
|
||||||
|
### 配置
|
||||||
|
|
||||||
|
#### `create_env_config() -> EnvConfig`
|
||||||
|
|
||||||
|
从环境变量创建配置(自动加载 `~/.openclaw/.env`)。
|
||||||
|
|
||||||
|
| 配置项 | 默认值 | 说明 |
|
||||||
|
|--------|--------|------|
|
||||||
|
| `AUTH_BASE` | `https://api-gw-test.yuanwei-lnc.com` | 认证基础 URL |
|
||||||
|
| `CLIENT_KEY` | **必需** | 客户端密钥(从全局配置加载) |
|
||||||
|
| `AUTH_CACHE_DIR` | `/tmp/skill-auth-cache` | 缓存目录 |
|
||||||
|
| `AUTH_MIN_TTL_SEC` | `60` | 最小令牌 TTL(秒) |
|
||||||
|
|
||||||
|
### 令牌管理
|
||||||
|
|
||||||
|
#### `get_access_token(dry_run, config) -> str`
|
||||||
|
|
||||||
|
获取访问令牌(带缓存)。
|
||||||
|
|
||||||
|
#### `refresh_access_token(dry_run, config) -> str`
|
||||||
|
|
||||||
|
刷新访问令牌(绕过缓存)。
|
||||||
|
|
||||||
|
### API 请求
|
||||||
|
|
||||||
|
#### `request_api(method, url, auth_token, body) -> ApiResponse`
|
||||||
|
|
||||||
|
发送 HTTP 请求。
|
||||||
|
|
||||||
|
#### `request_api_with_auto_refresh(method, url, dry_run, config, body) -> ApiResponse`
|
||||||
|
|
||||||
|
发送 API 请求并自动刷新令牌。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 多 Agent Skill 配置
|
||||||
|
|
||||||
|
对于多 Agent skill,可以在全局配置中添加:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# ~/.openclaw/.env
|
||||||
|
|
||||||
|
# 主配置
|
||||||
|
CLIENT_KEY=sk_ae28fc4e.xxx
|
||||||
|
|
||||||
|
# Agent 特定配置
|
||||||
|
AGENT_1_CLIENT_KEY=sk_agent1.xxx
|
||||||
|
AGENT_2_CLIENT_KEY=sk_agent2.xxx
|
||||||
|
|
||||||
|
# 或者使用统一配置
|
||||||
|
# 所有 agent 共享同一个 CLIENT_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
在代码中:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import os
|
||||||
|
from python_auth_runtime import create_env_config
|
||||||
|
|
||||||
|
# 主配置
|
||||||
|
config = create_env_config()
|
||||||
|
|
||||||
|
# 或者访问特定 agent 的配置
|
||||||
|
agent1_key = os.getenv("AGENT_1_CLIENT_KEY", config.client_key)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 环境变量列表
|
||||||
|
|
||||||
|
| 变量 | 默认值 | 说明 |
|
||||||
|
|------|--------|------|
|
||||||
|
| `CLIENT_KEY` | **必需** | 客户端密钥 |
|
||||||
|
| `AUTH_BASE` | `https://api-gw-test.yuanwei-lnc.com` | 认证基础 URL |
|
||||||
|
| `AUTH_CACHE_DIR` | `/tmp/skill-auth-cache` | 缓存目录 |
|
||||||
|
| `AUTH_MIN_TTL_SEC` | `60` | 最小令牌 TTL(秒) |
|
||||||
|
| `GEMINI_API_KEY` | - | Gemini API Key(用于翻译) |
|
||||||
|
| `ECOM_BASE` | - | 1688 API 基础 URL |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /Users/xiaolongxia/Documents/ai-build-app/skills/excel-toolkit/python_auth_runtime
|
||||||
|
uv run python scripts/example_usage.py
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
python_auth_runtime/
|
||||||
|
├── src/python_auth_runtime/
|
||||||
|
│ └── __init__.py # 核心实现(自动加载全局配置)
|
||||||
|
├── scripts/
|
||||||
|
│ ├── load_env.py # .env 加载工具(可选使用)
|
||||||
|
│ └── example_usage.py # 使用示例
|
||||||
|
├── pyproject.toml
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
README.md
|
||||||
|
pyproject.toml
|
||||||
|
src/clawd_auth_runtime_py.egg-info/PKG-INFO
|
||||||
|
src/clawd_auth_runtime_py.egg-info/SOURCES.txt
|
||||||
|
src/clawd_auth_runtime_py.egg-info/dependency_links.txt
|
||||||
|
src/clawd_auth_runtime_py.egg-info/requires.txt
|
||||||
|
src/clawd_auth_runtime_py.egg-info/top_level.txt
|
||||||
|
src/python_auth_runtime/__init__.py
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
requests>=2.28.0
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
python_auth_runtime
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Excel Toolkit 统一入口脚本
|
||||||
|
# 自动使用 uv run 执行,确保虚拟环境隔离
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
cd "$SCRIPT_DIR"
|
||||||
|
|
||||||
|
# 检测 uv 是否可用
|
||||||
|
if ! command -v uv &> /dev/null; then
|
||||||
|
echo "❌ uv not found. Install with: curl -LsSf https://astral.sh/uv/install.sh | sh" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 确保依赖已同步
|
||||||
|
if [ ! -d ".venv" ]; then
|
||||||
|
echo "📦 Syncing dependencies..."
|
||||||
|
uv sync
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 执行脚本
|
||||||
|
SCRIPT_NAME="$1"
|
||||||
|
shift
|
||||||
|
|
||||||
|
if [ -z "$SCRIPT_NAME" ]; then
|
||||||
|
echo "Usage: ./run.sh <script_name> [args...]"
|
||||||
|
echo ""
|
||||||
|
echo "Available scripts:"
|
||||||
|
ls scripts/*.py 2>/dev/null | xargs -n1 basename | sed 's/\.py$//' | sed 's/^/ /'
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
SCRIPT_PATH="scripts/${SCRIPT_NAME}.py"
|
||||||
|
if [ ! -f "$SCRIPT_PATH" ]; then
|
||||||
|
echo "❌ Script not found: $SCRIPT_PATH" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🚀 Running: $SCRIPT_PATH $@"
|
||||||
|
uv run python "$SCRIPT_PATH" "$@"
|
||||||
Binary file not shown.
|
|
@ -102,7 +102,7 @@ def get_api_key() -> str:
|
||||||
|
|
||||||
def get_model_name() -> str:
|
def get_model_name() -> str:
|
||||||
import os
|
import os
|
||||||
return os.getenv("GEMINI_MODEL", "gemini-2.0-flash-lite")
|
return os.getenv("GEMINI_MODEL", "gemini-2.0-flash")
|
||||||
|
|
||||||
|
|
||||||
def extract_chinese_content(
|
def extract_chinese_content(
|
||||||
|
|
@ -360,7 +360,7 @@ def parse_args() -> argparse.Namespace:
|
||||||
parser.add_argument("--output", "-o", type=Path, help="输出文件路径")
|
parser.add_argument("--output", "-o", type=Path, help="输出文件路径")
|
||||||
parser.add_argument("--columns", "-c", type=str, help="要翻译的列名(逗号分隔)")
|
parser.add_argument("--columns", "-c", type=str, help="要翻译的列名(逗号分隔)")
|
||||||
parser.add_argument("--sheet", "-s", type=str, help="要翻译的 Sheet 名称")
|
parser.add_argument("--sheet", "-s", type=str, help="要翻译的 Sheet 名称")
|
||||||
parser.add_argument("--model", "-m", type=str, default="gemini-2.0-flash-lite", help="Gemini 模型名称")
|
parser.add_argument("--model", "-m", type=str, default="gemini-2.0-flash", help="Gemini 模型名称")
|
||||||
parser.add_argument("--api-key", "-k", type=str, help="Gemini API 密钥")
|
parser.add_argument("--api-key", "-k", type=str, help="Gemini API 密钥")
|
||||||
parser.add_argument("--dry-run", action="store_true", help="预览模式")
|
parser.add_argument("--dry-run", action="store_true", help="预览模式")
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
Loading…
Reference in New Issue