import os, io, json from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload import pymupdf token_path = os.path.expanduser("~/.hermes/profiles/reviewer/google_token.json") with open(token_path) as f: creds = Credentials.from_authorized_user_info(json.load(f)) docs_service = build("docs", "v1", credentials=creds) drive_service = build("drive", "v3", credentials=creds) doc_id = "1sjTe7Im51CY2Tl0SNQrm8xmO7bYweMkq44E0WXaxs1I" doc = docs_service.documents().get(documentId=doc_id).execute() body = doc.get("body", {}) content = body.get("content", []) requests = [] # Iterate over body elements to find and fix text errors # 1. "Tự do- Hạnh phúc" -> "Độc lập - Tự do - Hạnh phúc" # 2. "TỉnhKhánh Hòa" -> "Tỉnh Khánh Hòa" def get_text_runs(element): runs = [] if "paragraph" in element: for el in element["paragraph"]["elements"]: if "textRun" in el: runs.append((el["startIndex"], el["endIndex"], el["textRun"]["content"])) return runs for element in content: runs = get_text_runs(element) for st, en, txt in runs: if "Tự do- Hạnh phúc" in txt: new_txt = txt.replace("Tự do- Hạnh phúc", "Tự do - Hạnh phúc") requests.append({ "deleteContentRange": {"range": {"startIndex": st, "endIndex": en - 1}} }) requests.append({ "insertText": {"location": {"index": st}, "text": new_txt} }) elif "TỉnhKhánh Hòa" in txt: new_txt = txt.replace("TỉnhKhánh Hòa", "Tỉnh Khánh Hòa") requests.append({ "deleteContentRange": {"range": {"startIndex": st, "endIndex": en - 1}} }) requests.append({ "insertText": {"location": {"index": st}, "text": new_txt} }) if requests: print(f"Applying {len(requests)} text fixes...") resp = docs_service.documents().batchUpdate( documentId=doc_id, body={"requests": requests} ).execute() print("Text fixes applied successfully!") # Export final PDF request = drive_service.files().export_media(fileId=doc_id, mimeType="application/pdf") pdf_data = request.execute() output_dir = "/opt/ai-os/products/ceo/projects/GLV/reports" os.makedirs(output_dir, exist_ok=True) pdf_filename = "So_Yeu_Ly_Lich_Vo_Thi_Yen_Nhi_Hoan_Chinh.pdf" pdf_full_path = os.path.join(output_dir, pdf_filename) with open(pdf_full_path, "wb") as f: f.write(pdf_data) print(f"Final PDF exported to: {pdf_full_path}")