-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.py
More file actions
1669 lines (1452 loc) · 57.1 KB
/
Copy pathevents.py
File metadata and controls
1669 lines (1452 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import os
import re
from collections.abc import Sequence
from datetime import date, datetime
from enum import Enum
from itertools import combinations
from typing import Any, Callable
from uuid import uuid4
import contacts as contacts_service
import event_photos as event_photos_service
from db import enrich_people, fetch_events, get_conn
from embeddings import embed_text
from observability.logger import get_runtime_logger
from schemas import (
ContactRelationshipIn,
EventIn,
ExternalEventPayload,
MeetingTranscriptPayload,
TodoIn,
)
from search_normalization import normalize_search_text
from tags_manager import (
_merge_tag_lists,
_normalize_strings,
_suggest_event_tags,
)
logger = get_runtime_logger(__name__)
MAX_EVENT_EMBED_CHARS = 6000
# GPT-OSS has a 128k token window. 300k transcript chars is a conservative direct-pass cap
# that leaves room for instructions, participant context, and structured JSON output.
MAX_TRANSCRIPT_SUMMARY_INPUT_CHARS = 300_000
MEETING_TRANSCRIPT_SUMMARY_TIMEOUT_SECONDS = 600
SUMMARY_LOG_PREVIEW_CHARS = 3000
ACTION_ITEMS_LOG_PREVIEW_CHARS = 5000
EVENT_TYPE_CHOICES = {
"generic",
"meeting",
"communication",
"task",
"creation",
"consumption",
"travel",
"personal",
"system",
"financial",
"observation",
"interaction",
"education",
"celebration",
"purchase",
"health",
}
class EventMergeMode(str, Enum):
ADDITIVE = "additive"
AUTHORITATIVE_EXTERNAL = "authoritative_external"
def _format_external_event_id(external_type: str, external_id: str) -> str:
if not external_type or not external_id:
raise ValueError("externalType and externalId are required")
normalized_type = external_type.strip().lower()
normalized_id = external_id.strip()
if not normalized_type:
raise ValueError("externalType cannot be blank")
if not normalized_id:
raise ValueError("externalId cannot be blank")
if normalized_type not in {"google", "hyprnote"}:
raise ValueError(f"Unsupported externalType: {external_type}")
return f"{normalized_type}:{normalized_id}"
def _guess_external_event_id(meeting_id: str | None, meeting_link: str | None) -> str | None:
if not meeting_id:
return None
normalized_id = meeting_id.strip()
if not normalized_id:
return None
if ":" in normalized_id:
prefix, raw = normalized_id.split(":", 1)
if prefix.strip().lower() == "google" and raw.strip():
return f"google:{raw.strip()}"
link = (meeting_link or "").lower()
if "google" in link or "@google" in normalized_id.lower():
try:
return _format_external_event_id("google", normalized_id)
except ValueError:
return None
return None
def _load_current_user_from_env() -> dict | None:
current_user_info = os.environ.get("CURRENT_USER_INFO")
if not current_user_info:
return None
try:
return json.loads(current_user_info)
except Exception:
return None
def _resolve_attendee_contacts(
attendee_emails: Sequence[str],
*,
contact_cache: dict[str, tuple[str | None, bool]],
current_user: dict | None,
) -> tuple[list[str], dict[str, list[str]]]:
contact_ids: list[str] = []
attendee_contacts_by_domain: dict[str, list[str]] = {}
for email in attendee_emails:
normalized = contacts_service.normalize_email(email)
created_now = False
contact_id: str | None = None
if normalized and normalized in contact_cache:
contact_id, _ = contact_cache[normalized]
else:
contact_id, created_now = contacts_service.ensure_contact_for_email(email)
if normalized:
contact_cache[normalized] = (contact_id, created_now)
if contact_id:
contact_ids.append(contact_id)
if normalized and "@" in normalized:
domain = normalized.split("@", 1)[1]
attendee_contacts_by_domain.setdefault(domain, []).append(contact_id)
unique_contacts = list(dict.fromkeys(contact_ids))
if current_user:
current_email = current_user.get("email")
if current_email:
normalized_current = contacts_service.normalize_email(current_email)
if normalized_current and normalized_current not in contact_cache:
contact_id, created_now = contacts_service.ensure_contact_for_email(current_email)
if normalized_current:
contact_cache[normalized_current] = (contact_id, created_now)
if contact_id and contact_id not in unique_contacts:
unique_contacts.append(contact_id)
if contact_id and normalized_current and "@" in normalized_current:
domain = normalized_current.split("@", 1)[1]
attendee_contacts_by_domain.setdefault(domain, []).append(contact_id)
return unique_contacts, attendee_contacts_by_domain
def _collect_attendee_emails(*sources: Any) -> list[str]:
emails: list[str] = []
seen: set[str] = set()
def _add_items(value: Any) -> None:
if value is None:
return
items = [value] if isinstance(value, str) else value
if not isinstance(items, Sequence) or isinstance(items, (bytes, bytearray, str)):
return
for item in items:
email: str | None = None
if isinstance(item, str):
email = item
elif isinstance(item, dict):
for key in ("email", "mail", "address"):
candidate = item.get(key)
if isinstance(candidate, str) and candidate.strip():
email = candidate
break
normalized = contacts_service.normalize_email(email) if email else None
if not normalized or normalized in seen:
continue
seen.add(normalized)
emails.append(normalized)
for source in sources:
_add_items(source)
return emails
def _get_existing_relationship_ids(relationship_ids: Sequence[str]) -> set[str]:
if not relationship_ids:
return set()
with get_conn() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT relationship_id
FROM contact_relationships
WHERE relationship_id = ANY(%s)
""",
(list(relationship_ids),),
)
rows = [dict(row) for row in cur.fetchall()]
existing_ids: set[str] = set()
for row in rows:
relationship_id = str(row["relationship_id"] or "")
if relationship_id:
existing_ids.add(relationship_id)
return existing_ids
def _create_coworker_relationships(attendee_contacts_by_domain: dict[str, list[str]]) -> None:
candidate_relationships: list[tuple[str, str, str]] = []
for domain, ids in attendee_contacts_by_domain.items():
unique_ids = sorted(set(ids))
if len(unique_ids) < 2:
continue
for a, b in combinations(unique_ids, 2):
relationship_id = f"rel:coworker:{domain}:{a}:{b}"
candidate_relationships.append((relationship_id, a, b))
existing_relationship_ids = _get_existing_relationship_ids(
[relationship_id for relationship_id, _a, _b in candidate_relationships]
)
for relationship_id, a, b in candidate_relationships:
if relationship_id in existing_relationship_ids:
continue
rel = ContactRelationshipIn(
relationship_id=relationship_id,
from_contact_id=a,
to_contact_id=b,
relationship_type="Co-worker",
reciprocal_type="Co-worker",
)
contacts_service.upsert_contact_relationship(rel)
def ingest_external_event(payload: ExternalEventPayload) -> str:
event = payload.event
external_identifier = _format_external_event_id(payload.external_type, payload.event.id)
existing_id = _get_event_id_by_external_id(external_identifier)
normalized_event_id = ""
if existing_id:
normalized_event_id = existing_id
if not normalized_event_id:
matched = _find_matching_meeting_event(event.title, event.start_date)
if matched:
normalized_event_id = matched
if not normalized_event_id:
normalized_event_id = f"{external_identifier}:{uuid4().hex[:8]}"
if normalized_event_id and normalized_event_id != event.id:
event.id = normalized_event_id
event.external_id = external_identifier
existing_event = _get_event_by_id(normalized_event_id)
if existing_event:
event = _merge_event(existing_event, event, mode=EventMergeMode.AUTHORITATIVE_EXTERNAL)
raw_payload = event.raw if isinstance(event.raw, dict) else {}
attendee_emails = _collect_attendee_emails(
event.attendees_emails,
raw_payload.get("attendees"),
raw_payload.get("attendeesEmails"),
raw_payload.get("attendeeEmails"),
)
contact_cache: dict[str, tuple[str | None, bool]] = {}
current_user = _load_current_user_from_env()
unique_contacts, attendee_contacts_by_domain = _resolve_attendee_contacts(
attendee_emails,
contact_cache=contact_cache,
current_user=current_user,
)
if unique_contacts:
event.people = unique_contacts
_create_coworker_relationships(attendee_contacts_by_domain)
ingest_event(event)
return normalized_event_id
def ingest_meeting_transcript(
payload: MeetingTranscriptPayload,
*,
current_user: dict,
todo_writer: Callable[[TodoIn], None] | None = None,
) -> dict[str, Any]:
current_email = contacts_service.normalize_email(current_user.get("email") or "")
if not current_email:
raise ValueError("current_user with email is required")
meeting = payload.meeting
title = (meeting.title or "").strip() or "Untitled meeting"
start_date = meeting.started_at
end_date = meeting.ended_at
transcript_text = _format_meeting_transcript(payload)
external_identifier = _get_transcript_external_identifier(payload)
event_id = _resolve_meeting_transcript_event_id(
title=title,
start_date=start_date,
external_identifier=external_identifier,
session_id=payload.session_id,
)
contact_cache: dict[str, tuple[str | None, bool]] = {}
participants = _collect_meeting_transcript_participants(payload)
unique_contacts, attendee_contacts_by_domain = _resolve_transcript_participant_contacts(
participants,
contact_cache=contact_cache,
current_user=current_user,
)
_create_coworker_relationships(attendee_contacts_by_domain)
logger.info(
"[meeting_transcript] Contacts resolved upload_id=%s participant_count=%d contact_ids=%s",
payload.upload_id,
len(participants),
unique_contacts,
)
people_context = _build_meeting_transcript_people_context(
participants,
contact_ids=unique_contacts,
current_user=current_user,
)
summary_result = _generate_meeting_transcript_summary(
payload,
transcript_text,
current_user=current_user,
people_context=people_context,
)
summary = summary_result["summary"]
action_items = _annotate_action_items_for_current_user(
summary_result["action_items"],
current_user=current_user,
current_user_identifiers=people_context.get("current_user_identifiers") or [],
)
summary_result = {**summary_result, "action_items": action_items}
logger.info(
"[meeting_transcript] Summary generated upload_id=%s session_id=%s transcript_hash=%s "
"summary_preview=%s action_items=%s",
payload.upload_id,
payload.session_id,
payload.transcript_hash,
_truncate_log_text(summary, SUMMARY_LOG_PREVIEW_CHARS),
_truncate_log_text(json.dumps(action_items, ensure_ascii=False), ACTION_ITEMS_LOG_PREVIEW_CHARS),
)
raw_payload = {
"source": "meeting_transcript_ingest",
"upload_id": payload.upload_id,
"session_id": payload.session_id,
"transcript_hash": payload.transcript_hash,
"meeting": payload.meeting.model_dump(by_alias=True, mode="json"),
"participants": [participant.model_dump() for participant in payload.participants],
"speaker_identities": [identity.model_dump() for identity in payload.speaker_identities],
"transcript": payload.transcript.model_dump(by_alias=True, mode="json"),
"transcript_text": transcript_text,
"people_context": people_context,
"summary_result": summary_result,
"action_items": action_items,
"attendee_contact_ids": unique_contacts,
}
event = EventIn(
id=event_id,
startDate=start_date,
endDate=end_date,
people=unique_contacts,
types=["meeting"],
title=title,
summary=summary,
raw=raw_payload,
externalId=external_identifier,
)
existing_event = _get_event_by_id(event_id)
if existing_event:
event = _merge_event(existing_event, event, mode=EventMergeMode.AUTHORITATIVE_EXTERNAL)
event.summary = summary
ingest_event(event)
created_todo_ids = _create_current_user_todos_from_action_items(
action_items,
event_id=event_id,
current_user=current_user,
current_user_identifiers=people_context.get("current_user_identifiers") or [],
current_user_contact_id=(contact_cache.get(current_email) or (None, False))[0],
todo_writer=todo_writer,
)
logger.info(
"[meeting_transcript] Ingestion complete upload_id=%s event_id=%s created_todo_ids=%s",
payload.upload_id,
event_id,
created_todo_ids,
)
return {
"event_id": event_id,
"summary": summary,
"action_items": action_items,
"created_todo_ids": created_todo_ids,
"contact_ids": unique_contacts,
}
def _truncate_log_text(value: str | None, limit: int) -> str:
text = str(value or "").strip()
if len(text) <= limit:
return text
return f"{text[:limit].rstrip()}..."
def _get_transcript_external_identifier(payload: MeetingTranscriptPayload) -> str | None:
provider = (payload.meeting.provider or "").strip().lower()
original_id = (payload.meeting.original_id or "").strip()
if not provider or not original_id:
return None
try:
return _format_external_event_id(provider, original_id)
except ValueError:
logger.warning(
"[meeting_transcript] Unsupported external meeting provider=%s; storing without external_id",
provider,
)
return None
def _resolve_meeting_transcript_event_id(
*,
title: str,
start_date: datetime,
external_identifier: str | None,
session_id: str | None,
) -> str:
if external_identifier:
existing_id = _get_event_id_by_external_id(external_identifier)
if existing_id:
return existing_id
matched = _find_matching_meeting_event(title, start_date)
if matched:
return matched
if external_identifier:
return f"{external_identifier}:{uuid4().hex[:8]}"
normalized_session = _slugify(session_id or start_date.strftime("%Y%m%dT%H%M%S"))
return f"meeting-transcript:{normalized_session}-{_slugify(title)}-{uuid4().hex[:8]}"
def _speaker_label_map(payload: MeetingTranscriptPayload) -> dict[str, str]:
labels: dict[str, str] = {}
for identity in payload.speaker_identities:
speaker_id = str(identity.id or "").strip()
if not speaker_id:
continue
identity_payload = identity.identity if isinstance(identity.identity, dict) else {}
label = (
str(identity_payload.get("name") or "").strip()
or str(identity.label or "").strip()
or str(identity_payload.get("email") or "").strip()
or speaker_id
)
labels[speaker_id] = label
return labels
def _format_meeting_transcript(payload: MeetingTranscriptPayload) -> str:
labels = _speaker_label_map(payload)
turns: list[dict[str, str]] = []
for segment in _sorted_transcript_segments(payload.transcript.segments):
text = " ".join(str(segment.text or "").split()).strip()
if not text:
continue
label = labels.get(str(segment.speaker_id or ""), segment.speaker_id or "Unknown speaker")
if turns and turns[-1]["label"] == label:
turns[-1]["text"] = _join_transcript_fragments(turns[-1]["text"], text)
else:
turns.append({"label": label, "text": text})
return "\n".join(f"{turn['label']}: {turn['text']}" for turn in turns).strip()
def _sorted_transcript_segments(segments: Sequence[Any]) -> list[Any]:
indexed_segments = list(enumerate(segments))
def sort_key(item: tuple[int, Any]) -> tuple[float, int]:
index, segment = item
started_at = getattr(segment, "started_at", None)
if isinstance(started_at, datetime):
return started_at.timestamp(), index
return float(index), index
return [segment for _index, segment in sorted(indexed_segments, key=sort_key)]
def _join_transcript_fragments(existing: str, incoming: str) -> str:
existing_text = existing.strip()
incoming_text = incoming.strip()
if not existing_text:
return incoming_text
if not incoming_text:
return existing_text
if existing_text.endswith(("-", "/", "(", "[", "{")):
return f"{existing_text}{incoming_text}"
return f"{existing_text} {incoming_text}"
def _collect_meeting_transcript_participants(
payload: MeetingTranscriptPayload,
) -> list[dict[str, str | None]]:
participants: list[dict[str, str | None]] = []
def add_participant(name: str | None, email: str | None, source: str | None) -> None:
cleaned_name = " ".join(str(name or "").split()).strip() or None
normalized_email = contacts_service.normalize_email(email or "")
if not cleaned_name and not normalized_email:
return
participants.append(
{
"name": cleaned_name,
"email": normalized_email,
"source": source,
}
)
for participant in payload.participants:
add_participant(participant.name, participant.email, participant.source)
for speaker_identity in payload.speaker_identities:
identity = speaker_identity.identity if isinstance(speaker_identity.identity, dict) else {}
if identity.get("kind") not in {"participant", "current_user"}:
continue
add_participant(
identity.get("name") or speaker_identity.label,
identity.get("email"),
speaker_identity.source or "speaker_identity",
)
deduped: list[dict[str, str | None]] = []
seen: set[tuple[str, str]] = set()
for participant in participants:
key = (
normalize_search_text(participant.get("name") or ""),
contacts_service.normalize_email(participant.get("email") or "") or "",
)
if key in seen:
continue
seen.add(key)
deduped.append(participant)
return deduped
def _resolve_transcript_participant_contacts(
participants: Sequence[dict[str, str | None]],
*,
contact_cache: dict[str, tuple[str | None, bool]],
current_user: dict,
) -> tuple[list[str], dict[str, list[str]]]:
current_email = contacts_service.normalize_email(current_user.get("email") or "")
if not current_email:
raise ValueError("current_user with email is required")
contact_ids: list[str] = []
attendee_contacts_by_domain: dict[str, list[str]] = {}
for participant in participants:
email = contacts_service.normalize_email(participant.get("email") or "")
if not email:
continue
display_name = participant.get("name")
created_now = False
contact_id: str | None = None
if email in contact_cache:
contact_id, _ = contact_cache[email]
else:
contact_id, created_now = contacts_service.ensure_contact_for_email(
email,
display_name=display_name,
)
contact_cache[email] = (contact_id, created_now)
if contact_id:
contact_ids.append(contact_id)
if "@" in email:
domain = email.split("@", 1)[1]
attendee_contacts_by_domain.setdefault(domain, []).append(contact_id)
if current_email not in contact_cache:
contact_id, created_now = contacts_service.ensure_contact_for_email(
current_email,
display_name=current_user.get("name"),
)
contact_cache[current_email] = (contact_id, created_now)
if contact_id:
contact_ids.append(contact_id)
if "@" in current_email:
domain = current_email.split("@", 1)[1]
attendee_contacts_by_domain.setdefault(domain, []).append(contact_id)
return list(dict.fromkeys(contact_ids)), attendee_contacts_by_domain
def _build_meeting_transcript_people_context(
participants: Sequence[dict[str, str | None]],
*,
contact_ids: Sequence[str],
current_user: dict,
) -> dict[str, Any]:
all_identifiers: set[str] = set()
current_user_identifiers: set[str] = set()
contact_entries: list[dict[str, Any]] = []
def add_terms(target: set[str], *values: Any) -> None:
for value in values:
if isinstance(value, (list, tuple, set)):
add_terms(target, *value)
continue
cleaned = " ".join(str(value or "").split()).strip()
if cleaned:
target.add(cleaned)
current_email = contacts_service.normalize_email(current_user.get("email") or "")
add_terms(current_user_identifiers, current_user.get("name"), current_email)
for participant in participants:
add_terms(all_identifiers, participant.get("name"), participant.get("email"))
for contact_id in contact_ids:
contact = contacts_service.get_contact(contact_id)
if not contact:
continue
contact_identifiers: set[str] = set()
add_terms(
contact_identifiers,
contact.get("display_name"),
contact.get("aliases") or [],
contact.get("emails") or [],
)
if not contact_identifiers:
continue
all_identifiers.update(contact_identifiers)
normalized_emails = {
contacts_service.normalize_email(email)
for email in contact.get("emails") or []
if contacts_service.normalize_email(email)
}
normalized_names = {normalize_search_text(term) for term in contact_identifiers}
if current_email in normalized_emails or normalize_search_text(current_user.get("name") or "") in normalized_names:
current_user_identifiers.update(contact_identifiers)
contact_entries.append(
{
"contact_id": contact_id,
"identifiers": sorted(contact_identifiers, key=lambda item: item.casefold()),
}
)
all_identifiers.update(current_user_identifiers)
return {
"current_user_identifiers": sorted(current_user_identifiers, key=lambda item: item.casefold()),
"people_identifiers": sorted(all_identifiers, key=lambda item: item.casefold()),
"contacts": contact_entries,
}
def _format_identifier_lines(identifiers: Sequence[Any]) -> str:
return "\n".join(f"- {identifier}" for identifier in identifiers if str(identifier or "").strip())
def _format_people_context_contacts(contacts: Sequence[Any]) -> str:
lines: list[str] = []
for contact in contacts:
if not isinstance(contact, dict):
continue
identifiers = ", ".join(str(item) for item in contact.get("identifiers") or [] if item)
if not identifiers:
continue
lines.append(f"- {contact.get('contact_id')}: {identifiers}")
return "\n".join(lines)
def _generate_meeting_transcript_summary(
payload: MeetingTranscriptPayload,
transcript_text: str,
*,
current_user: dict,
people_context: dict[str, Any],
) -> dict[str, Any]:
if not transcript_text:
return _fallback_meeting_transcript_summary(payload, transcript_text)
from llm_helpers import LLMUnavailableError, build_json_schema_response_format, call_llm_json
from llm_json_schemas import MEETING_TRANSCRIPT_SUMMARY_RESPONSE_SCHEMA
current_user_identifiers = _format_identifier_lines(
people_context.get("current_user_identifiers") or []
)
people_identifiers = _format_identifier_lines(people_context.get("people_identifiers") or [])
resolved_contacts = _format_people_context_contacts(people_context.get("contacts") or [])
authenticated_current_email = contacts_service.normalize_email(current_user.get("email") or "") or "unknown"
prompt = f"""
Summarize this meeting transcript for a personal memory system and extract action items.
Meeting title: {payload.meeting.title or "Untitled meeting"}
Meeting description: {payload.meeting.description or ""}
Authenticated current user email: {authenticated_current_email}
Current user identifiers (names, aliases, emails):
{current_user_identifiers or "- Unknown"}
All known identifiers for people involved (names, aliases, emails):
{people_identifiers or "- Unknown"}
Resolved contacts:
{resolved_contacts or "- None"}
Transcript:
{transcript_text[:MAX_TRANSCRIPT_SUMMARY_INPUT_CHARS]}
Return valid JSON only, matching the supplied response schema.
Summary rules:
- Include actual discussion topics, important context, decisions, and follow-ups when present.
- Always output content in English, even if original language of transcript is not English.
- If possible, identify who mentioned key points or decisions.
- Do not invent facts.
Action item rules:
- Only include action items that are explicit or strongly implied by a concrete commitment in the transcript.
- Assign action items to the named speaker/participant when the transcript makes the assignee clear.
- Use the current user's canonical name/email from the identifier set when the current user is the assignee.
- Use participant aliases/emails from the identifier sets to disambiguate assignees.
- Use null for unknown assignee_name, assignee_email, due_date, or evidence fields.
- Do not create action items for vague discussion topics or suggestions without ownership.
""".strip()
try:
generated = call_llm_json(
prompt,
system_prompt=(
"You write accurate meeting summaries and extract only grounded action items. "
"Return schema-valid JSON. Do not spend tokens on deliberation; "
"produce the JSON object directly."
),
use_fast_model=False,
timeout=MEETING_TRANSCRIPT_SUMMARY_TIMEOUT_SECONDS,
temperature=0.2,
reasoning_effort="high",
response_format=build_json_schema_response_format(
name="meeting_transcript_summary",
schema=MEETING_TRANSCRIPT_SUMMARY_RESPONSE_SCHEMA,
),
)
except (LLMUnavailableError, RuntimeError, ValueError, json.JSONDecodeError) as exc:
logger.warning("[meeting_transcript] LLM summary unavailable: %s", exc)
return _fallback_meeting_transcript_summary(payload, transcript_text)
return _normalize_meeting_summary_result(generated, payload, transcript_text)
def _normalize_meeting_summary_result(
result: dict[str, Any],
payload: MeetingTranscriptPayload,
transcript_text: str,
) -> dict[str, Any]:
summary = " ".join(str(result.get("summary") or "").split()).strip()
if not summary:
return _fallback_meeting_transcript_summary(payload, transcript_text)
action_items: list[dict[str, str | None]] = []
raw_action_items = result.get("action_items")
if isinstance(raw_action_items, list):
for item in raw_action_items:
if not isinstance(item, dict):
continue
task = " ".join(str(item.get("task") or "").split()).strip()
if not task:
continue
action_items.append(
{
"task": task,
"assignee_name": _clean_optional_text(item.get("assignee_name")),
"assignee_email": contacts_service.normalize_email(item.get("assignee_email") or ""),
"due_date": _clean_optional_text(item.get("due_date")),
"evidence": _clean_optional_text(item.get("evidence")),
}
)
return {"summary": summary, "action_items": action_items}
def _create_current_user_todos_from_action_items(
action_items: Sequence[dict[str, Any]],
*,
event_id: str,
current_user: dict,
current_user_identifiers: Sequence[Any],
current_user_contact_id: str | None,
todo_writer: Callable[[TodoIn], None] | None,
) -> list[str]:
if not todo_writer:
return []
current_email = contacts_service.normalize_email(current_user.get("email") or "")
current_emails = _current_user_email_set(
current_user,
current_user_identifiers=current_user_identifiers,
)
current_identifier_terms = {
normalize_search_text(identifier)
for identifier in current_user_identifiers
if normalize_search_text(identifier)
}
current_identifier_terms.add(normalize_search_text(current_user.get("name") or ""))
current_identifier_terms = {term for term in current_identifier_terms if term}
existing_todo_signatures = _get_existing_todo_signatures(event_id)
created_todo_ids: list[str] = []
for action_item in action_items:
if not _is_current_user_action_item(
action_item,
current_emails=current_emails or ({current_email} if current_email else set()),
current_identifier_terms=current_identifier_terms,
):
continue
task = _clean_optional_text(action_item.get("task"))
normalized_task = _normalize_todo_description(task)
if not task or not normalized_task or normalized_task in existing_todo_signatures:
continue
existing_todo_signatures.add(normalized_task)
todo_id = f"todo:{event_id}:transcript:{uuid4().hex[:8]}"
todo_writer(
TodoIn(
todo_id=todo_id,
description=task,
status="pending",
due_date=_parse_action_item_due_date(action_item.get("due_date")),
contact_ids=[current_user_contact_id] if current_user_contact_id else [],
event_ids=[event_id],
place_ids=[],
)
)
created_todo_ids.append(todo_id)
return created_todo_ids
def _current_user_email_set(
current_user: dict,
*,
current_user_identifiers: Sequence[Any],
) -> set[str]:
emails: set[str] = set()
current_email = contacts_service.normalize_email(current_user.get("email") or "")
if current_email:
emails.add(current_email)
for identifier in current_user_identifiers:
text = str(identifier or "").strip()
if "@" not in text:
continue
normalized = contacts_service.normalize_email(text)
if normalized:
emails.add(normalized)
return emails
def _annotate_action_items_for_current_user(
action_items: Sequence[dict[str, Any]],
*,
current_user: dict,
current_user_identifiers: Sequence[Any],
) -> list[dict[str, Any]]:
current_emails = _current_user_email_set(
current_user,
current_user_identifiers=current_user_identifiers,
)
current_identifier_terms = {
normalize_search_text(identifier)
for identifier in current_user_identifiers
if normalize_search_text(identifier)
}
current_identifier_terms.add(normalize_search_text(current_user.get("name") or ""))
current_identifier_terms = {term for term in current_identifier_terms if term}
annotated: list[dict[str, Any]] = []
for action_item in action_items:
item = dict(action_item)
item["belongs_to_current_user"] = _is_current_user_action_item(
item,
current_emails=current_emails,
current_identifier_terms=current_identifier_terms,
)
annotated.append(item)
return annotated
def _is_current_user_action_item(
action_item: dict[str, Any],
*,
current_emails: set[str],
current_identifier_terms: set[str],
) -> bool:
assignee_email = contacts_service.normalize_email(action_item.get("assignee_email") or "")
if assignee_email and assignee_email in current_emails:
return True
assignee_name = normalize_search_text(action_item.get("assignee_name") or "")
if not assignee_name:
return False
if assignee_name in {"current user", "me", "myself", "you"}:
return True
return assignee_name in current_identifier_terms
def _parse_action_item_due_date(value: Any) -> date | None:
cleaned = _clean_optional_text(value)
if not cleaned:
return None
try:
return date.fromisoformat(cleaned)
except ValueError:
return None
def _clean_optional_text(value: Any) -> str | None:
cleaned = " ".join(str(value or "").split()).strip()
return cleaned or None
def _fallback_meeting_transcript_summary(
payload: MeetingTranscriptPayload,
transcript_text: str,
) -> dict[str, Any]:
description = " ".join(str(payload.meeting.description or "").split()).strip()
excerpt = " ".join(str(transcript_text or "").split()).strip()
if excerpt:
if len(excerpt) > 1200:
excerpt = f"{excerpt[:1197].rstrip()}..."
return {"summary": f"Transcript excerpt: {excerpt}", "action_items": []}
if description:
return {"summary": description, "action_items": []}
return {"summary": payload.meeting.title or "Meeting transcript received.", "action_items": []}
def get_meeting(meeting_id: str) -> dict[str, Any] | None:
from db import fetch_event_people
with get_conn() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT
e.id,
e.start_date,
e.end_date,
e.tags,
e.types,
e.title,
e.summary,
e.external_id,
e.raw,
e.place_id,
p.name AS place_name,
p.city,
p.country,
p.lat,
p.lon
FROM events AS e
LEFT JOIN places AS p ON p.place_id = e.place_id
WHERE e.id = %s
""",
(meeting_id,),
)
row = cur.fetchone()
if not row:
return None
people_map = fetch_event_people(cur, [meeting_id])
people = people_map.get(meeting_id, [])
raw_data = row.get("raw") or {}
if isinstance(raw_data, str):
try:
raw_data = json.loads(raw_data)
except json.JSONDecodeError:
raw_data = {"content": raw_data}
start_value = row.get("start_date")
end_value = row.get("end_date")
place_id = row.get("place_id")
return {
"id": row["id"],
"start_date": start_value.isoformat() if start_value else None,
"end_date": end_value.isoformat() if end_value else None,
"title": row.get("title"),
"summary": row.get("summary"),
"people": people,
"tags": row.get("tags") or [],
"types": row.get("types") or [],
"external_id": row.get("external_id"),
"raw": raw_data,
"place": (
{
"place_id": place_id,