@larkup/tool-video-intelligence 0.2.10 → 0.3.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/.env.example +3 -0
- package/README.md +11 -6
- package/dist/agent.d.ts +50 -0
- package/dist/agent.js +505 -241
- package/dist/contracts.d.ts +57 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -4
- package/package.json +3 -3
- package/runtime/app/config.py +1 -1
- package/runtime/app/main.py +0 -4
- package/runtime/app/services/brain.py +694 -71
- package/runtime/app/services/embedding.py +1 -1
- package/runtime/app/services/pipeline.py +256 -11
- package/runtime/app/services/vision.py +191 -34
- package/runtime/app/utils/timing.py +82 -2
- package/tool.manifest.json +1 -1
|
@@ -16,7 +16,7 @@ import re
|
|
|
16
16
|
import time
|
|
17
17
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
18
18
|
from dataclasses import asdict, dataclass, field
|
|
19
|
-
from typing import Any
|
|
19
|
+
from typing import Any, Callable
|
|
20
20
|
|
|
21
21
|
import requests
|
|
22
22
|
|
|
@@ -138,7 +138,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
138
138
|
"overview": {"type": "string", "maxLength": 1200},
|
|
139
139
|
"participants": {
|
|
140
140
|
"type": "array",
|
|
141
|
-
"maxItems":
|
|
141
|
+
"maxItems": 16,
|
|
142
142
|
"items": {
|
|
143
143
|
"type": "object",
|
|
144
144
|
"properties": {
|
|
@@ -154,9 +154,42 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
154
154
|
"additionalProperties": False,
|
|
155
155
|
},
|
|
156
156
|
},
|
|
157
|
+
"visibleSubjects": {
|
|
158
|
+
"type": "array",
|
|
159
|
+
"maxItems": 24,
|
|
160
|
+
"items": {
|
|
161
|
+
"type": "object",
|
|
162
|
+
"properties": {
|
|
163
|
+
"identity": {"type": "string", "maxLength": 180},
|
|
164
|
+
"identityBasis": {
|
|
165
|
+
"type": "string",
|
|
166
|
+
"enum": ["source-named", "source-described", "unresolved"],
|
|
167
|
+
},
|
|
168
|
+
"appearances": {
|
|
169
|
+
"type": "array",
|
|
170
|
+
"maxItems": 32,
|
|
171
|
+
"items": {
|
|
172
|
+
"type": "object",
|
|
173
|
+
"properties": {
|
|
174
|
+
"startMs": {"type": "number"},
|
|
175
|
+
"endMs": {"type": "number"},
|
|
176
|
+
"confidence": {
|
|
177
|
+
"type": "string",
|
|
178
|
+
"enum": ["direct", "partial"],
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
"required": ["startMs", "endMs", "confidence"],
|
|
182
|
+
"additionalProperties": False,
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
"required": ["identity", "identityBasis", "appearances"],
|
|
187
|
+
"additionalProperties": False,
|
|
188
|
+
},
|
|
189
|
+
},
|
|
157
190
|
"stateHistory": {
|
|
158
191
|
"type": "array",
|
|
159
|
-
"maxItems":
|
|
192
|
+
"maxItems": 16,
|
|
160
193
|
"items": {
|
|
161
194
|
"type": "object",
|
|
162
195
|
"properties": {
|
|
@@ -171,7 +204,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
171
204
|
},
|
|
172
205
|
"keyEvents": {
|
|
173
206
|
"type": "array",
|
|
174
|
-
"maxItems":
|
|
207
|
+
"maxItems": 24,
|
|
175
208
|
"items": {
|
|
176
209
|
"type": "object",
|
|
177
210
|
"properties": {
|
|
@@ -186,7 +219,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
186
219
|
},
|
|
187
220
|
"narrative": {
|
|
188
221
|
"type": "array",
|
|
189
|
-
"maxItems":
|
|
222
|
+
"maxItems": 24,
|
|
190
223
|
"items": {
|
|
191
224
|
"type": "object",
|
|
192
225
|
"properties": {
|
|
@@ -201,7 +234,7 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
201
234
|
},
|
|
202
235
|
"context": {
|
|
203
236
|
"type": "array",
|
|
204
|
-
"maxItems":
|
|
237
|
+
"maxItems": 16,
|
|
205
238
|
"items": {
|
|
206
239
|
"type": "object",
|
|
207
240
|
"properties": {
|
|
@@ -218,13 +251,14 @@ KNOWLEDGE_JSON_SCHEMA: dict[str, Any] = {
|
|
|
218
251
|
},
|
|
219
252
|
"uncertainties": {
|
|
220
253
|
"type": "array",
|
|
221
|
-
"maxItems":
|
|
254
|
+
"maxItems": 8,
|
|
222
255
|
"items": {"type": "string", "maxLength": 240},
|
|
223
256
|
},
|
|
224
257
|
},
|
|
225
258
|
"required": [
|
|
226
259
|
"overview",
|
|
227
260
|
"participants",
|
|
261
|
+
"visibleSubjects",
|
|
228
262
|
"stateHistory",
|
|
229
263
|
"keyEvents",
|
|
230
264
|
"narrative",
|
|
@@ -239,7 +273,7 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
|
|
|
239
273
|
"properties": {
|
|
240
274
|
"items": {
|
|
241
275
|
"type": "array",
|
|
242
|
-
"maxItems":
|
|
276
|
+
"maxItems": 48,
|
|
243
277
|
"items": {
|
|
244
278
|
"type": "object",
|
|
245
279
|
"properties": {
|
|
@@ -247,6 +281,7 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
|
|
|
247
281
|
"type": "string",
|
|
248
282
|
"enum": [
|
|
249
283
|
"question",
|
|
284
|
+
"clue",
|
|
250
285
|
"heading",
|
|
251
286
|
"slide-item",
|
|
252
287
|
"board-item",
|
|
@@ -254,24 +289,96 @@ SOURCE_INVENTORY_JSON_SCHEMA: dict[str, Any] = {
|
|
|
254
289
|
],
|
|
255
290
|
},
|
|
256
291
|
"channel": {"type": "string", "enum": ["spoken", "visible"]},
|
|
292
|
+
"questionRole": {
|
|
293
|
+
"type": "string",
|
|
294
|
+
"enum": ["primary", "interactional", "rhetorical", "not-question"],
|
|
295
|
+
},
|
|
257
296
|
"text": {"type": "string", "maxLength": 600},
|
|
258
297
|
"answer": {"type": "string", "maxLength": 600},
|
|
298
|
+
"respondent": {"type": "string", "maxLength": 240},
|
|
259
299
|
"startMs": {"type": "number"},
|
|
260
300
|
"endMs": {"type": "number"},
|
|
261
301
|
},
|
|
262
302
|
"required": [
|
|
263
303
|
"kind",
|
|
264
304
|
"channel",
|
|
305
|
+
"questionRole",
|
|
265
306
|
"text",
|
|
266
307
|
"answer",
|
|
308
|
+
"respondent",
|
|
267
309
|
"startMs",
|
|
268
310
|
"endMs",
|
|
269
311
|
],
|
|
270
312
|
"additionalProperties": False,
|
|
271
313
|
},
|
|
272
|
-
}
|
|
314
|
+
},
|
|
315
|
+
"structures": {
|
|
316
|
+
"type": "array",
|
|
317
|
+
"maxItems": 24,
|
|
318
|
+
"items": {
|
|
319
|
+
"type": "object",
|
|
320
|
+
"properties": {
|
|
321
|
+
"kind": {"type": "string", "enum": ["grid", "sequence", "collection"]},
|
|
322
|
+
"label": {"type": "string", "maxLength": 240},
|
|
323
|
+
"dimensions": {
|
|
324
|
+
"type": "array",
|
|
325
|
+
"maxItems": 4,
|
|
326
|
+
"items": {
|
|
327
|
+
"type": "object",
|
|
328
|
+
"properties": {
|
|
329
|
+
"label": {"type": "string", "maxLength": 120},
|
|
330
|
+
"values": {
|
|
331
|
+
"type": "array",
|
|
332
|
+
"maxItems": 24,
|
|
333
|
+
"items": {"type": "string", "maxLength": 120},
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
"required": ["label", "values"],
|
|
337
|
+
"additionalProperties": False,
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
"startMs": {"type": "number"},
|
|
341
|
+
"endMs": {"type": "number"},
|
|
342
|
+
},
|
|
343
|
+
"required": ["kind", "label", "dimensions", "startMs", "endMs"],
|
|
344
|
+
"additionalProperties": False,
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
"taskInstances": {
|
|
348
|
+
"type": "array",
|
|
349
|
+
"maxItems": 128,
|
|
350
|
+
"items": {
|
|
351
|
+
"type": "object",
|
|
352
|
+
"properties": {
|
|
353
|
+
"prompt": {"type": "string", "maxLength": 600},
|
|
354
|
+
"channel": {"type": "string", "enum": ["spoken", "visible"]},
|
|
355
|
+
"answer": {"type": "string", "maxLength": 600},
|
|
356
|
+
"respondent": {"type": "string", "maxLength": 240},
|
|
357
|
+
"startMs": {"type": "number"},
|
|
358
|
+
"endMs": {"type": "number"},
|
|
359
|
+
},
|
|
360
|
+
"required": [
|
|
361
|
+
"prompt",
|
|
362
|
+
"channel",
|
|
363
|
+
"answer",
|
|
364
|
+
"respondent",
|
|
365
|
+
"startMs",
|
|
366
|
+
"endMs",
|
|
367
|
+
],
|
|
368
|
+
"additionalProperties": False,
|
|
369
|
+
},
|
|
370
|
+
},
|
|
371
|
+
},
|
|
372
|
+
"required": ["items", "structures", "taskInstances"],
|
|
373
|
+
"additionalProperties": False,
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
TASK_INSTANCE_JSON_SCHEMA: dict[str, Any] = {
|
|
377
|
+
"type": "object",
|
|
378
|
+
"properties": {
|
|
379
|
+
"taskInstances": SOURCE_INVENTORY_JSON_SCHEMA["properties"]["taskInstances"],
|
|
273
380
|
},
|
|
274
|
-
"required": ["
|
|
381
|
+
"required": ["taskInstances"],
|
|
275
382
|
"additionalProperties": False,
|
|
276
383
|
}
|
|
277
384
|
|
|
@@ -444,7 +551,7 @@ class PlannerDiagnostics:
|
|
|
444
551
|
# bounds, but the bounds themselves do not overlap in the direction that
|
|
445
552
|
# matters: the densest plan Fast can propose is still lighter than the
|
|
446
553
|
# lightest plan Balanced can, and likewise for Balanced against Thorough. That
|
|
447
|
-
# is what makes the three modes mean something
|
|
554
|
+
# is what makes the three modes mean something, with overlapping ranges a
|
|
448
555
|
# Fast run could legitimately come out slower than a Balanced one, which is
|
|
449
556
|
# what a user picking Fast is choosing against.
|
|
450
557
|
MODE_BOUNDS: dict[str, dict[str, tuple[float, float]]] = {
|
|
@@ -579,6 +686,14 @@ class AgentPlanner:
|
|
|
579
686
|
self.last_error: str | None = None
|
|
580
687
|
self.errors: list[str] = []
|
|
581
688
|
self.fallback_used = False
|
|
689
|
+
self.source_inventory_coverage: dict[str, Any] = {
|
|
690
|
+
"complete": False,
|
|
691
|
+
"totalWindows": 0,
|
|
692
|
+
"processedWindows": 0,
|
|
693
|
+
"reason": "source inventory has not run",
|
|
694
|
+
}
|
|
695
|
+
self.source_activity_structures: list[dict[str, Any]] = []
|
|
696
|
+
self.source_task_instances: list[dict[str, Any]] = []
|
|
582
697
|
|
|
583
698
|
def plan(
|
|
584
699
|
self,
|
|
@@ -673,6 +788,7 @@ class AgentPlanner:
|
|
|
673
788
|
semantic_observations=semantic_observations,
|
|
674
789
|
transcript=transcript,
|
|
675
790
|
overlay_text=overlay_text or [],
|
|
791
|
+
compact=True,
|
|
676
792
|
)
|
|
677
793
|
started = time.monotonic()
|
|
678
794
|
try:
|
|
@@ -681,21 +797,9 @@ class AgentPlanner:
|
|
|
681
797
|
self.requests += 1
|
|
682
798
|
try:
|
|
683
799
|
raw, usage = self._complete(
|
|
684
|
-
|
|
685
|
-
prompt
|
|
686
|
-
if attempt == 0 and self.provider != "google"
|
|
687
|
-
else _synthesis_prompt(
|
|
688
|
-
brief=brief,
|
|
689
|
-
duration_secs=duration_secs,
|
|
690
|
-
plan=plan,
|
|
691
|
-
semantic_observations=semantic_observations,
|
|
692
|
-
transcript=transcript,
|
|
693
|
-
overlay_text=overlay_text or [],
|
|
694
|
-
compact=True,
|
|
695
|
-
)
|
|
696
|
-
),
|
|
800
|
+
prompt,
|
|
697
801
|
[],
|
|
698
|
-
max_output_tokens=
|
|
802
|
+
max_output_tokens=6_000,
|
|
699
803
|
timeout_seconds=75,
|
|
700
804
|
json_schema=KNOWLEDGE_JSON_SCHEMA,
|
|
701
805
|
request_attempts=1,
|
|
@@ -717,7 +821,7 @@ class AgentPlanner:
|
|
|
717
821
|
)
|
|
718
822
|
# The audit is a second read of the same evidence. It pays
|
|
719
823
|
# for itself only when the draft actually makes claims that
|
|
720
|
-
# can contradict each other across time
|
|
824
|
+
# can contradict each other across time - two states, or a
|
|
721
825
|
# state plus an event that would move it.
|
|
722
826
|
if len(summary["stateHistory"]) >= 2 or (
|
|
723
827
|
summary["stateHistory"] and len(summary["keyEvents"]) >= 2
|
|
@@ -773,10 +877,19 @@ class AgentPlanner:
|
|
|
773
877
|
transcript: list[dict[str, Any]],
|
|
774
878
|
semantic_observations: list[dict[str, Any]],
|
|
775
879
|
overlay_text: list[dict[str, Any]] | None = None,
|
|
880
|
+
on_progress: Callable[[int, int], None] | None = None,
|
|
776
881
|
) -> list[dict[str, Any]]:
|
|
777
|
-
"""Map
|
|
882
|
+
"""Map source units and source-established layouts in bounded time chunks."""
|
|
778
883
|
fallback = _fallback_source_inventory(semantic_observations, duration_secs)
|
|
884
|
+
self.source_activity_structures = []
|
|
885
|
+
self.source_task_instances = []
|
|
779
886
|
if not self.enabled or not self.api_key:
|
|
887
|
+
self.source_inventory_coverage = {
|
|
888
|
+
"complete": False,
|
|
889
|
+
"totalWindows": 0,
|
|
890
|
+
"processedWindows": 0,
|
|
891
|
+
"reason": "source inventory model is unavailable",
|
|
892
|
+
}
|
|
780
893
|
return fallback
|
|
781
894
|
chunks = _source_inventory_chunks(
|
|
782
895
|
duration_secs=duration_secs,
|
|
@@ -785,9 +898,18 @@ class AgentPlanner:
|
|
|
785
898
|
overlay_text=overlay_text or [],
|
|
786
899
|
)
|
|
787
900
|
if not chunks:
|
|
901
|
+
self.source_inventory_coverage = {
|
|
902
|
+
"complete": False,
|
|
903
|
+
"totalWindows": 0,
|
|
904
|
+
"processedWindows": 0,
|
|
905
|
+
"reason": "no source evidence was available to scan",
|
|
906
|
+
}
|
|
788
907
|
return fallback
|
|
789
908
|
started = time.monotonic()
|
|
790
909
|
completed: dict[int, list[dict[str, Any]]] = {}
|
|
910
|
+
completed_structures: dict[int, list[dict[str, Any]]] = {}
|
|
911
|
+
completed_tasks: dict[int, list[dict[str, Any]]] = {}
|
|
912
|
+
completed_raw_item_counts: dict[int, int] = {}
|
|
791
913
|
errors: list[str] = []
|
|
792
914
|
usage_totals = {"promptTokens": 0, "completionTokens": 0}
|
|
793
915
|
|
|
@@ -795,17 +917,47 @@ class AgentPlanner:
|
|
|
795
917
|
raw, usage = self._complete(
|
|
796
918
|
_source_inventory_prompt(chunk),
|
|
797
919
|
[],
|
|
798
|
-
max_output_tokens=
|
|
799
|
-
timeout_seconds=
|
|
920
|
+
max_output_tokens=6_000,
|
|
921
|
+
timeout_seconds=75,
|
|
800
922
|
json_schema=SOURCE_INVENTORY_JSON_SCHEMA,
|
|
801
923
|
request_attempts=1,
|
|
802
924
|
)
|
|
803
|
-
|
|
925
|
+
items = _validated_source_inventory(raw, duration_secs, chunk)
|
|
926
|
+
tasks = _validated_source_task_instances(raw, duration_secs, chunk)
|
|
927
|
+
if not tasks and any(item["kind"] == "question" for item in items) and sum(
|
|
928
|
+
item["kind"] == "clue" for item in items
|
|
929
|
+
) >= 2:
|
|
930
|
+
task_raw, task_usage = self._complete(
|
|
931
|
+
_source_task_instance_prompt(chunk["range"], items),
|
|
932
|
+
[],
|
|
933
|
+
max_output_tokens=4_000,
|
|
934
|
+
timeout_seconds=30,
|
|
935
|
+
json_schema=TASK_INSTANCE_JSON_SCHEMA,
|
|
936
|
+
request_attempts=1,
|
|
937
|
+
)
|
|
938
|
+
tasks = _validated_source_task_instances(
|
|
939
|
+
task_raw, duration_secs, chunk
|
|
940
|
+
)
|
|
941
|
+
usage = {
|
|
942
|
+
"promptTokens": usage.get("promptTokens", 0)
|
|
943
|
+
+ task_usage.get("promptTokens", 0),
|
|
944
|
+
"completionTokens": usage.get("completionTokens", 0)
|
|
945
|
+
+ task_usage.get("completionTokens", 0),
|
|
946
|
+
}
|
|
947
|
+
return (
|
|
948
|
+
index,
|
|
949
|
+
items,
|
|
950
|
+
_validated_source_activity_structures(raw, duration_secs, chunk),
|
|
951
|
+
tasks,
|
|
952
|
+
len(raw.get("items") or []) if isinstance(raw, dict) else 0,
|
|
953
|
+
usage,
|
|
954
|
+
)
|
|
804
955
|
|
|
805
956
|
try:
|
|
806
|
-
# These requests contain disjoint time ranges
|
|
807
|
-
#
|
|
808
|
-
|
|
957
|
+
# These requests contain disjoint time ranges. Two concurrent maps
|
|
958
|
+
# keep a long source responsive without making several transcript-
|
|
959
|
+
# sized requests contend for the same hosted-model window.
|
|
960
|
+
with ThreadPoolExecutor(max_workers=min(2, len(chunks))) as executor:
|
|
809
961
|
futures = {
|
|
810
962
|
executor.submit(map_chunk, index, chunk): index
|
|
811
963
|
for index, chunk in enumerate(chunks)
|
|
@@ -813,8 +965,11 @@ class AgentPlanner:
|
|
|
813
965
|
for future in as_completed(futures):
|
|
814
966
|
self.requests += 1
|
|
815
967
|
try:
|
|
816
|
-
index, items, usage = future.result()
|
|
968
|
+
index, items, structures, tasks, raw_item_count, usage = future.result()
|
|
817
969
|
completed[index] = items
|
|
970
|
+
completed_structures[index] = structures
|
|
971
|
+
completed_tasks[index] = tasks
|
|
972
|
+
completed_raw_item_counts[index] = raw_item_count
|
|
818
973
|
usage_totals["promptTokens"] += usage.get("promptTokens", 0)
|
|
819
974
|
usage_totals["completionTokens"] += usage.get("completionTokens", 0)
|
|
820
975
|
except Exception as error:
|
|
@@ -822,14 +977,54 @@ class AgentPlanner:
|
|
|
822
977
|
f"source inventory chunk {futures[future]}: "
|
|
823
978
|
f"{type(error).__name__}: {error}"[:500]
|
|
824
979
|
)
|
|
980
|
+
if on_progress:
|
|
981
|
+
on_progress(len(completed) + len(errors), len(chunks))
|
|
825
982
|
self.prompt_tokens += usage_totals["promptTokens"]
|
|
826
983
|
self.completion_tokens += usage_totals["completionTokens"]
|
|
827
984
|
if errors:
|
|
828
985
|
self.errors.extend(errors[-3:])
|
|
829
|
-
|
|
986
|
+
self.source_inventory_coverage = {
|
|
987
|
+
"complete": len(completed) == len(chunks) and not errors,
|
|
988
|
+
"totalWindows": len(chunks),
|
|
989
|
+
"processedWindows": len(completed),
|
|
990
|
+
"modelItems": sum(completed_raw_item_counts.values()),
|
|
991
|
+
"acceptedItems": sum(len(items) for items in completed.values()),
|
|
992
|
+
**(
|
|
993
|
+
{}
|
|
994
|
+
if len(completed) == len(chunks) and not errors
|
|
995
|
+
else {"reason": "one or more source inventory windows failed"}
|
|
996
|
+
),
|
|
997
|
+
}
|
|
998
|
+
self.source_activity_structures = _merge_source_activity_structures(
|
|
999
|
+
*[
|
|
1000
|
+
completed_structures[index]
|
|
1001
|
+
for index in sorted(completed_structures)
|
|
1002
|
+
]
|
|
1003
|
+
)
|
|
1004
|
+
merged_items = _merge_source_inventory(
|
|
830
1005
|
fallback,
|
|
831
1006
|
*[completed[index] for index in sorted(completed)],
|
|
832
1007
|
)
|
|
1008
|
+
task_instances = _merge_source_task_instances(
|
|
1009
|
+
*[completed_tasks[index] for index in sorted(completed_tasks)]
|
|
1010
|
+
)
|
|
1011
|
+
self.source_task_instances = [
|
|
1012
|
+
task
|
|
1013
|
+
for task in task_instances
|
|
1014
|
+
if not any(
|
|
1015
|
+
item["kind"] == "question"
|
|
1016
|
+
and item["channel"] == task["channel"]
|
|
1017
|
+
and re.sub(r"\s+", " ", item["text"].casefold()).strip()
|
|
1018
|
+
== re.sub(r"\s+", " ", task["prompt"].casefold()).strip()
|
|
1019
|
+
# A held card can be inventoried several times while its
|
|
1020
|
+
# timer runs. It is still the same direct prompt, not a
|
|
1021
|
+
# continued instance, even when the readings are a minute
|
|
1022
|
+
# apart.
|
|
1023
|
+
and abs(item["startMs"] - task["startMs"]) <= 120_000
|
|
1024
|
+
for item in merged_items
|
|
1025
|
+
)
|
|
1026
|
+
]
|
|
1027
|
+
return merged_items
|
|
833
1028
|
finally:
|
|
834
1029
|
self.latency_ms += round((time.monotonic() - started) * 1_000)
|
|
835
1030
|
|
|
@@ -1180,7 +1375,9 @@ def _source_inventory_chunks(
|
|
|
1180
1375
|
semantic_observations: list[dict[str, Any]],
|
|
1181
1376
|
overlay_text: list[dict[str, Any]],
|
|
1182
1377
|
) -> list[dict[str, Any]]:
|
|
1183
|
-
|
|
1378
|
+
# Keep each map within a bounded evidence window instead of forcing one
|
|
1379
|
+
# completion to compress a quarter-hour of raw speech and visual notes.
|
|
1380
|
+
window_ms = 5 * 60 * 1_000
|
|
1184
1381
|
duration_ms = max(1, round(duration_secs * 1_000))
|
|
1185
1382
|
chunks: list[dict[str, Any]] = []
|
|
1186
1383
|
for start_ms in range(0, duration_ms, window_ms):
|
|
@@ -1247,38 +1444,85 @@ def _source_inventory_prompt(chunk: dict[str, Any]) -> str:
|
|
|
1247
1444
|
return (
|
|
1248
1445
|
"Create an exhaustive inventory of discrete source-authored units in this timestamped "
|
|
1249
1446
|
"portion of a recording. The source can be any kind of recording. Extract only: questions "
|
|
1250
|
-
"
|
|
1251
|
-
"board, or explicitly enumerated list items
|
|
1252
|
-
"
|
|
1253
|
-
"
|
|
1254
|
-
"
|
|
1255
|
-
"
|
|
1256
|
-
"
|
|
1447
|
+
"whose answer is a substantive part of the recording; headings or titles; individual slide, "
|
|
1448
|
+
"board, or explicitly enumerated list items; and declarative hints used to solve an explicit "
|
|
1449
|
+
"prompt. Use kind 'question' only for a standalone, content-bearing prompt that asks for an "
|
|
1450
|
+
"answer. In a dialogue, a substantive turn that invites an explanation is a source question "
|
|
1451
|
+
"even when phrased informally. A greeting, social check-in, turn-management request, rhetorical question, or casual "
|
|
1452
|
+
"banter is not a source question. Do not turn a declarative hint, a description, model "
|
|
1453
|
+
"instruction, or analysis prompt into a question: represent an explicit solving hint as kind "
|
|
1454
|
+
"'clue' and otherwise omit it. Preserve the source language and wording. For a spoken "
|
|
1455
|
+
"question, start at the actual interrogative or request and omit surrounding banter, answers, "
|
|
1456
|
+
"and reactions. Set questionRole to 'primary' only for a content-bearing question; use "
|
|
1457
|
+
"'interactional' for social or turn-management speech, 'rhetorical' when no answer is sought, "
|
|
1458
|
+
"and 'not-question' for every other kind. It is safer to omit an ambiguous spoken question "
|
|
1459
|
+
"than to label ordinary conversation as primary. If a nearby source passage explicitly answers a question, "
|
|
1460
|
+
"copy the answer; otherwise use an empty answer. If the answer itself names the person who "
|
|
1461
|
+
"gave it, copy only that supplied name or role into respondent; otherwise use an empty "
|
|
1462
|
+
"respondent. Give the narrowest supplied timestamp "
|
|
1257
1463
|
"that supports each item. A recurring header is one item in this portion, while separate "
|
|
1258
|
-
"questions or differently worded items remain separate.
|
|
1259
|
-
"
|
|
1260
|
-
"'
|
|
1464
|
+
"questions or differently worded items remain separate. Also record a structure only when "
|
|
1465
|
+
"the source itself establishes a repeated arrangement: 'grid' for independent labeled axes, "
|
|
1466
|
+
"'sequence' for an ordered run, or 'collection' for a named set. Preserve only labels and "
|
|
1467
|
+
"values directly present in the source; do not infer missing dimensions or entries. For a reusable "
|
|
1468
|
+
"source prompt followed by separately resolved clue bundles, add one taskInstances record for each "
|
|
1469
|
+
"separately resolved bundle. Its prompt must copy the exact reusable question already present in this "
|
|
1470
|
+
"portion; its time range must cover that bundle, not the earlier title. A new card/title, an answer "
|
|
1471
|
+
"reveal, or another directly observed reset can establish a separate bundle. Do not create a task "
|
|
1472
|
+
"instance from a clue alone or carry a prompt in from another portion. Never infer missing words or "
|
|
1473
|
+
"add outside facts. Return at most 48 items for this bounded portion. JSON only: {items:[{kind:'question'|'clue'|"
|
|
1474
|
+
"'heading'|'slide-item'|'board-item'|'list-item',channel:'spoken'|'visible',questionRole:"
|
|
1475
|
+
"'primary'|'interactional'|'rhetorical'|'not-question',text:string,answer:string,"
|
|
1476
|
+
"respondent:string,startMs:number,endMs:number}],structures:[{kind:'grid'|'sequence'|"
|
|
1477
|
+
"'collection',label:string,dimensions:[{label:string,values:string[]}],startMs:number,endMs:number}],"
|
|
1478
|
+
"taskInstances:[{prompt:string,channel:'spoken'|'visible',answer:string,respondent:string,"
|
|
1261
1479
|
"startMs:number,endMs:number}]}.\nINPUT:\n"
|
|
1262
1480
|
+ json.dumps(chunk, ensure_ascii=False, separators=(",", ":"))
|
|
1263
1481
|
)
|
|
1264
1482
|
|
|
1265
1483
|
|
|
1266
|
-
def
|
|
1267
|
-
|
|
1484
|
+
def _source_task_instance_prompt(
|
|
1485
|
+
source_range: dict[str, Any], items: list[dict[str, Any]]
|
|
1486
|
+
) -> str:
|
|
1487
|
+
return (
|
|
1488
|
+
"Reconcile reusable source prompts with their already-grounded clue items in one bounded "
|
|
1489
|
+
"portion of a recording. The input is chronological source evidence, not a topic summary. "
|
|
1490
|
+
"When one exact, explicit prompt introduces a repeated activity and later clue bundles are "
|
|
1491
|
+
"separately resolved, return one task instance per separately resolved bundle. Copy prompt "
|
|
1492
|
+
"exactly from an input question; do not turn a clue into a prompt or bring in a prompt not in "
|
|
1493
|
+
"the input. A new displayed item, a revealed answer, or an independently bounded run of clues "
|
|
1494
|
+
"can establish a new instance. Keep an empty answer/respondent if the input does not directly "
|
|
1495
|
+
"supply it. If the input does not establish separate instances, return an empty list. Return JSON only: "
|
|
1496
|
+
"{taskInstances:[{prompt:string,channel:'spoken'|'visible',answer:string,respondent:string,"
|
|
1497
|
+
"startMs:number,endMs:number}]}.\nINPUT:\n"
|
|
1498
|
+
+ json.dumps(
|
|
1499
|
+
{
|
|
1500
|
+
"range": source_range,
|
|
1501
|
+
"items": [
|
|
1502
|
+
{
|
|
1503
|
+
key: item[key]
|
|
1504
|
+
for key in (
|
|
1505
|
+
"kind",
|
|
1506
|
+
"channel",
|
|
1507
|
+
"text",
|
|
1508
|
+
"answer",
|
|
1509
|
+
"respondent",
|
|
1510
|
+
"startMs",
|
|
1511
|
+
"endMs",
|
|
1512
|
+
)
|
|
1513
|
+
}
|
|
1514
|
+
for item in items
|
|
1515
|
+
if item["kind"] in {"question", "clue"}
|
|
1516
|
+
],
|
|
1517
|
+
},
|
|
1518
|
+
ensure_ascii=False,
|
|
1519
|
+
separators=(",", ":"),
|
|
1520
|
+
)
|
|
1521
|
+
)
|
|
1268
1522
|
|
|
1269
1523
|
|
|
1270
|
-
def
|
|
1271
|
-
|
|
1272
|
-
if re.search(r"[?؟]\s*$", text):
|
|
1273
|
-
return True
|
|
1274
|
-
cue = re.compile(
|
|
1275
|
-
r"^(?:who|what|when|where|why|how|which|whose|whom|is|are|was|were|do|does|did|"
|
|
1276
|
-
r"can|could|would|will|name|list|identify|describe|tell|give|"
|
|
1277
|
-
r"من|ما|ماذا|متى|أين|اين|كيف|كم|هل|أي|اي|لماذا|مين|إيه|ايه|فين|امتى|ازاي|"
|
|
1278
|
-
r"اذكر|أذكر|حدد|سم|سمي)$",
|
|
1279
|
-
re.I,
|
|
1280
|
-
)
|
|
1281
|
-
return any(cue.match(term) for term in _inventory_terms(text)[:4])
|
|
1524
|
+
def _inventory_terms(value: str) -> list[str]:
|
|
1525
|
+
return re.findall(r"\w+", value.casefold(), re.UNICODE)
|
|
1282
1526
|
|
|
1283
1527
|
|
|
1284
1528
|
def _inventory_item_is_grounded(
|
|
@@ -1307,23 +1551,78 @@ def _inventory_item_is_grounded(
|
|
|
1307
1551
|
return matched / len(candidate_terms) >= 0.7
|
|
1308
1552
|
|
|
1309
1553
|
|
|
1554
|
+
def _inventory_detail_is_grounded(
|
|
1555
|
+
value: str, item: dict[str, Any], source_chunk: dict[str, Any]
|
|
1556
|
+
) -> bool:
|
|
1557
|
+
"""Keep answer metadata only when the nearby source evidence contains it."""
|
|
1558
|
+
candidate_terms = _inventory_terms(value)
|
|
1559
|
+
if not candidate_terms:
|
|
1560
|
+
return True
|
|
1561
|
+
start_ms = item["startMs"]
|
|
1562
|
+
end_ms = item["endMs"]
|
|
1563
|
+
nearby = [
|
|
1564
|
+
source
|
|
1565
|
+
for source in (
|
|
1566
|
+
list(source_chunk.get("spokenEvidence") or [])
|
|
1567
|
+
+ list(source_chunk.get("visibleEvidence") or [])
|
|
1568
|
+
)
|
|
1569
|
+
if float(source.get("startMs") or 0) <= end_ms + 15_000
|
|
1570
|
+
and float(source.get("endMs") or source.get("startMs") or 0)
|
|
1571
|
+
>= start_ms - 5_000
|
|
1572
|
+
]
|
|
1573
|
+
if not nearby:
|
|
1574
|
+
nearby = list(source_chunk.get("spokenEvidence") or []) + list(
|
|
1575
|
+
source_chunk.get("visibleEvidence") or []
|
|
1576
|
+
)
|
|
1577
|
+
source_terms = set(
|
|
1578
|
+
_inventory_terms(" ".join(str(source.get("text") or "") for source in nearby))
|
|
1579
|
+
)
|
|
1580
|
+
matched = sum(1 for term in candidate_terms if term in source_terms)
|
|
1581
|
+
# Metadata is more dangerous than the question text: a fabricated name can
|
|
1582
|
+
# share generic words such as "starts the round" with a real answer. Keep
|
|
1583
|
+
# it only for a near-exact match (or an exact short name/role).
|
|
1584
|
+
required_ratio = 1 if len(candidate_terms) <= 2 else 0.9
|
|
1585
|
+
return matched / len(candidate_terms) >= required_ratio
|
|
1586
|
+
|
|
1587
|
+
|
|
1310
1588
|
def _validated_source_inventory(
|
|
1311
1589
|
raw: dict[str, Any],
|
|
1312
1590
|
duration_secs: float,
|
|
1313
1591
|
source_chunk: dict[str, Any] | None = None,
|
|
1314
1592
|
) -> list[dict[str, Any]]:
|
|
1315
1593
|
duration_ms = max(1, round(duration_secs * 1_000))
|
|
1316
|
-
allowed_kinds = {
|
|
1594
|
+
allowed_kinds = {
|
|
1595
|
+
"question",
|
|
1596
|
+
"clue",
|
|
1597
|
+
"heading",
|
|
1598
|
+
"slide-item",
|
|
1599
|
+
"board-item",
|
|
1600
|
+
"list-item",
|
|
1601
|
+
}
|
|
1317
1602
|
allowed_channels = {"spoken", "visible"}
|
|
1603
|
+
allowed_question_roles = {
|
|
1604
|
+
"primary",
|
|
1605
|
+
"interactional",
|
|
1606
|
+
"rhetorical",
|
|
1607
|
+
"not-question",
|
|
1608
|
+
}
|
|
1318
1609
|
items: list[dict[str, Any]] = []
|
|
1319
1610
|
for candidate in raw.get("items") or []:
|
|
1320
1611
|
if not isinstance(candidate, dict):
|
|
1321
1612
|
continue
|
|
1322
1613
|
kind = str(candidate.get("kind") or "").strip()
|
|
1323
1614
|
channel = str(candidate.get("channel") or "").strip()
|
|
1615
|
+
question_role = str(candidate.get("questionRole") or "").strip()
|
|
1324
1616
|
text = str(candidate.get("text") or "").strip()[:600]
|
|
1325
1617
|
if kind not in allowed_kinds or channel not in allowed_channels or not text:
|
|
1326
1618
|
continue
|
|
1619
|
+
if not question_role:
|
|
1620
|
+
# Older runtimes did not emit a role. Keep their direct questions
|
|
1621
|
+
# readable after an upgrade, but require the new mapper to make
|
|
1622
|
+
# the distinction explicitly.
|
|
1623
|
+
question_role = "primary" if kind == "question" else "not-question"
|
|
1624
|
+
if question_role not in allowed_question_roles:
|
|
1625
|
+
continue
|
|
1327
1626
|
try:
|
|
1328
1627
|
start_ms = min(
|
|
1329
1628
|
duration_ms, max(0, round(float(candidate.get("startMs"))))
|
|
@@ -1337,19 +1636,192 @@ def _validated_source_inventory(
|
|
|
1337
1636
|
item = {
|
|
1338
1637
|
"kind": kind,
|
|
1339
1638
|
"channel": channel,
|
|
1639
|
+
"questionRole": question_role,
|
|
1340
1640
|
"text": text,
|
|
1341
1641
|
"answer": str(candidate.get("answer") or "").strip()[:600],
|
|
1642
|
+
"respondent": str(candidate.get("respondent") or "").strip()[:240],
|
|
1342
1643
|
"startMs": start_ms,
|
|
1343
1644
|
"endMs": end_ms,
|
|
1344
1645
|
}
|
|
1345
|
-
if kind == "question"
|
|
1646
|
+
if kind == "question":
|
|
1647
|
+
if question_role != "primary":
|
|
1648
|
+
continue
|
|
1649
|
+
elif question_role != "not-question":
|
|
1346
1650
|
continue
|
|
1347
1651
|
if source_chunk is not None and not _inventory_item_is_grounded(item, source_chunk):
|
|
1348
1652
|
continue
|
|
1653
|
+
if source_chunk is not None:
|
|
1654
|
+
if item["answer"] and not _inventory_detail_is_grounded(
|
|
1655
|
+
item["answer"], item, source_chunk
|
|
1656
|
+
):
|
|
1657
|
+
item["answer"] = ""
|
|
1658
|
+
if item["respondent"] and not _inventory_detail_is_grounded(
|
|
1659
|
+
item["respondent"], item, source_chunk
|
|
1660
|
+
):
|
|
1661
|
+
item["respondent"] = ""
|
|
1349
1662
|
items.append(item)
|
|
1350
1663
|
return items
|
|
1351
1664
|
|
|
1352
1665
|
|
|
1666
|
+
def _validated_source_activity_structures(
|
|
1667
|
+
raw: dict[str, Any],
|
|
1668
|
+
duration_secs: float,
|
|
1669
|
+
source_chunk: dict[str, Any] | None = None,
|
|
1670
|
+
) -> list[dict[str, Any]]:
|
|
1671
|
+
"""Keep only explicitly evidenced layouts; never manufacture a prompt count."""
|
|
1672
|
+
duration_ms = max(1, round(duration_secs * 1_000))
|
|
1673
|
+
allowed_kinds = {"grid", "sequence", "collection"}
|
|
1674
|
+
structures: list[dict[str, Any]] = []
|
|
1675
|
+
for candidate in raw.get("structures") or []:
|
|
1676
|
+
if not isinstance(candidate, dict):
|
|
1677
|
+
continue
|
|
1678
|
+
kind = str(candidate.get("kind") or "").strip()
|
|
1679
|
+
label = str(candidate.get("label") or "").strip()[:240]
|
|
1680
|
+
if kind not in allowed_kinds:
|
|
1681
|
+
continue
|
|
1682
|
+
try:
|
|
1683
|
+
start_ms = min(duration_ms, max(0, round(float(candidate.get("startMs")))))
|
|
1684
|
+
end_ms = min(
|
|
1685
|
+
duration_ms,
|
|
1686
|
+
max(start_ms, round(float(candidate.get("endMs")))),
|
|
1687
|
+
)
|
|
1688
|
+
except (TypeError, ValueError):
|
|
1689
|
+
continue
|
|
1690
|
+
dimensions: list[dict[str, Any]] = []
|
|
1691
|
+
for raw_dimension in candidate.get("dimensions") or []:
|
|
1692
|
+
if not isinstance(raw_dimension, dict):
|
|
1693
|
+
continue
|
|
1694
|
+
dimension_label = str(raw_dimension.get("label") or "").strip()[:120]
|
|
1695
|
+
values: list[str] = []
|
|
1696
|
+
for raw_value in raw_dimension.get("values") or []:
|
|
1697
|
+
value = str(raw_value or "").strip()[:120]
|
|
1698
|
+
normalized = re.sub(r"\s+", " ", value.casefold())
|
|
1699
|
+
if value and normalized not in {
|
|
1700
|
+
re.sub(r"\s+", " ", previous.casefold()) for previous in values
|
|
1701
|
+
}:
|
|
1702
|
+
values.append(value)
|
|
1703
|
+
if dimension_label and values:
|
|
1704
|
+
dimensions.append({"label": dimension_label, "values": values})
|
|
1705
|
+
if kind == "grid" and (
|
|
1706
|
+
len(dimensions) < 2 or any(len(item["values"]) < 2 for item in dimensions)
|
|
1707
|
+
):
|
|
1708
|
+
continue
|
|
1709
|
+
if kind in {"sequence", "collection"} and not dimensions:
|
|
1710
|
+
continue
|
|
1711
|
+
structure = {
|
|
1712
|
+
"kind": kind,
|
|
1713
|
+
"label": label,
|
|
1714
|
+
"dimensions": dimensions,
|
|
1715
|
+
"startMs": start_ms,
|
|
1716
|
+
"endMs": end_ms,
|
|
1717
|
+
}
|
|
1718
|
+
if kind == "grid":
|
|
1719
|
+
structure["promptCount"] = math.prod(
|
|
1720
|
+
len(dimension["values"]) for dimension in dimensions
|
|
1721
|
+
)
|
|
1722
|
+
# A layout claim is valuable only if its labels/values occur in the
|
|
1723
|
+
# same bounded source window. Empty labels are permitted because many
|
|
1724
|
+
# real source grids have labels only on their axes.
|
|
1725
|
+
direct_terms = " ".join(
|
|
1726
|
+
[label]
|
|
1727
|
+
+ [
|
|
1728
|
+
f"{dimension['label']} {' '.join(dimension['values'])}"
|
|
1729
|
+
for dimension in dimensions
|
|
1730
|
+
]
|
|
1731
|
+
).strip()
|
|
1732
|
+
if source_chunk is not None and direct_terms and not _inventory_detail_is_grounded(
|
|
1733
|
+
direct_terms,
|
|
1734
|
+
structure,
|
|
1735
|
+
source_chunk,
|
|
1736
|
+
):
|
|
1737
|
+
continue
|
|
1738
|
+
structures.append(structure)
|
|
1739
|
+
return structures
|
|
1740
|
+
|
|
1741
|
+
|
|
1742
|
+
def _source_text_is_grounded_anywhere(
|
|
1743
|
+
value: str, channel: str, source_chunk: dict[str, Any]
|
|
1744
|
+
) -> bool:
|
|
1745
|
+
source_key = "spokenEvidence" if channel == "spoken" else "visibleEvidence"
|
|
1746
|
+
candidate_terms = _inventory_terms(value)
|
|
1747
|
+
if not candidate_terms:
|
|
1748
|
+
return False
|
|
1749
|
+
source_terms = set(
|
|
1750
|
+
_inventory_terms(
|
|
1751
|
+
" ".join(
|
|
1752
|
+
str(source.get("text") or "")
|
|
1753
|
+
for source in source_chunk.get(source_key) or []
|
|
1754
|
+
)
|
|
1755
|
+
)
|
|
1756
|
+
)
|
|
1757
|
+
return sum(1 for term in candidate_terms if term in source_terms) / len(
|
|
1758
|
+
candidate_terms
|
|
1759
|
+
) >= 0.8
|
|
1760
|
+
|
|
1761
|
+
|
|
1762
|
+
def _validated_source_task_instances(
|
|
1763
|
+
raw: dict[str, Any],
|
|
1764
|
+
duration_secs: float,
|
|
1765
|
+
source_chunk: dict[str, Any] | None = None,
|
|
1766
|
+
) -> list[dict[str, Any]]:
|
|
1767
|
+
"""Validate continued prompt instances without treating their clues as questions."""
|
|
1768
|
+
duration_ms = max(1, round(duration_secs * 1_000))
|
|
1769
|
+
# A task can only continue a prompt the mapper already classified as a
|
|
1770
|
+
# primary source question. This is a structural provenance check, not a
|
|
1771
|
+
# vocabulary test for one language: the model is responsible for semantic
|
|
1772
|
+
# question classification and the validator requires it to be consistent
|
|
1773
|
+
# with its own source-backed inventory.
|
|
1774
|
+
source_prompts = {
|
|
1775
|
+
re.sub(r"\s+", " ", str(item.get("text") or "").casefold()).strip()
|
|
1776
|
+
for item in raw.get("items") or []
|
|
1777
|
+
if isinstance(item, dict)
|
|
1778
|
+
and item.get("kind") == "question"
|
|
1779
|
+
and item.get("questionRole", "primary") == "primary"
|
|
1780
|
+
and str(item.get("text") or "").strip()
|
|
1781
|
+
}
|
|
1782
|
+
tasks: list[dict[str, Any]] = []
|
|
1783
|
+
for candidate in raw.get("taskInstances") or []:
|
|
1784
|
+
if not isinstance(candidate, dict):
|
|
1785
|
+
continue
|
|
1786
|
+
prompt = str(candidate.get("prompt") or "").strip()[:600]
|
|
1787
|
+
channel = str(candidate.get("channel") or "").strip()
|
|
1788
|
+
if channel not in {"spoken", "visible"}:
|
|
1789
|
+
continue
|
|
1790
|
+
prompt_key = re.sub(r"\s+", " ", prompt.casefold()).strip()
|
|
1791
|
+
if not prompt_key or prompt_key not in source_prompts:
|
|
1792
|
+
continue
|
|
1793
|
+
try:
|
|
1794
|
+
start_ms = min(duration_ms, max(0, round(float(candidate.get("startMs")))))
|
|
1795
|
+
end_ms = min(
|
|
1796
|
+
duration_ms,
|
|
1797
|
+
max(start_ms, round(float(candidate.get("endMs")))),
|
|
1798
|
+
)
|
|
1799
|
+
except (TypeError, ValueError):
|
|
1800
|
+
continue
|
|
1801
|
+
task = {
|
|
1802
|
+
"id": f"task-{start_ms}",
|
|
1803
|
+
"prompt": prompt,
|
|
1804
|
+
"channel": channel,
|
|
1805
|
+
"answer": str(candidate.get("answer") or "").strip()[:600],
|
|
1806
|
+
"respondent": str(candidate.get("respondent") or "").strip()[:240],
|
|
1807
|
+
"startMs": start_ms,
|
|
1808
|
+
"endMs": end_ms,
|
|
1809
|
+
}
|
|
1810
|
+
if source_chunk is not None:
|
|
1811
|
+
if not _source_text_is_grounded_anywhere(prompt, channel, source_chunk):
|
|
1812
|
+
continue
|
|
1813
|
+
if task["answer"] and not _inventory_detail_is_grounded(
|
|
1814
|
+
task["answer"], task, source_chunk
|
|
1815
|
+
):
|
|
1816
|
+
task["answer"] = ""
|
|
1817
|
+
if task["respondent"] and not _inventory_detail_is_grounded(
|
|
1818
|
+
task["respondent"], task, source_chunk
|
|
1819
|
+
):
|
|
1820
|
+
task["respondent"] = ""
|
|
1821
|
+
tasks.append(task)
|
|
1822
|
+
return tasks
|
|
1823
|
+
|
|
1824
|
+
|
|
1353
1825
|
def _fallback_source_inventory(
|
|
1354
1826
|
semantic_observations: list[dict[str, Any]], duration_secs: float
|
|
1355
1827
|
) -> list[dict[str, Any]]:
|
|
@@ -1362,17 +1834,29 @@ def _fallback_source_inventory(
|
|
|
1362
1834
|
)
|
|
1363
1835
|
if not match:
|
|
1364
1836
|
continue
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1837
|
+
answer = ""
|
|
1838
|
+
respondent = ""
|
|
1839
|
+
for detail_line in lines[index + 1 : index + 4]:
|
|
1840
|
+
if re.match(r"^Source question \(", detail_line.strip(), re.I):
|
|
1841
|
+
break
|
|
1842
|
+
answer_match = re.match(
|
|
1843
|
+
r"^Source answer:\s*(.*)$", detail_line.strip(), re.I
|
|
1844
|
+
)
|
|
1845
|
+
respondent_match = re.match(
|
|
1846
|
+
r"^Source respondent:\s*(.*)$", detail_line.strip(), re.I
|
|
1847
|
+
)
|
|
1848
|
+
if answer_match:
|
|
1849
|
+
answer = answer_match.group(1).strip()[:600]
|
|
1850
|
+
if respondent_match:
|
|
1851
|
+
respondent = respondent_match.group(1).strip()[:240]
|
|
1370
1852
|
items.append(
|
|
1371
1853
|
{
|
|
1372
1854
|
"kind": "question",
|
|
1373
1855
|
"channel": match.group(1).lower(),
|
|
1856
|
+
"questionRole": "primary",
|
|
1374
1857
|
"text": match.group(2).strip()[:600],
|
|
1375
|
-
"answer":
|
|
1858
|
+
"answer": answer,
|
|
1859
|
+
"respondent": respondent,
|
|
1376
1860
|
"startMs": observation.get("startMs") or 0,
|
|
1377
1861
|
"endMs": observation.get("endMs") or observation.get("startMs") or 0,
|
|
1378
1862
|
}
|
|
@@ -1382,20 +1866,108 @@ def _fallback_source_inventory(
|
|
|
1382
1866
|
|
|
1383
1867
|
def _merge_source_inventory(*groups: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
1384
1868
|
merged: list[dict[str, Any]] = []
|
|
1385
|
-
|
|
1869
|
+
positions: dict[tuple[str, str, int], int] = {}
|
|
1386
1870
|
for item in sorted(
|
|
1387
1871
|
(item for group in groups for item in group),
|
|
1388
1872
|
key=lambda value: (value["startMs"], value["endMs"], value["kind"]),
|
|
1389
1873
|
):
|
|
1390
1874
|
normalized = re.sub(r"\s+", " ", item["text"].casefold()).strip()
|
|
1391
1875
|
key = (item["kind"], normalized, round(item["startMs"] / 5_000))
|
|
1392
|
-
if not normalized
|
|
1876
|
+
if not normalized:
|
|
1393
1877
|
continue
|
|
1394
|
-
|
|
1878
|
+
existing_index = positions.get(key)
|
|
1879
|
+
if existing_index is not None:
|
|
1880
|
+
existing = merged[existing_index]
|
|
1881
|
+
if not existing.get("answer") and item.get("answer"):
|
|
1882
|
+
existing["answer"] = item["answer"]
|
|
1883
|
+
if not existing.get("respondent") and item.get("respondent"):
|
|
1884
|
+
existing["respondent"] = item["respondent"]
|
|
1885
|
+
continue
|
|
1886
|
+
positions[key] = len(merged)
|
|
1395
1887
|
merged.append(item)
|
|
1396
1888
|
return merged[:2_000]
|
|
1397
1889
|
|
|
1398
1890
|
|
|
1891
|
+
def _merge_source_activity_structures(
|
|
1892
|
+
*groups: list[dict[str, Any]],
|
|
1893
|
+
) -> list[dict[str, Any]]:
|
|
1894
|
+
"""Merge overlapping readings of the same layout without joining later repeats."""
|
|
1895
|
+
merged: list[dict[str, Any]] = []
|
|
1896
|
+
positions: dict[tuple[str, str, int], int] = {}
|
|
1897
|
+
for structure in sorted(
|
|
1898
|
+
(item for group in groups for item in group),
|
|
1899
|
+
key=lambda value: (value["startMs"], value["endMs"], value["kind"]),
|
|
1900
|
+
):
|
|
1901
|
+
normalized_label = re.sub(r"\s+", " ", structure["label"].casefold()).strip()
|
|
1902
|
+
key = (structure["kind"], normalized_label, round(structure["startMs"] / 5_000))
|
|
1903
|
+
existing_index = positions.get(key)
|
|
1904
|
+
if existing_index is None:
|
|
1905
|
+
positions[key] = len(merged)
|
|
1906
|
+
merged.append(
|
|
1907
|
+
{
|
|
1908
|
+
**structure,
|
|
1909
|
+
"dimensions": [
|
|
1910
|
+
{"label": item["label"], "values": list(item["values"])}
|
|
1911
|
+
for item in structure["dimensions"]
|
|
1912
|
+
],
|
|
1913
|
+
}
|
|
1914
|
+
)
|
|
1915
|
+
continue
|
|
1916
|
+
existing = merged[existing_index]
|
|
1917
|
+
existing["endMs"] = max(existing["endMs"], structure["endMs"])
|
|
1918
|
+
dimensions_by_label = {
|
|
1919
|
+
re.sub(r"\s+", " ", item["label"].casefold()).strip(): item
|
|
1920
|
+
for item in existing["dimensions"]
|
|
1921
|
+
}
|
|
1922
|
+
for dimension in structure["dimensions"]:
|
|
1923
|
+
dimension_key = re.sub(r"\s+", " ", dimension["label"].casefold()).strip()
|
|
1924
|
+
target = dimensions_by_label.get(dimension_key)
|
|
1925
|
+
if target is None:
|
|
1926
|
+
target = {"label": dimension["label"], "values": []}
|
|
1927
|
+
existing["dimensions"].append(target)
|
|
1928
|
+
dimensions_by_label[dimension_key] = target
|
|
1929
|
+
known = {
|
|
1930
|
+
re.sub(r"\s+", " ", value.casefold()).strip()
|
|
1931
|
+
for value in target["values"]
|
|
1932
|
+
}
|
|
1933
|
+
for value in dimension["values"]:
|
|
1934
|
+
value_key = re.sub(r"\s+", " ", value.casefold()).strip()
|
|
1935
|
+
if value_key not in known:
|
|
1936
|
+
target["values"].append(value)
|
|
1937
|
+
known.add(value_key)
|
|
1938
|
+
if existing["kind"] == "grid":
|
|
1939
|
+
existing["promptCount"] = math.prod(
|
|
1940
|
+
len(dimension["values"]) for dimension in existing["dimensions"]
|
|
1941
|
+
)
|
|
1942
|
+
return merged[:256]
|
|
1943
|
+
|
|
1944
|
+
|
|
1945
|
+
def _merge_source_task_instances(
|
|
1946
|
+
*groups: list[dict[str, Any]],
|
|
1947
|
+
) -> list[dict[str, Any]]:
|
|
1948
|
+
"""Collapse overlapping reads of one continued task, retaining later turns."""
|
|
1949
|
+
merged: list[dict[str, Any]] = []
|
|
1950
|
+
positions: dict[tuple[str, str, int], int] = {}
|
|
1951
|
+
for task in sorted(
|
|
1952
|
+
(item for group in groups for item in group),
|
|
1953
|
+
key=lambda value: (value["startMs"], value["endMs"], value["prompt"]),
|
|
1954
|
+
):
|
|
1955
|
+
prompt_key = re.sub(r"\s+", " ", task["prompt"].casefold()).strip()
|
|
1956
|
+
key = (task["channel"], prompt_key, round(task["startMs"] / 5_000))
|
|
1957
|
+
existing_index = positions.get(key)
|
|
1958
|
+
if existing_index is None:
|
|
1959
|
+
positions[key] = len(merged)
|
|
1960
|
+
merged.append(dict(task))
|
|
1961
|
+
continue
|
|
1962
|
+
existing = merged[existing_index]
|
|
1963
|
+
existing["endMs"] = max(existing["endMs"], task["endMs"])
|
|
1964
|
+
if len(task.get("answer") or "") > len(existing.get("answer") or ""):
|
|
1965
|
+
existing["answer"] = task["answer"]
|
|
1966
|
+
if len(task.get("respondent") or "") > len(existing.get("respondent") or ""):
|
|
1967
|
+
existing["respondent"] = task["respondent"]
|
|
1968
|
+
return merged[:512]
|
|
1969
|
+
|
|
1970
|
+
|
|
1399
1971
|
def _synthesis_prompt(
|
|
1400
1972
|
*,
|
|
1401
1973
|
brief: dict[str, Any],
|
|
@@ -1482,6 +2054,13 @@ def _synthesis_prompt(
|
|
|
1482
2054
|
"- A later close-up, label, caption, presentation, celebration, or reaction does not identify "
|
|
1483
2055
|
"who performed an earlier action. Bind the name to that earlier actor only when an uninterrupted "
|
|
1484
2056
|
"sequence tracks the same subject or the supplied evidence explicitly states the relationship.\n"
|
|
2057
|
+
"- visibleSubjects is an appearance ledger. Include every named or source-distinguished visible "
|
|
2058
|
+
"subject whose appearances the evidence supports. Each appearance range must be one supplied "
|
|
2059
|
+
"range where that subject is actually present; keep separate appearances separate after a real "
|
|
2060
|
+
"absence or edit. identityBasis is source-named only when source evidence binds the name, "
|
|
2061
|
+
"source-described for a stable source-supported descriptor, and unresolved when the evidence "
|
|
2062
|
+
"cannot safely distinguish the subject. Never merge two entries from resemblance alone, and do "
|
|
2063
|
+
"not include a subject merely because they are discussed in speech.\n"
|
|
1485
2064
|
"- stateHistory tracks things that persist and change: a displayed value, a location, a phase, "
|
|
1486
2065
|
"a condition. Record each distinct value once with the span it held, and keep the sequence "
|
|
1487
2066
|
"self-consistent -- one thing cannot hold two values at the same time, and a value it never "
|
|
@@ -1507,6 +2086,8 @@ def _synthesis_prompt(
|
|
|
1507
2086
|
"where a display existed and when it changed. It never states what that text means: use it to "
|
|
1508
2087
|
"corroborate or locate, never as a fact on its own.\n"
|
|
1509
2088
|
"Return JSON only: {overview:string, participants:[{name,role,evidence:[{startMs,endMs}]}], "
|
|
2089
|
+
"visibleSubjects:[{identity,identityBasis:'source-named'|'source-described'|'unresolved',"
|
|
2090
|
+
"appearances:[{startMs,endMs,confidence:'direct'|'partial'}]}], "
|
|
1510
2091
|
"stateHistory:[{startMs,endMs,state,confidence:'direct'|'partial'}], "
|
|
1511
2092
|
"keyEvents:[{startMs,endMs,event,confidence:'direct'|'partial'}], "
|
|
1512
2093
|
"narrative:[{startMs,endMs,text,confidence:'direct'|'partial'}], "
|
|
@@ -1752,6 +2333,46 @@ def _validated_knowledge_summary(
|
|
|
1752
2333
|
if len(participants) == 50:
|
|
1753
2334
|
break
|
|
1754
2335
|
|
|
2336
|
+
visible_subjects: list[dict[str, Any]] = []
|
|
2337
|
+
for candidate in raw.get("visibleSubjects") or []:
|
|
2338
|
+
if not isinstance(candidate, dict):
|
|
2339
|
+
continue
|
|
2340
|
+
identity = str(candidate.get("identity") or "").strip()[:180]
|
|
2341
|
+
identity_basis = candidate.get("identityBasis")
|
|
2342
|
+
appearances = []
|
|
2343
|
+
for appearance in candidate.get("appearances") or []:
|
|
2344
|
+
if not isinstance(appearance, dict):
|
|
2345
|
+
continue
|
|
2346
|
+
evidence = source_range(appearance)
|
|
2347
|
+
if not evidence:
|
|
2348
|
+
continue
|
|
2349
|
+
appearances.append(
|
|
2350
|
+
{
|
|
2351
|
+
**evidence,
|
|
2352
|
+
"confidence": (
|
|
2353
|
+
appearance.get("confidence")
|
|
2354
|
+
if appearance.get("confidence") in {"direct", "partial"}
|
|
2355
|
+
else "partial"
|
|
2356
|
+
),
|
|
2357
|
+
}
|
|
2358
|
+
)
|
|
2359
|
+
if (
|
|
2360
|
+
identity
|
|
2361
|
+
and identity_basis in {"source-named", "source-described", "unresolved"}
|
|
2362
|
+
and appearances
|
|
2363
|
+
):
|
|
2364
|
+
visible_subjects.append(
|
|
2365
|
+
{
|
|
2366
|
+
"identity": identity,
|
|
2367
|
+
"identityBasis": identity_basis,
|
|
2368
|
+
"appearances": sorted(
|
|
2369
|
+
appearances, key=lambda item: (item["startMs"], item["endMs"])
|
|
2370
|
+
)[:32],
|
|
2371
|
+
}
|
|
2372
|
+
)
|
|
2373
|
+
if len(visible_subjects) == 96:
|
|
2374
|
+
break
|
|
2375
|
+
|
|
1755
2376
|
def timeline(key: str, text_key: str, limit: int) -> list[dict[str, Any]]:
|
|
1756
2377
|
items: list[dict[str, Any]] = []
|
|
1757
2378
|
for candidate in raw.get(key) or []:
|
|
@@ -1794,6 +2415,7 @@ def _validated_knowledge_summary(
|
|
|
1794
2415
|
return {
|
|
1795
2416
|
"overview": str(raw.get("overview") or "").strip()[:2_000],
|
|
1796
2417
|
"participants": participants,
|
|
2418
|
+
"visibleSubjects": visible_subjects,
|
|
1797
2419
|
"stateHistory": timeline("stateHistory", "state", 80),
|
|
1798
2420
|
"keyEvents": timeline("keyEvents", "event", 80),
|
|
1799
2421
|
"narrative": timeline("narrative", "text", 64),
|
|
@@ -1933,6 +2555,7 @@ def _fallback_knowledge_summary(
|
|
|
1933
2555
|
return {
|
|
1934
2556
|
"overview": overview,
|
|
1935
2557
|
"participants": list(participants_by_name.values())[:50],
|
|
2558
|
+
"visibleSubjects": [],
|
|
1936
2559
|
"stateHistory": state_history,
|
|
1937
2560
|
"keyEvents": key_events,
|
|
1938
2561
|
"narrative": narrative,
|