import gradio as gr import pandas as pd import requests import datetime import os import json import sys # ================= 🔧 核心配置 ================= FEISHU_APP_ID = "cli_a9bc5c7897f85cc6" FEISHU_APP_SECRET = "KAQWlr8qgkYMiC3nRrulBbNDWnlD5xGJ" DEFAULT_BASE_TOKEN = "SOgtbBGs9aibY5sSXsOcdwFlnzQ" DEFAULT_TABLE_ID = "tblwPQUD3MesubH5" # ================= 模块1:飞书数据引擎 ================= class FeishuEngine: def __init__(self): self.app_id = FEISHU_APP_ID self.app_secret = FEISHU_APP_SECRET def get_tenant_access_token(self): url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" req = {"app_id": self.app_id, "app_secret": self.app_secret} try: resp = requests.post(url, json=req, timeout=10).json() return resp.get("tenant_access_token", "") except Exception as e: print(f"飞书Token获取失败: {e}") return "" def fetch_base_records(self, app_token, table_id): token = self.get_tenant_access_token() if not token: return [], "❌ 飞书鉴权失败,请检查 App ID/Secret" url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records" headers = {"Authorization": f"Bearer {token}"} try: resp = requests.get(url, headers=headers, params={"page_size": 500}, timeout=20).json() if resp.get("code") == 0: return resp["data"].get("items", []), "ok" return [], f"飞书错误: {resp.get('msg')}" except Exception as e: return [], f"飞书网络异常: {str(e)}" # ================= 模块2:YouTube 深度引擎 ================= class YoutubeEngine: def __init__(self): self.api_url = "https://www.googleapis.com/youtube/v3" def fetch_channel_recent_data(self, channel_id, api_key): all_recent_videos = [] hot_videos = [] channel_info = {"title": "Unknown", "total_videos": 0} try: ch_url = f"{self.api_url}/channels" ch_res = requests.get(ch_url, params={ "part": "contentDetails,snippet,statistics", "id": channel_id, "key": api_key }, timeout=10).json() if "items" not in ch_res or not ch_res["items"]: return channel_info, [], [] item = ch_res["items"][0] channel_info["title"] = item["snippet"]["title"] channel_info["total_videos"] = int(item["statistics"].get("videoCount", 0)) upload_playlist_id = item["contentDetails"]["relatedPlaylists"]["uploads"] next_page_token = None for _ in range(5): pl_url = f"{self.api_url}/playlistItems" pl_res = requests.get(pl_url, params={ "part": "snippet,contentDetails", "playlistId": upload_playlist_id, "maxResults": 50, "pageToken": next_page_token, "key": api_key }, timeout=10).json() items = pl_res.get("items", []) if not items: break v_ids = [i["contentDetails"]["videoId"] for i in items] stats_url = f"{self.api_url}/videos" stats_res = requests.get(stats_url, params={ "part": "statistics,snippet", "id": ",".join(v_ids), "key": api_key }, timeout=10).json() for v in stats_res.get("items", []): if "statistics" not in v: continue views = int(v["statistics"].get("viewCount", 0)) raw_time = v["snippet"]["publishedAt"] date_str = raw_time[:10] time_str = raw_time.replace("T", " ").replace("Z", "")[:16] video_data = { "title": v["snippet"]["title"], "views": views, "url": f"https://www.youtube.com/watch?v={v['id']}", "channel": channel_info["title"], "time": time_str, "date": date_str } all_recent_videos.append(video_data) if views > 100: hot_videos.append(video_data) next_page_token = pl_res.get("nextPageToken") if not next_page_token: break return channel_info, all_recent_videos, hot_videos except Exception as e: print(f"Error fetching {channel_id}: {e}") return channel_info, [], [] # ================= 模块3:逻辑控制 (已添加去重逻辑) ================= class MCNController: def __init__(self): self.fs = FeishuEngine() self.yt = YoutubeEngine() def run_sync(self, app_token, table_id, progress=gr.Progress()): progress(0, desc="正在连接飞书...") records, msg = self.fs.fetch_base_records(app_token, table_id) if not records: return pd.DataFrame(), pd.DataFrame(), [], f"❌ 获取飞书数据失败: {msg}" # 数据容器 display_hot_videos = [] raw_stats_videos = [] channel_summary = [] # 【新增】:去重集合,用于记录已经处理过的 UC ID processed_ucs = set() total = len(records) for idx, item in enumerate(records): fields = item.get("fields", {}) def get_f(k): v = fields.get(k, "") if isinstance(v, list) and len(v) > 0: return str(v[0].get("text", v[0]) if isinstance(v[0], dict) else v[0]).strip() return str(v).strip() acc_id = get_f("账号id") uc_id = get_f("UC") api_key = get_f("API") # --- 【核心修改:去重逻辑】 --- if not uc_id: continue # 跳过空行 if uc_id in processed_ucs: print(f"⚠️ 跳过重复账号: {acc_id} ({uc_id})") continue # 如果已经处理过这个 UC,直接跳到下一个 processed_ucs.add(uc_id) # 记录该 UC 已处理 # --------------------------- progress((idx + 1) / total, desc=f"正在扫描: {acc_id}") if uc_id.startswith("UC") and len(api_key) > 10: info, all_v, hot_v = self.yt.fetch_channel_recent_data(uc_id, api_key) raw_stats_videos.extend(all_v) display_hot_videos.extend(hot_v) channel_summary.append({ "📺 频道名称": acc_id, "📹 历史总发片量": info["total_videos"], "🕵️ 近期扫描数": len(all_v), "🔥 爆款数(>100)": len(hot_v), "🔗 链接": f"https://www.youtube.com/channel/{uc_id}" }) else: channel_summary.append({ "📺 频道名称": f"{acc_id} (无效)", "📹 历史总发片量": 0, "🕵️ 近期扫描数": 0, "🔥 爆款数(>100)": 0, "🔗 链接": "配置错误" }) daily_df = pd.DataFrame() if raw_stats_videos: df_all = pd.DataFrame(raw_stats_videos) daily_counts = df_all.groupby('date').size().reset_index(name='发布数量') daily_df = daily_counts.sort_values('date', ascending=False) daily_df.columns = ["📅 日期", "📝 当日总发布数(所有账号)"] display_hot_videos = sorted(display_hot_videos, key=lambda x: x['time'], reverse=True) return pd.DataFrame(channel_summary), daily_df, display_hot_videos, f"✅ 扫描完成 (共处理 {len(processed_ucs)} 个唯一账号)" controller = MCNController() # ================= UI 布局 (保持不变) ================= def ui_run_sync(token, table): try: df_channels, df_daily, hot_videos, msg = controller.run_sync(token, table) if df_channels.empty: return df_channels, df_daily, msg, "