Spaces:
Sleeping

bp_open_api / app.py
FrankSun82's picture
Upload app.py
babe482 verified
Raw History Blame Contribute Delete
21 kB
# -*- coding: utf-8 -*-
"""
BytePlus短剧API - 安全版本
支持动态凭据输入的Gradio界面
特性:
1. 页面直接输入API凭据,代码不包含敏感信息
2. 凭据验证功能,确保API可用
3. 批量处理,每批10个剧目,提高效率
4. 完全公开部署安全,凭据仅会话使用
"""
import gradio as gr
import pandas as pd
import json
import os
from typing import Dict, List, Any, Optional, Tuple, Generator
from bytedrama_api_client import ByteDramaAPIClient
from datetime import datetime
# 支持的语言列表
LANGUAGES = {
"简体中文": "zh_hans",
"繁体中文": "zh_hant",
"英语": "en",
"越南语": "vi",
"印尼语": "in",
"泰语": "th",
"韩语": "ko",
"葡萄牙语": "pt",
"西班牙语": "es",
"日语": "ja"
}
def chunked(lst: List[Any], n: int):
"""将列表分割成指定大小的块"""
for i in range(0, len(lst), n):
yield lst[i:i+n]
class SecureDramaProcessor:
"""安全短剧处理器 - 支持动态API凭据"""
def __init__(self, user_id, role_id, secure_key):
self.client = ByteDramaAPIClient(
user_id=user_id,
role_id=role_id,
secure_key=secure_key,
debug_mode=True
)
self.should_stop = False # 停止标志位
def stop_processing(self):
"""设置停止标志位"""
self.should_stop = True
@staticmethod
def test_credentials(user_id, role_id, secure_key):
"""测试API凭据是否有效"""
try:
# 验证输入不为空
if not all([user_id, role_id, secure_key]):
return "❌ 请填写所有API凭据字段"
# 转换为整数
user_id = int(user_id)
role_id = int(role_id)
test_client = ByteDramaAPIClient(
user_id=user_id,
role_id=role_id,
secure_key=secure_key,
debug_mode=False
)
# 尝试获取一页数据来测试凭据
response = test_client.get_drama_list(page=1, page_size=1, lang="zh_hans")
if response.get("code") in ["100", "ok", 100, 200]:
return "✅ API凭据验证成功!可以开始处理"
else:
return f"❌ API凭据无效: {response.get('message', '未知错误')}"
except ValueError as e:
return f"❌ User ID和Role ID必须是数字: {str(e)}"
except Exception as e:
return f"❌ API凭据验证失败: {str(e)}"
def transform_episode_links(self, api_response: List[Dict], indices: List[int]) -> Dict[int, Dict[int, str]]:
"""
将API响应转换为你原脚本的格式: {file_id: {index: play_url}}
"""
result = {}
wanted = set(indices)
for item in api_response or []:
fid = item.get('file_id')
if not fid:
continue
urls = {}
for ep in item.get('episode_list', []) or []:
idx = ep.get('index')
if idx in wanted:
urls[idx] = ep.get('play_url', '')
result[int(fid)] = urls
return result
def process_complete_workflow(self, language_name: str, episode_indices: str, progress=gr.Progress()) -> Generator[Tuple[str, str], None, None]:
"""
一步完成整个工作流程(批量处理版本)
"""
try:
# 解析集数索引 - 支持空值或0表示不获取播放链接
if not episode_indices or episode_indices.strip() == "" or episode_indices.strip() == "0":
indices = [] # 空列表表示不获取播放链接
else:
indices = [int(x.strip()) for x in episode_indices.split() if x.strip().isdigit()]
if not indices:
yield "❌ 请输入有效的集数索引,如: 1 2 3 4 5,或留空不获取播放链接", ""
return
language_code = LANGUAGES.get(language_name, "zh_hans")
# 步骤1: 获取剧目列表
yield "📋 正在获取剧目列表...", ""
all_dramas = []
page = 1
page_size = 100
while True:
yield f"📄 正在获取第 {page} 页剧目列表...", ""
response = self.client.get_drama_list(
page=page,
page_size=page_size,
lang=language_code
)
if response.get("code") in ["100", "ok", 100, 200]:
dramas = response.get("data", [])
if not dramas:
yield f"✅ 剧目列表获取完成,共 {len(all_dramas)} 部剧目", ""
break
all_dramas.extend(dramas)
yield f"📊 已获取 {len(all_dramas)} 部剧目,继续获取下一页...", ""
page += 1
# 如果本页数据少于页面大小,说明已经是最后一页
if len(dramas) < page_size:
break
else:
error_msg = response.get("message", "未知错误")
yield f"❌ API错误: {error_msg}", ""
return
if not all_dramas:
yield "📭 暂无剧目数据", ""
return
# 如果不需要获取播放链接,直接返回剧目列表
if not indices:
yield f"✅ 剧目列表获取完成,共 {len(all_dramas)} 部剧目(不获取播放链接)", ""
complete_json = json.dumps(all_dramas, ensure_ascii=False, indent=2)
yield f"🎉 完成!共获取 {len(all_dramas)} 部剧目信息", complete_json
return
yield f"✅ 剧目列表获取完成,共 {len(all_dramas)} 部剧目,开始批量获取播放链接...", ""
# 步骤2: 批量获取播放链接(每批10个剧目)
processed_dramas = []
file_ids = [d.get('file_id') for d in all_dramas if d.get('file_id')]
file_ids = [int(fid) for fid in file_ids]
batch_size = 10 # 每批处理10个剧目
total_batches = (len(file_ids) + batch_size - 1) // batch_size
# 收集所有批次的下载链接结果
all_drama_links = {} # {file_id: {index: play_url}}
for bi, batch in enumerate(chunked(file_ids, batch_size), start=1):
# 检查是否需要停止
if self.should_stop:
yield f"⏹️ 处理已停止,已完成 {bi-1}/{total_batches} 个批次", ""
return
yield f"🔗 [批次 {bi}/{total_batches}] 正在处理 {len(batch)} 个剧目...", ""
# 构建批量下载配置
download_configs = [{"file_id": fid, "target_index": indices} for fid in batch]
# 批量获取下载链接
response = self.client.get_download_links(download_configs)
if response.get("code") in ["100", "ok", 100, 200]:
download_list = response.get("data", [])
# 转换API响应为你原脚本的格式
batch_drama_links = self.transform_episode_links(download_list, indices)
# 将本批次结果添加到总结果中
all_drama_links.update(batch_drama_links)
yield f"✅ [批次 {bi}] 处理完成,成功获取 {len(batch_drama_links)} 个剧目的播放链接", ""
else:
error_msg = response.get("message", "未知错误")
yield f"⚠️ [批次 {bi}] 处理失败: {error_msg}", ""
# 所有批次完成后,合并结果到所有剧目
yield "📦 正在合并所有批次的播放链接...", ""
successful_dramas = 0
for i, drama in enumerate(all_dramas):
drama_id = drama.get("file_id")
if drama_id in all_drama_links:
drama_with_links = drama.copy()
drama_with_links["episode_play_urls"] = all_drama_links[drama_id]
processed_dramas.append(drama_with_links)
successful_dramas += 1
else:
# 即使获取链接失败,也保留剧目信息
drama_with_links = drama.copy()
drama_with_links["episode_play_urls"] = {}
processed_dramas.append(drama_with_links)
# 更新合并进度
if (i + 1) % 50 == 0 or i == len(all_dramas) - 1:
yield f"📦 合并进度: {i+1}/{len(all_dramas)} 部剧目", ""
# 步骤3: 生成完整JSON数据
yield "📦 正在生成完整JSON数据...", ""
complete_json = json.dumps(processed_dramas, ensure_ascii=False, indent=2)
yield f"🎉 全部完成!共处理 {len(processed_dramas)} 部剧目,其中 {successful_dramas} 部成功获取播放链接", complete_json
except Exception as e:
yield f"❌ 处理失败: {str(e)}", ""
def save_complete_data(self, complete_json: str, language_name: str) -> Tuple[str, str]:
"""
保存完整数据到文件
"""
try:
# 创建保存目录
save_dir = "data/json"
os.makedirs(save_dir, exist_ok=True)
# 生成文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{language_name}_dramas_{timestamp}.json"
filepath = os.path.join(save_dir, filename)
# 保存文件
with open(filepath, 'w', encoding='utf-8') as f:
f.write(complete_json)
# 返回绝对路径
abs_filepath = os.path.abspath(filepath)
return abs_filepath, f"✅ 文件已保存: {filename}"
except Exception as e:
return "", f"❌ 保存失败: {str(e)}"
def create_secure_interface():
"""创建安全的Gradio界面"""
# 自定义CSS
custom_css = """
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
margin-bottom: 20px;
}
.credentials-panel {
background: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
}
.process-panel {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 5px;
margin-bottom: 20px;
}
.process-panel h3 {
margin-top: 0;
margin-bottom: 15px;
}
/* 增加输入框的底部间距 */
.input-group {
margin-bottom: 15px !important;
}
/* 按钮组增加顶部间距 */
.btn-group {
margin-top: 20px !important;
}
.json-display {
font-family: 'Courier New', monospace;
font-size: 12px;
height: 500px !important; /* 固定高度 */
overflow-y: auto !important; /* 强制垂直滚动 */
border: 1px solid #dee2e6;
border-radius: 8px;
}
/* 强制Code组件内部滚动 */
.json-display .cm-editor {
height: 100% !important;
}
.json-display .cm-scroller {
overflow: auto !important;
}
.status-box {
background: #e3f2fd;
border: 1px solid #bbdefb;
border-radius: 8px;
padding: 15px;
font-family: 'Courier New', monospace;
font-size: 14px;
min-height: 60px;
display: flex;
align-items: center;
gap: 10px;
}
.loading-spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #f3f3f3;
border-top: 2px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.security-notice {
background: #d4edda;
border: 1px solid #c3e6cb;
border-radius: 8px;
padding: 15px;
margin-bottom: 20px;
color: #155724;
}
.error-box {
background: #f8d7da;
border: 1px solid #f5c6cb;
border-radius: 8px;
padding: 15px;
color: #721c24;
}
.input-panel {
padding-bottom: 30px !important; /* 强制底部留白 */
min-height: 500px !important; /* 强制最小高度 */
display: block !important; /* 确保块级显示 */
}
"""
with gr.Blocks(title="BytePlus短剧API") as demo:
# 创建共享的处理器状态
processor_state = gr.State(None)
# 使用equal_height=False允许各列自由高度
with gr.Row(equal_height=False):
# 左侧输入参数区域 (1/4宽度)
with gr.Column(scale=1, min_width=300, elem_classes=["input-panel"]):
gr.Markdown("### ⚙️ 输入参数")
user_id_input = gr.Textbox(
label="User ID",
placeholder="请输入你的User ID",
type="text",
elem_classes=["input-group"]
)
secure_key_input = gr.Textbox(
label="Security Key",
placeholder="请输入你的Security Key",
type="text",
lines=2,
elem_classes=["input-group"]
)
def trim_security_key(text):
"""自动处理Security Key的换行和空格"""
if text:
return text.strip().replace('\n', '').replace('\r', '')
return text
# 绑定Security Key的自动处理事件
secure_key_input.blur(
fn=trim_security_key,
inputs=[secure_key_input],
outputs=[secure_key_input]
)
language_dropdown = gr.Dropdown(
choices=list(LANGUAGES.keys()),
value="简体中文",
label="选择语言",
elem_classes=["input-group"]
)
episode_indices = gr.Textbox(
label="集数索引",
placeholder="留空或输入0表示不获取播放链接",
value="1 2 3 4 5",
elem_classes=["input-group"]
)
# 使用HTML组件增加内部间距
gr.HTML('<div style="margin-bottom: 20px;"></div>')
with gr.Row(elem_classes=["btn-group"]):
process_btn = gr.Button("🚀 开始批量处理", variant="primary")
stop_btn = gr.Button("⏹️ 停止处理", variant="stop", visible=False, interactive=True)
# 中间结果展示区域 (2/4宽度)
with gr.Column(scale=2, min_width=400):
gr.Markdown("### 📋 处理结果")
status_text = gr.HTML(
value='<div class="status-box">等待开始处理...</div>',
label="处理状态"
)
complete_json = gr.Code(
label="完整数据 (JSON格式)",
language="json",
interactive=False,
elem_classes=["json-display"],
visible=True
)
# 右侧下载区域 (1/4宽度)
with gr.Column(scale=1, min_width=250):
gr.Markdown("### 💾 下载文件")
download_btn = gr.Button("💾 生成并下载", variant="secondary", visible=False)
download_file = gr.File(label="下载文件", visible=True)
# 事件绑定
def process_workflow(user_id, secure_key, language_name, episode_indices, progress=gr.Progress()):
# 首先验证凭据
test_result = SecureDramaProcessor.test_credentials(user_id, user_id, secure_key)
if "✅" not in test_result:
yield f'<div class="status-box">❌ {test_result}</div>', "", gr.update(visible=False), gr.update(visible=True), gr.update(visible=False, interactive=False), None
return
# 创建处理器实例并重置停止标志
processor = SecureDramaProcessor(int(user_id), int(user_id), secure_key)
# 执行工作流程
for status, json_data in processor.process_complete_workflow(language_name, episode_indices, progress):
if json_data:
yield f'<div class="status-box">{status}</div>', json_data, gr.update(visible=True), gr.update(visible=False), gr.update(visible=False, interactive=False), processor
else:
yield f'<div class="status-box"><div class="loading-spinner"></div>{status}</div>', json_data, gr.update(visible=False), gr.update(visible=True), gr.update(visible=False, interactive=False), processor
def save_and_download(complete_json, language_name, user_id, secure_key):
if complete_json and user_id and secure_key:
processor = SecureDramaProcessor(int(user_id), int(user_id), secure_key)
filepath, status = processor.save_complete_data(complete_json, language_name)
return filepath, f'<div class="status-box">{status}</div>', gr.update(visible=True)
return "", f'<div class="status-box">❌ 没有数据可下载或凭据无效</div>', gr.update(visible=False)
def start_processing(user_id, secure_key, language_name, episode_indices):
# 简单检查输入不为空,具体验证移到处理流程中
if not all([user_id, secure_key]):
return gr.update(interactive=True), gr.update(visible=False), gr.update(visible=False, interactive=False)
return gr.update(interactive=False), gr.update(visible=True), gr.update(visible=True, interactive=True)
def stop_processing(processor):
if processor:
processor.stop_processing()
return gr.update(interactive=True), gr.update(visible=False), gr.update(visible=False, interactive=False), f'<div class="status-box">⏹️ 处理已停止</div>'
def processing_complete():
return gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True)
# 绑定事件
process_btn.click(
fn=start_processing,
inputs=[user_id_input, secure_key_input, language_dropdown, episode_indices],
outputs=[process_btn, stop_btn, download_btn]
).then(
fn=process_workflow,
inputs=[user_id_input, secure_key_input, language_dropdown, episode_indices],
outputs=[status_text, complete_json, download_btn, stop_btn, processor_state],
show_progress=True
).then(
fn=processing_complete,
outputs=[process_btn, stop_btn, download_btn]
)
stop_btn.click(
fn=stop_processing,
inputs=[processor_state],
outputs=[process_btn, stop_btn, download_btn, status_text]
)
download_btn.click(
fn=save_and_download,
inputs=[complete_json, language_dropdown, user_id_input, secure_key_input],
outputs=[download_file, status_text, download_btn]
)
return demo
if __name__ == "__main__":
demo = create_secure_interface()
demo.launch()