Download src/main.py from Hetheclif/NEWS: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/Hetheclif/NEWS/resolve/main/src/main.py
- Command line
-
hf download hf://spaces/Hetheclif/NEWS/src/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Hetheclif/NEWS/resolve/main/src/main.py
13.7 kB
| """ | |
| 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""" | |
| <style> | |
| .stApp {{ background:{BG}; }} | |
| .stApp > header {{ background:transparent; }} | |
| [data-testid="stHeader"] {{ background:transparent; }} | |
| .block-container {{ padding-top:0.5rem; max-width:1440px; }} | |
| [data-testid="stSidebar"], [data-testid="stSidebarCollapsedControl"] {{ display:none; }} | |
| /* Layout helpers */ | |
| .topbar {{ display:flex; align-items:center; gap:0.8rem; flex-wrap:wrap; padding:0.2rem 0 0.6rem; }} | |
| .metrics {{ display:flex; gap:0.8rem; flex-wrap:wrap; margin:0.5rem 0; }} | |
| .met {{ background:{SURFACE}; border:1px solid {BORDER}; border-radius:10px; | |
| padding:0.5rem 1rem; text-align:center; min-width:95px; }} | |
| .met .v {{ font-size:1.25rem; font-weight:700; color:{TEXT}; }} | |
| .met .l {{ font-size:0.66rem; color:{MUTED}; margin-top:0.1rem; }} | |
| /* Card */ | |
| .card {{ background:{SURFACE}; border:1px solid {BORDER}; border-radius:12px; | |
| padding:1rem 1.2rem; margin-bottom:0.55rem; transition:border-color 0.12s; }} | |
| .card:hover {{ border-color:{BLUE}55; }} | |
| /* Badges */ | |
| .b {{ display:inline-block; border-radius:5px; padding:0.07rem 0.5rem; | |
| font-size:0.65rem; font-weight:600; margin-right:0.3rem; margin-bottom:0.15rem; }} | |
| a {{ color:{BLUE}; text-decoration:none; }} a:hover {{ text-decoration:underline; }} | |
| </style> | |
| """, 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 | |
| # =================================================================== | |
| 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""" | |
| <div style="display:flex;align-items:baseline;justify-content:space-between;padding:0 0 0.2rem 0;"> | |
| <div style="font-size:1.3rem;font-weight:700;color:{TEXT};">β Auto & AI Intelligence Dashboard</div> | |
| <div style="display:flex;gap:1.5rem;font-size:0.72rem;color:{MUTED};"> | |
| <span>π Last updated: <b style="color:{TEXT};">{last_upd} CST</b></span> | |
| <span id="countdown">β± Next refresh in <b style="color:{TEXT};">{mins:02d}:{secs:02d}</b></span> | |
| </div> | |
| </div> | |
| <script> | |
| var remaining = {remaining}; | |
| var el = document.getElementById("countdown"); | |
| var timer = setInterval(function() {{ | |
| remaining--; | |
| if (remaining <= 0) {{ clearInterval(timer); window.location.reload(); return; }} | |
| var m = Math.floor(remaining / 60); | |
| var s = remaining % 60; | |
| el.innerHTML = "β± Next refresh in <b style=\\"color:{TEXT};\\">" + String(m).padStart(2,"0") + ":" + String(s).padStart(2,"0") + "</b>"; | |
| }}, 1000); | |
| </script> | |
| """, 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("<br>", 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"""<div class="metrics"> | |
| <div class="met"><div class="v">{len(all_news)}</div><div class="l">π° Results</div></div> | |
| <div class="met"><div class="v">{len(sc)}</div><div class="l">π‘ Sources</div></div> | |
| <div class="met"><div class="v">{tagged}</div><div class="l">π’ Tagged</div></div> | |
| <div class="met"><div class="v">{enabled_n}</div><div class="l">π‘ Monitored</div></div> | |
| <div class="met"><div class="v" style="font-size:0.95rem;">{S(top_src, 14)}</div><div class="l">π Top Source</div></div> | |
| </div>""", 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"""<div style="text-align:center;padding:4rem 2rem;color:{MUTED};"> | |
| <div style="font-size:3rem;margin-bottom:0.8rem;">π</div> | |
| <div style="font-size:1.1rem;font-weight:600;">No results</div> | |
| <div style="font-size:0.85rem;margin-top:0.3rem;">Adjust date range or search terms.</div> | |
| </div>""", 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'<span class="b" style="background:{ri["color"]}22;color:{ri["color"]};">{ri["icon"]} {ri["name"]}</span>' | |
| # Company tags | |
| comp_h = "" | |
| for cn in companies[:4]: | |
| comp_h += f'<span class="b badge-cat" style="border:1px solid {BLUE}44;color:{MUTED};">{S(cn)}</span>' | |
| 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"""<div class="card"> | |
| <div style="display:flex;align-items:center;gap:0.3rem;flex-wrap:wrap;margin-bottom:0.4rem;"> | |
| <span class="b" style="background:{cc}22;color:{cc};">{src_label}</span> | |
| <span class="b badge-cat">{cat.upper()}</span> | |
| {role_h} | |
| </div> | |
| <div style="font-size:1.02rem;font-weight:600;color:{TEXT};line-height:1.5;margin-bottom:0.5rem;">{title}</div> | |
| <div style="font-size:0.87rem;color:{MUTED};line-height:1.65;margin-bottom:0.5rem;">{summary}</div> | |
| <div style="display:flex;flex-wrap:wrap;gap:0.2rem;margin-bottom:0.35rem;">{comp_h}</div> | |
| <div style="font-size:0.7rem;color:#475569;display:flex;align-items:center;gap:1rem;"> | |
| <span>π {ts_fmt}</span> | |
| {'<a href="' + url_s + '" target="_blank">Source β</a>' if url_s else ''} | |
| </div> | |
| </div>""", unsafe_allow_html=True) | |
| st.divider() | |
| st.caption(f"{db.total_count():,} articles indexed Β· {enabled_n} active sources") | |