Spaces:
Sleeping
Sleeping
File size: 8,761 Bytes
b0b42d4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
#!/usr/bin/env python3
"""
Hugging Face Spaces Entry Point for GCLI2API Lightspeed
HF Spaces 部署入口文件
This file serves as the entry point for Hugging Face Spaces deployment.
It imports and runs the main application from web.py with appropriate configurations.
"""
import os
import sys
import asyncio
import signal
import logging
from pathlib import Path
# 确保项目根目录在 Python 路径中
project_root = Path(__file__).parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
# 设置基础环境变量(HF Spaces 特定)
os.environ.setdefault('HOST', '0.0.0.0')
os.environ.setdefault('PORT', '7860') # HF Spaces 默认端口
# 如果没有设置密码,使用默认值(HF Spaces 用户需要在环境变量中设置)
if not os.environ.get('PASSWORD') and not os.environ.get('API_PASSWORD'):
print("⚠️ 警告: 未设置密码环境变量!")
print(" 请在 HF Spaces Settings 中设置 API_PASSWORD 和 PANEL_PASSWORD")
print(" 或者设置通用 PASSWORD 环境变量")
# 为了演示目的,设置默认密码
os.environ.setdefault('PASSWORD', 'hf_demo_password_please_change')
# 设置日志级别
os.environ.setdefault('LOG_LEVEL', 'INFO')
# HF Spaces 优化配置
os.environ.setdefault('CALLS_PER_ROTATION', '5') # 较少的轮换次数适合 HF Spaces
os.environ.setdefault('RETRY_429_ENABLED', 'true')
os.environ.setdefault('AUTO_BAN', 'true')
os.environ.setdefault('COMPATIBILITY_MODE', 'true') # 增强兼容性
# 确保 creds 目录存在
creds_dir = project_root / "creds"
creds_dir.mkdir(exist_ok=True)
def signal_handler(signum, frame):
"""处理系统信号,优雅关闭"""
print(f"\n收到信号 {signum},正在优雅关闭服务...")
sys.exit(0)
def setup_logging():
"""设置日志配置"""
logging.basicConfig(
level=getattr(logging, os.environ.get('LOG_LEVEL', 'INFO')),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def print_startup_info():
"""打印启动信息"""
port = os.environ.get('PORT', '7860')
host = os.environ.get('HOST', '0.0.0.0')
print("=" * 80)
print("🚀 GCLI2API Lightspeed - Hugging Face Spaces Edition")
print("=" * 80)
print(f"🌐 服务地址: http://{host}:{port}")
print(f"🎛️ 控制面板: http://{host}:{port}/auth")
print(f"📡 OpenAI API: http://{host}:{port}/v1")
print(f"🔧 Gemini API: http://{host}:{port}")
print("=" * 80)
# 检查关键环境变量
if os.environ.get('API_PASSWORD') or os.environ.get('PASSWORD'):
print("✅ API 密码已配置")
else:
print("⚠️ API 密码未配置,将使用默认密码")
if os.environ.get('PANEL_PASSWORD') or os.environ.get('PASSWORD'):
print("✅ 控制面板密码已配置")
else:
print("⚠️ 控制面板密码未配置,将使用默认密码")
# 检查凭证配置
gcli_creds = [k for k in os.environ.keys() if k.startswith('GCLI_CREDS_')]
if gcli_creds:
print(f"✅ 检测到 {len(gcli_creds)} 个环境变量凭证")
elif os.environ.get('AUTO_LOAD_ENV_CREDS') == 'true':
print("⚠️ 启用了环境变量凭证加载,但未检测到 GCLI_CREDS_* 变量")
else:
print("📁 将使用 creds 目录中的凭证文件")
print("=" * 80)
print()
async def main():
"""主函数"""
# 注册信号处理器
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# 设置日志
setup_logging()
# 打印启动信息
print_startup_info()
try:
# 导入主应用(延迟导入以确保环境变量已设置)
from web import main as web_main
print("🔄 正在启动 GCLI2API 服务...")
await web_main()
except KeyboardInterrupt:
print("\n👋 收到中断信号,正在关闭服务...")
except Exception as e:
print(f"❌ 启动失败: {e}")
logging.exception("启动过程中发生错误")
sys.exit(1)
def run_app():
"""运行应用(同步入口)"""
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n👋 服务已停止")
except Exception as e:
print(f"❌ 运行错误: {e}")
sys.exit(1)
if __name__ == "__main__":
run_app()
# HF Spaces 兼容性:提供 Gradio 接口(可选)
try:
import gradio as gr
def create_gradio_interface():
"""创建简单的 Gradio 界面用于 HF Spaces 展示"""
def show_info():
port = os.environ.get('PORT', '7860')
api_password = os.environ.get('API_PASSWORD') or os.environ.get('PASSWORD', 'hf_demo_password_please_change')
info = f"""
# 🚀 GCLI2API Lightspeed 已启动
## 🔗 访问链接
- **控制面板**: [点击访问管理界面](/auth) (密码: `{api_password}`)
- **API 文档**: [OpenAI 兼容端点](/v1/models)
## 📡 API 端点
- **OpenAI 格式**: `POST /v1/chat/completions`
- **Gemini 格式**: `POST /v1/models/{{model}}:generateContent`
## 🔑 认证信息
- **API 密钥**: `{api_password}`
- **使用方法**: 在请求头中添加 `Authorization: Bearer {api_password}`
## 💡 使用提示
1. 首次使用请先访问控制面板上传 Google OAuth 凭证文件
2. 支持多种模型变体,包括思维模型和搜索增强模型
3. 完整文档请查看项目 README
---
**注意**: 这是一个功能性的 API 服务,主要通过 HTTP 接口使用。
"""
return info
with gr.Blocks(title="GCLI2API Lightspeed", theme=gr.themes.Soft()) as demo:
gr.Markdown(show_info())
gr.Markdown("## 🔧 快速测试")
with gr.Row():
test_input = gr.Textbox(
label="测试消息",
placeholder="输入测试消息...",
value="Hello, how are you?"
)
test_btn = gr.Button("发送测试", variant="primary")
test_output = gr.Textbox(
label="API 响应",
lines=10,
interactive=False
)
def test_api(message):
import requests
import json
try:
port = os.environ.get('PORT', '7860')
api_password = os.environ.get('API_PASSWORD') or os.environ.get('PASSWORD', 'hf_demo_password_please_change')
response = requests.post(
f"http://127.0.0.1:{port}/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_password}",
"Content-Type": "application/json"
},
json={
"model": "gemini-2.5-pro",
"messages": [
{"role": "user", "content": message}
],
"temperature": 0.7
},
timeout=30
)
if response.status_code == 200:
result = response.json()
return json.dumps(result, indent=2, ensure_ascii=False)
else:
return f"错误 {response.status_code}: {response.text}"
except Exception as e:
return f"请求失败: {str(e)}\n\n请确保:\n1. 已配置有效的 Google OAuth 凭证\n2. API 服务正在运行"
test_btn.click(
test_api,
inputs=[test_input],
outputs=[test_output]
)
return demo
# 如果在 HF Spaces 环境中,启动 Gradio 界面
if os.environ.get('SPACE_ID'):
demo = create_gradio_interface()
# 在后台启动主应用
import threading
app_thread = threading.Thread(target=run_app, daemon=True)
app_thread.start()
# 启动 Gradio 界面
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True,
share=False
)
except ImportError:
# 如果没有 Gradio,直接运行主应用
if __name__ == "__main__":
run_app() |