-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze.py
More file actions
187 lines (171 loc) · 6.48 KB
/
Copy pathanalyze.py
File metadata and controls
187 lines (171 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
from __future__ import annotations
import json
import os
from typing import Any
from .chunking import merge_highlight_candidates, select_top_highlights
from .prompts import (
SYSTEM_PROMPT,
build_chapter_prompt,
build_highlight_prompt,
build_overall_summary_prompt,
)
from .schemas import AnalysisBundle, ChapterSummary, HighlightCandidate, TranscriptChunk
class Analyzer:
def __init__(self, *, model: str | None = None) -> None:
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY is not set.")
try:
from openai import OpenAI
except ImportError as exc:
raise RuntimeError("openai is not installed. Install dependencies from requirements.txt first.") from exc
self.client = OpenAI(api_key=api_key)
self.model = model or os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
def analyze(
self,
chunks: list[TranscriptChunk],
*,
highlight_count: int,
min_clip_seconds: int,
max_clip_seconds: int,
) -> AnalysisBundle:
if not chunks:
return AnalysisBundle(chapters=[], highlights=[], overall_summary="No transcript content was available.")
chapters = self.create_chapters(chunks)
highlight_pool: list[HighlightCandidate] = []
for chunk in chunks:
highlight_pool.extend(
self.score_highlights(
chunk,
min_clip_seconds=min_clip_seconds,
max_clip_seconds=max_clip_seconds,
)
)
merged = merge_highlight_candidates(highlight_pool)
highlights = select_top_highlights(merged, limit=highlight_count)
summary = self.create_overall_summary(chapters, highlight_count=len(highlights))
return AnalysisBundle(chapters=chapters, highlights=highlights, overall_summary=summary)
def create_chapters(self, chunks: list[TranscriptChunk]) -> list[ChapterSummary]:
payload = self._response_json(
name="chapter_summary",
schema=_chapter_schema(),
prompt=build_chapter_prompt(chunks),
)
chapters: list[ChapterSummary] = []
for item in payload.get("chapters", []):
chapters.append(
ChapterSummary(
title=item["title"].strip(),
start=float(item["start"]),
end=float(item["end"]),
summary=item["summary"].strip(),
)
)
return sorted(chapters, key=lambda item: (item.start, item.end))
def score_highlights(
self,
chunk: TranscriptChunk,
*,
min_clip_seconds: int,
max_clip_seconds: int,
) -> list[HighlightCandidate]:
payload = self._response_json(
name="highlight_candidates",
schema=_highlight_schema(),
prompt=build_highlight_prompt(
chunk,
min_clip_seconds=min_clip_seconds,
max_clip_seconds=max_clip_seconds,
),
)
items: list[HighlightCandidate] = []
for index, raw in enumerate(payload.get("highlights", []), start=1):
start = max(chunk.start, float(raw["start"]))
end = min(chunk.end, float(raw["end"]))
if end <= start:
continue
items.append(
HighlightCandidate(
id=f"{chunk.chunk_id}-h{index}",
start=start,
end=end,
duration=end - start,
score=float(raw["score"]),
title=raw["title"].strip(),
reason=raw["reason"].strip(),
excerpt=raw["excerpt"].strip(),
source_chunk_ids=[chunk.chunk_id],
)
)
return items
def create_overall_summary(self, chapters: list[ChapterSummary], *, highlight_count: int) -> str:
response = self.client.responses.create(
model=self.model,
instructions=SYSTEM_PROMPT,
input=build_overall_summary_prompt(chapters, highlight_count),
)
return (response.output_text or "").strip()
def _response_json(self, *, name: str, schema: dict[str, Any], prompt: str) -> dict[str, Any]:
response = self.client.responses.create(
model=self.model,
instructions=SYSTEM_PROMPT,
input=prompt,
text={
"format": {
"type": "json_schema",
"name": name,
"schema": schema,
"strict": True,
}
},
)
content = (response.output_text or "").strip()
if not content:
raise RuntimeError(f"The model returned an empty response for {name}.")
return json.loads(content)
def _chapter_schema() -> dict[str, Any]:
return {
"type": "object",
"properties": {
"chapters": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {"type": "string"},
"start": {"type": "number"},
"end": {"type": "number"},
"summary": {"type": "string"},
},
"required": ["title", "start", "end", "summary"],
"additionalProperties": False,
},
}
},
"required": ["chapters"],
"additionalProperties": False,
}
def _highlight_schema() -> dict[str, Any]:
return {
"type": "object",
"properties": {
"highlights": {
"type": "array",
"items": {
"type": "object",
"properties": {
"start": {"type": "number"},
"end": {"type": "number"},
"score": {"type": "number"},
"title": {"type": "string"},
"reason": {"type": "string"},
"excerpt": {"type": "string"},
},
"required": ["start", "end", "score", "title", "reason", "excerpt"],
"additionalProperties": False,
},
}
},
"required": ["highlights"],
"additionalProperties": False,
}