-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtypes.py
More file actions
1272 lines (1041 loc) · 40.5 KB
/
types.py
File metadata and controls
1272 lines (1041 loc) · 40.5 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
"""Data types for NotebookLM API client.
This module contains all dataclasses and re-exports enums from rpc/types.py
for convenient access.
Usage:
from notebooklm.types import Notebook, Source, Artifact, GenerationStatus
from notebooklm.types import AudioFormat, VideoFormat
from notebooklm.types import SourceType, ArtifactType # str enums for .kind
"""
import warnings
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, Optional
# Import exceptions from centralized module (re-export for backward compatibility)
from .exceptions import (
ArtifactDownloadError,
ArtifactError,
ArtifactNotFoundError,
ArtifactNotReadyError,
ArtifactParseError,
SourceAddError,
SourceError,
SourceNotFoundError,
SourceProcessingError,
SourceTimeoutError,
)
# Re-export enums from rpc/types.py for convenience
from .rpc.types import (
ArtifactStatus,
AudioFormat,
AudioLength,
ChatGoal,
ChatResponseLength,
DriveMimeType,
ExportType,
InfographicDetail,
InfographicOrientation,
InfographicStyle,
QuizDifficulty,
QuizQuantity,
ReportFormat,
ShareAccess,
SharePermission,
ShareViewLevel,
SlideDeckFormat,
SlideDeckLength,
SourceStatus,
VideoFormat,
VideoStyle,
artifact_status_to_str,
source_status_to_str,
)
# =============================================================================
# User-facing Type Enums (str enums for .kind property)
# =============================================================================
class UnknownTypeWarning(UserWarning):
"""Emitted when encountering unrecognized type codes from Google API.
This warning indicates the API returned a type code that this version
of notebooklm-py doesn't recognize. Consider updating to the latest version.
"""
pass
class SourceType(str, Enum):
"""User-facing source types.
This is a str enum, so comparisons work with both enum members and strings:
source.kind == SourceType.WEB_PAGE # True
source.kind == "web_page" # Also True
"""
GOOGLE_DOCS = "google_docs"
GOOGLE_SLIDES = "google_slides"
GOOGLE_SPREADSHEET = "google_spreadsheet"
PDF = "pdf"
PASTED_TEXT = "pasted_text"
WEB_PAGE = "web_page"
GOOGLE_DRIVE_AUDIO = "google_drive_audio"
GOOGLE_DRIVE_VIDEO = "google_drive_video"
YOUTUBE = "youtube"
MARKDOWN = "markdown"
DOCX = "docx"
CSV = "csv"
EPUB = "epub"
IMAGE = "image"
MEDIA = "media"
UNKNOWN = "unknown"
class ArtifactType(str, Enum):
"""User-facing artifact types.
This is a str enum that hides internal variant complexity. For example,
quizzes and flashcards are both type 4 internally but distinguished by variant.
Comparisons work with both enum members and strings:
artifact.kind == ArtifactType.AUDIO # True
artifact.kind == "audio" # Also True
"""
AUDIO = "audio"
VIDEO = "video"
REPORT = "report"
QUIZ = "quiz"
FLASHCARDS = "flashcards"
MIND_MAP = "mind_map"
INFOGRAPHIC = "infographic"
SLIDE_DECK = "slide_deck"
DATA_TABLE = "data_table"
UNKNOWN = "unknown"
# Module-level sets for warning deduplication
_warned_source_types: set[int] = set()
_warned_artifact_types: set[tuple[int, int | None]] = set()
# Mapping from internal int codes to SourceType enum
_SOURCE_TYPE_CODE_MAP: dict[int, SourceType] = {
1: SourceType.GOOGLE_DOCS,
2: SourceType.GOOGLE_SLIDES, # Was GOOGLE_OTHER, now more specific
3: SourceType.PDF,
4: SourceType.PASTED_TEXT,
5: SourceType.WEB_PAGE,
8: SourceType.MARKDOWN,
9: SourceType.YOUTUBE,
10: SourceType.MEDIA,
11: SourceType.DOCX,
13: SourceType.IMAGE,
14: SourceType.GOOGLE_SPREADSHEET,
16: SourceType.CSV,
17: SourceType.EPUB,
}
# Mapping from internal int codes to ArtifactType enum
_ARTIFACT_TYPE_CODE_MAP: dict[int, ArtifactType] = {
1: ArtifactType.AUDIO,
2: ArtifactType.REPORT,
3: ArtifactType.VIDEO,
5: ArtifactType.MIND_MAP,
7: ArtifactType.INFOGRAPHIC,
8: ArtifactType.SLIDE_DECK,
9: ArtifactType.DATA_TABLE,
}
# Backward-compatible mapping from SourceType to old source_type strings
# Used by deprecated Source.source_type property
# Old values were heuristic: "text", "url", "youtube", "text_file"
# Only includes types that _SOURCE_TYPE_CODE_MAP can produce
_SOURCE_TYPE_COMPAT_MAP: dict[SourceType, str] = {
SourceType.GOOGLE_DOCS: "text",
SourceType.GOOGLE_SLIDES: "text",
SourceType.GOOGLE_SPREADSHEET: "text",
SourceType.PDF: "text_file",
SourceType.PASTED_TEXT: "text",
SourceType.WEB_PAGE: "url",
SourceType.YOUTUBE: "youtube",
SourceType.MARKDOWN: "text_file",
SourceType.DOCX: "text_file",
SourceType.CSV: "text",
SourceType.EPUB: "text_file",
SourceType.IMAGE: "text",
SourceType.MEDIA: "text",
SourceType.UNKNOWN: "text",
}
def _safe_source_type(type_code: int | None) -> SourceType:
"""Convert internal type code to user-facing SourceType enum.
Args:
type_code: Integer type code from API response.
Returns:
SourceType enum member. Returns UNKNOWN for unrecognized codes.
"""
if type_code is None:
return SourceType.UNKNOWN
result = _SOURCE_TYPE_CODE_MAP.get(type_code)
if result is None:
if type_code not in _warned_source_types:
_warned_source_types.add(type_code)
warnings.warn(
f"Unknown source type code {type_code}. "
"Consider updating notebooklm-py to the latest version.",
UnknownTypeWarning,
stacklevel=3,
)
return SourceType.UNKNOWN
return result
def _extract_source_url(metadata: list[Any] | None) -> str | None:
"""Extract a source URL from NotebookLM source metadata.
NotebookLM stores URLs in different slots depending on the source type:
- metadata[7][0] for web/PDF-style sources
- metadata[5][0] for YouTube sources
- metadata[0] as a fallback in some nested response shapes
"""
if not isinstance(metadata, list):
return None
if len(metadata) > 7:
url_list = metadata[7]
if isinstance(url_list, list) and url_list:
first = url_list[0]
if isinstance(first, str) and first:
return first
if len(metadata) > 5:
youtube_data = metadata[5]
if isinstance(youtube_data, list) and youtube_data:
first = youtube_data[0]
if isinstance(first, str) and first:
return first
if metadata:
first = metadata[0]
if isinstance(first, str) and first.startswith("http"):
return first
return None
def _map_artifact_kind(artifact_type: int, variant: int | None) -> ArtifactType:
"""Convert internal artifact type and variant to user-facing ArtifactType.
Args:
artifact_type: ArtifactTypeCode integer value from API.
variant: Optional variant code (e.g., for quiz vs flashcards).
Returns:
ArtifactType enum member. Returns UNKNOWN for unrecognized types.
"""
# Handle QUIZ/FLASHCARDS distinction (both use type 4)
if artifact_type == 4: # ArtifactTypeCode.QUIZ
if variant == 1:
return ArtifactType.FLASHCARDS
elif variant == 2:
return ArtifactType.QUIZ
else:
key = (artifact_type, variant)
if key not in _warned_artifact_types:
_warned_artifact_types.add(key)
warnings.warn(
f"Unknown QUIZ variant {variant}. "
"Consider updating notebooklm-py to the latest version.",
UnknownTypeWarning,
stacklevel=3,
)
return ArtifactType.UNKNOWN
result = _ARTIFACT_TYPE_CODE_MAP.get(artifact_type)
if result is None:
key = (artifact_type, variant)
if key not in _warned_artifact_types:
_warned_artifact_types.add(key)
warnings.warn(
f"Unknown artifact type {artifact_type}. "
"Consider updating notebooklm-py to the latest version.",
UnknownTypeWarning,
stacklevel=3,
)
return ArtifactType.UNKNOWN
return result
__all__ = [
# Dataclasses
"Notebook",
"NotebookDescription",
"NotebookMetadata",
"SuggestedTopic",
"Source",
"SourceFulltext",
"SourceSummary",
"Artifact",
"GenerationStatus",
"ReportSuggestion",
"Note",
"ConversationTurn",
"ChatReference",
"AskResult",
"ChatMode",
"SharedUser",
"ShareStatus",
# Exceptions
"SourceError",
"SourceAddError",
"SourceProcessingError",
"SourceTimeoutError",
"SourceNotFoundError",
"ArtifactError",
"ArtifactNotFoundError",
"ArtifactNotReadyError",
"ArtifactParseError",
"ArtifactDownloadError",
# Warnings
"UnknownTypeWarning",
# User-facing type enums (str enums for .kind property)
"SourceType",
"ArtifactType",
# Re-exported enums (configuration/RPC)
"ArtifactStatus",
# Note: ArtifactTypeCode/StudioContentType are internal - not exported here
"AudioFormat",
"AudioLength",
"VideoFormat",
"VideoStyle",
"QuizQuantity",
"QuizDifficulty",
"InfographicOrientation",
"InfographicDetail",
"InfographicStyle",
"SlideDeckFormat",
"SlideDeckLength",
"ReportFormat",
"ChatGoal",
"ChatResponseLength",
"DriveMimeType",
"ExportType",
"SourceStatus",
"ShareAccess",
"ShareViewLevel",
"SharePermission",
# Helper functions
"artifact_status_to_str",
"source_status_to_str",
]
# =============================================================================
# Chat Mode Enum (service-level, not RPC-level)
# =============================================================================
class ChatMode(Enum):
"""Predefined chat modes for common use cases."""
DEFAULT = "default" # General purpose
LEARNING_GUIDE = "learning_guide" # Educational focus
CONCISE = "concise" # Brief responses
DETAILED = "detailed" # Verbose responses
# =============================================================================
# Notebook Types
# =============================================================================
@dataclass
class SourceSummary:
"""Simplified source information for metadata export.
This type provides a minimal representation of a source for
notebook metadata export, focusing on the most commonly needed fields.
Attributes:
kind: Source type (e.g., "pdf", "web_page", "youtube").
title: Source title if available.
url: Source URL if applicable (web/YouTube sources).
"""
kind: SourceType
title: str | None = None
url: str | None = None
def to_dict(self) -> dict[str, str | None]:
"""Convert to dictionary for JSON serialization.
Always includes all keys with null for missing values
to ensure consistent schema across all source entries.
"""
return {
"type": self.kind.value,
"title": self.title,
"url": self.url,
}
@dataclass
class Notebook:
"""Represents a NotebookLM notebook."""
id: str
title: str
created_at: datetime | None = None
sources_count: int = 0
is_owner: bool = True
@classmethod
def from_api_response(cls, data: list[Any]) -> "Notebook":
"""Parse notebook from API response.
Args:
data: Raw API response list.
Returns:
Notebook instance.
"""
raw_title = data[0] if len(data) > 0 and isinstance(data[0], str) else ""
title = raw_title.replace("thought\n", "").strip()
notebook_id = data[2] if len(data) > 2 and isinstance(data[2], str) else ""
created_at = None
if len(data) > 5 and isinstance(data[5], list) and len(data[5]) > 5:
ts_data = data[5][5]
if isinstance(ts_data, list) and len(ts_data) > 0:
try:
created_at = datetime.fromtimestamp(ts_data[0])
except (TypeError, ValueError):
pass
# Extract ownership - data[5][1] = False means owner, True means shared
is_owner = True
if len(data) > 5 and isinstance(data[5], list) and len(data[5]) > 1:
is_owner = data[5][1] is False
return cls(id=notebook_id, title=title, created_at=created_at, is_owner=is_owner)
@dataclass
class SuggestedTopic:
"""A suggested topic/question for the notebook."""
question: str
prompt: str
@dataclass
class NotebookDescription:
"""AI-generated description and suggested topics for a notebook."""
summary: str
suggested_topics: list[SuggestedTopic] = field(default_factory=list)
@classmethod
def from_api_response(cls, data: dict[str, Any]) -> "NotebookDescription":
"""Parse from get_notebook_description() response."""
topics = [
SuggestedTopic(question=t.get("question", ""), prompt=t.get("prompt", ""))
for t in data.get("suggested_topics", [])
]
return cls(
summary=data.get("summary", ""),
suggested_topics=topics,
)
@dataclass
class NotebookMetadata:
"""Combined notebook metadata with sources list.
This composes a Notebook with a list of simplified source information
for export/overview purposes.
Attributes:
notebook: The notebook object with all its details.
sources: List of simplified source information.
"""
notebook: Notebook
sources: list[SourceSummary] = field(default_factory=list)
@property
def id(self) -> str:
"""Get notebook ID."""
return self.notebook.id
@property
def title(self) -> str:
"""Get notebook title."""
return self.notebook.title
@property
def created_at(self) -> datetime | None:
"""Get creation timestamp."""
return self.notebook.created_at
@property
def is_owner(self) -> bool:
"""Get owner status."""
return self.notebook.is_owner
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for JSON serialization.
Flattens notebook fields for backward compatibility with issue spec.
"""
return {
"id": self.id,
"title": self.title,
"created_at": self.created_at.isoformat() if self.created_at else None,
"is_owner": self.is_owner,
"sources": [s.to_dict() for s in self.sources],
}
# =============================================================================
# Source Types
# =============================================================================
@dataclass
class Source:
"""Represents a NotebookLM source.
Attributes:
id: Unique source identifier.
title: Source title (may be URL if not yet processed).
url: Original URL for web/YouTube sources.
kind: Source type as SourceType enum (str enum, comparable to strings).
created_at: When the source was added.
status: Processing status (1=processing, 2=ready, 3=error).
Example:
source.kind == SourceType.WEB_PAGE # True
source.kind == "web_page" # Also True (str enum)
f"Type: {source.kind}" # "Type: web_page"
"""
id: str
title: str | None = None
url: str | None = None
_type_code: int | None = field(default=None, repr=False)
created_at: datetime | None = None
status: int = SourceStatus.READY # Default to READY (2)
@property
def kind(self) -> SourceType:
"""Get source type as SourceType enum.
Returns:
SourceType enum member. Returns SourceType.UNKNOWN for
unrecognized type codes (with a warning on first occurrence).
"""
return _safe_source_type(self._type_code)
@property
def source_type(self) -> str:
"""Deprecated: Use .kind instead.
Returns the old-style source type string for backward compatibility.
Values: "text", "url", "youtube", "text_file"
.. deprecated:: 0.3.0
Use the ``.kind`` property which returns a ``SourceType`` enum.
Will be removed in v0.4.0.
"""
warnings.warn(
"Source.source_type is deprecated, use .kind instead. Will be removed in v0.4.0.",
DeprecationWarning,
stacklevel=2,
)
return _SOURCE_TYPE_COMPAT_MAP.get(self.kind, "text")
@property
def is_ready(self) -> bool:
"""Check if source is ready for use (status=READY)."""
return self.status == SourceStatus.READY
@property
def is_processing(self) -> bool:
"""Check if source is still being processed (status=PROCESSING)."""
return self.status == SourceStatus.PROCESSING
@property
def is_error(self) -> bool:
"""Check if source processing failed (status=ERROR)."""
return self.status == SourceStatus.ERROR
@classmethod
def from_api_response(cls, data: list[Any], notebook_id: str | None = None) -> "Source":
"""Parse source data from various API response formats.
The API returns different structures for different operations:
- add_source: [[[[id], title, metadata]]] (deeply nested)
- list_sources: [[[id], title, metadata], ...] (one level less nesting)
- rename_source: May return simpler structure
Note:
This method does NOT parse the source status field. Sources created
via this method will have status=READY by default. To get accurate
status information (PROCESSING, READY, or ERROR), use
`client.sources.list()` or `client.sources.get()` which parse
status from the full notebook response structure.
"""
if not data or not isinstance(data, list):
raise ValueError(f"Invalid source data: {data}")
# Try deeply nested format: [[[[id], title, metadata, ...]]]
if isinstance(data[0], list) and len(data[0]) > 0:
if isinstance(data[0][0], list) and len(data[0][0]) > 0:
# Check if deeply nested vs medium nested
if isinstance(data[0][0][0], list):
# Deeply nested: [[[[id], title, ...]]]
entry = data[0][0]
source_id = entry[0][0] if isinstance(entry[0], list) else entry[0]
title = entry[1] if len(entry) > 1 else None
else:
# Medium nested: [[['id'], 'title', ...]]
entry = data[0]
source_id = entry[0][0] if isinstance(entry[0], list) else entry[0]
title = entry[1] if len(entry) > 1 else None
metadata = entry[2] if len(entry) > 2 else None
url = _extract_source_url(metadata)
type_code = None
if (
isinstance(metadata, list)
and len(metadata) > 4
and isinstance(metadata[4], int)
):
type_code = metadata[4]
return cls(id=str(source_id), title=title, url=url, _type_code=type_code)
# Deeply nested: continue with URL and type code extraction
url = None
type_code = None
if len(entry) > 2 and isinstance(entry[2], list):
url = _extract_source_url(entry[2])
# Extract type code at entry[2][4] if available
if len(entry[2]) > 4 and isinstance(entry[2][4], int):
type_code = entry[2][4]
return cls(
id=str(source_id),
title=title,
url=url,
_type_code=type_code,
)
# Simple flat format: [id, title] or [id, title, ...]
source_id = data[0] if len(data) > 0 else ""
title = data[1] if len(data) > 1 else None
return cls(id=str(source_id), title=title, _type_code=None)
@dataclass
class SourceFulltext:
"""Full text content of a source as indexed by NotebookLM.
This is the raw text content that was extracted/indexed from the source,
along with metadata. Returned by `client.sources.get_fulltext()`.
Attributes:
source_id: The source UUID.
title: Source title.
content: Full indexed text content.
kind: Source type as SourceType enum (use .kind property).
url: Original URL for web/YouTube sources.
char_count: Number of characters in the content.
Example:
fulltext.kind == SourceType.WEB_PAGE # True
fulltext.kind == "web_page" # Also True (str enum)
"""
source_id: str
title: str
content: str
_type_code: int | None = field(default=None, repr=False)
url: str | None = None
char_count: int = 0
@property
def kind(self) -> SourceType:
"""Get source type as SourceType enum."""
return _safe_source_type(self._type_code)
@property
def source_type(self) -> str:
"""Deprecated: Use .kind instead.
Returns the old-style source type string for backward compatibility.
Values: "text", "url", "youtube", "text_file"
.. deprecated:: 0.3.0
Use the ``.kind`` property which returns a ``SourceType`` enum.
Will be removed in v0.4.0.
"""
warnings.warn(
"SourceFulltext.source_type is deprecated, use .kind instead. "
"Will be removed in v0.4.0.",
DeprecationWarning,
stacklevel=2,
)
return _SOURCE_TYPE_COMPAT_MAP.get(self.kind, "text")
def find_citation_context(
self,
cited_text: str,
context_chars: int = 200,
) -> list[tuple[str, int]]:
"""Search for citation text and return matching contexts.
Best-effort heuristic using substring search. May fail or return
incorrect matches when:
- cited_text appears multiple times (all occurrences returned)
- NotebookLM truncated the citation during chunking
- Formatting differs between citation and indexed content
Note: ChatReference.start_char/end_char reference NotebookLM's internal
chunked index, NOT positions in this fulltext. Use this method instead.
Args:
cited_text: Text to search for (from ChatReference.cited_text).
context_chars: Surrounding context to include (default 200).
Returns:
List of (context, position) tuples for each match found.
Empty list if no matches. Position is start of match in content.
"""
if not cited_text or not self.content:
return []
# Use prefix for search (citations are often truncated)
search_text = cited_text[: min(40, len(cited_text))]
matches = []
pos = 0
while (idx := self.content.find(search_text, pos)) != -1:
start = max(0, idx - context_chars)
end = min(len(self.content), idx + len(search_text) + context_chars)
matches.append((self.content[start:end], idx))
pos = idx + len(search_text) # Skip past match to avoid overlaps
return matches
# =============================================================================
# Artifact Types
# =============================================================================
@dataclass
class Artifact:
"""Represents a NotebookLM artifact (studio content).
Artifacts are AI-generated content like Audio Overviews, Video Overviews,
Reports, Quizzes, Flashcards, Mind Maps, Infographics, Slide Decks, and
Data Tables.
Attributes:
id: Unique artifact identifier.
title: Artifact title.
kind: Artifact type as ArtifactType enum (str enum, comparable to strings).
status: Processing status (1=processing, 2=pending, 3=completed, 4=failed).
created_at: When the artifact was created.
url: Download URL (if available).
Example:
artifact.kind == ArtifactType.AUDIO # True
artifact.kind == "audio" # Also True (str enum)
f"Type: {artifact.kind}" # "Type: audio"
"""
id: str
title: str
_artifact_type: int = field(repr=False) # ArtifactTypeCode enum value
status: int # 1=processing, 2=pending, 3=completed, 4=failed
created_at: datetime | None = None
url: str | None = None
_variant: int | None = field(default=None, repr=False) # For type 4: 1=flashcards, 2=quiz
@property
def kind(self) -> ArtifactType:
"""Get artifact type as ArtifactType enum.
Returns:
ArtifactType enum member. Returns ArtifactType.UNKNOWN for
unrecognized type codes (with a warning on first occurrence).
"""
return _map_artifact_kind(self._artifact_type, self._variant)
@property
def artifact_type(self) -> int:
"""Deprecated: Use .kind instead.
Returns the raw integer type code for backward compatibility.
.. deprecated:: 0.3.0
Use the ``.kind`` property which returns an ``ArtifactType`` enum.
Will be removed in v0.4.0.
"""
warnings.warn(
"Artifact.artifact_type is deprecated, use .kind instead. Will be removed in v0.4.0.",
DeprecationWarning,
stacklevel=2,
)
return self._artifact_type
@property
def variant(self) -> int | None:
"""Deprecated: Use .kind, .is_quiz, or .is_flashcards instead.
Returns the variant code for type 4 artifacts (1=flashcards, 2=quiz).
.. deprecated:: 0.3.0
Use ``.kind == ArtifactType.QUIZ`` or ``.is_quiz`` / ``.is_flashcards``.
Will be removed in v0.4.0.
"""
warnings.warn(
"Artifact.variant is deprecated. Use .kind, .is_quiz, or .is_flashcards instead. "
"Will be removed in v0.4.0.",
DeprecationWarning,
stacklevel=2,
)
return self._variant
@classmethod
def from_api_response(cls, data: list[Any]) -> "Artifact":
"""Parse artifact from API response.
Structure: [id, title, type, ..., status, ..., metadata, ...]
Position 9 contains options with variant code at [9][1][0]:
- For type 4: 1=flashcards, 2=quiz
"""
artifact_id = data[0] if len(data) > 0 else ""
title = data[1] if len(data) > 1 else ""
artifact_type = data[2] if len(data) > 2 else 0
status = data[4] if len(data) > 4 else 0
# Extract timestamp from data[15][0]
created_at = None
if len(data) > 15 and isinstance(data[15], list) and len(data[15]) > 0:
try:
created_at = datetime.fromtimestamp(data[15][0])
except (TypeError, ValueError):
pass
# Extract variant code from data[9][1][0] for quiz/flashcard distinction
variant = None
if len(data) > 9 and isinstance(data[9], list) and len(data[9]) > 1:
options = data[9][1]
if isinstance(options, list) and len(options) > 0:
variant = options[0]
return cls(
id=str(artifact_id),
title=str(title),
_artifact_type=artifact_type,
status=status,
created_at=created_at,
_variant=variant,
)
@classmethod
def from_mind_map(cls, data: list[Any]) -> Optional["Artifact"]:
"""Parse artifact from mind map data (stored in notes system).
Mind map structure:
[
"mind_map_id",
[
"mind_map_id", # [1][0]: ID
"JSON_content", # [1][1]: Mind map JSON
[1, "user_id", [ts, ns]], # [1][2]: Metadata
None, # [1][3]
"title" # [1][4]: Title
]
]
Deleted/cleared mind map: ["id", None, 2]
Returns:
Artifact object, or None if deleted (status=2).
"""
if not isinstance(data, list) or len(data) < 1:
return None
mind_map_id = data[0] if len(data) > 0 else ""
# Check for deleted status (item[1] is None with status=2)
if len(data) >= 3 and data[1] is None and data[2] == 2:
return None # Deleted, don't include
# Extract title and timestamp from nested structure
title = ""
created_at = None
if len(data) > 1 and isinstance(data[1], list):
inner = data[1]
# Title is at position [4]
if len(inner) > 4 and isinstance(inner[4], str):
title = inner[4]
# Timestamp is at [2][2][0]
if len(inner) > 2 and isinstance(inner[2], list) and len(inner[2]) > 2:
ts_data = inner[2][2]
if isinstance(ts_data, list) and len(ts_data) > 0:
try:
created_at = datetime.fromtimestamp(ts_data[0])
except (TypeError, ValueError):
pass
return cls(
id=str(mind_map_id),
title=title,
_artifact_type=5, # ArtifactTypeCode.MIND_MAP
status=3, # Mind maps are always "completed" once created
created_at=created_at,
_variant=None,
)
@property
def is_completed(self) -> bool:
"""Check if artifact generation is complete (status=COMPLETED)."""
return self.status == ArtifactStatus.COMPLETED
@property
def is_processing(self) -> bool:
"""Check if artifact is being generated (status=PROCESSING)."""
return self.status == ArtifactStatus.PROCESSING
@property
def is_pending(self) -> bool:
"""Check if artifact is queued/transitional (status=PENDING)."""
return self.status == ArtifactStatus.PENDING
@property
def is_failed(self) -> bool:
"""Check if artifact generation failed (status=FAILED)."""
return self.status == ArtifactStatus.FAILED
@property
def status_str(self) -> str:
"""Get human-readable status string.
Returns:
"in_progress", "pending", "completed", "failed", or "unknown".
"""
return artifact_status_to_str(self.status)
@property
def is_quiz(self) -> bool:
"""Check if this is a quiz (type 4, variant 2)."""
return self._artifact_type == 4 and self._variant == 2
@property
def is_flashcards(self) -> bool:
"""Check if this is flashcards (type 4, variant 1)."""
return self._artifact_type == 4 and self._variant == 1
@property
def report_subtype(self) -> str | None:
"""Get the report subtype for type 2 artifacts.
Returns:
'briefing_doc', 'study_guide', 'blog_post', or None if not a report.
"""
if self._artifact_type != 2:
return None
title_lower = self.title.lower()
if title_lower.startswith("briefing doc"):
return "briefing_doc"
elif title_lower.startswith("study guide"):
return "study_guide"
elif title_lower.startswith("blog post"):
return "blog_post"
return "report"
@dataclass
class GenerationStatus:
"""Status of an artifact generation task.
Note: task_id and artifact_id are the same identifier. The API returns a single
ID when generation starts, which is used both for polling the task status during
generation and as the artifact's ID once complete. We use 'task_id' here to
emphasize its role in tracking the generation task.
"""
task_id: str # Same as artifact_id - used for polling and becomes Artifact.id
status: str # "pending", "in_progress", "completed", "failed", "not_found"
url: str | None = None
error: str | None = None
error_code: str | None = None # e.g., "USER_DISPLAYABLE_ERROR" for rate limits
metadata: dict[str, Any] | None = None
@property
def is_complete(self) -> bool:
"""Check if generation is complete."""
return self.status == "completed"
@property
def is_failed(self) -> bool:
"""Check if generation failed."""