opencontext-video 0.1.0__py3-none-any.whl

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.
Files changed (45) hide show
  1. oc_worker/__init__.py +14 -0
  2. oc_worker/agent.py +315 -0
  3. oc_worker/aggregation.py +160 -0
  4. oc_worker/api_client.py +296 -0
  5. oc_worker/cli.py +895 -0
  6. oc_worker/config.py +122 -0
  7. oc_worker/context.py +590 -0
  8. oc_worker/contract.py +113 -0
  9. oc_worker/errors.py +30 -0
  10. oc_worker/evaluation.py +148 -0
  11. oc_worker/ffmpeg.py +276 -0
  12. oc_worker/main.py +133 -0
  13. oc_worker/mcp_server.py +151 -0
  14. oc_worker/models.py +201 -0
  15. oc_worker/pdf.py +74 -0
  16. oc_worker/pipeline.py +699 -0
  17. oc_worker/providers/__init__.py +143 -0
  18. oc_worker/providers/http_status.py +31 -0
  19. oc_worker/providers/ocr/__init__.py +7 -0
  20. oc_worker/providers/ocr/base.py +17 -0
  21. oc_worker/providers/ocr/fixture.py +19 -0
  22. oc_worker/providers/ocr/tesseract.py +94 -0
  23. oc_worker/providers/text/__init__.py +5 -0
  24. oc_worker/providers/text/base.py +32 -0
  25. oc_worker/providers/text/ollama.py +83 -0
  26. oc_worker/providers/text/openai_compatible.py +93 -0
  27. oc_worker/providers/text/template.py +17 -0
  28. oc_worker/providers/transcription/__init__.py +5 -0
  29. oc_worker/providers/transcription/base.py +17 -0
  30. oc_worker/providers/transcription/faster_whisper.py +43 -0
  31. oc_worker/providers/transcription/fixture.py +24 -0
  32. oc_worker/providers/transcription/openai_audio.py +119 -0
  33. oc_worker/providers/transcription/openai_compatible.py +85 -0
  34. oc_worker/providers/vision/__init__.py +5 -0
  35. oc_worker/providers/vision/base.py +20 -0
  36. oc_worker/providers/vision/fixture.py +38 -0
  37. oc_worker/providers/vision/ollama.py +69 -0
  38. oc_worker/providers/vision/openai_compatible.py +166 -0
  39. oc_worker/replay.py +411 -0
  40. opencontext_video-0.1.0.dist-info/METADATA +253 -0
  41. opencontext_video-0.1.0.dist-info/RECORD +45 -0
  42. opencontext_video-0.1.0.dist-info/WHEEL +5 -0
  43. opencontext_video-0.1.0.dist-info/entry_points.txt +3 -0
  44. opencontext_video-0.1.0.dist-info/licenses/LICENSE +21 -0
  45. opencontext_video-0.1.0.dist-info/top_level.txt +1 -0
