|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import os |
| 16 | +import sys |
| 17 | + |
| 18 | +from adk_answering_agent.settings import ADK_DOCS_ROOT_PATH |
| 19 | +from adk_answering_agent.settings import ADK_PYTHON_ROOT_PATH |
| 20 | +from adk_answering_agent.settings import GCS_BUCKET_NAME |
| 21 | +from adk_answering_agent.settings import GOOGLE_CLOUD_PROJECT |
| 22 | +from adk_answering_agent.settings import VERTEXAI_DATASTORE_ID |
| 23 | +from google.api_core.exceptions import GoogleAPICallError |
| 24 | +from google.cloud import discoveryengine_v1beta as discoveryengine |
| 25 | +from google.cloud import storage |
| 26 | +import markdown |
| 27 | + |
| 28 | +GCS_PREFIX_TO_ROOT_PATH = { |
| 29 | + "adk-docs": ADK_DOCS_ROOT_PATH, |
| 30 | + "adk-python": ADK_PYTHON_ROOT_PATH, |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +def cleanup_gcs_prefix(project_id: str, bucket_name: str, prefix: str) -> bool: |
| 35 | + """Delete all the objects with the given prefix in the bucket.""" |
| 36 | + print(f"Start cleaning up GCS: gs://{bucket_name}/{prefix}...") |
| 37 | + try: |
| 38 | + storage_client = storage.Client(project=project_id) |
| 39 | + bucket = storage_client.bucket(bucket_name) |
| 40 | + blobs = list(bucket.list_blobs(prefix=prefix)) |
| 41 | + |
| 42 | + if not blobs: |
| 43 | + print("GCS target location is already empty, no need to clean up.") |
| 44 | + return True |
| 45 | + |
| 46 | + bucket.delete_blobs(blobs) |
| 47 | + print(f"Successfully deleted {len(blobs)} objects.") |
| 48 | + return True |
| 49 | + except GoogleAPICallError as e: |
| 50 | + print(f"[ERROR] Failed to clean up GCS: {e}", file=sys.stderr) |
| 51 | + return False |
| 52 | + |
| 53 | + |
| 54 | +def upload_directory_to_gcs( |
| 55 | + source_directory: str, project_id: str, bucket_name: str, prefix: str |
| 56 | +) -> bool: |
| 57 | + """Upload the whole directory into GCS.""" |
| 58 | + print( |
| 59 | + f"Start uploading directory {source_directory} to GCS:" |
| 60 | + f" gs://{bucket_name}/{prefix}..." |
| 61 | + ) |
| 62 | + |
| 63 | + if not os.path.isdir(source_directory): |
| 64 | + print(f"[Error] {source_directory} is not a directory or does not exist.") |
| 65 | + return False |
| 66 | + |
| 67 | + storage_client = storage.Client(project=project_id) |
| 68 | + bucket = storage_client.bucket(bucket_name) |
| 69 | + file_count = 0 |
| 70 | + for root, dirs, files in os.walk(source_directory): |
| 71 | + # Modify the 'dirs' list in-place to prevent os.walk from descending |
| 72 | + # into hidden directories. |
| 73 | + dirs[:] = [d for d in dirs if not d.startswith(".")] |
| 74 | + |
| 75 | + # Keep only .md and .py files. |
| 76 | + files = [f for f in files if f.endswith(".md") or f.endswith(".py")] |
| 77 | + |
| 78 | + for filename in files: |
| 79 | + local_path = os.path.join(root, filename) |
| 80 | + |
| 81 | + relative_path = os.path.relpath(local_path, source_directory) |
| 82 | + gcs_path = os.path.join(prefix, relative_path) |
| 83 | + |
| 84 | + try: |
| 85 | + content_type = None |
| 86 | + if filename.lower().endswith(".md"): |
| 87 | + # Vertex AI search doesn't recognize text/markdown, |
| 88 | + # convert it to html and use text/html instead |
| 89 | + content_type = "text/html" |
| 90 | + with open(local_path, "r", encoding="utf-8") as f: |
| 91 | + md_content = f.read() |
| 92 | + html_content = markdown.markdown( |
| 93 | + md_content, output_format="html5", encoding="utf-8" |
| 94 | + ) |
| 95 | + if not html_content: |
| 96 | + print(" - Skipped empty file: " + local_path) |
| 97 | + continue |
| 98 | + gcs_path = gcs_path.removesuffix(".md") + ".html" |
| 99 | + bucket.blob(gcs_path).upload_from_string( |
| 100 | + html_content, content_type=content_type |
| 101 | + ) |
| 102 | + else: # Python files |
| 103 | + bucket.blob(gcs_path).upload_from_filename( |
| 104 | + local_path, content_type=content_type |
| 105 | + ) |
| 106 | + type_msg = ( |
| 107 | + f"(type {content_type})" if content_type else "(type auto-detect)" |
| 108 | + ) |
| 109 | + print( |
| 110 | + f" - Uploaded {type_msg}: {local_path} ->" |
| 111 | + f" gs://{bucket_name}/{gcs_path}" |
| 112 | + ) |
| 113 | + file_count += 1 |
| 114 | + except GoogleAPICallError as e: |
| 115 | + print( |
| 116 | + f"[ERROR] Error uploading file {local_path}: {e}", file=sys.stderr |
| 117 | + ) |
| 118 | + return False |
| 119 | + |
| 120 | + print(f"Sucessfully uploaded {file_count} files to GCS.") |
| 121 | + return True |
| 122 | + |
| 123 | + |
| 124 | +def import_from_gcs_to_vertex_ai( |
| 125 | + full_datastore_id: str, |
| 126 | + gcs_bucket: str, |
| 127 | +) -> bool: |
| 128 | + """Triggers a bulk import task from a GCS folder to Vertex AI Search.""" |
| 129 | + print(f"Triggering FULL SYNC import from gs://{gcs_bucket}/**...") |
| 130 | + |
| 131 | + try: |
| 132 | + client = discoveryengine.DocumentServiceClient() |
| 133 | + gcs_uri = f"gs://{gcs_bucket}/**" |
| 134 | + request = discoveryengine.ImportDocumentsRequest( |
| 135 | + # parent has the format of |
| 136 | + # "projects/{project_number}/locations/{location}/collections/{collection}/dataStores/{datastore_id}/branches/default_branch" |
| 137 | + parent=full_datastore_id + "/branches/default_branch", |
| 138 | + # Specify the GCS source and use "content" for unstructed data. |
| 139 | + gcs_source=discoveryengine.GcsSource( |
| 140 | + input_uris=[gcs_uri], data_schema="content" |
| 141 | + ), |
| 142 | + reconciliation_mode=discoveryengine.ImportDocumentsRequest.ReconciliationMode.FULL, |
| 143 | + ) |
| 144 | + operation = client.import_documents(request=request) |
| 145 | + print( |
| 146 | + "Successfully started full sync import operation." |
| 147 | + f"Operation Name: {operation.operation.name}" |
| 148 | + ) |
| 149 | + return True |
| 150 | + |
| 151 | + except GoogleAPICallError as e: |
| 152 | + print(f"[ERROR] Error triggering import: {e}", file=sys.stderr) |
| 153 | + return False |
| 154 | + |
| 155 | + |
| 156 | +def main(): |
| 157 | + # Check required environment variables. |
| 158 | + if not GOOGLE_CLOUD_PROJECT: |
| 159 | + print( |
| 160 | + "[ERROR] GOOGLE_CLOUD_PROJECT environment variable not set. Exiting...", |
| 161 | + file=sys.stderr, |
| 162 | + ) |
| 163 | + return 1 |
| 164 | + if not GCS_BUCKET_NAME: |
| 165 | + print( |
| 166 | + "[ERROR] GCS_BUCKET_NAME environment variable not set. Exiting...", |
| 167 | + file=sys.stderr, |
| 168 | + ) |
| 169 | + return 1 |
| 170 | + if not VERTEXAI_DATASTORE_ID: |
| 171 | + print( |
| 172 | + "[ERROR] VERTEXAI_DATASTORE_ID environment variable not set." |
| 173 | + " Exiting...", |
| 174 | + file=sys.stderr, |
| 175 | + ) |
| 176 | + return 1 |
| 177 | + if not ADK_DOCS_ROOT_PATH: |
| 178 | + print( |
| 179 | + "[ERROR] ADK_DOCS_ROOT_PATH environment variable not set. Exiting...", |
| 180 | + file=sys.stderr, |
| 181 | + ) |
| 182 | + return 1 |
| 183 | + if not ADK_PYTHON_ROOT_PATH: |
| 184 | + print( |
| 185 | + "[ERROR] ADK_PYTHON_ROOT_PATH environment variable not set. Exiting...", |
| 186 | + file=sys.stderr, |
| 187 | + ) |
| 188 | + return 1 |
| 189 | + |
| 190 | + for gcs_prefix in GCS_PREFIX_TO_ROOT_PATH: |
| 191 | + # 1. Cleanup the GSC for a clean start. |
| 192 | + if not cleanup_gcs_prefix( |
| 193 | + GOOGLE_CLOUD_PROJECT, GCS_BUCKET_NAME, gcs_prefix |
| 194 | + ): |
| 195 | + print("[ERROR] Failed to clean up GCS. Exiting...", file=sys.stderr) |
| 196 | + return 1 |
| 197 | + |
| 198 | + # 2. Upload the docs to GCS. |
| 199 | + if not upload_directory_to_gcs( |
| 200 | + GCS_PREFIX_TO_ROOT_PATH[gcs_prefix], |
| 201 | + GOOGLE_CLOUD_PROJECT, |
| 202 | + GCS_BUCKET_NAME, |
| 203 | + gcs_prefix, |
| 204 | + ): |
| 205 | + print("[ERROR] Failed to upload docs to GCS. Exiting...", file=sys.stderr) |
| 206 | + return 1 |
| 207 | + |
| 208 | + # 3. Import the docs from GCS to Vertex AI Search. |
| 209 | + if not import_from_gcs_to_vertex_ai(VERTEXAI_DATASTORE_ID, GCS_BUCKET_NAME): |
| 210 | + print( |
| 211 | + "[ERROR] Failed to import docs from GCS to Vertex AI Search." |
| 212 | + " Exiting...", |
| 213 | + file=sys.stderr, |
| 214 | + ) |
| 215 | + return 1 |
| 216 | + |
| 217 | + print("--- Sync task has been successfully initiated ---") |
| 218 | + return 0 |
| 219 | + |
| 220 | + |
| 221 | +if __name__ == "__main__": |
| 222 | + sys.exit(main()) |
0 commit comments