mutt/master_ai_sync.py

103 lines
3.6 KiB
Python
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
import subprocess
import os
import sys
import logging
import requests
from pathlib import Path
from datetime import datetime
# === CONFIG ===
BASE_DIR = Path("/home/matrixhasyou/mutt")
PYTHON_BIN = "/usr/bin/python3"
GOOGLE_PYTHON_BIN = "/home/matrixhasyou/swarm-services/domovoy-bot/venv-google/bin/python"
EXPORT_SCRIPT = BASE_DIR / "export_emails.py"
CONSOLIDATE_SCRIPT = BASE_DIR / "consolidate_to_mega_pdf.py"
DRIVE_SYNC_SCRIPT = Path("/home/matrixhasyou/domovoy_drive_sync.py")
MASTER_PDF = BASE_DIR / "ALL_EMAILS_CONSOLIDATED.pdf"
BOT_TOKEN = "8725618164:AAH1tGalq-pw1l0t4P5c0sdLkCVJdh7IE7M"
CHAT_ID = "197957361"
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("MasterSync")
def send_tg(text):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
try:
requests.post(url, json={"chat_id": CHAT_ID, "text": text, "parse_mode": "HTML"},
timeout=20)
except Exception as e:
log.error(f"TG notification failed: {e}")
def run_step(name, cmd):
log.info(f"--- Step: {name} ---")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
log.error(f"Step {name} FAILED!")
log.error(result.stderr)
return False, result.stderr
log.info(f"Step {name} completed.")
return True, result.stdout
def main():
start_time = datetime.now()
log.info(f"Starting Master Sync at {start_time}")
# 1. Export Emails
ok, out_export = run_step("Export Emails", [PYTHON_BIN, str(EXPORT_SCRIPT)])
if not ok:
send_tg(f"❌ <b>Mutt Master Sync: FAILED</b>\nStep: Export Emails\nError: <code>{out_export[:200]}</code>")
return
# 2. Consolidate PDF
ok, out_consolidate = run_step("Consolidate PDF", [PYTHON_BIN, str(CONSOLIDATE_SCRIPT)])
if not ok:
send_tg(f"❌ <b>Mutt Master Sync: FAILED</b>\nStep: Consolidate PDF\nError: <code>{out_consolidate[:200]}</code>")
return
# 3. Sync to G-Drive
ok, out_drive = run_step("G-Drive Sync", [GOOGLE_PYTHON_BIN, str(DRIVE_SYNC_SCRIPT), str(MASTER_PDF)])
if not ok:
send_tg(f"❌ <b>Mutt Master Sync: FAILED</b>\nStep: G-Drive Sync\nError: <code>{out_drive[:200]}</code>")
return
end_time = datetime.now()
# Parsing Stats
new_emails = 0
total_emails = 0
for line in out_export.split('\n'):
if "Processed this run:" in line:
try: new_emails = int(line.split(':')[-1].strip())
except: pass
for line in out_consolidate.split('\n'):
if "Found" in line and "PDFs" in line:
try: total_emails = int(line.split('Found')[-1].split('PDFs')[0].strip())
except: pass
pdf_size_mb = os.path.getsize(MASTER_PDF) / (1024 * 1024)
summary = f"""
🚀 <b>AI ПОЧТОВЫЙ ТУРБО-СИНХРОН: OK</b> 🚀
📥 <b>Новых писем:</b> <code>{new_emails}</code>
📚 <b>Всего в архиве:</b> <code>{total_emails}</code>
🐘 <b>Размер PDF:</b> <code>{pdf_size_mb:.2f} МБ</code>
☁️ <b>G-Drive:</b> Обновлено ✅
📅 {end_time.strftime("%Y-%m-%d %H:%M")}
<i>Робот закончил работу. NotebookLM готов к анализу.</i>
"""
send_tg(summary)
log.info("Master Sync completed successfully.")
# Save last sync time for web UI
sync_time_file = Path("/home/matrixhasyou/mutt/last_ai_sync.txt")
with open(sync_time_file, "w") as f:
f.write(end_time.strftime("%Y-%m-%d %H:%M:%S"))
if __name__ == "__main__":
main()