@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +28 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Table Operation Manager
|
|
3
|
+
|
|
4
|
+
This module provides high-level table operations that orchestrate
|
|
5
|
+
multiple Google Docs API calls for complex table manipulations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import List, Dict, Any, Tuple, Optional
|
|
11
|
+
|
|
12
|
+
from gdocs.docs_helpers import (
|
|
13
|
+
create_insert_table_request,
|
|
14
|
+
create_insert_text_request,
|
|
15
|
+
create_pin_table_header_rows_request,
|
|
16
|
+
)
|
|
17
|
+
from gdocs.docs_structure import find_tables
|
|
18
|
+
from gdocs.docs_tables import validate_table_data
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TableOperationManager:
|
|
24
|
+
"""
|
|
25
|
+
High-level manager for Google Docs table operations.
|
|
26
|
+
|
|
27
|
+
Handles complex multi-step table operations including:
|
|
28
|
+
- Creating tables with data population
|
|
29
|
+
- Populating existing tables
|
|
30
|
+
- Managing cell-by-cell operations with proper index refreshing
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, service):
|
|
34
|
+
"""
|
|
35
|
+
Initialize the table operation manager.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
service: Google Docs API service instance
|
|
39
|
+
"""
|
|
40
|
+
self.service = service
|
|
41
|
+
|
|
42
|
+
async def create_and_populate_table(
|
|
43
|
+
self,
|
|
44
|
+
document_id: str,
|
|
45
|
+
table_data: List[List[str]],
|
|
46
|
+
index: int,
|
|
47
|
+
bold_headers: bool = True,
|
|
48
|
+
tab_id: Optional[str] = None,
|
|
49
|
+
header_rows: int = 0,
|
|
50
|
+
) -> Tuple[bool, str, Dict[str, Any]]:
|
|
51
|
+
"""
|
|
52
|
+
Creates a table and populates it with data in a reliable multi-step process.
|
|
53
|
+
|
|
54
|
+
This method extracts the complex logic from create_table_with_data tool function.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
document_id: ID of the document to update
|
|
58
|
+
table_data: 2D list of strings for table content
|
|
59
|
+
index: Position to insert the table
|
|
60
|
+
bold_headers: Whether to make the first row bold
|
|
61
|
+
tab_id: Optional tab ID for targeting a specific tab
|
|
62
|
+
header_rows: Number of leading rows to mark as a repeating page header
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
Tuple of (success, message, metadata)
|
|
66
|
+
"""
|
|
67
|
+
logger.debug(
|
|
68
|
+
f"Creating table at index {index}, dimensions: {len(table_data)}x{len(table_data[0]) if table_data and len(table_data) > 0 else 0}"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
# Validate input data
|
|
72
|
+
is_valid, error_msg = validate_table_data(table_data)
|
|
73
|
+
if not is_valid:
|
|
74
|
+
return False, f"Invalid table data: {error_msg}", {}
|
|
75
|
+
|
|
76
|
+
rows = len(table_data)
|
|
77
|
+
cols = len(table_data[0])
|
|
78
|
+
|
|
79
|
+
if not 0 <= header_rows <= rows:
|
|
80
|
+
return (
|
|
81
|
+
False,
|
|
82
|
+
f"header_rows must be between 0 and the table row count ({rows})",
|
|
83
|
+
{},
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
# Step 1: Create empty table
|
|
88
|
+
await self._create_empty_table(document_id, index, rows, cols, tab_id)
|
|
89
|
+
|
|
90
|
+
# Step 2: Get fresh document structure to find actual cell positions
|
|
91
|
+
fresh_tables = await self._get_document_tables(document_id, tab_id)
|
|
92
|
+
if not fresh_tables:
|
|
93
|
+
return False, "Could not find table after creation", {}
|
|
94
|
+
|
|
95
|
+
# Step 3: Find the newly created table by insertion index
|
|
96
|
+
# The table should be at or near the requested index
|
|
97
|
+
target_table = self._find_table_near_index(fresh_tables, index)
|
|
98
|
+
if not target_table:
|
|
99
|
+
return (
|
|
100
|
+
False,
|
|
101
|
+
f"Could not locate newly created table near index {index}",
|
|
102
|
+
{},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Step 4: Populate all cells and pin any header rows in one batch.
|
|
106
|
+
try:
|
|
107
|
+
population_count = await self._populate_table_cells_batch(
|
|
108
|
+
document_id,
|
|
109
|
+
target_table,
|
|
110
|
+
table_data,
|
|
111
|
+
bold_headers,
|
|
112
|
+
tab_id,
|
|
113
|
+
header_rows,
|
|
114
|
+
)
|
|
115
|
+
except Exception as e:
|
|
116
|
+
if header_rows <= 0:
|
|
117
|
+
raise
|
|
118
|
+
|
|
119
|
+
logger.error(
|
|
120
|
+
"Table was created, but the population/header-pinning batch "
|
|
121
|
+
f"failed: {str(e)}"
|
|
122
|
+
)
|
|
123
|
+
return (
|
|
124
|
+
True,
|
|
125
|
+
"Table was created, but population and header pinning failed: "
|
|
126
|
+
f"{str(e)}. Do not retry table creation.",
|
|
127
|
+
{
|
|
128
|
+
"rows": rows,
|
|
129
|
+
"columns": cols,
|
|
130
|
+
"populated_cells": 0,
|
|
131
|
+
"total_cells": rows * cols,
|
|
132
|
+
"table_created": True,
|
|
133
|
+
"partial_success": True,
|
|
134
|
+
"header_rows_applied": False,
|
|
135
|
+
},
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
metadata = {
|
|
139
|
+
"rows": rows,
|
|
140
|
+
"columns": cols,
|
|
141
|
+
"populated_cells": population_count,
|
|
142
|
+
"total_cells": rows * cols,
|
|
143
|
+
"header_rows_applied": header_rows > 0,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return (
|
|
147
|
+
True,
|
|
148
|
+
f"Successfully created {rows}x{cols} table and populated {population_count} cells",
|
|
149
|
+
metadata,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
except Exception as e:
|
|
153
|
+
logger.error(f"Failed to create and populate table: {str(e)}")
|
|
154
|
+
return False, f"Table creation failed: {str(e)}", {}
|
|
155
|
+
|
|
156
|
+
async def _create_empty_table(
|
|
157
|
+
self,
|
|
158
|
+
document_id: str,
|
|
159
|
+
index: int,
|
|
160
|
+
rows: int,
|
|
161
|
+
cols: int,
|
|
162
|
+
tab_id: Optional[str] = None,
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Create an empty table at the specified index."""
|
|
165
|
+
logger.debug(f"Creating {rows}x{cols} table at index {index}")
|
|
166
|
+
|
|
167
|
+
await asyncio.to_thread(
|
|
168
|
+
self.service.documents()
|
|
169
|
+
.batchUpdate(
|
|
170
|
+
documentId=document_id,
|
|
171
|
+
body={
|
|
172
|
+
"requests": [create_insert_table_request(index, rows, cols, tab_id)]
|
|
173
|
+
},
|
|
174
|
+
)
|
|
175
|
+
.execute
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
async def _get_document_tables(
|
|
179
|
+
self, document_id: str, tab_id: Optional[str] = None
|
|
180
|
+
) -> List[Dict[str, Any]]:
|
|
181
|
+
"""Get fresh document structure and extract table information."""
|
|
182
|
+
doc = await asyncio.to_thread(
|
|
183
|
+
self.service.documents()
|
|
184
|
+
.get(documentId=document_id, includeTabsContent=bool(tab_id))
|
|
185
|
+
.execute
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
if tab_id:
|
|
189
|
+
tab = self._find_tab(doc.get("tabs", []), tab_id)
|
|
190
|
+
if not tab:
|
|
191
|
+
raise ValueError(f"Tab {tab_id} not found in document.")
|
|
192
|
+
if "documentTab" not in tab:
|
|
193
|
+
raise ValueError(
|
|
194
|
+
f"Tab {tab_id} is not a document tab and has no body content."
|
|
195
|
+
)
|
|
196
|
+
doc = tab["documentTab"]
|
|
197
|
+
|
|
198
|
+
return find_tables(doc)
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _find_tab(tabs: list, target_id: str):
|
|
202
|
+
"""Recursively find a tab by ID."""
|
|
203
|
+
for tab in tabs:
|
|
204
|
+
if tab.get("tabProperties", {}).get("tabId") == target_id:
|
|
205
|
+
return tab
|
|
206
|
+
if "childTabs" in tab:
|
|
207
|
+
found = TableOperationManager._find_tab(tab["childTabs"], target_id)
|
|
208
|
+
if found:
|
|
209
|
+
return found
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _find_table_near_index(
|
|
214
|
+
tables: List[Dict[str, Any]], target_index: int
|
|
215
|
+
) -> Optional[Dict[str, Any]]:
|
|
216
|
+
"""
|
|
217
|
+
Find the table whose start_index is closest to the target insertion index.
|
|
218
|
+
|
|
219
|
+
When a table is inserted at an index, the table's actual start_index
|
|
220
|
+
will be at or very near the requested index. We find the best match
|
|
221
|
+
rather than blindly using tables[-1].
|
|
222
|
+
"""
|
|
223
|
+
if not tables:
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
best_match = None
|
|
227
|
+
best_distance = float("inf")
|
|
228
|
+
|
|
229
|
+
for table in tables:
|
|
230
|
+
distance = abs(table["start_index"] - target_index)
|
|
231
|
+
if distance < best_distance:
|
|
232
|
+
best_distance = distance
|
|
233
|
+
best_match = table
|
|
234
|
+
|
|
235
|
+
# If the closest table is very far from the target, something is wrong.
|
|
236
|
+
# Return None so the caller can fail cleanly rather than populate
|
|
237
|
+
# the wrong table.
|
|
238
|
+
if best_distance > 10:
|
|
239
|
+
logger.warning(
|
|
240
|
+
f"Closest table to index {target_index} is at {best_match['start_index']} "
|
|
241
|
+
f"(distance={best_distance}). This may indicate an index mismatch."
|
|
242
|
+
)
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
return best_match
|
|
246
|
+
|
|
247
|
+
async def _populate_table_cells_batch(
|
|
248
|
+
self,
|
|
249
|
+
document_id: str,
|
|
250
|
+
table: Dict[str, Any],
|
|
251
|
+
table_data: List[List[str]],
|
|
252
|
+
bold_headers: bool,
|
|
253
|
+
tab_id: Optional[str] = None,
|
|
254
|
+
header_rows: int = 0,
|
|
255
|
+
) -> int:
|
|
256
|
+
"""
|
|
257
|
+
Populate table cells and optionally pin header rows in one batchUpdate call.
|
|
258
|
+
|
|
259
|
+
Builds all insertText and updateTextStyle requests at once,
|
|
260
|
+
processing cells in reverse document order to avoid index shifting.
|
|
261
|
+
"""
|
|
262
|
+
cells = table.get("cells", [])
|
|
263
|
+
if not cells:
|
|
264
|
+
logger.warning("No cell information found in table")
|
|
265
|
+
|
|
266
|
+
requests = []
|
|
267
|
+
population_count = 0
|
|
268
|
+
|
|
269
|
+
# Build a list of (row_idx, col_idx, cell, text, should_bold) tuples
|
|
270
|
+
# then sort by insertion_index descending so insertions don't shift later indices
|
|
271
|
+
cell_operations = []
|
|
272
|
+
|
|
273
|
+
for row_idx, row_data in enumerate(table_data if cells else []):
|
|
274
|
+
if row_idx >= len(cells):
|
|
275
|
+
logger.warning(
|
|
276
|
+
f"Data has more rows ({len(table_data)}) than table ({len(cells)})"
|
|
277
|
+
)
|
|
278
|
+
break
|
|
279
|
+
|
|
280
|
+
for col_idx, cell_text in enumerate(row_data):
|
|
281
|
+
if col_idx >= len(cells[row_idx]):
|
|
282
|
+
logger.warning(
|
|
283
|
+
f"Data has more columns ({len(row_data)}) than table row {row_idx} ({len(cells[row_idx])})"
|
|
284
|
+
)
|
|
285
|
+
break
|
|
286
|
+
|
|
287
|
+
if not cell_text: # Skip empty cells
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
cell = cells[row_idx][col_idx]
|
|
291
|
+
insertion_index = cell.get("insertion_index")
|
|
292
|
+
|
|
293
|
+
if insertion_index is None:
|
|
294
|
+
logger.warning(
|
|
295
|
+
f"No insertion_index for cell ({row_idx},{col_idx}), skipping"
|
|
296
|
+
)
|
|
297
|
+
continue
|
|
298
|
+
|
|
299
|
+
should_bold = bold_headers and row_idx == 0
|
|
300
|
+
cell_operations.append(
|
|
301
|
+
(insertion_index, row_idx, col_idx, cell_text, should_bold)
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
# Sort by insertion_index descending — process last cells first
|
|
305
|
+
# so that earlier insertions don't shift the indices of later ones
|
|
306
|
+
cell_operations.sort(key=lambda x: x[0], reverse=True)
|
|
307
|
+
|
|
308
|
+
for (
|
|
309
|
+
insertion_index,
|
|
310
|
+
row_idx,
|
|
311
|
+
col_idx,
|
|
312
|
+
cell_text,
|
|
313
|
+
should_bold,
|
|
314
|
+
) in cell_operations:
|
|
315
|
+
# Insert text using the helper that properly handles tab_id
|
|
316
|
+
requests.append(
|
|
317
|
+
create_insert_text_request(
|
|
318
|
+
index=insertion_index, text=cell_text, tab_id=tab_id
|
|
319
|
+
)
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
# Apply bold formatting if this is a header cell
|
|
323
|
+
if should_bold:
|
|
324
|
+
style_request = {
|
|
325
|
+
"updateTextStyle": {
|
|
326
|
+
"range": {
|
|
327
|
+
"startIndex": insertion_index,
|
|
328
|
+
"endIndex": insertion_index + len(cell_text),
|
|
329
|
+
},
|
|
330
|
+
"textStyle": {"bold": True},
|
|
331
|
+
"fields": "bold",
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if tab_id:
|
|
335
|
+
style_request["updateTextStyle"]["range"]["tabId"] = tab_id
|
|
336
|
+
requests.append(style_request)
|
|
337
|
+
|
|
338
|
+
population_count += 1
|
|
339
|
+
|
|
340
|
+
if header_rows > 0:
|
|
341
|
+
requests.append(
|
|
342
|
+
create_pin_table_header_rows_request(
|
|
343
|
+
table_start_index=table["start_index"],
|
|
344
|
+
pinned_header_rows_count=header_rows,
|
|
345
|
+
tab_id=tab_id,
|
|
346
|
+
)
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
if not requests:
|
|
350
|
+
logger.warning("No cell population requests generated")
|
|
351
|
+
return 0
|
|
352
|
+
|
|
353
|
+
logger.debug(
|
|
354
|
+
f"Sending {len(requests)} requests to populate {population_count} cells"
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
# Execute all insertions in a single batchUpdate
|
|
358
|
+
await asyncio.to_thread(
|
|
359
|
+
self.service.documents()
|
|
360
|
+
.batchUpdate(
|
|
361
|
+
documentId=document_id,
|
|
362
|
+
body={"requests": requests},
|
|
363
|
+
)
|
|
364
|
+
.execute
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
return population_count
|
|
368
|
+
|
|
369
|
+
async def populate_existing_table(
|
|
370
|
+
self,
|
|
371
|
+
document_id: str,
|
|
372
|
+
table_index: int,
|
|
373
|
+
table_data: List[List[str]],
|
|
374
|
+
tab_id: Optional[str] = None,
|
|
375
|
+
) -> Tuple[bool, str, Dict[str, Any]]:
|
|
376
|
+
"""
|
|
377
|
+
Populate an existing table with data.
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
document_id: ID of the document
|
|
381
|
+
table_index: Index of the table to populate (0-based)
|
|
382
|
+
table_data: 2D list of data to insert
|
|
383
|
+
tab_id: Optional tab ID for targeting a specific tab
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
Tuple of (success, message, metadata)
|
|
387
|
+
"""
|
|
388
|
+
try:
|
|
389
|
+
tables = await self._get_document_tables(document_id, tab_id)
|
|
390
|
+
if table_index < 0 or table_index >= len(tables):
|
|
391
|
+
return (
|
|
392
|
+
False,
|
|
393
|
+
f"Table index {table_index} not found. Document has {len(tables)} tables",
|
|
394
|
+
{},
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
table_info = tables[table_index]
|
|
398
|
+
|
|
399
|
+
# Validate dimensions
|
|
400
|
+
table_rows = table_info["rows"]
|
|
401
|
+
table_cols = table_info["columns"]
|
|
402
|
+
data_rows = len(table_data)
|
|
403
|
+
data_cols = len(table_data[0]) if table_data else 0
|
|
404
|
+
|
|
405
|
+
if data_rows > table_rows or data_cols > table_cols:
|
|
406
|
+
return (
|
|
407
|
+
False,
|
|
408
|
+
f"Data ({data_rows}x{data_cols}) exceeds table dimensions ({table_rows}x{table_cols})",
|
|
409
|
+
{},
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
# Populate cells using batch operation
|
|
413
|
+
population_count = await self._populate_existing_table_cells_batch(
|
|
414
|
+
document_id, table_info, table_data, tab_id
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
metadata = {
|
|
418
|
+
"table_index": table_index,
|
|
419
|
+
"populated_cells": population_count,
|
|
420
|
+
"table_dimensions": f"{table_rows}x{table_cols}",
|
|
421
|
+
"data_dimensions": f"{data_rows}x{data_cols}",
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return (
|
|
425
|
+
True,
|
|
426
|
+
f"Successfully populated {population_count} cells in existing table",
|
|
427
|
+
metadata,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
except Exception as e:
|
|
431
|
+
return False, f"Failed to populate existing table: {str(e)}", {}
|
|
432
|
+
|
|
433
|
+
async def _populate_existing_table_cells_batch(
|
|
434
|
+
self,
|
|
435
|
+
document_id: str,
|
|
436
|
+
table_info: Dict[str, Any],
|
|
437
|
+
table_data: List[List[str]],
|
|
438
|
+
tab_id: Optional[str] = None,
|
|
439
|
+
) -> int:
|
|
440
|
+
"""Populate cells in an existing table using a single batch operation."""
|
|
441
|
+
cells = table_info.get("cells", [])
|
|
442
|
+
if not cells:
|
|
443
|
+
return 0
|
|
444
|
+
|
|
445
|
+
requests = []
|
|
446
|
+
population_count = 0
|
|
447
|
+
|
|
448
|
+
# Build operations list sorted by index descending
|
|
449
|
+
cell_operations = []
|
|
450
|
+
|
|
451
|
+
for row_idx, row_data in enumerate(table_data):
|
|
452
|
+
if row_idx >= len(cells):
|
|
453
|
+
break
|
|
454
|
+
|
|
455
|
+
for col_idx, cell_text in enumerate(row_data):
|
|
456
|
+
if not cell_text:
|
|
457
|
+
continue
|
|
458
|
+
|
|
459
|
+
if col_idx >= len(cells[row_idx]):
|
|
460
|
+
continue
|
|
461
|
+
|
|
462
|
+
cell = cells[row_idx][col_idx]
|
|
463
|
+
# For existing tables, insert at end of existing content
|
|
464
|
+
cell_end = cell["end_index"] - 1 # Don't include cell end marker
|
|
465
|
+
cell_operations.append((cell_end, cell_text))
|
|
466
|
+
|
|
467
|
+
# Sort by index descending to avoid shifting
|
|
468
|
+
cell_operations.sort(key=lambda x: x[0], reverse=True)
|
|
469
|
+
|
|
470
|
+
for cell_end, cell_text in cell_operations:
|
|
471
|
+
requests.append(
|
|
472
|
+
create_insert_text_request(
|
|
473
|
+
index=cell_end, text=cell_text, tab_id=tab_id
|
|
474
|
+
)
|
|
475
|
+
)
|
|
476
|
+
population_count += 1
|
|
477
|
+
|
|
478
|
+
if requests:
|
|
479
|
+
await asyncio.to_thread(
|
|
480
|
+
self.service.documents()
|
|
481
|
+
.batchUpdate(
|
|
482
|
+
documentId=document_id,
|
|
483
|
+
body={"requests": requests},
|
|
484
|
+
)
|
|
485
|
+
.execute
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
return population_count
|