gformbot 0.4.2__tar.gz → 0.4.3__tar.gz
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.
- {gformbot-0.4.2 → gformbot-0.4.3}/CHANGELOG.md +7 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/PKG-INFO +5 -5
- {gformbot-0.4.2 → gformbot-0.4.3}/README.md +4 -4
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/__init__.py +1 -1
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/ai.py +3 -1
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/ai_draft.py +53 -3
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/ai_partition.py +3 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/chatgpt_http.py +7 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/cli.py +118 -58
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/editor.html +72 -20
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/editor.py +40 -32
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/followups.py +82 -41
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/generation.py +5 -1
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/state.py +17 -8
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/PKG-INFO +5 -5
- {gformbot-0.4.2 → gformbot-0.4.3}/pyproject.toml +1 -1
- {gformbot-0.4.2 → gformbot-0.4.3}/LICENSE +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/LICENSE-chatgpt-protocol +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/MANIFEST.in +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/SECURITY.md +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/__main__.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/access.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/ai_context.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/answers.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/artifacts.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/config.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/execution.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/generation_contacts.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/generation_quality.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/generation_review.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/generator.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/grids.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/inspector.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/locking.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/logger.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/media.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/patterns.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/previews.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/routing.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/terminal.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/transport.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot/validation.py +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/SOURCES.txt +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/dependency_links.txt +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/entry_points.txt +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/requires.txt +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/gformbot.egg-info/top_level.txt +0 -0
- {gformbot-0.4.2 → gformbot-0.4.3}/setup.cfg +0 -0
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.3
|
|
4
|
+
|
|
5
|
+
- Show the form introduction before the question table and open the preview automatically in Start a new form.
|
|
6
|
+
- Show repeated confirmation messages once and highlight follow-up links after submission.
|
|
7
|
+
- Resume interrupted AI generation and review from Saved batches, with progress and timestamps.
|
|
8
|
+
- Edit multiple responses and save them together. Pick up links copied after the prompt opens and use a plain menu pointer.
|
|
9
|
+
|
|
3
10
|
## 0.4.2
|
|
4
11
|
|
|
5
12
|
- Lead the README and PyPI quickstart with Quick submit and synthetic response generation.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gformbot
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.3
|
|
4
4
|
Summary: Generate, prepare, and submit Google Forms responses with ChatGPT or supplied data.
|
|
5
5
|
Author: yogeshkrishna
|
|
6
6
|
License-Expression: Apache-2.0 AND MIT
|
|
@@ -88,7 +88,7 @@ python -m gformbot generate "YOUR_RESPONDER_URL" -n 5 -m "Vary the fictional sig
|
|
|
88
88
|
<img src="https://raw.githubusercontent.com/yogeshkrishna/google_form_test_bot/master/readme/workflow.svg" alt="Read the form, choose answers, validate the batch, and submit over HTTPS." width="900">
|
|
89
89
|
</p>
|
|
90
90
|
|
|
91
|
-
Choose **Start a new form**
|
|
91
|
+
Choose **Start a new form** to see the form introduction and questions before choosing where the answers come from. In **Review or edit responses**, move between responses and choose **Save and finish** to save your edits together.
|
|
92
92
|
|
|
93
93
|
## Choose your answer source
|
|
94
94
|
|
|
@@ -132,9 +132,9 @@ The form must be open to responses without Google sign-in. Account-verified emai
|
|
|
132
132
|
| What you see | What to do |
|
|
133
133
|
| --- | --- |
|
|
134
134
|
| **Ready to submit** | Open the plan from **Saved batches** to review, export, or send it. |
|
|
135
|
-
| **
|
|
136
|
-
| **
|
|
137
|
-
| **AI generation interrupted** |
|
|
135
|
+
| **Submission interrupted** | Open **Saved batches** and choose the batch by its progress and date. Confirmed responses are skipped. |
|
|
136
|
+
| **A response needs checking** | Look in Google Forms or the linked sheet before choosing whether to retry. A lost connection can leave the result uncertain. |
|
|
137
|
+
| **AI generation or quality review interrupted** | Open **Saved batches** to pick up the saved AI draft. |
|
|
138
138
|
| **Looking for a receipt or instructions?** | Open **More options → View recent activity** from the folder you ran the batch in, or use `log --followups`. |
|
|
139
139
|
|
|
140
140
|
GFormBot tracks submission outcomes in a local journal. Keep the original plan and journal when resuming. Files supplied as input and plans made with `prepare` are preserved. Temporary plans created for submission can be cleaned up after Google confirms the entire batch.
|
|
@@ -48,7 +48,7 @@ python -m gformbot generate "YOUR_RESPONDER_URL" -n 5 -m "Vary the fictional sig
|
|
|
48
48
|
<img src="https://raw.githubusercontent.com/yogeshkrishna/google_form_test_bot/master/readme/workflow.svg" alt="Read the form, choose answers, validate the batch, and submit over HTTPS." width="900">
|
|
49
49
|
</p>
|
|
50
50
|
|
|
51
|
-
Choose **Start a new form**
|
|
51
|
+
Choose **Start a new form** to see the form introduction and questions before choosing where the answers come from. In **Review or edit responses**, move between responses and choose **Save and finish** to save your edits together.
|
|
52
52
|
|
|
53
53
|
## Choose your answer source
|
|
54
54
|
|
|
@@ -92,9 +92,9 @@ The form must be open to responses without Google sign-in. Account-verified emai
|
|
|
92
92
|
| What you see | What to do |
|
|
93
93
|
| --- | --- |
|
|
94
94
|
| **Ready to submit** | Open the plan from **Saved batches** to review, export, or send it. |
|
|
95
|
-
| **
|
|
96
|
-
| **
|
|
97
|
-
| **AI generation interrupted** |
|
|
95
|
+
| **Submission interrupted** | Open **Saved batches** and choose the batch by its progress and date. Confirmed responses are skipped. |
|
|
96
|
+
| **A response needs checking** | Look in Google Forms or the linked sheet before choosing whether to retry. A lost connection can leave the result uncertain. |
|
|
97
|
+
| **AI generation or quality review interrupted** | Open **Saved batches** to pick up the saved AI draft. |
|
|
98
98
|
| **Looking for a receipt or instructions?** | Open **More options → View recent activity** from the folder you ran the batch in, or use `log --followups`. |
|
|
99
99
|
|
|
100
100
|
GFormBot tracks submission outcomes in a local journal. Keep the original plan and journal when resuming. Files supplied as input and plans made with `prepare` are preserved. Temporary plans created for submission can be cleaned up after Google confirms the entire batch.
|
|
@@ -993,7 +993,7 @@ def _generate_responses(
|
|
|
993
993
|
attempts[index] += 1
|
|
994
994
|
try:
|
|
995
995
|
content = client.ask(messages, timeout=timeout)
|
|
996
|
-
except (ChatHTTPError, RuntimeError) as exc:
|
|
996
|
+
except (ChatHTTPError, RuntimeError, KeyboardInterrupt) as exc:
|
|
997
997
|
partial = getattr(exc, "partial_content", "")
|
|
998
998
|
if partial:
|
|
999
999
|
valid, _, _ = _validate_records(
|
|
@@ -1001,6 +1001,8 @@ def _generate_responses(
|
|
|
1001
1001
|
)
|
|
1002
1002
|
accept(valid)
|
|
1003
1003
|
completed = sum(row is not None for row in answers)
|
|
1004
|
+
if isinstance(exc, KeyboardInterrupt):
|
|
1005
|
+
raise
|
|
1004
1006
|
if getattr(exc, "retryable", False):
|
|
1005
1007
|
for index in pending:
|
|
1006
1008
|
if answers[index] is None:
|
|
@@ -232,6 +232,10 @@ def _rows(rows):
|
|
|
232
232
|
return None if rows is None else [{int(key): value for key, value in row.items()} for row in rows]
|
|
233
233
|
|
|
234
234
|
|
|
235
|
+
def saved_paths():
|
|
236
|
+
return (previews.index_path().parent / "ai-drafts").glob("*.json")
|
|
237
|
+
|
|
238
|
+
|
|
235
239
|
def partition_flat_profiles(config, profiles, partials):
|
|
236
240
|
"""Keep accepted flat profiles and start only pending profiles in the partitioner."""
|
|
237
241
|
from .ai_partition import _units
|
|
@@ -295,6 +299,44 @@ class Draft:
|
|
|
295
299
|
def strategy(self):
|
|
296
300
|
return self._strategy
|
|
297
301
|
|
|
302
|
+
@property
|
|
303
|
+
def created_at(self):
|
|
304
|
+
return datetime.fromisoformat(self._payload["created_at"])
|
|
305
|
+
|
|
306
|
+
def progress_label(self):
|
|
307
|
+
profiles = self.state["profiles"]
|
|
308
|
+
total = len(profiles)
|
|
309
|
+
if self.strategy == "flat":
|
|
310
|
+
generated = sum(profile["position"] == 1 for profile in profiles)
|
|
311
|
+
else:
|
|
312
|
+
from .ai_partition import _units
|
|
313
|
+
|
|
314
|
+
sizes = {page: len(units) for page, units in _units(self.config).items()}
|
|
315
|
+
generated = routed = saved_groups = total_groups = 0
|
|
316
|
+
for profile in profiles:
|
|
317
|
+
if profile["route"] is None:
|
|
318
|
+
continue
|
|
319
|
+
groups = sum(sizes.get(page, 0) for page in profile["route"])
|
|
320
|
+
routed += 1
|
|
321
|
+
saved_groups += profile["position"]
|
|
322
|
+
total_groups += groups
|
|
323
|
+
generated += profile["position"] == groups
|
|
324
|
+
if generated < total and saved_groups:
|
|
325
|
+
if routed == total:
|
|
326
|
+
progress = f"{saved_groups}/{total_groups} question groups saved"
|
|
327
|
+
else:
|
|
328
|
+
unit = "question group" if saved_groups == 1 else "question groups"
|
|
329
|
+
progress = f"{saved_groups} {unit} saved"
|
|
330
|
+
return f"{generated}/{total} generated · {progress}"
|
|
331
|
+
if generated == total:
|
|
332
|
+
checked = len(self.state.get("review", {}).get("checked", ()))
|
|
333
|
+
review_total = self.state.get("setup", {}).get("review_total")
|
|
334
|
+
if type(review_total) is int and 0 < review_total <= total and checked <= review_total:
|
|
335
|
+
return f"{checked}/{review_total} quality checked"
|
|
336
|
+
if checked:
|
|
337
|
+
return f"{checked} quality checked"
|
|
338
|
+
return f"{generated}/{total} generated"
|
|
339
|
+
|
|
298
340
|
@classmethod
|
|
299
341
|
def create(cls, config, reference, instructions, partials, state, *, options=None):
|
|
300
342
|
validate_config(config)
|
|
@@ -332,14 +374,22 @@ class Draft:
|
|
|
332
374
|
return cls(path, payload, _read(path)[1], stored)
|
|
333
375
|
|
|
334
376
|
@classmethod
|
|
335
|
-
def
|
|
377
|
+
def read(cls, path):
|
|
336
378
|
path = clean_path(path).absolute()
|
|
337
379
|
payload, digest = _read(path)
|
|
338
380
|
config = _validate(payload)
|
|
339
|
-
if payload["form_fingerprint"] != _fingerprint(current):
|
|
340
|
-
raise ValueError("The form or its instructions changed. Start a new generation request.")
|
|
341
381
|
return cls(path, payload, digest, config)
|
|
342
382
|
|
|
383
|
+
@classmethod
|
|
384
|
+
def load(cls, path, current):
|
|
385
|
+
draft = cls.read(path)
|
|
386
|
+
draft.check_form(current)
|
|
387
|
+
return draft
|
|
388
|
+
|
|
389
|
+
def check_form(self, current):
|
|
390
|
+
if self._payload["form_fingerprint"] != _fingerprint(current):
|
|
391
|
+
raise ValueError("The form or its instructions changed. Start a new generation request.")
|
|
392
|
+
|
|
343
393
|
def _unchanged(self):
|
|
344
394
|
payload, digest = _read(self.path)
|
|
345
395
|
if digest != self._digest:
|
|
@@ -537,6 +537,9 @@ def generate_partitioned(
|
|
|
537
537
|
},
|
|
538
538
|
provider_error=getattr(error, "provider_error", None),
|
|
539
539
|
) from error
|
|
540
|
+
except KeyboardInterrupt:
|
|
541
|
+
client.cancel()
|
|
542
|
+
raise
|
|
540
543
|
finally:
|
|
541
544
|
executor.shutdown(wait=True, cancel_futures=True)
|
|
542
545
|
if own_client:
|
|
@@ -374,6 +374,13 @@ class Client:
|
|
|
374
374
|
# Retain the last line in case the event's blank separator arrives next.
|
|
375
375
|
last_newline = body.rfind(b"\n")
|
|
376
376
|
scan_from = max(scan_from, body.rfind(b"\n", scan_from, last_newline) + 1)
|
|
377
|
+
except KeyboardInterrupt as interrupt:
|
|
378
|
+
if streaming and body:
|
|
379
|
+
try:
|
|
380
|
+
interrupt.partial_content = _parse_stream(body)
|
|
381
|
+
except ChatHTTPError as error:
|
|
382
|
+
interrupt.partial_content = error.partial_content
|
|
383
|
+
raise
|
|
377
384
|
except ChatHTTPError as error:
|
|
378
385
|
failure = error
|
|
379
386
|
except (urllib3.exceptions.TimeoutError, TimeoutError):
|
|
@@ -56,7 +56,7 @@ def _choice(value, name):
|
|
|
56
56
|
return MenuChoice(value, name)
|
|
57
57
|
|
|
58
58
|
|
|
59
|
-
def _ask_text(message, default="", *, completed=False):
|
|
59
|
+
def _ask_text(message, default="", *, completed=False, watch_clipboard=None):
|
|
60
60
|
if _INQUIRER:
|
|
61
61
|
from InquirerPy import get_style, inquirer
|
|
62
62
|
|
|
@@ -67,7 +67,10 @@ def _ask_text(message, default="", *, completed=False):
|
|
|
67
67
|
style_override=False,
|
|
68
68
|
)
|
|
69
69
|
options["transformer"] = lambda value: value.strip() or default or "(skipped)"
|
|
70
|
-
|
|
70
|
+
prompt = inquirer.text(message=message, **options)
|
|
71
|
+
if watch_clipboard is not None:
|
|
72
|
+
_watch_clipboard_link(prompt, watch_clipboard)
|
|
73
|
+
value = run_prompt(prompt, typing=True)
|
|
71
74
|
if value is None:
|
|
72
75
|
raise click.Abort()
|
|
73
76
|
return value.strip() or default
|
|
@@ -103,7 +106,10 @@ def _ask_select(message, choices, default=None):
|
|
|
103
106
|
from InquirerPy import inquirer
|
|
104
107
|
|
|
105
108
|
prompt = inquirer.select(
|
|
106
|
-
message=message,
|
|
109
|
+
message=message,
|
|
110
|
+
choices=[{"value": c.value, "name": c.name} for c in choices],
|
|
111
|
+
default=default,
|
|
112
|
+
pointer=">",
|
|
107
113
|
)
|
|
108
114
|
if message == "Start" and not console.no_color:
|
|
109
115
|
accent_choice(prompt, "quick")
|
|
@@ -157,12 +163,34 @@ def _clipboard_url():
|
|
|
157
163
|
import pyperclip
|
|
158
164
|
|
|
159
165
|
value = pyperclip.paste().strip()
|
|
166
|
+
if not value.isprintable():
|
|
167
|
+
return None
|
|
160
168
|
valid, _ = _validate_form_url(value)
|
|
161
169
|
return value if valid else None
|
|
162
170
|
except Exception:
|
|
163
171
|
return None
|
|
164
172
|
|
|
165
173
|
|
|
174
|
+
def _watch_clipboard_link(prompt, previous):
|
|
175
|
+
from asyncio import sleep, to_thread
|
|
176
|
+
|
|
177
|
+
session = prompt._session
|
|
178
|
+
buffer = session.default_buffer
|
|
179
|
+
app = session.app
|
|
180
|
+
|
|
181
|
+
async def fill_empty_link():
|
|
182
|
+
while not buffer.text:
|
|
183
|
+
await sleep(0.25)
|
|
184
|
+
if buffer.text:
|
|
185
|
+
return
|
|
186
|
+
link = await to_thread(_clipboard_url)
|
|
187
|
+
if link and link != previous and not buffer.text:
|
|
188
|
+
buffer.insert_text(link)
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
app.pre_run_callables.append(lambda: app.create_background_task(fill_empty_link()))
|
|
192
|
+
|
|
193
|
+
|
|
166
194
|
def _validate_form_url(url):
|
|
167
195
|
from .inspector import clean_url
|
|
168
196
|
|
|
@@ -181,7 +209,9 @@ def _url_prompt(*, completed=False):
|
|
|
181
209
|
return url
|
|
182
210
|
try:
|
|
183
211
|
while True:
|
|
184
|
-
entered = _ask_text(
|
|
212
|
+
entered = _ask_text(
|
|
213
|
+
"Paste your public Google Form link", watch_clipboard=url or "", **options
|
|
214
|
+
)
|
|
185
215
|
valid, message = _validate_form_url(entered)
|
|
186
216
|
if valid:
|
|
187
217
|
return entered
|
|
@@ -200,6 +230,18 @@ def _show_form(config):
|
|
|
200
230
|
_section(config.form_title)
|
|
201
231
|
if config.form_description:
|
|
202
232
|
console.print(Text(config.form_description))
|
|
233
|
+
first_question = 2 if config.questions and config.questions[0].entry_id == "emailAddress" else 1
|
|
234
|
+
notes_by_question = {}
|
|
235
|
+
for note in config.instructions:
|
|
236
|
+
index = note["before_question"]
|
|
237
|
+
if note["page"] == 1 and index <= first_question:
|
|
238
|
+
if note["title"]:
|
|
239
|
+
console.print(Text(note["title"], style="bold"))
|
|
240
|
+
if note["description"]:
|
|
241
|
+
console.print(Text(note["description"]))
|
|
242
|
+
else:
|
|
243
|
+
notes_by_question.setdefault(index, []).append(note)
|
|
244
|
+
console.print()
|
|
203
245
|
table = Table(show_lines=True, header_style="bold cyan", expand=True)
|
|
204
246
|
table.add_column("Q", style="dim", no_wrap=True)
|
|
205
247
|
table.add_column("Question / description", ratio=3)
|
|
@@ -207,7 +249,7 @@ def _show_form(config):
|
|
|
207
249
|
table.add_column("Choices / rules", ratio=3)
|
|
208
250
|
previous_page = None
|
|
209
251
|
for q in config.questions:
|
|
210
|
-
notes =
|
|
252
|
+
notes = notes_by_question.pop(q.index, [])
|
|
211
253
|
|
|
212
254
|
def show_note(note):
|
|
213
255
|
table.add_row(
|
|
@@ -277,8 +319,8 @@ def _show_form(config):
|
|
|
277
319
|
Text(asset["caption"]),
|
|
278
320
|
)
|
|
279
321
|
console.print(media_table)
|
|
280
|
-
for
|
|
281
|
-
|
|
322
|
+
for notes in notes_by_question.values():
|
|
323
|
+
for note in notes:
|
|
282
324
|
_info(note["title"] + ("\n" + note["description"] if note["description"] else ""))
|
|
283
325
|
for issue in config.unsupported:
|
|
284
326
|
console.print(Text(issue, style="yellow"))
|
|
@@ -551,18 +593,19 @@ def _save_plan(config, answers, path=None, source="prepared", *, cleanup_on_succ
|
|
|
551
593
|
continue
|
|
552
594
|
atomic_json(target, payload)
|
|
553
595
|
break
|
|
554
|
-
if draft is not None:
|
|
555
|
-
try:
|
|
556
|
-
draft.finish()
|
|
557
|
-
except (OSError, ValueError) as exc:
|
|
558
|
-
_info(f"Could not remove the finished generation draft: {exc}")
|
|
559
|
-
config._generation_draft = None
|
|
560
596
|
from .previews import remember
|
|
561
597
|
|
|
562
598
|
try:
|
|
563
599
|
remember(target)
|
|
564
600
|
except OSError as exc:
|
|
565
601
|
_info(f"Answers saved, but could not remember their location: {exc}. Use the saved file with --data.")
|
|
602
|
+
else:
|
|
603
|
+
if draft is not None:
|
|
604
|
+
try:
|
|
605
|
+
draft.finish()
|
|
606
|
+
except (OSError, ValueError) as exc:
|
|
607
|
+
_info(f"Could not remove the finished generation draft: {exc}")
|
|
608
|
+
config._generation_draft = None
|
|
566
609
|
_info(f"Answers saved: {target.resolve()}")
|
|
567
610
|
return target
|
|
568
611
|
|
|
@@ -751,38 +794,34 @@ def _pending_preview(config, answers):
|
|
|
751
794
|
def _edit_batch(config, answers, path):
|
|
752
795
|
from .artifacts import digest
|
|
753
796
|
from .editor import review
|
|
754
|
-
from .generator import validate_answer
|
|
755
797
|
from .locking import file_lock
|
|
756
798
|
from .state import Journal, atomic_json, batch_id
|
|
757
799
|
|
|
758
800
|
path = clean_path(path)
|
|
759
|
-
config, answers = _load_plan(path)
|
|
760
801
|
expected = digest(path)
|
|
802
|
+
config, answers = _load_plan(path)
|
|
803
|
+
payload = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
804
|
+
journal = Journal(batch_id(payload))
|
|
805
|
+
confirmed = set(config._submitted_indices)
|
|
761
806
|
|
|
762
807
|
def statuses():
|
|
763
|
-
|
|
764
|
-
confirmed = set(current._submitted_indices)
|
|
808
|
+
outcomes = journal.states()
|
|
765
809
|
return [
|
|
766
810
|
"confirmed"
|
|
767
|
-
if i in confirmed
|
|
811
|
+
if i in confirmed or outcomes.get(i) == "confirmed"
|
|
768
812
|
else "uncertain"
|
|
769
|
-
if
|
|
813
|
+
if outcomes.get(i) in {"attempted", "reviewing", "uncertain"}
|
|
770
814
|
else "ready"
|
|
771
815
|
for i in range(1, len(answers) + 1)
|
|
772
816
|
]
|
|
773
817
|
|
|
774
|
-
def save(
|
|
775
|
-
nonlocal expected
|
|
818
|
+
def save(edits):
|
|
776
819
|
with file_lock(path, timeout=5):
|
|
777
820
|
if digest(path) != expected:
|
|
778
821
|
raise ValueError("The response file changed. Close the editor and reopen the batch.")
|
|
779
|
-
payload
|
|
780
|
-
answer = validate_answer(config, candidate)
|
|
781
|
-
Journal(batch_id(payload)).edit(payload, index, answer, lambda data: atomic_json(path, data))
|
|
782
|
-
expected = digest(path)
|
|
783
|
-
return answer
|
|
822
|
+
journal.edit(payload, edits, lambda data: atomic_json(path, data))
|
|
784
823
|
|
|
785
|
-
_info("Opening the local response editor.
|
|
824
|
+
_info("Opening the local response editor. Finish in the editor to return here.")
|
|
786
825
|
review(config, answers, save, statuses)
|
|
787
826
|
current, rows = _load_plan(path)
|
|
788
827
|
return current, rows, path
|
|
@@ -878,11 +917,19 @@ class SavedPreview:
|
|
|
878
917
|
answers: list
|
|
879
918
|
|
|
880
919
|
|
|
881
|
-
|
|
920
|
+
@dataclass
|
|
921
|
+
class SavedDraft:
|
|
922
|
+
path: Path
|
|
923
|
+
progress: str
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
def _saved_batches(config=None, *, started_only=False, include_drafts=False):
|
|
882
927
|
from .inspector import schema_fingerprint
|
|
883
928
|
from .previews import candidates
|
|
929
|
+
from .state import batch_id
|
|
884
930
|
|
|
885
931
|
matches, unreadable = [], 0
|
|
932
|
+
plan_ids = set()
|
|
886
933
|
for path, known in candidates().items():
|
|
887
934
|
try:
|
|
888
935
|
payload = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
@@ -893,6 +940,8 @@ def _saved_batches(config=None, *, started_only=False):
|
|
|
893
940
|
if not isinstance(payload, dict) or payload.get("kind") != "gformbot-run":
|
|
894
941
|
continue
|
|
895
942
|
saved, answers = _load_plan(path)
|
|
943
|
+
if include_drafts:
|
|
944
|
+
plan_ids.add(batch_id(payload))
|
|
896
945
|
if config is not None and schema_fingerprint(saved) != schema_fingerprint(config):
|
|
897
946
|
continue
|
|
898
947
|
if len(saved._submitted_indices) == saved.count:
|
|
@@ -906,41 +955,40 @@ def _saved_batches(config=None, *, started_only=False):
|
|
|
906
955
|
matches.append((created, SavedPreview(path, saved, answers)))
|
|
907
956
|
except (ValueError, OSError, KeyError, TypeError, OverflowError):
|
|
908
957
|
unreadable += 1
|
|
958
|
+
if include_drafts:
|
|
959
|
+
from .ai_draft import Draft, saved_paths
|
|
960
|
+
|
|
961
|
+
for path in saved_paths():
|
|
962
|
+
try:
|
|
963
|
+
draft = Draft.read(path)
|
|
964
|
+
if draft.identity not in plan_ids:
|
|
965
|
+
matches.append(
|
|
966
|
+
(draft.created_at.timestamp(), SavedDraft(draft.path, draft.progress_label()))
|
|
967
|
+
)
|
|
968
|
+
except (OSError, ValueError, KeyError, TypeError, AttributeError, OverflowError):
|
|
969
|
+
unreadable += 1
|
|
909
970
|
matches.sort(key=lambda item: (item[0], str(item[1].path)), reverse=True)
|
|
910
971
|
return matches, unreadable
|
|
911
972
|
|
|
912
973
|
|
|
913
|
-
def _batch_label(batch):
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
uncertain = sum(
|
|
917
|
-
index not in confirmed and state in {"attempted", "reviewing", "uncertain"}
|
|
918
|
-
for index, state in saved._outcomes.items()
|
|
919
|
-
)
|
|
920
|
-
remaining = saved.count - len(confirmed) - uncertain
|
|
921
|
-
if uncertain:
|
|
922
|
-
status = f"Needs checking ({uncertain})"
|
|
923
|
-
elif saved._submission_started or saved._outcomes or confirmed:
|
|
924
|
-
status = "Interrupted"
|
|
974
|
+
def _batch_label(batch, created):
|
|
975
|
+
if isinstance(batch, SavedDraft):
|
|
976
|
+
progress = batch.progress
|
|
925
977
|
else:
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
return (
|
|
930
|
-
f"{saved.form_title or 'Untitled form'} | {status} · {remaining} ready "
|
|
931
|
-
f"· {len(confirmed)}/{saved.count} submitted | {batch.path.name}"
|
|
932
|
-
)
|
|
978
|
+
saved = batch.config
|
|
979
|
+
progress = f"{len(saved._submitted_indices)}/{saved.count} submitted"
|
|
980
|
+
return f"{progress} | {datetime.fromtimestamp(created):%a, %d %b %Y %H:%M}"
|
|
933
981
|
|
|
934
982
|
|
|
935
|
-
def _select_saved_preview(config=None, *, started_only=False):
|
|
983
|
+
def _select_saved_preview(config=None, *, started_only=False, include_drafts=False):
|
|
936
984
|
from .inspector import schema_fingerprint
|
|
937
985
|
|
|
938
986
|
while True:
|
|
939
|
-
matches, unreadable = _saved_batches(config, started_only=started_only)
|
|
940
|
-
_info("
|
|
987
|
+
matches, unreadable = _saved_batches(config, started_only=started_only, include_drafts=include_drafts)
|
|
988
|
+
_info("Newest first by creation time. Confirmed submissions are skipped.")
|
|
941
989
|
if unreadable:
|
|
942
|
-
_info(f"Skipped {unreadable} unreadable
|
|
943
|
-
choices = [_choice(batch, _batch_label(batch)) for
|
|
990
|
+
_info(f"Skipped {unreadable} unreadable saved file(s).")
|
|
991
|
+
choices = [_choice(batch, _batch_label(batch, created)) for created, batch in matches]
|
|
944
992
|
if not choices:
|
|
945
993
|
_info(
|
|
946
994
|
"No unfinished response batches found."
|
|
@@ -953,6 +1001,8 @@ def _select_saved_preview(config=None, *, started_only=False):
|
|
|
953
1001
|
continue
|
|
954
1002
|
if selected == "back":
|
|
955
1003
|
return None
|
|
1004
|
+
if isinstance(selected, SavedDraft):
|
|
1005
|
+
return selected
|
|
956
1006
|
# Recheck progress and schema if another process changed the selected file.
|
|
957
1007
|
try:
|
|
958
1008
|
saved, answers = _load_plan(selected.path)
|
|
@@ -1150,11 +1200,20 @@ def _wizard():
|
|
|
1150
1200
|
|
|
1151
1201
|
|
|
1152
1202
|
def _resume_batch():
|
|
1153
|
-
while selected := _select_saved_preview():
|
|
1203
|
+
while selected := _select_saved_preview(include_drafts=True):
|
|
1154
1204
|
try:
|
|
1205
|
+
if isinstance(selected, SavedDraft):
|
|
1206
|
+
path = _resume_generation(None, selected.path)
|
|
1207
|
+
config, answers = _load_plan(path)
|
|
1208
|
+
selected = SavedPreview(path, config, answers)
|
|
1209
|
+
else:
|
|
1210
|
+
_info(f"Form: {selected.config.form_title or 'Untitled form'}")
|
|
1155
1211
|
_manage_batch(selected.config, selected.answers, selected.path)
|
|
1156
1212
|
except PromptBack:
|
|
1157
1213
|
continue
|
|
1214
|
+
except (OSError, ValueError) as exc:
|
|
1215
|
+
_info(f"Could not continue this batch: {exc}")
|
|
1216
|
+
continue
|
|
1158
1217
|
return
|
|
1159
1218
|
|
|
1160
1219
|
|
|
@@ -1219,12 +1278,10 @@ def _new_batch_wizard():
|
|
|
1219
1278
|
while True:
|
|
1220
1279
|
url = _url_prompt()
|
|
1221
1280
|
try:
|
|
1222
|
-
|
|
1223
|
-
config = _run_inspect(url, display=False)
|
|
1281
|
+
config = _run_inspect(url)
|
|
1224
1282
|
except ValueError as exc:
|
|
1225
1283
|
console.print(Text(str(exc), style="yellow"))
|
|
1226
1284
|
continue
|
|
1227
|
-
_info(config.form_title or "Form ready")
|
|
1228
1285
|
config._prompt_csv_count = True
|
|
1229
1286
|
try:
|
|
1230
1287
|
_form_choices(config)
|
|
@@ -1496,10 +1553,13 @@ def _resume_generation(url, resume, *, evidence=None):
|
|
|
1496
1553
|
from .ai_draft import Draft
|
|
1497
1554
|
from .locking import file_lock
|
|
1498
1555
|
|
|
1499
|
-
current = _run_inspect(url, display=False)
|
|
1500
1556
|
path = clean_path(resume).absolute()
|
|
1501
1557
|
with file_lock(path.with_name(path.name + ".resume")):
|
|
1502
|
-
draft = Draft.
|
|
1558
|
+
draft = Draft.read(path)
|
|
1559
|
+
if url is None:
|
|
1560
|
+
_info(f"Form: {draft.config.form_title or 'Untitled form'}")
|
|
1561
|
+
url = draft.config.url
|
|
1562
|
+
draft.check_form(_run_inspect(url, display=False))
|
|
1503
1563
|
answers = _generate(
|
|
1504
1564
|
draft.config,
|
|
1505
1565
|
draft.reference,
|
|
@@ -13,20 +13,43 @@
|
|
|
13
13
|
<header><div class="brand">GFormBot · Local editor</div><h1>Review or edit responses</h1><p id="title"></p><p>Changes stay on this computer. This editor never submits responses or sends them to AI.</p></header>
|
|
14
14
|
<div class="toolbar"><button id="previous" type="button" aria-label="Previous response">← Previous</button><select id="response" aria-label="Choose a response"></select><button id="next" type="button" aria-label="Next response">Next →</button><span class="badge" id="position"></span></div>
|
|
15
15
|
<p id="readonly" class="notice" hidden></p>
|
|
16
|
+
<button id="discard-response" type="button" hidden>Drop edits to this response</button>
|
|
16
17
|
<input id="search" class="search" type="search" placeholder="Search questions…" aria-label="Search questions">
|
|
17
18
|
<p id="message" class="error" role="alert"></p>
|
|
18
19
|
<form id="form" novalidate><div id="questions"></div><details id="skipped"><summary>Questions outside this response’s current route</summary><p class="hint">Changing a routing answer may make these questions required. Validation will tell you which answers are needed.</p><div id="unused"></div></details></form>
|
|
19
20
|
<p id="empty" hidden>No questions match your search.</p>
|
|
20
21
|
</main>
|
|
21
|
-
<div class="footer"><div class="footer-inner"><span id="status" class="status" role="status" aria-live="polite">Opening your responses…</span><button id="cancel" type="button">
|
|
22
|
+
<div class="footer"><div class="footer-inner"><span id="status" class="status" role="status" aria-live="polite">Opening your responses…</span><button id="cancel" type="button" hidden>Cancel</button><button id="done" class="primary" type="button" disabled>Done</button></div></div>
|
|
22
23
|
<script>
|
|
23
24
|
'use strict';
|
|
24
25
|
const el=id=>document.getElementById(id);
|
|
25
26
|
const make=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
|
|
26
|
-
|
|
27
|
+
const edits=new Map();
|
|
28
|
+
let state,current,busy=false,closing=false,fields=[];
|
|
27
29
|
async function api(path,body){const r=await fetch(path,body===undefined?{cache:'no-store'}:{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await r.json();if(!r.ok){const error=new Error(data.error||'Could not complete this action.');error.data=data;throw error;}return data;}
|
|
28
|
-
function
|
|
29
|
-
|
|
30
|
+
function updateFooter(){
|
|
31
|
+
const count=edits.size;
|
|
32
|
+
el('status').textContent=busy?'Please wait…':count?`${count} ${count===1?'response':'responses'} with unsaved edits`:'';
|
|
33
|
+
el('done').textContent=count?'Save and finish':'Done';el('done').disabled=busy||!current;
|
|
34
|
+
el('cancel').hidden=!count;el('cancel').disabled=busy;
|
|
35
|
+
}
|
|
36
|
+
function setBusy(value){
|
|
37
|
+
busy=value;el('response').disabled=value;el('previous').disabled=value||!current||current.index===1;
|
|
38
|
+
el('next').disabled=value||!current||current.index===state.count;
|
|
39
|
+
el('discard-response').disabled=value;
|
|
40
|
+
for(const item of fields)item.box.disabled=value;
|
|
41
|
+
updateFooter();
|
|
42
|
+
}
|
|
43
|
+
function stage(question,value){
|
|
44
|
+
if(busy||current.status!=='ready')return;
|
|
45
|
+
const key=String(question.index);
|
|
46
|
+
const draft=edits.get(current.index)||{answers:{}};
|
|
47
|
+
if(JSON.stringify(value)===JSON.stringify(current.answers[key]))delete draft.answers[key];
|
|
48
|
+
else draft.answers[key]=value;
|
|
49
|
+
if(Object.keys(draft.answers).length)edits.set(current.index,draft);
|
|
50
|
+
else edits.delete(current.index);
|
|
51
|
+
updateFooter();
|
|
52
|
+
}
|
|
30
53
|
function optionLabels(q,value){return Array.isArray(value)?value:typeof value==='string'&&value?[value]:[];}
|
|
31
54
|
function field(q,value,locked){
|
|
32
55
|
const box=make('fieldset');box.id='q'+q.index;box.dataset.search=(q.text+' '+q.description+' '+q.grid_title+' '+q.grid_row).toLowerCase();
|
|
@@ -50,32 +73,61 @@ function field(q,value,locked){
|
|
|
50
73
|
if(q.qtype==='time'){input.type='time';input.step='60';}
|
|
51
74
|
box.append(input);if(q.format)box.append(make('p','Format: '+q.format,'hint'));read=()=>q.qtype==='date'?input.value.replace('T',' '):input.value;
|
|
52
75
|
}
|
|
53
|
-
const error=make('p','','error');error.id='error'+q.index;box.append(error);box.querySelectorAll('input,select,textarea').forEach(input=>input.setAttribute('aria-describedby',error.id));box.addEventListener('input',()=>
|
|
76
|
+
const error=make('p','','error');error.id='error'+q.index;box.append(error);box.querySelectorAll('input,select,textarea').forEach(input=>input.setAttribute('aria-describedby',error.id));box.addEventListener('input',()=>stage(q,read()));box.addEventListener('change',()=>stage(q,read()));return {box};
|
|
54
77
|
}
|
|
55
|
-
function render(
|
|
78
|
+
function render(){
|
|
79
|
+
const draft=edits.get(current.index);
|
|
80
|
+
const answers={...current.answers,...draft?.answers};const active=draft?.active||current.active;
|
|
56
81
|
fields=[];el('questions').replaceChildren();el('unused').replaceChildren();const reached=new Set(active);const locked=current.status!=='ready';
|
|
57
82
|
for(const q of state.questions){const item=field(q,answers[String(q.index)],locked);fields.push(item);(reached.has(q.index)?el('questions'):el('unused')).append(item.box);}
|
|
58
83
|
el('skipped').hidden=el('unused').childElementCount===0;filter();
|
|
59
|
-
el('position').textContent=current.index+' of '+state.count;el('response').value=String(current.index);
|
|
84
|
+
el('position').textContent=current.index+' of '+state.count;el('response').value=String(current.index);
|
|
60
85
|
el('readonly').hidden=!locked;el('readonly').textContent=current.status==='confirmed'?'This response was already submitted. You can read it, but cannot change it.':'This response may already have been submitted. Return to the CLI to check its outcome before editing.';
|
|
86
|
+
el('discard-response').hidden=!locked||!draft;
|
|
61
87
|
}
|
|
62
88
|
function filter(){const query=el('search').value.toLowerCase().trim();let visible=0;for(const item of fields){item.box.hidden=!!query&&!item.box.dataset.search.includes(query);if(!item.box.hidden)visible++;}if(query)el('skipped').open=true;el('empty').hidden=visible!==0;}
|
|
63
89
|
async function load(index){
|
|
64
|
-
if(busy)
|
|
65
|
-
|
|
66
|
-
try{current=await api('response?index='+index);render();
|
|
90
|
+
if(busy)return;
|
|
91
|
+
setBusy(true);
|
|
92
|
+
try{current=await api('response?index='+index);render();el('message').textContent='';}
|
|
93
|
+
catch(error){if(current)el('response').value=String(current.index);el('message').textContent=error.message;}
|
|
94
|
+
finally{setBusy(false);}
|
|
67
95
|
}
|
|
68
|
-
el('previous').addEventListener('click',()=>load(current.index-1));el('next').addEventListener('click',()=>load(current.index+1));el('response').addEventListener('change',()=>load(Number(el('response').value)));el('search').addEventListener('input',filter);
|
|
96
|
+
el('previous').addEventListener('click',()=>{if(current)load(current.index-1);});el('next').addEventListener('click',()=>{if(current)load(current.index+1);});el('response').addEventListener('change',()=>load(Number(el('response').value)));el('search').addEventListener('input',filter);
|
|
69
97
|
el('form').addEventListener('submit',event=>event.preventDefault());
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
98
|
+
async function finish(save){
|
|
99
|
+
if(busy)return;
|
|
100
|
+
setBusy(true);el('message').textContent='';
|
|
101
|
+
const hasEdits=edits.size>0;
|
|
102
|
+
try{
|
|
103
|
+
if(save&&hasEdits){
|
|
104
|
+
const responses=Object.fromEntries([...edits].map(([index,draft])=>[index,draft.answers]));
|
|
105
|
+
await api('save',{responses});
|
|
106
|
+
}else await api('close',{});
|
|
107
|
+
closing=true;edits.clear();
|
|
108
|
+
const title=save?(hasEdits?'Changes saved':'Review complete'):'Edits discarded';
|
|
109
|
+
document.querySelector('main').replaceChildren(make('h1',title),make('p','You can close this tab and return to your terminal.'));
|
|
110
|
+
document.querySelector('.footer').hidden=true;
|
|
111
|
+
}catch(error){
|
|
112
|
+
const {index,question,active}=error.data||{};
|
|
113
|
+
if(index){
|
|
114
|
+
if(active&&edits.has(index))edits.get(index).active=active;
|
|
115
|
+
try{current=await api('response?index='+index);if(question)el('search').value='';render();}catch{}
|
|
116
|
+
const box=current?.index===index&&el('q'+question);
|
|
117
|
+
if(box){
|
|
118
|
+
box.classList.add('invalid');el('error'+question).textContent=error.message;
|
|
119
|
+
const details=box.closest('details');if(details)details.open=true;
|
|
120
|
+
box.scrollIntoView({behavior:'smooth',block:'center'});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
el('message').textContent=error.message;
|
|
124
|
+
setBusy(false);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
el('cancel').addEventListener('click',()=>{if(confirm('Discard all unsaved edits and return to the CLI?'))finish(false);});
|
|
128
|
+
el('discard-response').addEventListener('click',()=>{edits.delete(current.index);render();el('message').textContent='';updateFooter();});
|
|
129
|
+
el('done').addEventListener('click',()=>finish(true));
|
|
130
|
+
window.addEventListener('beforeunload',event=>{if(edits.size&&!closing){event.preventDefault();event.returnValue='';}});
|
|
79
131
|
async function start(){try{state=await api('state');el('title').textContent=state.title;state.statuses.forEach((status,i)=>{const opt=make('option','Response '+(i+1)+(status==='ready'?'':status==='confirmed'?' · Submitted':' · Needs checking'));opt.value=String(i+1);el('response').append(opt);});await load(state.initial_index);}catch(error){el('message').textContent=error.message;el('status').textContent='Editor unavailable. Return to your terminal.';}}
|
|
80
132
|
start();
|
|
81
133
|
</script>
|
|
@@ -19,6 +19,8 @@ from .generator import validate_answer
|
|
|
19
19
|
from .routing import Routing
|
|
20
20
|
from .validation import date_format, time_format
|
|
21
21
|
|
|
22
|
+
_MAX_EDIT_BYTES = 32 * 1024 * 1024
|
|
23
|
+
|
|
22
24
|
|
|
23
25
|
class EditorServer:
|
|
24
26
|
def __init__(self, config, answers, save, statuses=None):
|
|
@@ -138,18 +140,17 @@ class EditorServer:
|
|
|
138
140
|
return
|
|
139
141
|
name, _ = route
|
|
140
142
|
try:
|
|
141
|
-
length = int(self.headers.get("Content-Length", "0"))
|
|
142
|
-
if not 0 < length <= 4 * 1024 * 1024:
|
|
143
|
-
self.send(413, {"error": "The editor request is too large or empty."})
|
|
144
|
-
return
|
|
145
|
-
raw = self.rfile.read(length)
|
|
146
143
|
if (
|
|
147
144
|
self.headers.get("Origin") != owner.origin
|
|
148
145
|
or self.headers.get("Content-Type", "").split(";")[0] != "application/json"
|
|
149
146
|
):
|
|
150
147
|
self.send(403, {"error": "Only this editor can save changes."})
|
|
151
148
|
return
|
|
152
|
-
|
|
149
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
150
|
+
if not 0 < length <= _MAX_EDIT_BYTES:
|
|
151
|
+
self.send(413, {"error": "The editor request is too large or empty."})
|
|
152
|
+
return
|
|
153
|
+
payload = json.loads(self.rfile.read(length))
|
|
153
154
|
if not isinstance(payload, dict):
|
|
154
155
|
raise ValueError("Expected an answer object.")
|
|
155
156
|
if name == "close":
|
|
@@ -159,33 +160,29 @@ class EditorServer:
|
|
|
159
160
|
if name != "save":
|
|
160
161
|
self.send(404, {"error": "Unknown editor action."})
|
|
161
162
|
return
|
|
162
|
-
|
|
163
|
-
if
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
)
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
try:
|
|
173
|
-
answer = validate_answer(config, candidate)
|
|
174
|
-
except ValueError as exc:
|
|
175
|
-
error = {"error": str(exc)}
|
|
176
|
-
match = re.search(r"\bQ(\d+)", str(exc))
|
|
177
|
-
if match:
|
|
178
|
-
error["question"] = int(match[1])
|
|
179
|
-
try:
|
|
180
|
-
error["active"] = sorted(
|
|
181
|
-
Routing(config).active({int(k): v for k, v in candidate.items()})
|
|
163
|
+
changes = payload.get("responses")
|
|
164
|
+
if not isinstance(changes, dict) or not changes or len(changes) > len(owner.answers):
|
|
165
|
+
raise ValueError("Send edits for existing responses.")
|
|
166
|
+
states = owner.statuses()
|
|
167
|
+
validated = {}
|
|
168
|
+
for key, patch in changes.items():
|
|
169
|
+
index = owner.index(key)
|
|
170
|
+
if str(index) != key or not isinstance(patch, dict) or not patch:
|
|
171
|
+
raise ValueError(
|
|
172
|
+
"Each edited response needs a response number and changed answers."
|
|
182
173
|
)
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
174
|
+
if states[index - 1] != "ready":
|
|
175
|
+
self.send(409, {"index": index, "error": f"Response {index} is now read-only."})
|
|
176
|
+
return
|
|
177
|
+
candidate = {**{str(k): v for k, v in owner.answers[index - 1].items()}, **patch}
|
|
178
|
+
try:
|
|
179
|
+
validated[index] = validate_answer(config, candidate)
|
|
180
|
+
except ValueError as exc:
|
|
181
|
+
self.send(400, owner.validation_error(index, candidate, exc))
|
|
182
|
+
return
|
|
183
|
+
owner.save(validated)
|
|
184
|
+
owner.closed = True
|
|
185
|
+
self.send(200, {"saved": len(validated)})
|
|
189
186
|
except sqlite3.Error:
|
|
190
187
|
self.send(
|
|
191
188
|
409,
|
|
@@ -216,6 +213,17 @@ class EditorServer:
|
|
|
216
213
|
"status": self.statuses()[index - 1],
|
|
217
214
|
}
|
|
218
215
|
|
|
216
|
+
def validation_error(self, index, candidate, exc):
|
|
217
|
+
error = {"index": index, "error": f"Response {index}: {exc}"}
|
|
218
|
+
match = re.search(r"\bQ(\d+)", str(exc))
|
|
219
|
+
if match:
|
|
220
|
+
error["question"] = int(match[1])
|
|
221
|
+
try:
|
|
222
|
+
error["active"] = sorted(Routing(self.config).active({int(k): v for k, v in candidate.items()}))
|
|
223
|
+
except (ValueError, TypeError):
|
|
224
|
+
pass
|
|
225
|
+
return error
|
|
226
|
+
|
|
219
227
|
def run(self):
|
|
220
228
|
while not self.closed and time.monotonic() - self.last_request < 1800:
|
|
221
229
|
self.server.handle_request()
|
|
@@ -89,50 +89,91 @@ def _sanitize(block, base):
|
|
|
89
89
|
return {"text": text, "links": links}
|
|
90
90
|
|
|
91
91
|
|
|
92
|
+
def _instruction_lines(text, links):
|
|
93
|
+
lines = [text] if text else []
|
|
94
|
+
for link in links:
|
|
95
|
+
if link not in text:
|
|
96
|
+
lines.append(link + (" [redacted; may not work]" if "REDACTED" in link else ""))
|
|
97
|
+
if "REDACTED" in text:
|
|
98
|
+
lines.append("Redacted links may not work.")
|
|
99
|
+
return lines
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _details(records):
|
|
103
|
+
if not records:
|
|
104
|
+
return ["No saved form instructions yet."]
|
|
105
|
+
groups = defaultdict(lambda: defaultdict(set))
|
|
106
|
+
for record in records:
|
|
107
|
+
block = record["content"]
|
|
108
|
+
source = (record["batch"], record["title"], record["stage"], record["section"])
|
|
109
|
+
groups[block["text"], tuple(block["links"])][source].add(record["response"])
|
|
110
|
+
lines = ["Saved form instructions"]
|
|
111
|
+
for (text, links), sources in groups.items():
|
|
112
|
+
for (batch, title, stage, section), ids in sources.items():
|
|
113
|
+
numbers = ", ".join(map(str, sorted(ids)[:8])) + (f" ({len(ids)} total)" if len(ids) > 8 else "")
|
|
114
|
+
location = (
|
|
115
|
+
"After submission"
|
|
116
|
+
if stage == "confirmation"
|
|
117
|
+
else "Introduction"
|
|
118
|
+
if stage == "intro"
|
|
119
|
+
else f"Section {section}"
|
|
120
|
+
)
|
|
121
|
+
lines.append(f"{title} | Response {numbers} | {location} | batch {batch[:8]}")
|
|
122
|
+
lines.extend(_instruction_lines(text, links))
|
|
123
|
+
return lines
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _response_scope(ids):
|
|
127
|
+
if len(ids) == 1:
|
|
128
|
+
return f"Response {next(iter(ids))}"
|
|
129
|
+
if len(ids) > 8:
|
|
130
|
+
return f"{len(ids)} responses"
|
|
131
|
+
return "Responses " + ", ".join(map(str, sorted(ids)))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _summary(records, log_path):
|
|
135
|
+
confirmations = defaultdict(set)
|
|
136
|
+
actions = defaultdict(lambda: defaultdict(set))
|
|
137
|
+
confirmed = set()
|
|
138
|
+
observed = set()
|
|
139
|
+
for record in records:
|
|
140
|
+
stage, response = record["stage"], record["response"]
|
|
141
|
+
observed.add(response)
|
|
142
|
+
text, links = record["content"]["text"], record["content"]["links"]
|
|
143
|
+
if stage == "confirmation":
|
|
144
|
+
confirmed.add(response)
|
|
145
|
+
if text and text.casefold().rstrip(".! ") != "your response has been recorded":
|
|
146
|
+
confirmations[text].add(response)
|
|
147
|
+
text = "" # The confirmation text is already shown above its links.
|
|
148
|
+
if links:
|
|
149
|
+
section = record["section"] if stage == "section" else None
|
|
150
|
+
actions[text, tuple(links)][section].add(response)
|
|
151
|
+
lines = ["Confirmation message"] if confirmations else []
|
|
152
|
+
for text, ids in confirmations.items():
|
|
153
|
+
if ids != confirmed:
|
|
154
|
+
lines.append(_response_scope(ids))
|
|
155
|
+
lines.extend(_instruction_lines(text, ()))
|
|
156
|
+
if actions:
|
|
157
|
+
lines.append("Next steps")
|
|
158
|
+
for (text, links), sources in actions.items():
|
|
159
|
+
for section, ids in sources.items():
|
|
160
|
+
labels = [f"Section {section}"] if section is not None else []
|
|
161
|
+
if ids != observed:
|
|
162
|
+
labels.append(_response_scope(ids))
|
|
163
|
+
if labels:
|
|
164
|
+
lines.append(" · ".join(labels))
|
|
165
|
+
lines.extend(_instruction_lines(text, links))
|
|
166
|
+
command = "gformbot log --followups"
|
|
167
|
+
if log_path and str(log_path) != "gformbot-runs.csv":
|
|
168
|
+
command = f'gformbot log "{log_path}" --followups'
|
|
169
|
+
lines.append("Form instructions: " + command)
|
|
170
|
+
return lines
|
|
171
|
+
|
|
172
|
+
|
|
92
173
|
def display(records, ui, *, full=False, warning="", log_path=None):
|
|
93
174
|
"""Group repeated directions and print literal text, safe on older Windows consoles."""
|
|
94
175
|
try:
|
|
95
|
-
|
|
96
|
-
for record in records:
|
|
97
|
-
block = record["content"]
|
|
98
|
-
default = block["text"].strip().lower().rstrip(".! ") == "your response has been recorded"
|
|
99
|
-
if not full and not block["links"] and (record["stage"] != "confirmation" or default):
|
|
100
|
-
continue
|
|
101
|
-
key = json.dumps(block, sort_keys=True, ensure_ascii=False)
|
|
102
|
-
if key not in groups:
|
|
103
|
-
groups[key] = (block, defaultdict(set))
|
|
104
|
-
source = (record["batch"], record["title"], record["stage"], record["section"])
|
|
105
|
-
groups[key][1][source].add(record["response"])
|
|
106
|
-
lines = ["Next steps" if not full else "Saved form instructions"] if groups else []
|
|
107
|
-
for block, sources in groups.values():
|
|
108
|
-
for (batch, title, stage, section), ids in sources.items():
|
|
109
|
-
numbers = ", ".join(map(str, sorted(ids)[:8])) + (
|
|
110
|
-
f" ({len(ids)} total)" if len(ids) > 8 else ""
|
|
111
|
-
)
|
|
112
|
-
location = (
|
|
113
|
-
"After submission"
|
|
114
|
-
if stage == "confirmation"
|
|
115
|
-
else "Introduction"
|
|
116
|
-
if stage == "intro"
|
|
117
|
-
else f"Section {section}"
|
|
118
|
-
)
|
|
119
|
-
lines.append(
|
|
120
|
-
f"{title} | Response {numbers} | {location}" + (f" | batch {batch[:8]}" if full else "")
|
|
121
|
-
)
|
|
122
|
-
if block["text"]:
|
|
123
|
-
lines.append(block["text"])
|
|
124
|
-
for link in block["links"]:
|
|
125
|
-
if link not in block["text"]:
|
|
126
|
-
lines.append(link + (" [redacted; may not work]" if "REDACTED" in link else ""))
|
|
127
|
-
if "REDACTED" in block["text"]:
|
|
128
|
-
lines.append("Redacted links may not work.")
|
|
129
|
-
if records and not full:
|
|
130
|
-
command = "gformbot log --followups"
|
|
131
|
-
if log_path and str(log_path) != "gformbot-runs.csv":
|
|
132
|
-
command = f'gformbot log "{log_path}" --followups'
|
|
133
|
-
lines.append("Form instructions: " + command)
|
|
134
|
-
if full and not records:
|
|
135
|
-
lines.append("No saved form instructions yet.")
|
|
176
|
+
lines = _details(records) if full else _summary(records, log_path)
|
|
136
177
|
if warning:
|
|
137
178
|
lines.append(warning)
|
|
138
179
|
if lines:
|
|
@@ -304,7 +304,7 @@ class Generation:
|
|
|
304
304
|
try:
|
|
305
305
|
reply = ask(build_review_request(context, outbound, retry=retry))
|
|
306
306
|
reviewed = parse_review_response(reply, outbound)
|
|
307
|
-
except (ValueError, OSError) as exc:
|
|
307
|
+
except (ValueError, OSError, KeyboardInterrupt) as exc:
|
|
308
308
|
failure = exc
|
|
309
309
|
reviewed = parse_review_response(getattr(exc, "partial_content", ""), outbound)
|
|
310
310
|
if reviewed:
|
|
@@ -401,6 +401,9 @@ class Generation:
|
|
|
401
401
|
)
|
|
402
402
|
profiles = self._checks(rows)
|
|
403
403
|
if profiles:
|
|
404
|
+
if self.setup.get("review_total") != len(profiles):
|
|
405
|
+
self.setup["review_total"] = len(profiles)
|
|
406
|
+
self._save()
|
|
404
407
|
self._review(lambda messages: client.ask(messages, timeout=180), rows, profiles)
|
|
405
408
|
signals = self.quality.batch_signals(rows)
|
|
406
409
|
if signals:
|
|
@@ -413,5 +416,6 @@ class Generation:
|
|
|
413
416
|
return rows
|
|
414
417
|
except (ValueError, OSError, KeyboardInterrupt):
|
|
415
418
|
if self.draft is not None:
|
|
419
|
+
self.status("AI progress saved. Open Saved batches from Start to continue.")
|
|
416
420
|
self.status(f'Resume with: gformbot prepare "{self.config.url}" --resume "{self.draft.path}"')
|
|
417
421
|
raise
|
|
@@ -175,9 +175,11 @@ class Journal:
|
|
|
175
175
|
"INSERT OR IGNORE INTO batches(batch,content) VALUES(?,?)", (self.identity, signature)
|
|
176
176
|
)
|
|
177
177
|
|
|
178
|
-
def edit(self, payload,
|
|
178
|
+
def edit(self, payload, answers, write):
|
|
179
179
|
"""Serialize edits against submission claims; never reset response identities or outcomes."""
|
|
180
|
-
if
|
|
180
|
+
if not answers or any(
|
|
181
|
+
type(index) is not int or not 1 <= index <= len(payload["responses"]) for index in answers
|
|
182
|
+
):
|
|
181
183
|
raise ValueError("Choose an existing response number.")
|
|
182
184
|
with self._connect() as connection:
|
|
183
185
|
connection.execute("BEGIN IMMEDIATE")
|
|
@@ -186,13 +188,20 @@ class Journal:
|
|
|
186
188
|
).fetchone()
|
|
187
189
|
if bound is not None and bound != (_content_digest(payload),):
|
|
188
190
|
raise ValueError("This batch changed. Reopen it before editing.")
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
191
|
+
protected = set(payload.get("submitted_indices", []))
|
|
192
|
+
protected.update(
|
|
193
|
+
index
|
|
194
|
+
for (index,) in connection.execute(
|
|
195
|
+
"SELECT response FROM responses WHERE batch=? AND state != 'prepared'", (self.identity,)
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
if conflict := protected.intersection(answers):
|
|
199
|
+
raise ValueError(
|
|
200
|
+
f"Response {min(conflict)} is submitted or needs checking and cannot be edited."
|
|
201
|
+
)
|
|
194
202
|
changed = {**payload, "responses": list(payload["responses"])}
|
|
195
|
-
|
|
203
|
+
for index, answer in answers.items():
|
|
204
|
+
changed["responses"][index - 1] = {str(key): value for key, value in answer.items()}
|
|
196
205
|
changed["batch_id"] = payload.get("batch_id") or self.identity
|
|
197
206
|
write(changed)
|
|
198
207
|
# An interrupted commit after the atomic file write leaves a binding
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gformbot
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.3
|
|
4
4
|
Summary: Generate, prepare, and submit Google Forms responses with ChatGPT or supplied data.
|
|
5
5
|
Author: yogeshkrishna
|
|
6
6
|
License-Expression: Apache-2.0 AND MIT
|
|
@@ -88,7 +88,7 @@ python -m gformbot generate "YOUR_RESPONDER_URL" -n 5 -m "Vary the fictional sig
|
|
|
88
88
|
<img src="https://raw.githubusercontent.com/yogeshkrishna/google_form_test_bot/master/readme/workflow.svg" alt="Read the form, choose answers, validate the batch, and submit over HTTPS." width="900">
|
|
89
89
|
</p>
|
|
90
90
|
|
|
91
|
-
Choose **Start a new form**
|
|
91
|
+
Choose **Start a new form** to see the form introduction and questions before choosing where the answers come from. In **Review or edit responses**, move between responses and choose **Save and finish** to save your edits together.
|
|
92
92
|
|
|
93
93
|
## Choose your answer source
|
|
94
94
|
|
|
@@ -132,9 +132,9 @@ The form must be open to responses without Google sign-in. Account-verified emai
|
|
|
132
132
|
| What you see | What to do |
|
|
133
133
|
| --- | --- |
|
|
134
134
|
| **Ready to submit** | Open the plan from **Saved batches** to review, export, or send it. |
|
|
135
|
-
| **
|
|
136
|
-
| **
|
|
137
|
-
| **AI generation interrupted** |
|
|
135
|
+
| **Submission interrupted** | Open **Saved batches** and choose the batch by its progress and date. Confirmed responses are skipped. |
|
|
136
|
+
| **A response needs checking** | Look in Google Forms or the linked sheet before choosing whether to retry. A lost connection can leave the result uncertain. |
|
|
137
|
+
| **AI generation or quality review interrupted** | Open **Saved batches** to pick up the saved AI draft. |
|
|
138
138
|
| **Looking for a receipt or instructions?** | Open **More options → View recent activity** from the folder you ran the batch in, or use `log --followups`. |
|
|
139
139
|
|
|
140
140
|
GFormBot tracks submission outcomes in a local journal. Keep the original plan and journal when resuming. Files supplied as input and plans made with `prepare` are preserved. Temporary plans created for submission can be cleaned up after Google confirms the entire batch.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "gformbot"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.3"
|
|
8
8
|
description = "Generate, prepare, and submit Google Forms responses with ChatGPT or supplied data."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0 AND MIT"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|