oc_worker/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """OpenContext media processing worker."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+
6
+ def package_version() -> str:
7
+ """Return the installed package version without a second release literal."""
8
+ try:
9
+ return version("opencontext-video")
10
+ except PackageNotFoundError:
11
+ return "0.0.0+unknown"
12
+
13
+
14
+ __version__ = package_version()
oc_worker/agent.py ADDED
@@ -0,0 +1,315 @@
1
+ """Evidence-preserving implementation briefs for coding agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections import Counter
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from oc_worker.context import format_timestamp
13
+
14
+ _SKIP_DIRECTORIES = {
15
+ ".git",
16
+ ".next",
17
+ ".pytest_cache",
18
+ ".ruff_cache",
19
+ ".tmp",
20
+ ".venv",
21
+ "__pycache__",
22
+ "build",
23
+ "coverage",
24
+ "dist",
25
+ "node_modules",
26
+ "vendor",
27
+ }
28
+ _LANGUAGE_EXTENSIONS = {
29
+ ".css": "CSS",
30
+ ".go": "Go",
31
+ ".html": "HTML",
32
+ ".java": "Java",
33
+ ".js": "JavaScript",
34
+ ".jsx": "JavaScript",
35
+ ".kt": "Kotlin",
36
+ ".md": "Markdown",
37
+ ".py": "Python",
38
+ ".rb": "Ruby",
39
+ ".rs": "Rust",
40
+ ".sh": "Shell",
41
+ ".sql": "SQL",
42
+ ".swift": "Swift",
43
+ ".ts": "TypeScript",
44
+ ".tsx": "TypeScript",
45
+ }
46
+ _MAX_SCAN_FILES = 1_000
47
+ _MAX_TEXT_FILE_BYTES = 1_000_000
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class RepositoryProfile:
52
+ name: str
53
+ languages: tuple[str, ...]
54
+ technologies: tuple[str, ...]
55
+ manifests: tuple[str, ...]
56
+
57
+ def as_dict(self) -> dict[str, Any]:
58
+ return {
59
+ "name": self.name,
60
+ "languages": list(self.languages),
61
+ "technologies": list(self.technologies),
62
+ "manifests": list(self.manifests),
63
+ }
64
+
65
+
66
+ def _read_small_json(path: Path) -> dict[str, Any]:
67
+ try:
68
+ if path.stat().st_size > _MAX_TEXT_FILE_BYTES:
69
+ return {}
70
+ value = json.loads(path.read_text(encoding="utf-8"))
71
+ except (OSError, ValueError):
72
+ return {}
73
+ return value if isinstance(value, dict) else {}
74
+
75
+
76
+ def detect_repository_profile(repository: str | Path | None) -> RepositoryProfile | None:
77
+ """Inspect a repository's structure without executing or uploading it."""
78
+ if repository is None:
79
+ return None
80
+ root = Path(repository).expanduser().resolve()
81
+ if not root.is_dir():
82
+ raise ValueError(f"Repository path is not a directory: {root}")
83
+
84
+ language_counts: Counter[str] = Counter()
85
+ manifests: set[str] = set()
86
+ technologies: set[str] = set()
87
+ scanned = 0
88
+ for current, directories, files in os.walk(root):
89
+ directories[:] = sorted(
90
+ directory for directory in directories if directory not in _SKIP_DIRECTORIES
91
+ )
92
+ current_path = Path(current)
93
+ for filename in sorted(files):
94
+ if scanned >= _MAX_SCAN_FILES:
95
+ break
96
+ scanned += 1
97
+ path = current_path / filename
98
+ language = _LANGUAGE_EXTENSIONS.get(path.suffix.lower())
99
+ if language:
100
+ language_counts[language] += 1
101
+ if filename in {
102
+ "Cargo.toml",
103
+ "Dockerfile",
104
+ "build.gradle",
105
+ "docker-compose.yml",
106
+ "go.mod",
107
+ "package.json",
108
+ "pom.xml",
109
+ "pyproject.toml",
110
+ "requirements.txt",
111
+ "schema.prisma",
112
+ }:
113
+ manifests.add(path.relative_to(root).as_posix())
114
+ if scanned >= _MAX_SCAN_FILES:
115
+ break
116
+
117
+ package_manifests = [
118
+ manifest for manifest in manifests if manifest.endswith("package.json")
119
+ ]
120
+ if package_manifests:
121
+ technologies.add("Node.js")
122
+ language_counts["JavaScript"] += 1
123
+ for manifest in package_manifests[:20]:
124
+ package = _read_small_json(root / manifest)
125
+ dependencies = {
126
+ **(package.get("dependencies") or {}),
127
+ **(package.get("devDependencies") or {}),
128
+ }
129
+ if "next" in dependencies:
130
+ technologies.add("Next.js")
131
+ if "react" in dependencies:
132
+ technologies.add("React")
133
+ if "prisma" in dependencies or "@prisma/client" in dependencies:
134
+ technologies.add("Prisma")
135
+ if "vitest" in dependencies:
136
+ technologies.add("Vitest")
137
+ if "typescript" in dependencies:
138
+ technologies.add("TypeScript")
139
+
140
+ if (root / "pyproject.toml").is_file() or (root / "requirements.txt").is_file():
141
+ language_counts["Python"] += 1
142
+ technologies.add("Python")
143
+ if (root / "schema.prisma").is_file() or any(
144
+ manifest.endswith("schema.prisma") for manifest in manifests
145
+ ):
146
+ technologies.add("Prisma")
147
+ if (root / "Dockerfile").is_file() or (root / "docker-compose.yml").is_file():
148
+ technologies.add("Docker")
149
+ if (root / ".github" / "workflows").is_dir():
150
+ technologies.add("GitHub Actions")
151
+
152
+ return RepositoryProfile(
153
+ name=root.name,
154
+ languages=tuple(
155
+ language for language, _count in language_counts.most_common(8)
156
+ ),
157
+ technologies=tuple(sorted(technologies)),
158
+ manifests=tuple(sorted(manifests)[:30]),
159
+ )
160
+
161
+
162
+ def load_context_payload(path: str | Path) -> dict[str, Any]:
163
+ context_path = Path(path).expanduser().resolve()
164
+ try:
165
+ payload = json.loads(context_path.read_text(encoding="utf-8"))
166
+ except OSError as exc:
167
+ raise ValueError(f"Could not read context JSON: {context_path}") from exc
168
+ except ValueError as exc:
169
+ raise ValueError(f"Context file is not valid JSON: {context_path}") from exc
170
+ if not isinstance(payload, dict):
171
+ raise ValueError("Context JSON must be an object")
172
+ if not isinstance(payload.get("source"), dict):
173
+ raise ValueError("Context JSON is missing source metadata")
174
+ if not isinstance(payload.get("evidence"), list):
175
+ raise ValueError("Context JSON is missing an evidence ledger")
176
+ return payload
177
+
178
+
179
+ def _marker(record: dict[str, Any]) -> str:
180
+ evidence_id = int(record.get("id") or 0)
181
+ timestamp = format_timestamp(float(record.get("timestampSec") or 0))
182
+ certainty = str(record.get("certainty") or "OBSERVED").title()
183
+ return f"[E{evidence_id:04d} · {timestamp} · {certainty}]"
184
+
185
+
186
+ def _bullet_records(
187
+ evidence: list[dict[str, Any]],
188
+ *,
189
+ collections: set[str],
190
+ limit: int = 40,
191
+ ) -> list[str]:
192
+ rows: list[str] = []
193
+ seen: set[str] = set()
194
+ for record in evidence:
195
+ source = record.get("source")
196
+ if not isinstance(source, dict) or source.get("collection") not in collections:
197
+ continue
198
+ text = str(record.get("text") or "").strip()
199
+ if not text or text in seen:
200
+ continue
201
+ seen.add(text)
202
+ rows.append(f"- {text} {_marker(record)}")
203
+ if len(rows) >= limit:
204
+ break
205
+ return rows
206
+
207
+
208
+ def build_implementation_brief(
209
+ payload: dict[str, Any],
210
+ *,
211
+ repository: str | Path | None = None,
212
+ task: str | None = None,
213
+ ) -> str:
214
+ """Render a repository-aware prompt from an evidence-linked context payload."""
215
+ source = payload.get("source") or {}
216
+ evidence = [item for item in payload.get("evidence") or [] if isinstance(item, dict)]
217
+ source_name = str(source.get("name") or "recorded workflow")
218
+ requested_task = (
219
+ task.strip()
220
+ if task and task.strip()
221
+ else "Implement the recorded workflow in this repository."
222
+ )
223
+ profile = detect_repository_profile(repository)
224
+
225
+ lines = [
226
+ f"# Implementation Brief: {source_name}",
227
+ "",
228
+ "> Generated deterministically from OpenContext evidence. Preserve the",
229
+ "> evidence markers when carrying claims into code or tests.",
230
+ "",
231
+ "## Task",
232
+ "",
233
+ requested_task,
234
+ "",
235
+ "## Repository fit",
236
+ "",
237
+ ]
238
+ if profile:
239
+ lines.extend(
240
+ [
241
+ f"- Repository: `{profile.name}`",
242
+ f"- Languages: {', '.join(profile.languages) or 'not detected'}",
243
+ f"- Technologies: {', '.join(profile.technologies) or 'not detected'}",
244
+ "- Manifests: "
245
+ + (
246
+ ", ".join(f"`{item}`" for item in profile.manifests)
247
+ or "none detected"
248
+ ),
249
+ ]
250
+ )
251
+ else:
252
+ lines.append("- Repository profile not supplied; inspect the target codebase first.")
253
+
254
+ lines.extend(["", "## Observed workflow", ""])
255
+ timeline = [item for item in payload.get("timeline") or [] if isinstance(item, dict)]
256
+ if timeline:
257
+ for item in timeline[:30]:
258
+ start = format_timestamp(float(item.get("start") or 0))
259
+ end = format_timestamp(float(item.get("end") or item.get("start") or 0))
260
+ title = str(item.get("title") or "Scene")
261
+ summary = str(item.get("summary") or "").strip()
262
+ lines.append(
263
+ f"- `[{start}-{end}]` **{title}**"
264
+ + (f" — {summary}" if summary else "")
265
+ )
266
+ else:
267
+ lines.append("- No visual timeline was recorded.")
268
+
269
+ lines.extend(["", "## Implementation targets", ""])
270
+ targets = _bullet_records(
271
+ evidence,
272
+ collections={"uiHierarchy", "interactions", "stateTransitions"},
273
+ )
274
+ lines.extend(targets or ["- No implementation targets were extracted."])
275
+
276
+ lines.extend(["", "## Acceptance criteria", ""])
277
+ criteria = _bullet_records(
278
+ evidence,
279
+ collections={"interactions", "stateTransitions", "visibleText"},
280
+ )
281
+ if criteria:
282
+ lines.extend(f"- [ ] {row[2:]}" for row in criteria)
283
+ else:
284
+ lines.append("- [ ] Implement only behavior directly supported by the evidence.")
285
+
286
+ lines.extend(["", "## Transcript context", ""])
287
+ transcript = _bullet_records(evidence, collections={"transcript"}, limit=30)
288
+ lines.extend(transcript or ["- No transcript evidence was extracted."])
289
+
290
+ lines.extend(["", "## Uncertainty and review", ""])
291
+ uncertain = [
292
+ record
293
+ for record in evidence
294
+ if str(record.get("certainty") or "").upper() != "OBSERVED"
295
+ ]
296
+ if uncertain:
297
+ for record in uncertain[:30]:
298
+ lines.append(f"- Verify: {record.get('text')} {_marker(record)}")
299
+ else:
300
+ lines.append("- No inferred or uncertain evidence was recorded.")
301
+
302
+ lines.extend(
303
+ [
304
+ "",
305
+ "## Agent instructions",
306
+ "",
307
+ "1. Inspect the repository and identify the files implementing the observed flow.",
308
+ "2. Map each acceptance criterion to an implementation and a test.",
309
+ "3. Treat inferred or uncertain evidence as a hypothesis to verify.",
310
+ "4. Do not invent behavior that has no evidence marker.",
311
+ "5. Preserve timestamped evidence IDs in the final handoff.",
312
+ "",
313
+ ]
314
+ )
315
+ return "\n".join(lines)
@@ -0,0 +1,160 @@
1
+ """Pure, deterministic scene-row aggregation + frame selection helpers.
2
+
3
+ No I/O and no randomness: given the same inputs this always produces
4
+ the same timeline payload. Contract (matches packages/schemas
5
+ TimelineEntrySchema and apps/web demo-result.json):
6
+
7
+ - AGGREGATING/GENERATING_CONTEXT ``timeline`` is a list of canonical
8
+ scene rows ``{start: number, end: number, title?: string, summary: string}``
9
+ built from visual observations only (the web zod contract rejects any
10
+ other entry shape).
11
+ - Each row is one consecutive run of observations (sorted by timestampSec)
12
+ whose sceneTitle is equal; untitled observations are single-observation
13
+ rows without a ``title`` key.
14
+ - start = first observation timestamp of the run; end = next run's start,
15
+ or the video duration for the last run (clamped so end >= start; when the
16
+ duration is unknown/zero the last run ends at its own start).
17
+ - summary is deterministic prose (description, then changes, then an
18
+ "(inferred)" marker when any member was not OBSERVED).
19
+
20
+ Detail-level frame filtering is NOT applied here: ANALYZING already
21
+ stride-filters frames with ``frame_selected`` before observations reach
22
+ this module (pipeline.py).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from typing import Any
28
+
29
+ from oc_worker.models import (
30
+ Certainty,
31
+ DetailLevel,
32
+ VisualObservation,
33
+ )
34
+
35
+ _UNCERTAIN_CERTAINTIES = (Certainty.INFERRED, Certainty.UNCERTAIN)
36
+
37
+
38
+ def frame_selected(timestamp_sec: float, detail_level: DetailLevel | str) -> bool:
39
+ """True when the frame at ``timestamp_sec`` is analyzed at this level.
40
+
41
+ Detail-level semantics live in the ANALYZING stage: this decides which
42
+ extracted frames the vision provider analyzes (LOW -> every 10th frame,
43
+ MEDIUM -> every 3rd, HIGH -> every frame).
44
+ """
45
+ level = DetailLevel(detail_level)
46
+ if level is DetailLevel.HIGH:
47
+ return True
48
+ stride = 10 if level is DetailLevel.LOW else 3
49
+ return int(round(timestamp_sec)) % stride == 0
50
+
51
+
52
+ def _strip_title(scene_title: str | None) -> str | None:
53
+ """Scene title trimmed; None when the observation is untitled."""
54
+ if scene_title is None:
55
+ return None
56
+ title = scene_title.strip()
57
+ return title or None
58
+
59
+
60
+ def _group_observations(
61
+ observations: list[VisualObservation],
62
+ ) -> list[list[VisualObservation]]:
63
+ """Split timestamp-sorted observations into consecutive same-title runs.
64
+
65
+ Stable: equal timestamps keep input order (Python's sort is stable).
66
+ Untitled observations (None/blank sceneTitle) are their own
67
+ single-observation groups and never merge with titled neighbours.
68
+ """
69
+ sorted_obs = sorted(observations, key=lambda obs: obs.timestampSec)
70
+ groups: list[list[VisualObservation]] = []
71
+ for obs in sorted_obs:
72
+ title = _strip_title(obs.sceneTitle)
73
+ if groups:
74
+ current = groups[-1]
75
+ current_title = _strip_title(current[-1].sceneTitle)
76
+ if current_title is not None and title == current_title:
77
+ current.append(obs)
78
+ continue
79
+ groups.append([obs])
80
+ return groups
81
+
82
+
83
+ def _group_summary(group: list[VisualObservation]) -> str:
84
+ """Deterministic prose summary for one scene row.
85
+
86
+ - description: visualDescription of the group's first observation that
87
+ has one (else no description part)
88
+ - "; changes: <joined>" appended when any observation in the group has
89
+ importantChanges (joined with "; ", empty items dropped)
90
+ - " (inferred)" appended when any observation in the group had
91
+ certainty INFERRED or UNCERTAIN (the marker alone when the group has
92
+ no description and no changes)
93
+ No trailing separators: empty parts are skipped.
94
+ """
95
+ description = ""
96
+ changes: list[str] = []
97
+ inferred = False
98
+ for obs in group:
99
+ if not description and obs.visualDescription and obs.visualDescription.strip():
100
+ description = obs.visualDescription.strip()
101
+ for change in obs.importantChanges:
102
+ if change and change.strip():
103
+ changes.append(change.strip())
104
+ if obs.certainty in _UNCERTAIN_CERTAINTIES:
105
+ inferred = True
106
+ parts: list[str] = []
107
+ if description:
108
+ parts.append(description)
109
+ if changes:
110
+ parts.append(f"changes: {'; '.join(changes)}")
111
+ summary = "; ".join(parts)
112
+ if inferred:
113
+ summary = f"{summary} (inferred)" if summary else "(inferred)"
114
+ return summary
115
+
116
+
117
+ def build_timeline(
118
+ observations: list[VisualObservation], duration_sec: float | None
119
+ ) -> list[dict[str, Any]]:
120
+ """Build the canonical scene-row timeline from visual observations.
121
+
122
+ Observations are already frame-filtered by the ANALYZING stride, so no
123
+ re-filtering happens here. Rows cover the video continuously: each row
124
+ starts at its first observation and ends where the next row starts; the
125
+ last row ends at ``duration_sec`` (unknown/zero duration -> its own
126
+ start; always clamped so end >= start). Returns a list of dicts with
127
+ exactly the keys start/end[/title]/summary and float bounds; same
128
+ inputs always produce the same rows.
129
+ """
130
+ rows: list[dict[str, Any]] = []
131
+ for group in _group_observations(observations):
132
+ start = float(group[0].timestampSec)
133
+ title = _strip_title(group[0].sceneTitle)
134
+ row: dict[str, Any] = {"start": start}
135
+ rows.append(row)
136
+ row["end"] = start
137
+ if title is not None:
138
+ row["title"] = title
139
+ row["summary"] = _group_summary(group)
140
+ for index, row in enumerate(rows):
141
+ if index + 1 < len(rows):
142
+ row["end"] = max(row["start"], rows[index + 1]["start"])
143
+ continue
144
+ if duration_sec is not None and float(duration_sec) > 0:
145
+ row["end"] = max(row["start"], float(duration_sec))
146
+ return rows
147
+
148
+
149
+ def mark_interaction_certainty(observation: dict[str, Any]) -> dict[str, Any]:
150
+ """Legacy tolerance: mark dict-shaped interactions as INFERRED.
151
+
152
+ Canonical interactions are one-sentence strings and carry no per-item
153
+ marker (observation-level ``certainty`` governs); they pass through
154
+ untouched. Dict items a provider may still return (pre-validation)
155
+ keep the historical INFERRED stamp.
156
+ """
157
+ for item in observation.get("interactions", []):
158
+ if isinstance(item, dict):
159
+ item["certainty"] = Certainty.INFERRED.value
160
+ return observation