Spaces:
Sleeping
Sleeping
Create sync_bailian_models.py
Browse files
scripts/sync_bailian_models.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import sqlite3
|
| 5 |
+
import requests
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
# 设置数据库路径和百炼API端点
|
| 9 |
+
DB_PATH = "/app/server/data/freeapi.db"
|
| 10 |
+
BAILIAN_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/models"
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
# 获取百炼的API Key
|
| 14 |
+
api_key = os.getenv("BAILIAN_API_KEY")
|
| 15 |
+
if not api_key:
|
| 16 |
+
print("❌ 错误: 环境变量 BAILIAN_API_KEY 未设置")
|
| 17 |
+
return 1
|
| 18 |
+
|
| 19 |
+
# 调用百炼API获取模型列表
|
| 20 |
+
headers = {"Authorization": f"Bearer {api_key}"}
|
| 21 |
+
try:
|
| 22 |
+
response = requests.get(BAILIAN_URL, headers=headers, timeout=30)
|
| 23 |
+
response.raise_for_status()
|
| 24 |
+
models_data = response.json()
|
| 25 |
+
# 假设返回的JSON结构与 OpenAI 兼容模式一致,即包含一个 'data' 列表
|
| 26 |
+
models_list = [item["id"] for item in models_data.get("data", [])]
|
| 27 |
+
if not models_list:
|
| 28 |
+
print("⚠️ 警告: 未能从API获取到任何模型。")
|
| 29 |
+
return 1
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"❌ 请求百炼API失败: {e}")
|
| 32 |
+
return 1
|
| 33 |
+
|
| 34 |
+
# 连接数据库
|
| 35 |
+
try:
|
| 36 |
+
conn = sqlite3.connect(DB_PATH)
|
| 37 |
+
cursor = conn.cursor()
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"❌ 无法连接数据库: {e}")
|
| 40 |
+
return 1
|
| 41 |
+
|
| 42 |
+
# 同步模型列表
|
| 43 |
+
added_count = 0
|
| 44 |
+
for model_id in models_list:
|
| 45 |
+
# 检查模型是否已存在
|
| 46 |
+
cursor.execute("SELECT 1 FROM models WHERE id = ?", (model_id,))
|
| 47 |
+
if not cursor.fetchone():
|
| 48 |
+
cursor.execute("INSERT INTO models (id, name, provider_id, enabled, created_at) VALUES (?, ?, ?, 1, ?)",
|
| 49 |
+
(model_id, model_id, 1, datetime.utcnow().isoformat()))
|
| 50 |
+
added_count += 1
|
| 51 |
+
print(f"➕ 添加模型: {model_id}")
|
| 52 |
+
else:
|
| 53 |
+
print(f"⏭️ 模型已存在: {model_id}")
|
| 54 |
+
|
| 55 |
+
conn.commit()
|
| 56 |
+
conn.close()
|
| 57 |
+
print(f"✅ 同步完成。新增模型数量: {added_count}")
|
| 58 |
+
return 0
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
sys.exit(main())
|