forked from KeithCu/writeragent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection.py
More file actions
374 lines (292 loc) · 13.7 KB
/
Copy pathselection.py
File metadata and controls
374 lines (292 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import logging
from typing import Any, cast
try:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
UNO_DISPOSED_EXCEPTIONS = (DisposedException, RuntimeException, UnoException)
except ImportError:
UNO_DISPOSED_EXCEPTIONS = cast("Any", (Exception,))
from plugin.framework.i18n import _
from plugin.framework.uno_context import get_ctx
from plugin.framework.async_stream import run_stream_async
from plugin.framework.config import get_api_config, set_config, get_current_endpoint
from plugin.framework.client.llm_client import LlmClient
from plugin.doc.document_helpers import (
WriterCompoundUndo,
get_string_without_tracked_deletions,
build_writer_rewrite_prompt,
WriterStreamedRewriteSession,
)
from plugin.chatbot.config_ui_helpers import update_lru_history
from .dialogs import msgbox
from .dialog_views import input_box
log = logging.getLogger("writeragent.chatbot.selection")
# ── Extend Selection ─────────────────────────────────────────────
def action_extend_selection(services):
"""Get document selection -> stream AI completion -> append to text."""
ctx = get_ctx()
doc_svc = services.document
doc = doc_svc.get_active_document()
if not doc:
msgbox(ctx, "WriterAgent", "No document open")
return
doc_type = doc_svc.detect_doc_type(doc)
if doc_type == "writer":
_extend_writer(services, ctx, doc)
elif doc_type == "calc":
_extend_calc(services, ctx, doc)
else:
msgbox(ctx, "WriterAgent", "Extend selection not supported for this document type")
def _extend_writer(services, ctx, doc):
"""Extend selection in a Writer document."""
try:
selection = doc.CurrentController.getSelection()
text_range = selection.getByIndex(0)
selected_text = get_string_without_tracked_deletions(text_range)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to get Writer selection (likely disposed): %s", e)
else:
log.debug("No valid Writer selection found: %s", e)
msgbox(ctx, "WriterAgent", "No text selected")
return
if not selected_text:
msgbox(ctx, "WriterAgent", "No text selected")
return
config = services.config.proxy_for("chatbot")
system_prompt = config.get("system_prompt") or ""
_mt = config.get("extend_selection_max_tokens") or 70
max_tokens = int(float(_mt))
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": selected_text})
compound_undo = WriterCompoundUndo(doc, "WriterAgent: Extend selection")
def apply_chunk(text, is_thinking=False):
if not is_thinking:
try:
text_range.setString(text_range.getString() + text)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to append text to Writer selection (likely disposed): %s", e)
else:
log.exception("Failed to append text")
def on_done():
compound_undo.close()
def on_error(e):
try:
log.exception("Extend selection failed")
msgbox(ctx, _("WriterAgent: Extend Selection"), str(e))
finally:
compound_undo.close()
api_config = get_api_config(ctx)
client = LlmClient(api_config, ctx)
run_stream_async(ctx, client, messages, tools=None, apply_chunk_fn=apply_chunk, on_done_fn=on_done, on_error_fn=on_error, max_tokens=max_tokens)
def _extend_calc(services, ctx, doc):
"""Extend selection in a Calc document."""
try:
sheet = doc.CurrentController.ActiveSheet
selection = doc.CurrentController.Selection
area = selection.getRangeAddress()
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to get Calc selection (likely disposed): %s", e)
else:
log.debug("No valid Calc selection found: %s", e)
msgbox(ctx, "WriterAgent", "No cells selected")
return
config = services.config.proxy_for("chatbot")
system_prompt = config.get("system_prompt") or ""
_mt = config.get("extend_selection_max_tokens") or 70
max_tokens = int(float(_mt))
# Build task list
tasks = []
cell_range = sheet.getCellRangeByPosition(area.StartColumn, area.StartRow, area.EndColumn, area.EndRow)
data_array = cell_range.getDataArray()
for row_idx, row in enumerate(range(area.StartRow, area.EndRow + 1)):
for col_idx, col in enumerate(range(area.StartColumn, area.EndColumn + 1)):
raw_val = data_array[row_idx][col_idx]
cell_text = str(raw_val) if raw_val != "" and raw_val is not None else ""
if cell_text:
cell = sheet.getCellByPosition(col, row)
tasks.append((cell, cell_text))
if not tasks:
msgbox(ctx, "WriterAgent", "No cells with content selected")
return
api_config = get_api_config(ctx)
client = LlmClient(api_config, ctx)
# Process cells sequentially via callback chain
task_index = [0]
def run_next_cell():
if task_index[0] >= len(tasks):
return
cell, cell_text = tasks[task_index[0]]
task_index[0] += 1
msgs = []
if system_prompt:
msgs.append({"role": "system", "content": system_prompt})
msgs.append({"role": "user", "content": cell_text})
def apply_chunk(text, is_thinking=False):
if not is_thinking:
try:
cell.setString(cell.getString() + text)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to append text to Calc cell (likely disposed): %s", e)
def on_error(e):
log.exception("Extend selection (calc) failed")
msgbox(ctx, _("WriterAgent: Extend Selection"), str(e))
run_stream_async(ctx, client, msgs, tools=None, apply_chunk_fn=apply_chunk, on_done_fn=run_next_cell, on_error_fn=on_error, max_tokens=max_tokens)
run_next_cell()
# ── Edit Selection ───────────────────────────────────────────────
def action_edit_selection(services):
"""Get selection -> input instructions -> stream AI -> replace text."""
ctx = get_ctx()
doc_svc = services.document
doc = doc_svc.get_active_document()
if not doc:
msgbox(ctx, "WriterAgent", "No document open")
return
doc_type = doc_svc.detect_doc_type(doc)
if doc_type == "writer":
_edit_writer(services, ctx, doc)
elif doc_type == "calc":
_edit_calc(services, ctx, doc)
else:
msgbox(ctx, "WriterAgent", "Edit selection not supported for this document type")
def _show_edit_input():
"""Show the edit instructions dialog. Returns (user_input, extra_instructions); empty strings if cancelled.
Uses the shared EditInputDialog.xdl (legacy_ui.input_box) so menu and shortcut share the same UI.
"""
ctx = get_ctx()
user_input, extra_instructions = input_box(ctx, "Please enter edit instructions!", "Input", "")
return user_input, extra_instructions
def _edit_writer(services, ctx, doc):
"""Edit selection in a Writer document."""
try:
selection = doc.CurrentController.getSelection()
text_range = selection.getByIndex(0)
original_text = get_string_without_tracked_deletions(text_range)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to get Writer selection for edit (likely disposed): %s", e)
else:
log.debug("No valid Writer selection found for edit: %s", e)
msgbox(ctx, "WriterAgent", "No text selected")
return
if not original_text:
msgbox(ctx, "WriterAgent", "No text selected")
return
user_input, extra_instructions = _show_edit_input()
if not user_input:
return
if extra_instructions:
set_config(ctx, "additional_instructions", extra_instructions)
update_lru_history(ctx, extra_instructions, "prompt_lru", get_current_endpoint(ctx))
config = services.config.proxy_for("chatbot")
system_prompt = extra_instructions or config.get("system_prompt") or ""
_mnt = config.get("edit_selection_max_new_tokens") or 0
max_new_tokens = int(float(_mnt))
prompt = build_writer_rewrite_prompt(original_text, user_input)
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
max_tokens = len(original_text) + max_new_tokens
session = WriterStreamedRewriteSession(doc, text_range, original_text)
def apply_chunk(text, is_thinking=False):
if not is_thinking:
session.append_chunk(text)
def on_done():
warning = session.finish()
if warning:
log.warning("Writer streamed rewrite fallback: %s", warning)
msgbox(ctx, _("WriterAgent: Edit Selection"), warning)
def on_error(e):
try:
session.abort_and_restore()
except Exception as recovery_err:
if isinstance(recovery_err, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to restore original text (likely disposed): %s", recovery_err)
log.exception("Edit selection failed")
msgbox(ctx, _("WriterAgent: Edit Selection"), str(e))
api_config = get_api_config(ctx)
client = LlmClient(api_config, ctx)
run_stream_async(ctx, client, messages, tools=None, apply_chunk_fn=apply_chunk, on_done_fn=on_done, on_error_fn=on_error, max_tokens=max_tokens)
def _edit_calc(services, ctx, doc):
"""Edit selection in a Calc document."""
try:
sheet = doc.CurrentController.ActiveSheet
selection = doc.CurrentController.Selection
area = selection.getRangeAddress()
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to get Calc selection for edit (likely disposed): %s", e)
else:
log.debug("No valid Calc selection found for edit: %s", e)
msgbox(ctx, "WriterAgent", "No cells selected")
return
user_input, extra_instructions = _show_edit_input()
if not user_input:
return
if extra_instructions:
set_config(ctx, "additional_instructions", extra_instructions)
update_lru_history(ctx, extra_instructions, "prompt_lru", get_current_endpoint(ctx))
config = services.config.proxy_for("chatbot")
system_prompt = extra_instructions or config.get("system_prompt") or ""
_mnt = config.get("edit_selection_max_new_tokens") or 0
max_new_tokens = int(float(_mnt))
# Build task list
tasks = []
cell_range = sheet.getCellRangeByPosition(area.StartColumn, area.StartRow, area.EndColumn, area.EndRow)
data_array = cell_range.getDataArray()
for row_idx, row in enumerate(range(area.StartRow, area.EndRow + 1)):
for col_idx, col in enumerate(range(area.StartColumn, area.EndColumn + 1)):
raw_val = data_array[row_idx][col_idx]
original = str(raw_val) if raw_val != "" and raw_val is not None else ""
prompt = (
"ORIGINAL VERSION:\n" + original + "\n Below is an edited version according to the following "
"instructions. Don't waste time thinking, be as fast as "
"you can. The edited text will be a shorter or longer "
"version of the original text based on the instructions. "
"There are no comments in the edited version. The edited "
"version is followed by the end of the document. The "
"original version will be edited as follows to create "
"the edited version:\n" + user_input + "\nEDITED VERSION:\n"
)
max_tokens = len(original) + max_new_tokens
cell = sheet.getCellByPosition(col, row)
tasks.append((cell, prompt, max_tokens, original))
if not tasks:
return
api_config = get_api_config(ctx)
client = LlmClient(api_config, ctx)
# Process cells sequentially
task_index = [0]
def run_next_cell():
if task_index[0] >= len(tasks):
return
cell, prompt, max_tok, original = tasks[task_index[0]]
task_index[0] += 1
cell.setString("")
msgs = []
if system_prompt:
msgs.append({"role": "system", "content": system_prompt})
msgs.append({"role": "user", "content": prompt})
def apply_chunk(text, is_thinking=False):
if not is_thinking:
try:
cell.setString(cell.getString() + text)
except Exception as e:
if isinstance(e, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to write text to Calc cell (likely disposed): %s", e)
def on_error(e):
try:
cell.setString(original)
except Exception as recovery_err:
if isinstance(recovery_err, UNO_DISPOSED_EXCEPTIONS):
log.debug("Failed to restore original cell text (likely disposed): %s", recovery_err)
log.exception("Edit selection (calc) failed")
msgbox(ctx, _("WriterAgent: Edit Selection"), str(e))
run_stream_async(ctx, client, msgs, tools=None, apply_chunk_fn=apply_chunk, on_done_fn=run_next_cell, on_error_fn=on_error, max_tokens=max_tok)
run_next_cell()