import streamlit as st import sqlite3 import pandas as pd import math # ================= 1. 页面基础配置 ================= st.set_page_config( page_title="YouTube 数据看板", layout="wide", initial_sidebar_state="collapsed" ) st.title("📺 YouTube 汇总频道数据监控") DB_FILE = 'youtube_data.db' # ================= 2. 初始化 Session State ================= if 'current_page' not in st.session_state: st.session_state.current_page = 1 if 'page_size' not in st.session_state: st.session_state.page_size = 100 if 'sort_field' not in st.session_state: st.session_state.sort_field = 'date' if 'sort_order' not in st.session_state: st.session_state.sort_order = 'DESC' if 'filter_channel' not in st.session_state: st.session_state.filter_channel = '全部频道' # 🔥 新增:备注筛选状态 if 'filter_note' not in st.session_state: st.session_state.filter_note = '全部数据' if 'search_keyword' not in st.session_state: st.session_state.search_keyword = '' # ================= 3. 数据库操作函数 (升级版) ================= def get_all_channels(): """获取所有频道名称""" try: conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("SELECT DISTINCT channel FROM videos") channels = [row[0] for row in cursor.fetchall() if row[0]] conn.close() return ['全部频道'] + channels except: return ['全部频道'] def build_where_clause(channel_filter, note_filter, keyword): """🔥 动态构建 SQL 的 WHERE 语句 (增加了 note_filter)""" conditions = [] params = [] # 1. 频道筛选 if channel_filter != '全部频道': conditions.append("channel = ?") params.append(channel_filter) # 2. 🔥 备注筛选 (核心修改) if note_filter == '只看新增': conditions.append("note = '新增'") # 3. 关键词搜索 if keyword: keyword_str = f"%{keyword}%" conditions.append("(title LIKE ? OR date LIKE ? OR crawled_at LIKE ?)") params.extend([keyword_str, keyword_str, keyword_str]) where_sql = " WHERE " + " AND ".join(conditions) if conditions else "" return where_sql, params def get_total_count(channel_filter, note_filter, keyword): """获取总条数""" try: conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() # 传入 note_filter where_sql, params = build_where_clause(channel_filter, note_filter, keyword) cursor.execute(f"SELECT COUNT(*) FROM videos {where_sql}", params) count = cursor.fetchone()[0] conn.close() return count except: return 0 def load_data(page, page_size, sort_field, sort_order, channel_filter, note_filter, keyword): """加载数据""" offset = (page - 1) * page_size try: conn = sqlite3.connect(DB_FILE) # 传入 note_filter where_sql, params = build_where_clause(channel_filter, note_filter, keyword) # ✅ 记得查出 note 列 query = f""" SELECT url, url as link_url, channel, title, date, duration, views, crawled_at, note FROM videos {where_sql} ORDER BY {sort_field} {sort_order} LIMIT {page_size} OFFSET {offset} """ df = pd.read_sql_query(query, conn, params=params) conn.close() return df except Exception as e: st.error(f"读取数据库出错: {e}") return pd.DataFrame() # ================= 4. 顶部筛选与排序区 (布局升级) ================= st.markdown("### 🔍 数据筛选") # 🔥 修改:分成 3 列,中间放备注筛选 f1, f2, f3 = st.columns([1, 1, 2]) with f1: all_channels = get_all_channels() try: idx = all_channels.index(st.session_state.filter_channel) except: idx = 0 selected_channel = st.selectbox("选择频道", options=all_channels, index=idx) if selected_channel != st.session_state.filter_channel: st.session_state.filter_channel = selected_channel st.session_state.current_page = 1 st.rerun() with f2: # 🔥 新增:备注筛选下拉框 note_options = ["全部数据", "只看新增"] try: note_idx = note_options.index(st.session_state.filter_note) except: note_idx = 0 selected_note = st.selectbox("状态筛选", options=note_options, index=note_idx) if selected_note != st.session_state.filter_note: st.session_state.filter_note = selected_note st.session_state.current_page = 1 # 筛选变了,重置页码 st.rerun() with f3: search_input = st.text_input( "关键词搜索 (支持搜标题 / 日期)", value=st.session_state.search_keyword ) if search_input != st.session_state.search_keyword: st.session_state.search_keyword = search_input st.session_state.current_page = 1 st.rerun() st.divider() # 第二行:排序器 s1, s2, s3 = st.columns([1, 1, 6]) with s1: sort_mapping = { "🔥 播放量": "views", "📅 发布日期": "date", "⏰ 视频时长": "duration", "🕷️ 抓取时间": "crawled_at" } selected_sort_label = st.selectbox( "全局排序依据", options=list(sort_mapping.keys()), index=0 if st.session_state.sort_field == 'views' else 1 ) new_sort_field = sort_mapping[selected_sort_label] if new_sort_field != st.session_state.sort_field: st.session_state.sort_field = new_sort_field st.session_state.current_page = 1 st.rerun() with s2: order_mapping = { "⬇️ 从高到低": "DESC", "⬆️ 从低到高": "ASC" } selected_order_label = st.selectbox( "排序方式", options=list(order_mapping.keys()), index=0 if st.session_state.sort_order == 'DESC' else 1 ) new_order = order_mapping[selected_order_label] if new_order != st.session_state.sort_order: st.session_state.sort_order = new_order st.session_state.current_page = 1 st.rerun() # ================= 5. 数据加载逻辑 ================= # 获取总数 (传入 filter_note) total_rows = get_total_count( st.session_state.filter_channel, st.session_state.filter_note, # ✅ 传入 st.session_state.search_keyword ) # 计算分页 total_pages = math.ceil(total_rows / st.session_state.page_size) if total_pages == 0: total_pages = 1 if st.session_state.current_page > total_pages: st.session_state.current_page = total_pages # 加载数据 (传入 filter_note) df = load_data( st.session_state.current_page, st.session_state.page_size, st.session_state.sort_field, st.session_state.sort_order, st.session_state.filter_channel, st.session_state.filter_note, # ✅ 传入 st.session_state.search_keyword ) # ================= 6. 表格展示区 ================= if not df.empty: st.dataframe( df, use_container_width=True, hide_index=True, height=600, column_config={ "url": st.column_config.TextColumn("原始链接", width="medium", help="复制此链接"), "link_url": st.column_config.LinkColumn("跳转", display_text="点击观看 ▶️", width="small"), "channel": st.column_config.TextColumn("频道名称", width="medium"), "title": st.column_config.TextColumn("视频标题", width="large"), "date": st.column_config.TextColumn("发布日期/状态", width="medium"), "duration": st.column_config.TextColumn("时长", width="small"), "views": st.column_config.NumberColumn("播放量", format="%d"), "crawled_at": "抓取时间", "note": st.column_config.TextColumn("备注", width="small") # ✅ 显示备注列 } ) else: st.warning("🧐 没有找到符合条件的数据。如果是'只看新增'模式下没数据,说明今天还没跑爬虫,或者没有新视频入库。") # ================= 7. 底部控制栏 ================= st.divider() c1, c2, c3, c4, c5, c6 = st.columns([1.5, 1.5, 0.8, 1.5, 0.8, 1.5]) with c1: st.markdown(f"**找到 {total_rows} 条**") with c2: new_page_size = st.selectbox( "每页显示", options=[10, 50, 100, 200], index=[10, 50, 100, 200].index(st.session_state.page_size), label_visibility="collapsed" ) if new_page_size != st.session_state.page_size: st.session_state.page_size = new_page_size st.session_state.current_page = 1 st.rerun() with c3: if st.button("◀", disabled=(st.session_state.current_page == 1)): st.session_state.current_page -= 1 st.rerun() with c4: st.markdown(f"
第 {st.session_state.current_page} / {total_pages} 页
", unsafe_allow_html=True) with c5: if st.button("▶", disabled=(st.session_state.current_page == total_pages)): st.session_state.current_page += 1 st.rerun() with c6: target_page = st.number_input( "前往", min_value=1, max_value=total_pages, value=st.session_state.current_page, label_visibility="collapsed", placeholder="前往" ) if target_page != st.session_state.current_page: st.session_state.current_page = target_page st.rerun()