#!/usr/bin/env python3 """ daily_tracker.py — Theo dõi tài nguyên và cập nhật từ Hội nghị Hà Nội APA 2026. Tự động đồng bộ tài liệu mới lên NotebookLM và trích xuất phân tích chuyên sâu. Chạy định kỳ qua Cron job vào 13:00 hằng ngày. """ import os import sys import json import subprocess import urllib.request import urllib.parse from datetime import datetime import re BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) SOURCES_DIR = os.path.join(BASE_DIR, "sources") BRIEFS_DIR = os.path.join(BASE_DIR, "daily_briefs") TARGET_URL = "https://hanoiapa-authenticity.org/en/resources" NOTEBOOK_ID = "3497f3f2-4374-4781-a7ea-d43d540d7642" CHAT_ID = "-1003707758328" THREAD_ID = 9896 def get_telegram_token(): env_file = "/root/.hermes/.env" if os.path.exists(env_file): with open(env_file, "r") as f: for line in f: if line.startswith("TELEGRAM_BOT_TOKEN="): return line.strip().split("=", 1)[1] return os.environ.get("TELEGRAM_BOT_TOKEN") def send_telegram_alert(text): token = get_telegram_token() if not token: print("[WARN] Khong tim thay TELEGRAM_BOT_TOKEN") return False url = f"https://api.telegram.org/bot{token}/sendMessage" payload = { "chat_id": CHAT_ID, "message_thread_id": THREAD_ID, "text": text, "parse_mode": "HTML" } data = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=10) as resp: return resp.status == 200 except Exception as e: print(f"[ERR] Gui tin nhan Telegram that bai: {e}") return False def scan_resources(): req = urllib.request.Request(TARGET_URL, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}) try: with urllib.request.urlopen(req, timeout=15) as resp: html = resp.read().decode("utf-8", errors="ignore") except Exception as e: print(f"[ERR] Khong the tai trang resources: {e}") return [] # Tim tat ca cac lien ket PDF links = re.findall(r'href=[\'"]([^\'"]+\.pdf[^\'"]*)[\'"]', html, re.IGNORECASE) unique_links = [] for l in links: full_url = urllib.parse.urljoin(TARGET_URL, l) if full_url not in unique_links: unique_links.append(full_url) return unique_links def download_file(url, dest_path): req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) try: with urllib.request.urlopen(req, timeout=30) as resp, open(dest_path, "wb") as out: out.write(resp.read()) return True except Exception as e: print(f"[ERR] Tai file that bai {url}: {e}") return False def upload_to_notebooklm(file_path, title): """Dong bo tep tin moi len Google NotebookLM qua nlm CLI.""" try: cmd = [ "nlm", "source", "add", NOTEBOOK_ID, "--file", file_path, "--title", title, "--wait" ] res = subprocess.run(cmd, capture_output=True, text=True, timeout=120) if res.returncode == 0: print(f"[+] Da dong bo len NotebookLM: {title}") return True else: print(f"[WARN] Dong bo NotebookLM that bai cho {title}: {res.stderr}") return False except Exception as e: print(f"[ERR] Loi khi goi nlm source add: {e}") return False def query_notebooklm_insights(): """Truy van NotebookLM de lay cac phan tich, de xuat va tong hop moi nhat tu hoi nghi.""" try: prompt = ( "Hay tom tat 3 diem dot pha quan trong nhat ve mat hoc thuat va chinh sach " "tu cac phien thao luan gan nhat cua Hoi nghi Ha Noi APA 2026, dac biet ve " "tinh xac thuc cua di san song, su tham gia cua cong dong va de xuat cho Van kien Ha Noi." ) cmd = ["nlm", "query", "notebook", NOTEBOOK_ID, prompt, "--json"] res = subprocess.run(cmd, capture_output=True, text=True, timeout=60) if res.returncode == 0: data = json.loads(res.stdout) return data.get("answer", "") except Exception as e: print(f"[ERR] Loi khi truy van NotebookLM: {e}") return "" def main(): os.makedirs(SOURCES_DIR, exist_ok=True) os.makedirs(BRIEFS_DIR, exist_ok=True) today = datetime.now().strftime("%Y-%m-%d") brief_file = os.path.join(BRIEFS_DIR, f"{today}.md") print(f"[*] Bat dau quet tai nguyen Hoi nghi Ha Noi APA tai {TARGET_URL}...") pdf_links = scan_resources() print(f"[*] Tim thay {len(pdf_links)} tai lieu PDF.") new_downloads = [] for link in pdf_links: filename = os.path.basename(urllib.parse.urlparse(link).path) if not filename: filename = "document.pdf" dest = os.path.join(SOURCES_DIR, filename) if not os.path.exists(dest): print(f"[+] Phat hien file moi: {filename}. Dang tai ve...") if download_file(link, dest): new_downloads.append(filename) # Dong bo ngay len NotebookLM upload_to_notebooklm(dest, filename) else: print(f"[.] File da ton tai: {filename}") # Truy van insights tu NotebookLM print("[*] Dang truy van insights tu NotebookLM...") nlm_insights = query_notebooklm_insights() # Ghi log daily brief neu chua co file phan tich chi tiet if not os.path.exists(brief_file) or os.path.getsize(brief_file) < 1000: with open(brief_file, "w", encoding="utf-8") as f: f.write(f"# BÁO CÁO THEO DÕI VÀ PHÂN TÍCH HỘI NGHỊ HÀ NỘI APA ({today})\n\n") f.write(f"* Thời gian quét: {datetime.now().strftime('%H:%M:%S %d/%m/%Y')}\n") f.write(f"* Tổng số tài liệu phát hiện trên hệ thống: {len(pdf_links)}\n") f.write(f"* Số tài liệu mới tải về hôm nay: {len(new_downloads)}\n\n") if new_downloads: f.write("## Tài liệu mới phát sinh trong ngày:\n") for item in new_downloads: f.write(f"* `{item}` (Đã đồng bộ lên NotebookLM)\n") f.write("\n") else: f.write("## Trạng thái tài nguyên:\nChưa phát sinh thêm tệp PDF mới trên cổng website.\n\n") if nlm_insights: f.write("## Phân tích Tổng hợp từ Sổ tay NotebookLM (Live Transcripts):\n\n") f.write(nlm_insights + "\n") print(f"[*] Da cap nhat nhat ky theo doi tai {brief_file}") # Gui thong bao Telegram ngan gon bang HTML if new_downloads: items_str = "\n".join([f"• {d}" for d in new_downloads]) msg = ( f"📢 CẬP NHẬT HỘI NGHỊ HÀ NỘI APA 2026 ({today})\n\n" f"Phát hiện {len(new_downloads)} tài liệu mới đã tải về và đồng bộ lên NotebookLM:\n" f"{items_str}\n\n" f"🔗 Xem chi tiết: https://vmi3427693.tail8c1aaf.ts.net/files/opt/ai-os/products/ceo/projects/scholarships/asean-australia-ai-dt-2026/hanoi_apa_conference/daily_briefs/{today}.md" ) else: msg = ( f"✅ GIÁM SÁT HỘI NGHỊ HÀ NỘI APA 2026 ({today})\n\n" f"Đã quét cổng tài nguyên và phân tích biên bản thảo luận trong NotebookLM.\n" f"Dự thảo Văn kiện Hà Nội đang được Tiểu ban Kỹ thuật hoàn thiện.\n\n" f"🔗 Xem phân tích chuyên sâu: https://vmi3427693.tail8c1aaf.ts.net/files/opt/ai-os/products/ceo/projects/scholarships/asean-australia-ai-dt-2026/hanoi_apa_conference/daily_briefs/{today}.md" ) send_telegram_alert(msg) print("[*] Da gui thong bao qua Telegram thanh cong.") if __name__ == "__main__": main()