Spaces:
Runtime error
Runtime error
Download app.py from CLASSZhao2653/yahoo_2_test: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/spaces/CLASSZhao2653/yahoo_2_test/resolve/main/app.py
- Command line
-
hf download hf://spaces/CLASSZhao2653/yahoo_2_test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/CLASSZhao2653/yahoo_2_test/resolve/main/app.py
18.7 kB
| """ | |
| 霸王猫自动化控制台 - Gradio 前端 (支持多账号与多地址自由切换) | |
| """ | |
| import gradio as gr | |
| import pandas as pd | |
| from datetime import datetime, timezone, timedelta | |
| from config_manager import ( | |
| load_accounts, save_accounts, | |
| load_locations, save_locations, load_location | |
| ) | |
| from brm_api import BrmApi | |
| from sniper_engine import GLOBAL_ENGINE, append_log, get_recent_logs, clear_logs | |
| from brm_cipher import CIPHER | |
| BJ_TZ = timezone(timedelta(hours=8)) | |
| # 内存缓存当前爬取的店铺数据 | |
| CURRENT_SHOPS_CACHE = [] | |
| def get_current_api(account_name): | |
| accs = load_accounts() | |
| if account_name not in accs: | |
| return None | |
| cred = accs[account_name] | |
| return BrmApi(cred.get("authorization", ""), cred.get("tokenid", "")) | |
| # ---------- 下拉与状态联动 ---------- | |
| def refresh_accounts_dropdown(): | |
| accs = load_accounts() | |
| names = list(accs.keys()) | |
| return gr.update(choices=names, value=names[0] if names else None) | |
| def refresh_locations_dropdown(): | |
| locs = load_locations() | |
| names = list(locs.keys()) | |
| return gr.update(choices=names, value=names[0] if names else None) | |
| def fetch_user_card(account_name): | |
| if not account_name: | |
| return "⚠️ 未选择账号" | |
| api = get_current_api(account_name) | |
| if not api: | |
| return "⚠️ 凭据获取失败" | |
| succ, info = api.get_user_info() | |
| if succ: | |
| return ( | |
| f"### 👤 当前账号: **{account_name}**\n" | |
| f"- **绑定手机**: `{info['phone']}`\n" | |
| f"- **平台余额**: <span style='color:red;font-size:18px;'>¥{info['balance']:.2f}</span>\n" | |
| f"- **累计收益**: ¥{info['earnings']:.2f} | **信用分**: {info['score']}" | |
| ) | |
| return f"❌ 账号状态异常: {info}" | |
| def handle_search(account_name, loc_name, keyword, platform, max_pages): | |
| global CURRENT_SHOPS_CACHE | |
| api = get_current_api(account_name) | |
| if not api: | |
| return pd.DataFrame(), gr.update(choices=[]) | |
| loc_info = load_location(loc_name) | |
| if not loc_info: | |
| append_log("⚠️ 未获取到有效地址配置,请先在设置页添加地址!") | |
| return pd.DataFrame(), gr.update(choices=[]) | |
| max_pages = int(max_pages) | |
| city_name = loc_info.get("cityName", "未知") | |
| append_log(f"🔍 正在爬取店铺列表 [地址: {loc_name}({city_name})] (关键词: '{keyword}', 平台: '{platform or '全部'}', 深度: 前 {max_pages} 页)...") | |
| # 传入动态选定的 loc_info | |
| succ, shops = api.search_shops(keyword=keyword, platform=platform, page=1, page_size=10, max_pages=max_pages, loc_info=loc_info) | |
| if not succ: | |
| append_log(f"❌ 拉取失败: {shops}") | |
| return pd.DataFrame(), gr.update(choices=[]) | |
| CURRENT_SHOPS_CACHE = shops | |
| append_log(f"✅ 成功聚合加载了 {len(shops)} 家可用店铺!") | |
| df = pd.DataFrame(shops) | |
| choices = [f"[{s['平台']}] {s['店铺名称']} (返¥{s['返利']}|ID:{s['活动ID']})" for s in shops] | |
| return df, gr.update(choices=choices, value=choices[0] if choices else None) | |
| def handle_shop_selected(selected_str): | |
| if not selected_str or not CURRENT_SHOPS_CACHE: | |
| return "", "", "" | |
| try: | |
| act_id = selected_str.split("ID:")[-1].replace(")", "").strip() | |
| matched = next((s for s in CURRENT_SHOPS_CACHE if s["活动ID"] == act_id), None) | |
| if matched: | |
| info_text = f"🎯 已选定目标: **{matched['店铺名称']}** | 门槛: ¥{matched['门槛']} | 返利: ¥{matched['返利']} | 库存: {matched['剩余库存']}" | |
| return act_id, matched['店铺名称'], info_text | |
| except Exception: | |
| pass | |
| return "", "", "" | |
| def handle_fire_action(account_name, activity_id, shop_name, action_mode, target_time, retries): | |
| if not activity_id: | |
| return "⚠️ 请先在上方表格或下拉框中选择要抢的店铺!" | |
| api = get_current_api(account_name) | |
| if not api: | |
| return "⚠️ 账号无效" | |
| if action_mode == "立即抢单": | |
| succ, msg = GLOBAL_ENGINE.flash_fire_once(api, activity_id, shop_name) | |
| return f"{'✅ 成功' if succ else '❌ 失败'}: {msg}" | |
| else: | |
| if not target_time: | |
| return "⚠️ 请填写预约开抢时间 (格式如 10:00:00)" | |
| task_id = GLOBAL_ENGINE.schedule_fire(api, activity_id, shop_name, target_time, int(retries)) | |
| return f"⏰ 定时任务安放成功!任务ID: {task_id} (将在 {target_time} 准时开火)" | |
| # ---------- 账号管理逻辑 ---------- | |
| def handle_add_account(name, auth, tokenid): | |
| if not name or not auth or not tokenid: | |
| return "⚠️ 账号名称与 Token 不能为空", refresh_accounts_dropdown() | |
| accs = load_accounts() | |
| accs[name] = {"authorization": auth.strip(), "tokenid": tokenid.strip()} | |
| save_accounts(accs) | |
| return f"✅ 账号 [{name}] 保存成功", refresh_accounts_dropdown() | |
| def handle_delete_account(name): | |
| accs = load_accounts() | |
| if name in accs: | |
| del accs[name] | |
| save_accounts(accs) | |
| return f"✅ 账号 [{name}] 已删除", refresh_accounts_dropdown() | |
| return "⚠️ 账号不存在", refresh_accounts_dropdown() | |
| # ---------- 多地址管理逻辑 ---------- | |
| def handle_save_location(alias, city, raw_lat, raw_lon): | |
| alias = (alias or "").strip() | |
| city = (city or "").strip() | |
| raw_lat = (raw_lat or "").strip() | |
| raw_lon = (raw_lon or "").strip() | |
| if not alias: | |
| return "⚠️ 地址备注名称不能为空 (例如: 锦州家里、乌鲁木齐公司)!", "", "", "", refresh_locations_dropdown(), refresh_locations_dropdown() | |
| if not city or not raw_lat or not raw_lon: | |
| return "⚠️ 城市名称与经纬度均不能为空!", "", "", "", refresh_locations_dropdown(), refresh_locations_dropdown() | |
| try: | |
| enc_lat, enc_lng, sign = CIPHER.calc_location_and_sign(raw_lat, raw_lon) | |
| except Exception as e: | |
| return f"❌ 坐标加密计算失败: {e}", "", "", "", refresh_locations_dropdown(), refresh_locations_dropdown() | |
| locs = load_locations() | |
| locs[alias] = { | |
| "cityName": city, | |
| "raw_lat": raw_lat, | |
| "raw_lng": raw_lon, | |
| "latitude": enc_lat, | |
| "longitude": enc_lng, | |
| "sign": sign | |
| } | |
| save_locations(locs) | |
| msg = f"✅ 地址 **[{alias}]** 已保存!算法已生成最新签名密文。" | |
| top_dd = refresh_locations_dropdown() | |
| edit_dd = refresh_locations_dropdown() | |
| return msg, enc_lat, enc_lng, sign, top_dd, edit_dd | |
| def handle_delete_location(alias): | |
| locs = load_locations() | |
| if alias in locs: | |
| del locs[alias] | |
| save_locations(locs) | |
| msg = f"✅ 地址 [{alias}] 已成功删除!" | |
| else: | |
| msg = "⚠️ 地址不存在!" | |
| top_dd = refresh_locations_dropdown() | |
| edit_dd = refresh_locations_dropdown() | |
| return msg, top_dd, edit_dd | |
| def handle_load_location_details(alias): | |
| """在设置页面中切换查看已有地址时,自动回填输入框""" | |
| if not alias: | |
| return "", "", "", "", "", "" | |
| loc = load_location(alias) | |
| if not loc: | |
| return alias, "", "", "", "", "" | |
| return ( | |
| alias, | |
| loc.get("cityName", ""), | |
| loc.get("raw_lat", ""), | |
| loc.get("raw_lng", ""), | |
| loc.get("latitude", ""), | |
| loc.get("longitude", ""), | |
| loc.get("sign", "") | |
| ) | |
| def get_tasks_df(): | |
| tasks = GLOBAL_ENGINE.list_tasks() | |
| return pd.DataFrame(tasks) if tasks else pd.DataFrame(columns=["任务ID", "店铺名称", "活动ID", "预定开抢时间"]) | |
| def handle_cancel_task(task_id): | |
| if not task_id: | |
| return "⚠️ 请输入要取消的任务ID", get_tasks_df() | |
| succ = GLOBAL_ENGINE.cancel_task(task_id) | |
| return ("✅ 取消成功" if succ else "❌ 未找到对应任务"), get_tasks_df() | |
| # ---------- Gradio UI 布局 ---------- | |
| def create_ui(): | |
| locs = load_locations() | |
| init_loc_names = list(locs.keys()) | |
| default_loc_name = init_loc_names[0] if init_loc_names else None | |
| default_loc = locs.get(default_loc_name, {}) | |
| accs = load_accounts() | |
| init_acc_names = list(accs.keys()) | |
| with gr.Blocks(title="霸王猫极速抢单系统") as demo: | |
| gr.Markdown("# 🐱 霸王猫外卖返利 - 极速抢付终端") | |
| # 顶部全局控制区:账号与地址自由切换 | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| acc_dropdown = gr.Dropdown( | |
| label="👤 当前操作账号", | |
| choices=init_acc_names, | |
| value=init_acc_names[0] if init_acc_names else None, | |
| interactive=True | |
| ) | |
| with gr.Column(scale=2): | |
| loc_dropdown = gr.Dropdown( | |
| label="📍 当前所在地址 (搜索定位将使用此项)", | |
| choices=init_loc_names, | |
| value=default_loc_name, | |
| interactive=True | |
| ) | |
| with gr.Column(scale=3): | |
| user_card_md = gr.Markdown(value="正在读取账号状态...") | |
| acc_dropdown.change(fetch_user_card, inputs=[acc_dropdown], outputs=[user_card_md]) | |
| demo.load(fetch_user_card, inputs=[acc_dropdown], outputs=[user_card_md]) | |
| with gr.Tabs(): | |
| # ================= TAB 1: 选店与下单 ================= | |
| with gr.Tab("🏬 爬取店铺与下单"): | |
| with gr.Row(): | |
| search_kw = gr.Textbox(label="店铺名称搜索", placeholder="输入关键词 (留空默认拉取周边推荐)", scale=3) | |
| platform_sel = gr.Dropdown( | |
| label="平台筛选", | |
| choices=[("全部", ""), ("美团", "1"), ("饿了么/淘宝", "2"), ("美团闪购", "5")], | |
| value="", | |
| scale=2 | |
| ) | |
| page_slider = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="连续抓取页数 (每页10家)", scale=2) | |
| btn_search = gr.Button("📡 立即拉取/刷新店铺", variant="primary", scale=2) | |
| shops_table = gr.Dataframe(label="可抢店铺池", interactive=False) | |
| gr.Markdown("---") | |
| gr.Markdown("### 🎯 目标发射阵地") | |
| with gr.Row(): | |
| target_dropdown = gr.Dropdown(label="快捷选择目标店铺", choices=[], interactive=True) | |
| target_act_id = gr.Textbox(label="活动 Activity ID (自动填入/可手动输入)", interactive=True) | |
| target_shop_name = gr.Textbox(label="店铺名称", interactive=False) | |
| shop_info_badge = gr.Markdown("💡 请在上方拉取并选定店铺") | |
| target_dropdown.change( | |
| handle_shop_selected, | |
| inputs=[target_dropdown], | |
| outputs=[target_act_id, target_shop_name, shop_info_badge] | |
| ) | |
| with gr.Row(): | |
| action_mode = gr.Radio(["立即抢单", "定时抢单"], label="抢单模式", value="立即抢单") | |
| default_time = (datetime.now(BJ_TZ) + timedelta(minutes=5)).strftime("%H:%M:00") | |
| target_time_input = gr.Textbox(label="开抢时间点 (精确到秒)", value=default_time) | |
| retries_input = gr.Number(label="齐射次数", value=5, precision=0) | |
| btn_fire = gr.Button("🔥 启动打击指令 (抢占 + 自动余额扣款)", variant="stop") | |
| fire_result_msg = gr.Markdown() | |
| btn_search.click( | |
| handle_search, | |
| inputs=[acc_dropdown, loc_dropdown, search_kw, platform_sel, page_slider], | |
| outputs=[shops_table, target_dropdown] | |
| ) | |
| btn_fire.click( | |
| handle_fire_action, | |
| inputs=[acc_dropdown, target_act_id, target_shop_name, action_mode, target_time_input, retries_input], | |
| outputs=[fire_result_msg] | |
| ) | |
| # ================= TAB 2: 任务大厅与日志 ================= | |
| with gr.Tab("⏱️ 预约大厅与黑匣子"): | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| gr.Markdown("#### 📋 正在潜伏的定时狙击任务") | |
| tasks_df_ui = gr.Dataframe(value=get_tasks_df(), interactive=False) | |
| with gr.Row(): | |
| cancel_tid_input = gr.Textbox(label="任务ID", placeholder="粘贴要取消的任务ID") | |
| btn_cancel_task = gr.Button("🛑 取消该任务", variant="secondary") | |
| btn_refresh_tasks = gr.Button("🔄 刷新任务列表") | |
| btn_refresh_tasks.click(get_tasks_df, outputs=[tasks_df_ui]) | |
| btn_cancel_task.click(handle_cancel_task, inputs=[cancel_tid_input], outputs=[fire_result_msg, tasks_df_ui]) | |
| with gr.Column(scale=3): | |
| gr.Markdown("#### 📜 实时运行日志 (每秒自动推流)") | |
| log_box = gr.Textbox(lines=14, label="系统控制台输出", value=get_recent_logs(), autoscroll=True) | |
| btn_clear_log = gr.Button("清空终端窗口") | |
| timer = gr.Timer(1.0) | |
| timer.tick(get_recent_logs, outputs=[log_box]) | |
| btn_clear_log.click(clear_logs, outputs=[log_box]) | |
| # ================= TAB 3: 多账号与多地址配置 ================= | |
| with gr.Tab("⚙️ 多账号与多地址设置"): | |
| # ---------- 账号池 ---------- | |
| gr.Markdown("### 👥 账号池管理") | |
| with gr.Row(): | |
| new_acc_name = gr.Textbox(label="账号备注名称 (如: 主号-4018)") | |
| new_auth = gr.Textbox(label="Authorization", type="password") | |
| new_tokenid = gr.Textbox(label="Tokenid", type="password") | |
| with gr.Row(): | |
| btn_add_acc = gr.Button("➕ 添加 / 更新账号", variant="primary") | |
| btn_del_acc = gr.Button("🗑️ 删除当前选中账号", variant="secondary") | |
| acc_manage_msg = gr.Markdown() | |
| btn_add_acc.click( | |
| handle_add_account, | |
| inputs=[new_acc_name, new_auth, new_tokenid], | |
| outputs=[acc_manage_msg, acc_dropdown] | |
| ) | |
| btn_del_acc.click( | |
| handle_delete_account, | |
| inputs=[acc_dropdown], | |
| outputs=[acc_manage_msg, acc_dropdown] | |
| ) | |
| gr.Markdown("---") | |
| # ---------- 多地址池 ---------- | |
| gr.Markdown("### 🌍 多地址定位库管理 (`location_config.json`)") | |
| gr.Markdown("<small style='color: gray;'>你可以保存多个常用地址(例如:锦州家里、沈阳公司、乌鲁木齐等)。在上方下拉框或此处自由切换,系统将自动使用对应位置进行周边店铺扫描。</small>") | |
| with gr.Row(): | |
| loc_picker = gr.Dropdown( | |
| label="📂 快速载入已有地址进行编辑/查看", | |
| choices=init_loc_names, | |
| value=default_loc_name, | |
| interactive=True | |
| ) | |
| with gr.Row(): | |
| loc_alias = gr.Textbox(label="地址备注名称", placeholder="例如: 锦州-家里 / 乌鲁木齐-公司", value=default_loc_name or "", scale=2) | |
| loc_city = gr.Textbox(label="所属城市 (cityName)", value=default_loc.get("cityName", "锦州"), scale=2) | |
| loc_lat = gr.Textbox(label="真实纬度 (latitude)", placeholder="例如: 41.123200", value=default_loc.get("raw_lat", ""), scale=2) | |
| loc_lon = gr.Textbox(label="真实经度 (longitude)", placeholder="例如: 121.134543", value=default_loc.get("raw_lng", ""), scale=2) | |
| with gr.Row(): | |
| enc_lat_preview = gr.Textbox(label="计算出的纬度密文", value=default_loc.get("latitude", ""), interactive=False) | |
| enc_lon_preview = gr.Textbox(label="计算出的经度密文", value=default_loc.get("longitude", ""), interactive=False) | |
| enc_sign_preview = gr.Textbox(label="计算出的 Sign 签名", value=default_loc.get("sign", ""), interactive=False) | |
| with gr.Row(): | |
| btn_save_loc = gr.Button("💾 保存/更新该地址", variant="primary") | |
| btn_del_loc = gr.Button("🗑️ 删除该地址", variant="secondary") | |
| loc_manage_msg = gr.Markdown() | |
| # 选择地址时回显输入框 | |
| loc_picker.change( | |
| handle_load_location_details, | |
| inputs=[loc_picker], | |
| outputs=[loc_alias, loc_city, loc_lat, loc_lon, enc_lat_preview, enc_lon_preview, enc_sign_preview] | |
| ) | |
| # 保存地址 | |
| btn_save_loc.click( | |
| handle_save_location, | |
| inputs=[loc_alias, loc_city, loc_lat, loc_lon], | |
| outputs=[loc_manage_msg, enc_lat_preview, enc_lon_preview, enc_sign_preview, loc_dropdown, loc_picker] | |
| ) | |
| # 删除地址 | |
| btn_del_loc.click( | |
| handle_delete_location, | |
| inputs=[loc_alias], | |
| outputs=[loc_manage_msg, loc_dropdown, loc_picker] | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| app = create_ui() | |
| try: | |
| app.launch(server_name="0.0.0.0", server_port=7862, share=False, theme=gr.themes.Soft()) | |
| except TypeError: | |
| app.launch(server_name="0.0.0.0", server_port=7862, share=False) |