Download app.py from elelabc/yt: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/elelabc/yt/resolve/main/app.py
- Command line
-
hf download hf://spaces/elelabc/yt/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elelabc/yt/resolve/main/app.py
11.7 kB
| 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, "<div>无数据</div>" | |
| hot_html = f""" | |
| <div class="hot-container"> | |
| <div class="hot-header">🔥 爆款视频列表 (播放 > 100) - {len(hot_videos)} 条</div> | |
| <div class="hot-scroll"> | |
| """ | |
| for v in hot_videos: | |
| hot_html += f""" | |
| <div class="video-row"> | |
| <span class="v-time">{v['time']}</span> | |
| <span class="v-views">👁️ {v['views']:,}</span> | |
| <span class="v-channel">[{v['channel']}]</span> | |
| <a href="{v['url']}" target="_blank" class="v-link">{v['title']}</a> | |
| </div> | |
| """ | |
| hot_html += "</div></div>" | |
| return df_channels, df_daily, f"{msg} - {datetime.datetime.now().strftime('%H:%M:%S')}", hot_html | |
| except Exception as e: | |
| return pd.DataFrame(), pd.DataFrame(), f"❌ 错误: {e}", "" | |
| custom_css = """ | |
| <style> | |
| .hot-container { background: #fff1f0; border: 2px solid #ffccc7; border-radius: 12px; padding: 15px; margin-bottom: 25px; } | |
| .hot-header { color: #cf1322; font-size: 1.2rem; font-weight: bold; margin-bottom: 15px; border-bottom: 2px solid #ffccc7; padding-bottom: 8px; } | |
| .hot-scroll { max-height: 500px; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; } | |
| .video-row { background: white; padding: 8px 15px; border-radius: 6px; border-left: 5px solid #cf1322; display: flex; align-items: center; gap: 12px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); } | |
| .v-time { color: #8c8c8c; font-family: monospace; font-size: 0.85rem; min-width: 120px; } | |
| .v-views { color: #cf1322; font-weight: bold; min-width: 80px; text-align: right; } | |
| .v-channel { color: #595959; font-size: 0.8rem; min-width: 100px; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | |
| .v-link { color: #262626; text-decoration: none; font-weight: 500; flex-grow: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | |
| .v-link:hover { color: #cf1322; text-decoration: underline; } | |
| </style> | |
| """ | |
| with gr.Blocks(title="MCN看板") as app: | |
| gr.HTML(custom_css) | |
| gr.Markdown("# 🚀 YouTube MCN 深度数据看板") | |
| with gr.Accordion("⚙️ 系统配置", open=False): | |
| with gr.Row(): | |
| t_token = gr.Textbox(label="Base Token", value=DEFAULT_BASE_TOKEN) | |
| t_table = gr.Textbox(label="Table ID", value=DEFAULT_TABLE_ID) | |
| btn = gr.Button("🔄 立即同步数据", variant="primary") | |
| status = gr.Textbox(label="状态", show_label=False) | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| gr.Markdown("### 📊 账号维度统计") | |
| table_channels = gr.DataFrame(interactive=False) | |
| with gr.Column(scale=2): | |
| gr.Markdown("### 📅 每日总发布量 (近5页视频统计)") | |
| table_daily = gr.DataFrame(interactive=False) | |
| gr.Markdown("### 🔥 爆款视频监控 (播放量 > 100)") | |
| hot_display = gr.HTML() | |
| btn.click(ui_run_sync, [t_token, t_table], [table_channels, table_daily, status, hot_display]) | |
| if __name__ == "__main__": | |
| app.launch() |