Download deploy/ingest/run.py from eduzrh/helloworld: direct link, hf CLI and curl.
- Browser
- Download file 6.09 kB
-
https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/deploy/ingest/run.py
- Command line
-
hf download hf://datasets/eduzrh/helloworld/deploy/ingest/run.py
-
curl -L -o run.py https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/deploy/ingest/run.py
6.09 kB
| """入口:采集 + 写入 + 导出。""" | |
| import os | |
| import sqlite3 | |
| import subprocess | |
| import sys | |
| import time | |
| import traceback | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from aggregate import agg_daily, build_outputs, WEIGHT # noqa: E402 | |
| from ingest_events import (DB, init_db, latest_export_urls, parse_gdelt, # noqa: E402 | |
| fetch_usgs, fetch_eonet) | |
| def insert_rows(con, rows): | |
| if not rows: | |
| return 0 | |
| n = 0 | |
| for r in rows: | |
| try: | |
| con.execute("INSERT OR REPLACE INTO events VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", r) | |
| n += 1 | |
| except sqlite3.Error: | |
| continue | |
| con.commit() | |
| return n | |
| def main(): | |
| os.makedirs(os.path.dirname(DB), exist_ok=True) | |
| con = sqlite3.connect(DB) | |
| init_db(con) | |
| report = {"gdelt": 0, "frames": [], "usgs": 0, "eonet": 0, "errors": []} | |
| # GDELT:默认 2 帧(约 30 分钟);backfill 时可传帧数,96 帧约等于 24 小时 | |
| limit = int(sys.argv[1]) if len(sys.argv) > 1 else 2 | |
| try: | |
| frames = latest_export_urls(limit=limit) | |
| for stamp, blob in frames: | |
| rows = parse_gdelt(stamp, blob) | |
| n = insert_rows(con, rows) | |
| report["gdelt"] += n | |
| report["frames"].append({"stamp": stamp, "rows": n}) | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append("gdelt: " + repr(e)[:200]) | |
| try: | |
| report["usgs"] = insert_rows(con, fetch_usgs()) | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append("usgs: " + repr(e)[:200]) | |
| try: | |
| report["eonet"] = insert_rows(con, fetch_eonet()) | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append("eonet: " + repr(e)[:200]) | |
| # 重算最近两天的日聚合(跨零点时补齐) | |
| dates = [r[0] for r in con.execute( | |
| "SELECT DISTINCT date FROM events WHERE date >= date('now','-2 day')").fetchall()] | |
| for d in dates: | |
| agg_daily(con, d) | |
| # 帧统计 | |
| for fr in report["frames"]: | |
| s = fr["stamp"] | |
| row = con.execute( | |
| "SELECT COUNT(*), COUNT(DISTINCT country) FROM events WHERE ts LIKE ?", | |
| (s[:4] + "-" + s[4:6] + "-" + s[6:8] + "T" + s[8:10] + ":" + s[10:12] + "%",) | |
| ).fetchone() | |
| top = con.execute( | |
| "SELECT category FROM events WHERE ts LIKE ? GROUP BY category " | |
| "ORDER BY COUNT(*) DESC LIMIT 1", | |
| (s[:4] + "-" + s[4:6] + "-" + s[6:8] + "T" + s[8:10] + ":" + s[10:12] + "%",) | |
| ).fetchone() | |
| epi = sum(WEIGHT.get(c, .5) * n for c, n in con.execute( | |
| "SELECT category, COUNT(*) FROM events WHERE ts LIKE ? GROUP BY category", | |
| (s[:4] + "-" + s[4:6] + "-" + s[6:8] + "T" + s[8:10] + ":" + s[10:12] + "%",)).fetchall()) | |
| con.execute("INSERT OR REPLACE INTO frames VALUES (?,?,?,?,?,datetime('now'))", | |
| (s, row[0], row[1], round(epi, 1), top[0] if top else "—")) | |
| con.commit() | |
| summary = build_outputs(con) | |
| con.close() | |
| # 要闻:独立脚本,失败不影响事件入库 | |
| try: | |
| r = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), | |
| "headlines.py")], | |
| capture_output=True, text=True, timeout=200) | |
| report["headlines"] = (r.stdout or "").strip()[:300] | |
| if r.returncode != 0: | |
| report["errors"].append("headlines: " + (r.stderr or "")[-200:]) | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append("headlines: " + repr(e)[:150]) | |
| # 卫星星历:TLE 每天变一次就够,文件超过 12 小时才重新拉 | |
| sat_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "globe", "data", "satellites.json") | |
| sat_path = os.path.normpath(sat_path) | |
| try: | |
| fresh = os.path.exists(sat_path) and (time.time() - os.path.getmtime(sat_path)) < 12 * 3600 | |
| if not fresh: | |
| r = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), | |
| "satellites.py")], | |
| capture_output=True, text=True, timeout=180) | |
| report["satellites"] = (r.stdout or "").strip()[:200] | |
| if r.returncode != 0: | |
| report["errors"].append("satellites: " + (r.stderr or "")[-200:]) | |
| else: | |
| report["satellites"] = "fresh, skipped" | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append("satellites: " + repr(e)[:150]) | |
| # GDACS 灾害预警 / FIRMS 火点:按各自鲜度刷新,失败不影响主流程 | |
| here = os.path.dirname(os.path.abspath(__file__)) | |
| for name, script, out, hours, tmo in ( | |
| ("gdacs", "gdacs.py", "disasters.json", 0.5, 120), | |
| ("firms", "firms.py", "fires.json", 1.0, 200), | |
| ("flights", "flights.py", "flights.json", 0.34, 220)): | |
| path = os.path.normpath(os.path.join(here, "..", "globe", "data", out)) | |
| try: | |
| if os.path.exists(path) and (time.time() - os.path.getmtime(path)) < hours * 3600: | |
| report[name] = "fresh, skipped" | |
| continue | |
| r = subprocess.run([sys.executable, os.path.join(here, script)], | |
| capture_output=True, text=True, timeout=tmo) | |
| report[name] = (r.stdout or "").strip()[:200] | |
| if r.returncode != 0: | |
| report["errors"].append(name + ": " + (r.stderr or "")[-160:]) | |
| except Exception as e: # noqa: BLE001 | |
| report["errors"].append(name + ": " + repr(e)[:120]) | |
| report["summary"] = {"total": summary["total_events"], | |
| "today": summary["today_events"], | |
| "countries": summary["countries"]} | |
| print(__import__("json").dumps(report, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except Exception: # noqa: BLE001 | |
| traceback.print_exc() | |
| sys.exit(1) | |