#!/usr/bin/env python3 """ openmaic_load_from_drive.py Load file từ Google Drive vào thư mục inbox của OpenMAIC. Sử dụng: python3 openmaic_load_from_drive.py "" Ví dụ: python3 openmaic_load_from_drive.py "https://drive.google.com/file/d/1aBc.../view" python3 openmaic_load_from_drive.py "1aBcXYZ123" """ import sys import os import re import subprocess from pathlib import Path INBOX_DIR = Path("/opt/ai-os/products/ceo/projects/tech/OpenMAIC/data/inbox") GAPI_SCRIPT = "/root/.hermes/profiles/reviewer/skills/productivity/google-workspace/scripts/google_api.py" def extract_file_id(input_str: str) -> str: """Trích xuất Google Drive File ID từ URL hoặc ID trực tiếp.""" patterns = [ r"/file/d/([a-zA-Z0-9_\-]+)", r"id=([a-zA-Z0-9_\-]+)", r"^([a-zA-Z0-9_\-]{25,})$", ] for pattern in patterns: match = re.search(pattern, input_str.strip()) if match: return match.group(1) return input_str.strip() def get_file_metadata(file_id: str) -> dict: """Lấy metadata của file từ Google Drive API.""" result = subprocess.run( ["python3", GAPI_SCRIPT, "drive", "get", file_id], capture_output=True, text=True ) if result.returncode != 0: print(f"Lỗi lấy metadata: {result.stderr}") return {} import json try: return json.loads(result.stdout) except Exception: return {} def download_file(file_id: str, output_path: str) -> bool: """Tải file từ Google Drive về đường dẫn chỉ định.""" result = subprocess.run( ["python3", GAPI_SCRIPT, "drive", "download", file_id, "--output", output_path], capture_output=True, text=True ) if result.returncode != 0: print(f"Lỗi tải file: {result.stderr}") return False return True def main(): if len(sys.argv) < 2: print("Sử dụng: python3 openmaic_load_from_drive.py \"\"") sys.exit(1) raw_input = sys.argv[1] file_id = extract_file_id(raw_input) print(f"Drive File ID: {file_id}") meta = get_file_metadata(file_id) filename = meta.get("name", f"drive_file_{file_id}") mime = meta.get("mimeType", "") if not filename.endswith((".pdf", ".txt", ".docx", ".md", ".pptx", ".xlsx")): ext_map = { "application/pdf": ".pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", "application/vnd.ms-powerpoint": ".pptx", "text/plain": ".txt", } ext = ext_map.get(mime, "") if ext and not filename.endswith(ext): filename = filename + ext INBOX_DIR.mkdir(parents=True, exist_ok=True) output_path = str(INBOX_DIR / filename) print(f"Đang tải: {filename}") print(f"Lưu tại: {output_path}") success = download_file(file_id, output_path) if success: size = Path(output_path).stat().st_size if Path(output_path).exists() else 0 print(f"Tải thành công: {filename} ({size:,} bytes)") print(f"Sẵn sàng để upload lên OpenMAIC tại: https://openmaic.161-97-131-21.sslip.io") else: print("Tải thất bại. Kiểm tra kết nối Google Drive.") sys.exit(1) if __name__ == "__main__": main()