diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8b9d976 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# Gemini API Key 配置 +# 获取 API Key: https://aistudio.google.com/app/apikey + +# 方式 1: 使用 Gemini API Key(推荐) +GEMINI_API_KEY=your-api-key-here + +# 方式 2: 使用 Google API Key(备选) +# GOOGLE_API_KEY=your-google-api-key-here diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..388bd44 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ + +# Environment variables (contains secrets) +.env +.env.local +*.env diff --git a/README.md b/README.md index 1a7b2df..72921e3 100644 --- a/README.md +++ b/README.md @@ -541,3 +541,35 @@ pyproject.toml 已包含镜像配置: [tool.uv] index-url = "https://pypi.tuna.tsinghua.edu.cn/simple" ``` + +## 环境变量配置 + +### 方式 1: 使用 .env 文件(推荐) + +在项目根目录创建 `.env` 文件: + +```bash +# .env +GEMINI_API_KEY=your-api-key-here +``` + +脚本会自动加载 `.env` 文件中的环境变量。 + +**注意**: `.env` 文件已添加到 `.gitignore`,不会被提交到 git。 + +### 方式 2: 命令行设置 + +```bash +export GEMINI_API_KEY="your-api-key" +uv run python scripts/translate_excel.py --file data.xlsx +``` + +### 方式 3: 命令行参数 + +```bash +uv run python scripts/translate_excel.py --file data.xlsx --api-key your-api-key +``` + +### 获取 API Key + +访问:https://aistudio.google.com/app/apikey diff --git a/scripts/load_env.py b/scripts/load_env.py new file mode 100644 index 0000000..f03c3f2 --- /dev/null +++ b/scripts/load_env.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +""" +从 .env 文件加载环境变量 +""" +import os +from pathlib import Path + +def load_env(env_path: Path | None = None) -> None: + """ + 从 .env 文件加载环境变量 + + Args: + env_path: .env 文件路径(默认:当前目录的 .env) + """ + if env_path is None: + # 查找 .env 文件 + possible_paths = [ + Path(".env"), + Path(__file__).parent.parent / ".env", + Path.cwd() / ".env", + ] + for p in possible_paths: + if p.exists(): + env_path = p + break + + if not env_path or not env_path.exists(): + return # 没有 .env 文件,跳过 + + 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 + # 解析 KEY=VALUE + if "=" in line: + key, value = line.split("=", 1) + key = key.strip() + value = value.strip() + # 只设置尚未存在的环境变量 + if key not in os.environ: + os.environ[key] = value + print(f" ✓ {key} = {value[:10]}...")