""" Automotive & AI Intelligence Dashboard """ import streamlit as st import pandas as pd import html as _html import json import time from datetime import datetime, timedelta, date, timezone from database import NewsDatabase from news_aggregator import NewsAggregator from config import COMPANIES_BY_ROLE, INDUSTRY_ROLES, RSS_SOURCES AUTO_REFRESH_SEC = 1800 # 30 minutes CST = timezone(timedelta(hours=8)) def bj_now(): """Current Beijing time (CST / UTC+8).""" return datetime.now(CST) def bj_fmt(dt=None): """Format datetime as Beijing time string.""" if dt is None: dt = bj_now() return dt.strftime("%Y-%m-%d %H:%M") st.set_page_config(page_title="Auto & AI Intelligence", page_icon="●", layout="wide") # ── Palette ── BG = "#0b0f15"; SURFACE = "#131820"; BORDER = "#1e293b" TEXT = "#e2e8f0"; MUTED = "#94a3b8" BLUE = "#3b82f6"; GREEN = "#10b981"; AMBER = "#f59e0b" RED = "#ef4444"; PURPLE = "#8b5cf6"; CYAN = "#06b6d4" CAT_META = { "全部": ("●", "All", TEXT), "auto": ("🏭", "汽车产业", BLUE), "ad": ("🚗", "自动驾驶", GREEN), "AI": ("🤖", "AI", CYAN), "arxiv": ("📄", "arXiv", AMBER), "tech": ("💻", "科技", PURPLE), } CAT_MAP = { "auto": {"cats": ["auto", "EV"], "roles": ["oem", "ev", "tier1", "battery", "mobility"]}, "ad": {"cats": ["ad"], "roles": ["ad"]}, "AI": {"cats": ["AI"], "roles": []}, "arxiv": {"cats": ["arxiv"], "roles": []}, "tech": {"cats": ["tech"], "roles": ["chip"]}, } # =================================================================== st.markdown(f""" """, unsafe_allow_html=True) # =================================================================== _U = {"“": '"', "”": '"', "‘": "'", "’": "'", "—": "---", "–": "--", "…": "...", "\xa0": " "} def S(text, max_len=None): if not text: return "" for f, p in _U.items(): text = text.replace(f, p) if max_len: text = text[:max_len] return _html.escape(text) def _parse_ts(ts_str): """Robust timestamp parsing.""" if not ts_str: return None for fmt in ["%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%d", "%a, %d %b %Y %H:%M:%S %z", "%a, %d %b %Y %H:%M:%S %Z"]: try: return datetime.strptime(ts_str[:25].strip(), fmt) except: pass try: return pd.to_datetime(ts_str).to_pydatetime() except: return None # =================================================================== @st.cache_resource def _db(): return NewsDatabase() db = _db() agg = NewsAggregator(db) # ── Auto-fetch: first deploy or data older than 30 min ── if "last_fetch_ts" not in st.session_state: st.session_state.last_fetch_ts = 0.0 if "last_fetch_str" not in st.session_state: st.session_state.last_fetch_str = "—" now_ts = time.time() stale = (now_ts - st.session_state.last_fetch_ts) > AUTO_REFRESH_SEC if db.total_count() == 0 or stale: with st.spinner("Refreshing data from all sources..."): agg.run_update() st.session_state.last_fetch_ts = time.time() st.session_state.last_fetch_str = bj_fmt() st.cache_resource.clear() st.rerun() # =================================================================== # Top Bar # =================================================================== remaining = max(0, int(AUTO_REFRESH_SEC - (time.time() - st.session_state.last_fetch_ts))) mins, secs = divmod(remaining, 60) last_upd = st.session_state.last_fetch_str st.markdown(f"""
● Auto & AI Intelligence Dashboard
🕐 Last updated: {last_upd} CST ⏱ Next refresh in {mins:02d}:{secs:02d}
""", unsafe_allow_html=True) c1, c2, c3 = st.columns([2.2, 3, 1.2]) with c1: date_range = st.date_input( "📅", value=(bj_now().date() - timedelta(days=30), bj_now().date()), min_value=date(2020, 1, 1), max_value=bj_now().date(), format="YYYY-MM-DD", label_visibility="visible") with c2: query = st.text_input("🔎", placeholder="Search companies, keywords, technologies...", label_visibility="visible") with c3: st.markdown("
", unsafe_allow_html=True) if st.button("🔄 Refresh", use_container_width=True): with st.spinner("Fetching all sources..."): n = agg.run_update() st.session_state.last_fetch_ts = time.time() st.session_state.last_fetch_str = bj_fmt() st.cache_resource.clear() st.rerun() # =================================================================== # Category Pills (st.pills — reliable state) # =================================================================== cat_keys = list(CAT_META.keys()) cat_labels = [f"{CAT_META[k][0]} {CAT_META[k][1]}" for k in cat_keys] active_cat = st.radio( "", cat_keys, index=0, horizontal=True, format_func=lambda k: f"{CAT_META[k][0]} {CAT_META[k][1]}", label_visibility="collapsed") # =================================================================== # Load & Filter # =================================================================== all_news = db.get_news(limit=800) # Date filter — parse timestamps properly if isinstance(date_range, (list, tuple)) and len(date_range) == 2: d_start, d_end = date_range filtered = [] for n in all_news: dt = _parse_ts(n.get("published_at") or "") if dt is None: filtered.append(n) # keep items with unparseable dates elif d_start <= dt.date() <= d_end: filtered.append(n) all_news = filtered # Category filter — match source category OR article roles if active_cat and active_cat != "全部": spec = CAT_MAP.get(active_cat, {}) allowed_cats = spec.get("cats", [active_cat]) allowed_roles = spec.get("roles", []) filtered = [] for n in all_news: cat_match = n.get("category") in allowed_cats role_match = any(r in (n.get("roles") or "[]") for r in allowed_roles) if allowed_roles else False if cat_match or role_match: filtered.append(n) all_news = filtered # Keyword if query: q = query.lower() all_news = [n for n in all_news if q in (n.get("title_en") or "").lower() or q in (n.get("summary_en") or "").lower() or q in (n.get("companies") or "").lower() or q in (n.get("source") or "").lower()] # =================================================================== # Metrics # =================================================================== from collections import Counter sc = Counter(n.get("source") for n in all_news) top_src = sc.most_common(1)[0][0] if sc else "—" cc = Counter(n.get("category") for n in all_news) tagged = sum(1 for n in all_news if json.loads(n.get("companies") or "[]")) enabled_n = len([s for s in RSS_SOURCES if s.enabled]) st.markdown(f"""
{len(all_news)}
📰 Results
{len(sc)}
📡 Sources
{tagged}
🏢 Tagged
{enabled_n}
📡 Monitored
{S(top_src, 14)}
🔝 Top Source
""", unsafe_allow_html=True) st.divider() # =================================================================== # Cards # =================================================================== CAT_COLORS = {"EV": GREEN, "auto": BLUE, "ad": GREEN, "AI": CYAN, "arxiv": AMBER, "tech": PURPLE} SRC_MAP = { "CN EV Post": "🇨🇳 CN EV Post", "CarNewsChina": "🇨🇳 CarNewsChina", "Pandaily": "🇨🇳 Pandaily", "AI News": "🧠 AI News", "HackerNews — AI+Robotics": "💬 HN AI", "TechCrunch — AI": "🤖 TC AI", "TechCrunch – Transportation": "🚗 TC", "Electrek": "⚡ Electrek", "InsideEVs": "🔋 InsideEVs", "TeslaRati": "🚀 TeslaRati", "GreenCarReports": "🌿 GCR", "CleanTechnica": "☀️ CleanTechnica", "Ars Technica – Cars": "🔬 Ars", "The Drive": "🏎️ The Drive", "Just Auto": "🏭 Just Auto", "Automotive World": "🌐 Auto World", "Electrive": "⚡ Electrive", "Charged EVs": "🔌 Charged EVs", "The Driven": "🇦🇺 The Driven", "Crunchbase News": "💰 Crunchbase", "VentureBeat": "🚀 VentureBeat", "Wired Transportation": "📡 Wired", "36氪 (36Kr)": "🇨🇳 36Kr", "Semiconductor Engineering": "💾 SemiEng", "EE News Europe": "🇪🇺 EE News", "Autonomous Vehicle Intl": "🚗 AV Intl", "MIT Technology Review": "📖 MIT TechRev", "OpenAI Blog": "🧠 OpenAI", "NVIDIA Developer": "💻 NVIDIA Dev", "NVIDIA Blog": "🟢 NVIDIA Blog", "arXiv cs.AI": "📄 arXiv AI", "arXiv cs.LG": "📄 arXiv ML", "EE Times": "⚡ EE Times", "Power Electronics News": "🔌 Power Elec", "IoT Automotive News": "📶 IoT Auto", } if not all_news: st.markdown(f"""
📭
No results
Adjust date range or search terms.
""", unsafe_allow_html=True) if db.total_count() == 0: if st.button("🔄 Fetch initial data", use_container_width=True): with st.spinner("..."): agg.run_update(); st.rerun() else: for item in all_news: companies = json.loads(item.get("companies") or "[]") roles = json.loads(item.get("roles") or "[]") source = item.get("source", "") cat = item.get("category", "auto") cc = CAT_COLORS.get(cat, MUTED) src_label = SRC_MAP.get(source, source) # Role chips role_h = "" for r in roles: if r in INDUSTRY_ROLES: ri = INDUSTRY_ROLES[r] role_h += f'{ri["icon"]} {ri["name"]}' # Company tags comp_h = "" for cn in companies[:4]: comp_h += f'{S(cn)}' title = S(item.get("title_en") or item.get("title_zh") or "", 150) summary = S(item.get("summary_en") or item.get("summary_zh") or "", 400) dt = _parse_ts(item.get("published_at") or "") ts_fmt = dt.strftime("%Y-%m-%d %H:%M") if dt else "" url_s = S(item.get("url") or "") st.markdown(f"""
{src_label} {cat.upper()} {role_h}
{title}
{summary}
{comp_h}
🕐 {ts_fmt} {'Source →' if url_s else ''}
""", unsafe_allow_html=True) st.divider() st.caption(f"{db.total_count():,} articles indexed · {enabled_n} active sources")