-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy path_artifacts.py
More file actions
2336 lines (1989 loc) · 82.4 KB
/
_artifacts.py
File metadata and controls
2336 lines (1989 loc) · 82.4 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
"""Artifacts API for NotebookLM studio content.
Provides operations for generating, listing, downloading, and managing
AI-generated artifacts including Audio Overviews, Video Overviews, Reports,
Quizzes, Flashcards, Infographics, Slide Decks, Data Tables, and Mind Maps.
"""
import asyncio
import builtins
import csv
import html
import json
import logging
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
import httpx
from ._core import ClientCore
from .auth import load_httpx_cookies
from .exceptions import ValidationError
from .rpc import (
ArtifactStatus,
ArtifactTypeCode,
AudioFormat,
AudioLength,
ExportType,
InfographicDetail,
InfographicOrientation,
InfographicStyle,
QuizDifficulty,
QuizQuantity,
ReportFormat,
RPCError,
RPCMethod,
SlideDeckFormat,
SlideDeckLength,
VideoFormat,
VideoStyle,
artifact_status_to_str,
)
from .types import (
Artifact,
ArtifactDownloadError,
ArtifactNotFoundError,
ArtifactNotReadyError,
ArtifactParseError,
ArtifactType,
GenerationStatus,
ReportSuggestion,
)
logger = logging.getLogger(__name__)
# Media artifact types that require URL availability before reporting completion
_MEDIA_ARTIFACT_TYPES = frozenset(
{
ArtifactTypeCode.AUDIO.value,
ArtifactTypeCode.VIDEO.value,
ArtifactTypeCode.INFOGRAPHIC.value,
ArtifactTypeCode.SLIDE_DECK.value,
}
)
if TYPE_CHECKING:
from ._notes import NotesAPI
def _extract_app_data(html_content: str) -> dict:
"""Extract JSON from data-app-data HTML attribute.
The quiz/flashcard HTML embeds JSON in a data-app-data attribute
with HTML-encoded content (e.g., " for quotes).
"""
match = re.search(r'data-app-data="([^"]+)"', html_content)
if not match:
raise ArtifactParseError(
"quiz/flashcard",
details="No data-app-data attribute found in HTML",
)
encoded_json = match.group(1)
decoded_json = html.unescape(encoded_json)
return json.loads(decoded_json)
def _format_quiz_markdown(title: str, questions: list[dict]) -> str:
"""Format quiz as markdown."""
lines = [f"# {title}", ""]
for i, q in enumerate(questions, 1):
lines.append(f"## Question {i}")
lines.append(q.get("question", ""))
lines.append("")
for opt in q.get("answerOptions", []):
marker = "[x]" if opt.get("isCorrect") else "[ ]"
lines.append(f"- {marker} {opt.get('text', '')}")
if q.get("hint"):
lines.append("")
lines.append(f"**Hint:** {q['hint']}")
lines.append("")
return "\n".join(lines)
def _format_flashcards_markdown(title: str, cards: list[dict]) -> str:
"""Format flashcards as markdown."""
lines = [f"# {title}", ""]
for i, card in enumerate(cards, 1):
front = card.get("f", "")
back = card.get("b", "")
lines.extend(
[
f"## Card {i}",
"",
f"**Q:** {front}",
"",
f"**A:** {back}",
"",
"---",
"",
]
)
return "\n".join(lines)
def _extract_cell_text(cell: Any) -> str:
"""Recursively extract text from a nested cell structure.
Data table cells have deeply nested arrays with position markers (integers)
and text content (strings). This function traverses the structure and
concatenates all text fragments found.
"""
if isinstance(cell, str):
return cell
if isinstance(cell, int):
return ""
if isinstance(cell, list):
return "".join(text for item in cell if (text := _extract_cell_text(item)))
return ""
def _parse_data_table(raw_data: list) -> tuple[list[str], list[list[str]]]:
"""Parse rich-text data table into headers and rows.
Data tables from NotebookLM have a complex nested structure with position
markers. This function navigates to the rows array and extracts text from
each cell.
Structure: raw_data[0][0][0][0][4][2] contains the rows array where:
- [0][0][0][0] navigates through wrapper layers
- [4] contains the table content section [type, flags, rows_array]
- [2] is the actual rows array
Each row has format: [start_pos, end_pos, [cell_array]]
Each cell is deeply nested: [pos, pos, [[pos, pos, [[pos, pos, [["text"]]]]]]]
Returns:
Tuple of (headers, rows) where headers is a list of column names
and rows is a list of row data (each row is a list of cell strings).
Raises:
ArtifactParseError: If the data structure cannot be parsed or is empty.
"""
try:
# Navigate through nested wrappers to reach the rows array
rows_array = raw_data[0][0][0][0][4][2]
if not rows_array:
raise ArtifactParseError("data_table", details="Empty data table")
headers: list[str] = []
rows: list[list[str]] = []
for i, row_section in enumerate(rows_array):
# Each row_section is [start_pos, end_pos, cell_array]
if not isinstance(row_section, list) or len(row_section) < 3:
continue
cell_array = row_section[2]
if not isinstance(cell_array, list):
continue
row_values = [_extract_cell_text(cell) for cell in cell_array]
if i == 0:
headers = row_values
else:
rows.append(row_values)
# Validate we extracted usable data
if not headers:
raise ArtifactParseError(
"data_table",
details="Failed to extract headers from data table",
)
return headers, rows
except (IndexError, TypeError, KeyError) as e:
raise ArtifactParseError(
"data_table",
details=f"Failed to parse data table structure: {e}",
cause=e,
) from e
class ArtifactsAPI:
"""Operations on NotebookLM artifacts (studio content).
Artifacts are AI-generated content including Audio Overviews, Video Overviews,
Reports, Quizzes, Flashcards, Infographics, Slide Decks, Data Tables, and Mind Maps.
Usage:
async with NotebookLMClient.from_storage() as client:
# Generate
status = await client.artifacts.generate_audio(notebook_id)
await client.artifacts.wait_for_completion(notebook_id, status.task_id)
# Download
await client.artifacts.download_audio(notebook_id, "output.mp4")
# List and manage
artifacts = await client.artifacts.list(notebook_id)
await client.artifacts.rename(notebook_id, artifact_id, "New Title")
"""
def __init__(
self,
core: ClientCore,
notes_api: "NotesAPI",
storage_path: Path | None = None,
):
"""Initialize the artifacts API.
Args:
core: The core client infrastructure.
notes_api: The notes API for accessing notes/mind maps.
storage_path: Path to storage state file for loading download cookies.
"""
self._core = core
self._notes = notes_api
self._storage_path = storage_path
# =========================================================================
# List/Get Operations
# =========================================================================
async def list(
self, notebook_id: str, artifact_type: ArtifactType | None = None
) -> list[Artifact]:
"""List all artifacts in a notebook, including mind maps.
This returns all AI-generated content: Audio Overviews, Video Overviews,
Reports, Quizzes, Flashcards, Infographics, Slide Decks, Data Tables,
and Mind Maps.
Note: Mind maps are stored in a separate system (notes) but are included
here since they are AI-generated studio content.
Args:
notebook_id: The notebook ID.
artifact_type: Optional ArtifactType to filter by.
Use ArtifactType.MIND_MAP to get only mind maps.
Returns:
List of Artifact objects.
"""
logger.debug("Listing artifacts in notebook %s", notebook_id)
artifacts: list[Artifact] = []
# Fetch studio artifacts (audio, video, reports, etc.)
params = [[2], notebook_id, 'NOT artifact.status = "ARTIFACT_STATUS_SUGGESTED"']
result = await self._core.rpc_call(
RPCMethod.LIST_ARTIFACTS,
params,
source_path=f"/notebook/{notebook_id}",
allow_null=True,
)
artifacts_data: list[Any] = []
if result and isinstance(result, list) and len(result) > 0:
artifacts_data = result[0] if isinstance(result[0], list) else result
for art_data in artifacts_data:
if isinstance(art_data, list) and len(art_data) > 0:
artifact = Artifact.from_api_response(art_data)
if artifact_type is None or artifact.kind == artifact_type:
artifacts.append(artifact)
# Fetch mind maps from notes system (if not filtering to non-mind-map type)
if artifact_type is None or artifact_type == ArtifactType.MIND_MAP:
try:
mind_maps = await self._notes.list_mind_maps(notebook_id)
for mm_data in mind_maps:
mind_map_artifact = Artifact.from_mind_map(mm_data)
if mind_map_artifact is not None: # None means deleted (status=2)
if artifact_type is None or mind_map_artifact.kind == artifact_type:
artifacts.append(mind_map_artifact)
except (RPCError, httpx.HTTPError) as e:
# Network/API errors - log and continue with studio artifacts
# This ensures users can see their audio/video/reports even if
# the mind maps endpoint is temporarily unavailable
logger.warning("Failed to fetch mind maps: %s", e)
return artifacts
async def get(self, notebook_id: str, artifact_id: str) -> Artifact | None:
"""Get a specific artifact by ID.
Args:
notebook_id: The notebook ID.
artifact_id: The artifact ID.
Returns:
Artifact object, or None if not found.
"""
logger.debug("Getting artifact %s from notebook %s", artifact_id, notebook_id)
artifacts = await self.list(notebook_id)
for artifact in artifacts:
if artifact.id == artifact_id:
return artifact
return None
async def list_audio(self, notebook_id: str) -> builtins.list[Artifact]:
"""List audio overview artifacts."""
return await self.list(notebook_id, ArtifactType.AUDIO)
async def list_video(self, notebook_id: str) -> builtins.list[Artifact]:
"""List video overview artifacts."""
return await self.list(notebook_id, ArtifactType.VIDEO)
async def list_reports(self, notebook_id: str) -> builtins.list[Artifact]:
"""List report artifacts (Briefing Doc, Study Guide, Blog Post)."""
return await self.list(notebook_id, ArtifactType.REPORT)
async def list_quizzes(self, notebook_id: str) -> builtins.list[Artifact]:
"""List quiz artifacts."""
return await self.list(notebook_id, ArtifactType.QUIZ)
async def list_flashcards(self, notebook_id: str) -> builtins.list[Artifact]:
"""List flashcard artifacts."""
return await self.list(notebook_id, ArtifactType.FLASHCARDS)
async def list_infographics(self, notebook_id: str) -> builtins.list[Artifact]:
"""List infographic artifacts."""
return await self.list(notebook_id, ArtifactType.INFOGRAPHIC)
async def list_slide_decks(self, notebook_id: str) -> builtins.list[Artifact]:
"""List slide deck artifacts."""
return await self.list(notebook_id, ArtifactType.SLIDE_DECK)
async def list_data_tables(self, notebook_id: str) -> builtins.list[Artifact]:
"""List data table artifacts."""
return await self.list(notebook_id, ArtifactType.DATA_TABLE)
# =========================================================================
# Generate Operations
# =========================================================================
async def generate_audio(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
audio_format: AudioFormat | None = None,
audio_length: AudioLength | None = None,
) -> GenerationStatus:
"""Generate an Audio Overview (podcast).
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Custom instructions for the podcast hosts.
audio_format: DEEP_DIVE, BRIEF, CRITIQUE, or DEBATE.
audio_length: SHORT, DEFAULT, or LONG.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
source_ids_double = [[sid] for sid in source_ids] if source_ids else []
format_code = audio_format.value if audio_format else None
length_code = audio_length.value if audio_length else None
params = [
[2],
notebook_id,
[
None,
None,
1, # ArtifactTypeCode.AUDIO
source_ids_triple,
None,
None,
[
None,
[
instructions,
length_code,
None,
source_ids_double,
language,
None,
format_code,
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_video(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
video_format: VideoFormat | None = None,
video_style: VideoStyle | None = None,
) -> GenerationStatus:
"""Generate a Video Overview.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Custom instructions for video generation.
video_format: EXPLAINER or BRIEF.
video_style: AUTO_SELECT, CLASSIC, WHITEBOARD, etc.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
source_ids_double = [[sid] for sid in source_ids] if source_ids else []
format_code = video_format.value if video_format else None
style_code = video_style.value if video_style else None
params = [
[2],
notebook_id,
[
None,
None,
3, # ArtifactTypeCode.VIDEO
source_ids_triple,
None,
None,
None,
None,
[
None,
None,
[
source_ids_double,
language,
instructions,
None,
format_code,
style_code,
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_cinematic_video(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
) -> GenerationStatus:
"""Generate a Cinematic Video Overview.
Cinematic videos use AI-generated documentary-style footage (Veo 3)
instead of the slide-deck animations used by standard video overviews.
They do not accept VideoStyle options.
Requires a Google AI Ultra subscription. Uses the same CREATE_ARTIFACT
RPC as standard videos with VideoFormat.CINEMATIC (3). Parameter
structure verified against NotebookLM web UI network traffic
(March 2026).
Note: Generation takes significantly longer than standard videos
(~30-40 minutes) due to Veo 3 rendering.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Custom instructions for video generation.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
source_ids_double = [[sid] for sid in source_ids] if source_ids else []
params = [
[2],
notebook_id,
[
None,
None,
ArtifactTypeCode.VIDEO.value,
source_ids_triple,
None,
None,
None,
None,
[
None,
None,
[
source_ids_double,
language,
instructions,
None,
VideoFormat.CINEMATIC.value,
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_report(
self,
notebook_id: str,
report_format: ReportFormat = ReportFormat.BRIEFING_DOC,
source_ids: builtins.list[str] | None = None,
language: str = "en",
custom_prompt: str | None = None,
extra_instructions: str | None = None,
) -> GenerationStatus:
"""Generate a report artifact.
Args:
notebook_id: The notebook ID.
report_format: BRIEFING_DOC, STUDY_GUIDE, BLOG_POST, or CUSTOM.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
custom_prompt: Prompt for CUSTOM format. Falls back to a generic
default if None.
extra_instructions: Additional instructions appended to the built-in
template prompt. Ignored when report_format is CUSTOM; for custom
reports, embed all instructions in custom_prompt instead.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
format_configs = {
ReportFormat.BRIEFING_DOC: {
"title": "Briefing Doc",
"description": "Key insights and important quotes",
"prompt": (
"Create a comprehensive briefing document that includes an "
"Executive Summary, detailed analysis of key themes, important "
"quotes with context, and actionable insights."
),
},
ReportFormat.STUDY_GUIDE: {
"title": "Study Guide",
"description": "Short-answer quiz, essay questions, glossary",
"prompt": (
"Create a comprehensive study guide that includes key concepts, "
"short-answer practice questions, essay prompts for deeper "
"exploration, and a glossary of important terms."
),
},
ReportFormat.BLOG_POST: {
"title": "Blog Post",
"description": "Insightful takeaways in readable article format",
"prompt": (
"Write an engaging blog post that presents the key insights "
"in an accessible, reader-friendly format. Include an attention-"
"grabbing introduction, well-organized sections, and a compelling "
"conclusion with takeaways."
),
},
ReportFormat.CUSTOM: {
"title": "Custom Report",
"description": "Custom format",
"prompt": custom_prompt or "Create a report based on the provided sources.",
},
}
config = format_configs[report_format]
if extra_instructions and report_format != ReportFormat.CUSTOM:
config = {**config, "prompt": f"{config['prompt']}\n\n{extra_instructions}"}
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
source_ids_double = [[sid] for sid in source_ids] if source_ids else []
params = [
[2],
notebook_id,
[
None,
None,
2, # ArtifactTypeCode.REPORT
source_ids_triple,
None,
None,
None,
[
None,
[
config["title"],
config["description"],
None,
source_ids_double,
language,
config["prompt"],
None,
True,
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_study_guide(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
extra_instructions: str | None = None,
) -> GenerationStatus:
"""Generate a study guide report.
Convenience method wrapping generate_report with STUDY_GUIDE format.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
extra_instructions: Additional instructions appended to the default template.
Returns:
GenerationStatus with task_id for polling.
"""
return await self.generate_report(
notebook_id,
report_format=ReportFormat.STUDY_GUIDE,
source_ids=source_ids,
language=language,
extra_instructions=extra_instructions,
)
async def generate_quiz(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
instructions: str | None = None,
quantity: QuizQuantity | None = None,
difficulty: QuizDifficulty | None = None,
) -> GenerationStatus:
"""Generate a quiz.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
instructions: Custom instructions for quiz generation.
quantity: FEWER, STANDARD, or MORE questions.
difficulty: EASY, MEDIUM, or HARD.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
quantity_code = quantity.value if quantity else None
difficulty_code = difficulty.value if difficulty else None
params = [
[2],
notebook_id,
[
None,
None,
4, # ArtifactTypeCode.QUIZ_FLASHCARD
source_ids_triple,
None,
None,
None,
None,
None,
[
None,
[
2, # Variant: quiz
None,
instructions,
None,
None,
None,
None,
[quantity_code, difficulty_code],
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_flashcards(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
instructions: str | None = None,
quantity: QuizQuantity | None = None,
difficulty: QuizDifficulty | None = None,
) -> GenerationStatus:
"""Generate flashcards.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
instructions: Custom instructions for flashcard generation.
quantity: FEWER, STANDARD, or MORE cards.
difficulty: EASY, MEDIUM, or HARD.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
quantity_code = quantity.value if quantity else None
difficulty_code = difficulty.value if difficulty else None
params = [
[2],
notebook_id,
[
None,
None,
4, # ArtifactTypeCode.QUIZ_FLASHCARD
source_ids_triple,
None,
None,
None,
None,
None,
[
None,
[
1, # Variant: flashcards
None,
instructions,
None,
None,
None,
[difficulty_code, quantity_code],
],
],
],
]
return await self._call_generate(notebook_id, params)
async def generate_infographic(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
orientation: InfographicOrientation | None = None,
detail_level: InfographicDetail | None = None,
style: InfographicStyle | None = None,
) -> GenerationStatus:
"""Generate an infographic.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Custom instructions for infographic generation.
orientation: LANDSCAPE, PORTRAIT, or SQUARE.
detail_level: CONCISE, STANDARD, or DETAILED.
style: Visual style preset for the infographic.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
orientation_code = orientation.value if orientation else None
detail_code = detail_level.value if detail_level else None
style_code = style.value if style else None
params = [
[2],
notebook_id,
[
None,
None,
7, # ArtifactTypeCode.INFOGRAPHIC
source_ids_triple,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
[[instructions, language, None, orientation_code, detail_code, style_code]],
],
]
return await self._call_generate(notebook_id, params)
async def generate_slide_deck(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
slide_format: SlideDeckFormat | None = None,
slide_length: SlideDeckLength | None = None,
) -> GenerationStatus:
"""Generate a slide deck.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Custom instructions for slide deck generation.
slide_format: DETAILED_DECK or PRESENTER_SLIDES.
slide_length: DEFAULT or SHORT.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
format_code = slide_format.value if slide_format else None
length_code = slide_length.value if slide_length else None
params = [
[2],
notebook_id,
[
None,
None,
8, # ArtifactTypeCode.SLIDE_DECK
source_ids_triple,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
[[instructions, language, format_code, length_code]],
],
]
return await self._call_generate(notebook_id, params)
async def revise_slide(
self,
notebook_id: str,
artifact_id: str,
slide_index: int,
prompt: str,
) -> GenerationStatus:
"""Revise an individual slide in a completed slide deck using a prompt.
The slide deck must already be generated (status=COMPLETED) before
calling this method. Use poll_status() to wait for the revision to complete.
Args:
notebook_id: The notebook ID.
artifact_id: The slide deck artifact ID to revise.
slide_index: Zero-based index of the slide to revise.
prompt: Natural language instruction for the revision
(e.g. "Move the title up", "Remove taxonomy section").
Returns:
GenerationStatus with task_id for polling.
"""
if slide_index < 0:
raise ValidationError(f"slide_index must be >= 0, got {slide_index}")
params = [
[2],
artifact_id,
[[[slide_index, prompt]]],
]
try:
result = await self._core.rpc_call(
RPCMethod.REVISE_SLIDE,
params,
source_path=f"/notebook/{notebook_id}",
allow_null=True,
)
if result is None:
logger.warning("REVISE_SLIDE returned null result for artifact %s", artifact_id)
return self._parse_generation_result(result)
except RPCError as e:
if e.rpc_code == "USER_DISPLAYABLE_ERROR":
return GenerationStatus(
task_id="",
status="failed",
error=str(e),
error_code=str(e.rpc_code) if e.rpc_code is not None else None,
)
raise
async def generate_data_table(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
) -> GenerationStatus:
"""Generate a data table.
Args:
notebook_id: The notebook ID.
source_ids: Source IDs to include. If None, uses all sources.
language: Language code (default: "en").
instructions: Description of desired table structure.
Returns:
GenerationStatus with task_id for polling.
"""
if source_ids is None:
source_ids = await self._core.get_source_ids(notebook_id)
source_ids_triple = [[[sid]] for sid in source_ids] if source_ids else []
params = [
[2],
notebook_id,
[
None,
None,
9, # ArtifactTypeCode.DATA_TABLE
source_ids_triple,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
[None, [instructions, language]],
],
]
return await self._call_generate(notebook_id, params)
async def generate_mind_map(
self,
notebook_id: str,
source_ids: builtins.list[str] | None = None,
language: str = "en",
instructions: str | None = None,
) -> dict[str, Any]:
"""Generate an interactive mind map.
The mind map is generated and saved as a note in the notebook.
It will appear in artifact listings with type MIND_MAP (5).
Args:
notebook_id: The notebook ID.