Spaces:
Sleeping
Sleeping
Delete gradio_drama_secure.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510# -*- coding: utf-8 -*-"""BytePlus短剧API - 安全版本支持动态凭据输入的Gradio界面
特性:1. 页面直接输入API凭据,代码不包含敏感信息2. 凭据验证功能,确保API可用3. 批量处理,每批10个剧目,提高效率4. 完全公开部署安全,凭据仅会话使用"""
import gradio as grimport pandas as pdimport jsonimport osfrom typing import Dict, List, Any, Optional, Tuple, Generatorfrom bytedrama_api_client import ByteDramaAPIClientfrom datetime import datetime
# 支持的语言列表LANGUAGES = { "简体中文": "zh_hans", "繁体中文": "zh_hant", "英语": "en", "越南语": "vi", "印尼语": "in", "泰语": "th", "韩语": "ko", "葡萄牙语": "pt", "西班牙语": "es"}
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: 20px; margin-bottom: 20px; } .process-panel h3 { margin-top: 0; margin-bottom: 15px; } .json-display { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; font-family: 'Courier New', monospace; font-size: 12px; max-height: 300px; overflow-y: auto; } .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; } """ with gr.Blocks(title="BytePlus短剧API", css=custom_css, theme=gr.themes.Soft()) as demo: # 创建共享的处理器状态 processor_state = gr.State(None) with gr.Row(): # 左侧输入参数区域 (1/4宽度) with gr.Column(scale=1): gr.HTML(""" <div class="process-panel"> <h3>⚙️ 输入参数</h3> </div> """) user_id_input = gr.Textbox( label="User ID", placeholder="请输入你的User ID", type="text" ) secure_key_input = gr.Textbox( label="Security Key", placeholder="请输入你的Security Key", type="text", lines=2 ) 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="选择语言" ) episode_indices = gr.Textbox( label="集数索引", placeholder="留空或输入0表示不获取播放链接,如: 1 2 3 4 5", value="1 2 3 4 5" ) with gr.Row(): process_btn = gr.Button("🚀 开始批��处理", variant="primary") stop_btn = gr.Button("⏹️ 停止处理", variant="stop", visible=False, interactive=True) download_btn = gr.Button("💾 下载完整JSON", variant="secondary", visible=False) download_file = gr.File(label="下载文件", visible=True) # 右侧结果展示区域 (3/4宽度) with gr.Column(scale=3): gr.HTML(""" <div class="process-panel"> <h3>📋 处理结果</h3> </div> """) 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 ) # 事件绑定 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( share=False, # 可以设置为True,因���凭据是动态输入的 server_name="127.0.0.1", server_port=7871, theme=gr.themes.Soft(), css=demo.css )gradio_drama_secure.pyDeleted-510