Spaces:
Sleeping
Sleeping
Download bytedrama_api_client.py from FrankSun82/bp_open_api: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/spaces/FrankSun82/bp_open_api/resolve/main/bytedrama_api_client.py
- Command line
-
hf download hf://spaces/FrankSun82/bp_open_api/bytedrama_api_client.py
-
curl -L -o bytedrama_api_client.py https://huggingface.co/spaces/FrankSun82/bp_open_api/resolve/main/bytedrama_api_client.py
11.8 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| 火山引擎短剧OpenAPI客户端 | |
| 简化POST请求调用,自动处理签名生成 | |
| """ | |
| import hashlib | |
| import json | |
| import time | |
| import requests | |
| import os | |
| from datetime import datetime | |
| from typing import Dict, List, Any, Optional | |
| class ByteDramaAPIClient: | |
| """火山引擎短剧API客户端""" | |
| def __init__(self, user_id: int, role_id: int, secure_key: str, debug_mode: bool = False, debug_file_path: str = None): | |
| """ | |
| 初始化API客户端 | |
| Args: | |
| user_id: 用户ID | |
| role_id: 角色ID | |
| secure_key: 安全密钥 | |
| debug_mode: 是否开启调试模式,打印请求和响应数据 | |
| debug_file_path: 调试文件路径,如果指定则保存到文件而不是打印 | |
| """ | |
| self.user_id = user_id | |
| self.role_id = role_id | |
| self.secure_key = secure_key | |
| self.base_url = "https://open-api.bytedrama.com/bytedrama/open/api/sp" | |
| self.debug_mode = debug_mode | |
| self.debug_file_path = debug_file_path or "api_debug.log" | |
| # 如果开启调试模式且指定了文件路径,确保目录存在 | |
| if self.debug_mode and debug_file_path: | |
| os.makedirs(os.path.dirname(os.path.abspath(self.debug_file_path)), exist_ok=True) | |
| def _log_debug(self, log_type: str, data: Dict[str, Any]): | |
| """ | |
| 记录调试信息 | |
| Args: | |
| log_type: 日志类型 (REQUEST/RESPONSE/ERROR) | |
| data: 要记录的数据 | |
| """ | |
| if not self.debug_mode: | |
| return | |
| timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| log_entry = { | |
| "timestamp": timestamp, | |
| "type": log_type, | |
| "data": data | |
| } | |
| formatted_log = f"\n{'='*60}\n[{timestamp}] {log_type}\n{'='*60}\n{json.dumps(data, ensure_ascii=False, indent=2)}\n" | |
| if hasattr(self, 'debug_file_path') and self.debug_file_path != "api_debug.log": | |
| # 保存到指定文件 | |
| with open(self.debug_file_path, 'a', encoding='utf-8') as f: | |
| f.write(formatted_log) | |
| else: | |
| # 打印到控制台 | |
| print(formatted_log) | |
| def _generate_sign(self, params: Dict[str, Any]) -> str: | |
| """ | |
| 生成签名 | |
| Args: | |
| params: 参数字典 | |
| Returns: | |
| MD5签名字符串 | |
| """ | |
| # 过滤掉sign字段 | |
| sign_params = {k: v for k, v in params.items() if k != 'sign'} | |
| # 构建签名字符串 | |
| sign_list = [] | |
| for key, value in sign_params.items(): | |
| if isinstance(value, (list, dict)): | |
| value_str = json.dumps(value, separators=(',', ':'), ensure_ascii=False) | |
| else: | |
| value_str = str(value) | |
| if value_str: # 只有非空值才参与签名 | |
| sign_list.append(f"{key}={value_str}") | |
| # 按字母序排序 | |
| sign_list.sort() | |
| sign_str = "&".join(sign_list) | |
| # 加盐并MD5 | |
| final_str = sign_str + self.secure_key | |
| sign = hashlib.md5(final_str.encode('utf-8')).hexdigest() | |
| return sign | |
| def _build_auth_info(self) -> Dict[str, Any]: | |
| """构建认证信息""" | |
| timestamp = str(int(time.time())) | |
| auth_params = { | |
| "user_id": self.user_id, | |
| "role_id": self.role_id, | |
| "timestamp": timestamp | |
| } | |
| # 生成签名 | |
| sign = self._generate_sign(auth_params) | |
| auth_params["sign"] = sign | |
| return auth_params | |
| def _make_request(self, endpoint: str, controller: Dict[str, Any] = None, | |
| page_info: Dict[str, Any] = None) -> Dict[str, Any]: | |
| """ | |
| 发送POST请求 | |
| Args: | |
| endpoint: API端点 | |
| controller: 业务控制参数 | |
| page_info: 分页信息 | |
| Returns: | |
| API响应数据 | |
| """ | |
| url = f"{self.base_url}/{endpoint}" | |
| # 构建请求体 | |
| payload = { | |
| "auth_info": self._build_auth_info() | |
| } | |
| if controller: | |
| payload["controller"] = controller | |
| if page_info: | |
| payload["page_info"] = page_info | |
| # 发送请求 | |
| headers = { | |
| 'Content-Type': 'application/json', | |
| 'Accept': 'application/json' | |
| } | |
| # 调试模式:记录请求数据 | |
| if self.debug_mode: | |
| self._log_debug("REQUEST", { | |
| "url": url, | |
| "headers": headers, | |
| "payload": payload | |
| }) | |
| try: | |
| response = requests.post(url, json=payload, headers=headers, timeout=30) | |
| response.raise_for_status() | |
| response_data = response.json() | |
| # 调试模式:记录响应数据 | |
| if self.debug_mode: | |
| self._log_debug("RESPONSE", { | |
| "status_code": response.status_code, | |
| "headers": dict(response.headers), | |
| "data": response_data | |
| }) | |
| return response_data | |
| except requests.exceptions.RequestException as e: | |
| error_response = {"error": f"请求失败: {str(e)}"} | |
| if self.debug_mode: | |
| self._log_debug("ERROR", {"error": str(e), "endpoint": endpoint}) | |
| return error_response | |
| except json.JSONDecodeError as e: | |
| error_response = {"error": f"JSON解析失败: {str(e)}"} | |
| if self.debug_mode: | |
| self._log_debug("JSON_ERROR", {"error": str(e), "endpoint": endpoint}) | |
| return error_response | |
| def get_categories(self) -> Dict[str, Any]: | |
| """ | |
| 获取分类列表 | |
| Returns: | |
| 分类列表数据 | |
| """ | |
| return self._make_request("category/list") | |
| def get_drama_list(self, page=1, page_size=100, shortplay_ids=None, category_ids=None, | |
| lang=None, voice_lang=None, progress_state=None, title=None) -> Dict[str, Any]: | |
| """ | |
| 获取剧目列表 - 支持完整API参数 | |
| Args: | |
| page: 页码,默认1 | |
| page_size: 每页数量,默认100 | |
| shortplay_ids: 短剧ID列表,可选 | |
| category_ids: 分类ID列表,可选 | |
| lang: 字幕语言,可选 (单个字符串,如'zh_hans') | |
| voice_lang: 音频语言,可选 (单个字符串,如'zh_hans') | |
| progress_state: 完结状态,可选 (0=连载中, 1=完结) | |
| title: 标题关键词,可选 | |
| Returns: | |
| dict: API响应结果 | |
| """ | |
| controller = {} | |
| # 添加所有可选参数 | |
| if shortplay_ids: | |
| controller['shortplay_ids'] = shortplay_ids | |
| if category_ids: | |
| controller['category_ids'] = category_ids | |
| if lang: | |
| controller['lang'] = [lang] if isinstance(lang, str) else lang | |
| if voice_lang: | |
| controller['voice_lang'] = [voice_lang] if isinstance(voice_lang, str) else voice_lang | |
| if progress_state is not None: | |
| controller['progress_state'] = progress_state | |
| if title: | |
| controller['title'] = title | |
| page_info = { | |
| 'page': page, | |
| 'page_size': page_size | |
| } | |
| return self._make_request('file/list', controller=controller, page_info=page_info) | |
| def get_download_links(self, download_configs: List[Dict[str, Any]]) -> Dict[str, Any]: | |
| """ | |
| 获取下载链接 | |
| Args: | |
| download_configs: 下载配置列表 | |
| 格式: [{"file_id": 4028, "target_index": [1,2,3]}] | |
| Returns: | |
| 下载链接数据 | |
| """ | |
| controller = { | |
| "download_config": download_configs | |
| } | |
| return self._make_request("file/download", controller) | |
| def search_dramas_by_keyword(self, keyword: str, limit: int = 50) -> List[Dict[str, Any]]: | |
| """ | |
| 根据关键词搜索剧目 | |
| Args: | |
| keyword: 搜索关键词 | |
| limit: 返回数量限制 | |
| Returns: | |
| 匹配的剧目列表 | |
| """ | |
| result = self.get_drama_list(title=keyword, page_size=limit) | |
| if result.get("code") == "100" and result.get("data"): | |
| return result["data"] | |
| return [] | |
| def get_drama_by_categories(self, category_names: List[str]) -> List[Dict[str, Any]]: | |
| """ | |
| 根据分类名称获取剧目 | |
| Args: | |
| category_names: 分类名称列表,如["男频", "都市"] | |
| Returns: | |
| 匹配的剧目列表 | |
| """ | |
| # 先获取分类列表 | |
| categories_result = self.get_categories() | |
| if categories_result.get("code") != "100": | |
| return [] | |
| # 找到匹配的分类ID | |
| category_ids = [] | |
| for category in categories_result.get("data", []): | |
| for name in category_names: | |
| if name in category.get("name", ""): | |
| category_ids.append(category["id"]) | |
| break | |
| if not category_ids: | |
| return [] | |
| # 根据分类ID获取剧目 | |
| result = self.get_drama_list(category_ids=category_ids, page_size=200) | |
| if result.get("code") == "100" and result.get("data"): | |
| return result["data"] | |
| return [] | |
| def main(): | |
| """示例用法""" | |
| # 配置你的认证信息 | |
| USER_ID = 5000910 # 替换为你的user_id | |
| ROLE_ID = 5000910 # 替换为你的role_id | |
| SECURE_KEY = "4c237***********************************94e5133" # 替换为你的secure_key | |
| # 创建客户端 | |
| client = ByteDramaAPIClient(USER_ID, ROLE_ID, SECURE_KEY) | |
| print("=== 火山引擎短剧API测试 ===\n") | |
| # 1. 获取分类列表 | |
| print("1. 获取分类列表...") | |
| categories = client.get_categories() | |
| if categories.get("code") == "100": | |
| print(f"✅ 成功获取 {len(categories.get('data', []))} 个分类") | |
| # 显示前5个分类 | |
| for i, cat in enumerate(categories.get("data", [])[:5]): | |
| print(f" - {cat['name']} (ID: {cat['id']})") | |
| if len(categories.get("data", [])) > 5: | |
| print(f" ... 还有 {len(categories.get('data', [])) - 5} 个分类") | |
| else: | |
| print(f"❌ 获取分类失败: {categories}") | |
| print() | |
| # 2. 获取剧目列表 | |
| print("2. 获取剧目列表...") | |
| dramas = client.get_drama_list(page_size=5) # 只获取5个作为示例 | |
| if dramas.get("code") == "100": | |
| drama_list = dramas.get("data", []) | |
| print(f"✅ 成功获取 {len(drama_list)} 个剧目") | |
| for drama in drama_list: | |
| print(f" - {drama['title']} (ID: {drama['file_id']}, 共{drama['total']}集)") | |
| else: | |
| print(f"❌ 获取剧目失败: {dramas}") | |
| print() | |
| # 3. 搜索特定剧目 | |
| print("3. 搜索剧目...") | |
| search_results = client.search_dramas_by_keyword("妻子", limit=3) | |
| if search_results: | |
| print(f"✅ 找到 {len(search_results)} 个相关剧目") | |
| for drama in search_results: | |
| print(f" - {drama['title']} (ID: {drama['file_id']})") | |
| else: | |
| print("❌ 未找到相关剧目") | |
| if __name__ == "__main__": | |
| main() | |