-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathgenerate.py
More file actions
1178 lines (1042 loc) · 36.7 KB
/
generate.py
File metadata and controls
1178 lines (1042 loc) · 36.7 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
"""Generate content CLI commands.
Commands:
audio Generate audio overview (podcast)
video Generate video overview
cinematic-video Generate cinematic video overview (AI documentary footage)
slide-deck Generate slide deck
quiz Generate quiz
flashcards Generate flashcards
infographic Generate infographic
data-table Generate data table
mind-map Generate mind map
report Generate report
"""
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
import click
from ..client import NotebookLMClient
from ..types import (
AudioFormat,
AudioLength,
GenerationStatus,
InfographicDetail,
InfographicOrientation,
InfographicStyle,
QuizDifficulty,
QuizQuantity,
ReportFormat,
SlideDeckFormat,
SlideDeckLength,
VideoFormat,
VideoStyle,
)
from .helpers import (
console,
json_error_response,
json_output_response,
require_notebook,
resolve_notebook_id,
resolve_source_ids,
with_client,
)
from .language import SUPPORTED_LANGUAGES, get_language
from .options import json_option, retry_option
DEFAULT_LANGUAGE = "en"
# Retry constants
RETRY_INITIAL_DELAY = 60.0 # seconds
RETRY_MAX_DELAY = 300.0 # 5 minutes
RETRY_BACKOFF_MULTIPLIER = 2.0
_INFOGRAPHIC_STYLE_MAP = {
"auto": InfographicStyle.AUTO_SELECT,
"sketch-note": InfographicStyle.SKETCH_NOTE,
"professional": InfographicStyle.PROFESSIONAL,
"bento-grid": InfographicStyle.BENTO_GRID,
"editorial": InfographicStyle.EDITORIAL,
"instructional": InfographicStyle.INSTRUCTIONAL,
"bricks": InfographicStyle.BRICKS,
"clay": InfographicStyle.CLAY,
"anime": InfographicStyle.ANIME,
"kawaii": InfographicStyle.KAWAII,
"scientific": InfographicStyle.SCIENTIFIC,
}
def calculate_backoff_delay(
attempt: int,
initial_delay: float = RETRY_INITIAL_DELAY,
max_delay: float = RETRY_MAX_DELAY,
multiplier: float = RETRY_BACKOFF_MULTIPLIER,
) -> float:
"""Calculate exponential backoff delay for a retry attempt.
Args:
attempt: The current attempt number (0-indexed).
initial_delay: Initial delay in seconds.
max_delay: Maximum delay cap in seconds.
multiplier: Backoff multiplier.
Returns:
Delay in seconds for this attempt.
"""
delay = initial_delay * (multiplier**attempt)
return min(delay, max_delay)
async def generate_with_retry(
generate_fn: Callable[[], Awaitable[GenerationStatus | None]],
max_retries: int,
artifact_type: str,
json_output: bool = False,
) -> GenerationStatus | None:
"""Generate artifact with retry on rate limit.
Retries the generation call with exponential backoff when rate limited.
Always makes at least one attempt, even when max_retries=0.
Args:
generate_fn: Async function that performs the generation.
max_retries: Maximum number of retries (0 = no retry, just one attempt).
artifact_type: Display name for progress messages.
json_output: Whether to suppress console output.
Returns:
GenerationStatus or None if generation failed.
"""
for attempt in range(max_retries + 1):
result = await generate_fn()
# Return immediately if not rate limited (success or other failure)
if not isinstance(result, GenerationStatus) or not result.is_rate_limited:
return result
# Rate limited with no retries left
if attempt >= max_retries:
return result
# Wait before retry
delay = calculate_backoff_delay(attempt)
if not json_output:
console.print(
f"[yellow]{artifact_type.title()} rate limited. "
f"Retrying in {int(delay)}s (attempt {attempt + 2}/{max_retries + 1})...[/yellow]"
)
await asyncio.sleep(delay)
# Unreachable, but satisfies type checker
return None
def resolve_language(language: str | None) -> str:
"""Resolve language from CLI flag, config, or default.
Priority: CLI flag > config file > "en" default.
Uses explicit None checks to avoid treating empty string as falsy.
Validates that the language code is supported.
"""
if language is not None:
if language not in SUPPORTED_LANGUAGES:
raise click.BadParameter(
f"Unknown language code: {language}\n"
"Run 'notebooklm language list' to see supported codes.",
param_hint="'--language'",
)
return language
config_lang = get_language()
if config_lang is not None:
return config_lang
return DEFAULT_LANGUAGE
async def handle_generation_result(
client: NotebookLMClient,
notebook_id: str,
result: Any,
artifact_type: str,
wait: bool = False,
json_output: bool = False,
timeout: float = 300.0,
) -> GenerationStatus | None:
"""Handle generation result with optional waiting and output formatting.
Consolidates common pattern across all generate commands:
- Check for None/failed result
- Optionally wait for completion
- Output status in JSON or console format
Args:
client: The NotebookLM client.
notebook_id: The notebook ID.
result: The generation result from artifacts API.
artifact_type: Display name for the artifact type (e.g., "audio", "video").
wait: Whether to wait for completion.
json_output: Whether to output as JSON.
timeout: Timeout for waiting (default: 300s).
Returns:
Final GenerationStatus, or None if generation failed.
"""
# Handle failed generation or rate limiting
if not result:
if json_output:
json_error_response(
"GENERATION_FAILED",
f"{artifact_type.title()} generation failed",
)
else:
console.print(f"[red]{artifact_type.title()} generation failed.[/red]")
return None
# Check for rate limiting (result exists but failed due to rate limit)
if isinstance(result, GenerationStatus) and result.is_rate_limited:
if json_output:
json_error_response(
"RATE_LIMITED",
f"{artifact_type.title()} generation rate limited by Google",
)
else:
console.print(
f"[red]{artifact_type.title()} generation rate limited by Google.[/red]\n"
"[yellow]Daily quota may be exceeded. Try again in 1-24 hours, "
"or use --retry N to retry automatically.[/yellow]"
)
return result
# Extract task_id from various result formats
task_id: str | None = None
status: Any = result
if isinstance(result, GenerationStatus):
task_id = result.task_id
status = result
elif isinstance(result, dict):
task_id = result.get("artifact_id") or result.get("task_id")
status = result
elif isinstance(result, list) and len(result) > 0:
task_id = result[0] if isinstance(result[0], str) else None
status = result
# Wait for completion if requested
if wait and task_id:
if not json_output:
console.print(f"[yellow]Generating {artifact_type}...[/yellow] Task: {task_id}")
status = await client.artifacts.wait_for_completion(notebook_id, task_id, timeout=timeout)
# Output status
_output_generation_status(status, artifact_type, json_output)
return status if isinstance(status, GenerationStatus) else None
def _extract_task_id(status: Any) -> str | None:
"""Extract task ID from various status formats.
Handles GenerationStatus objects, dicts with task_id/artifact_id keys,
and lists where the first element is an ID string.
"""
if hasattr(status, "task_id"):
return status.task_id
if isinstance(status, dict):
return status.get("task_id") or status.get("artifact_id")
if isinstance(status, list) and len(status) > 0 and isinstance(status[0], str):
return status[0]
return None
def _output_generation_status(status: Any, artifact_type: str, json_output: bool) -> None:
"""Output generation status in appropriate format."""
is_complete = hasattr(status, "is_complete") and status.is_complete
is_failed = hasattr(status, "is_failed") and status.is_failed
if json_output:
if is_complete:
json_output_response(
{
"task_id": getattr(status, "task_id", None),
"status": "completed",
"url": getattr(status, "url", None),
}
)
elif is_failed:
json_error_response(
"GENERATION_FAILED",
getattr(status, "error", None) or f"{artifact_type.title()} generation failed",
)
else:
task_id = _extract_task_id(status)
json_output_response({"task_id": task_id, "status": "pending"})
else:
if is_complete:
url = getattr(status, "url", None)
if url:
console.print(f"[green]{artifact_type.title()} ready:[/green] {url}")
else:
console.print(f"[green]{artifact_type.title()} ready[/green]")
elif is_failed:
console.print(f"[red]Failed:[/red] {getattr(status, 'error', 'Unknown error')}")
else:
task_id = _extract_task_id(status)
console.print(f"[yellow]Started:[/yellow] {task_id or status}")
@click.group()
def generate():
"""Generate content from notebook.
\b
LLM-friendly design: Describe what you want in natural language.
\b
Examples:
notebooklm use nb123
notebooklm generate video "a funny explainer for kids age 5"
notebooklm generate audio "deep dive focusing on chapter 3"
notebooklm generate quiz "focus on vocabulary terms"
\b
Types:
audio Audio overview (podcast)
video Video overview
slide-deck Slide deck
quiz Quiz
flashcards Flashcards
infographic Infographic
data-table Data table
mind-map Mind map
report Report (briefing-doc, study-guide, blog-post, custom)
"""
pass
@generate.command("audio")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option(
"--format",
"audio_format",
type=click.Choice(["deep-dive", "brief", "critique", "debate"]),
default="deep-dive",
)
@click.option(
"--length",
"audio_length",
type=click.Choice(["short", "default", "long"]),
default="default",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_audio(
ctx,
description,
notebook_id,
audio_format,
audio_length,
language,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate audio overview (podcast).
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate audio "deep dive focusing on key themes"
notebooklm generate audio "make it funny and casual" --format debate
notebooklm generate audio -s src_001 -s src_002 "from specific sources"
"""
nb_id = require_notebook(notebook_id)
format_map = {
"deep-dive": AudioFormat.DEEP_DIVE,
"brief": AudioFormat.BRIEF,
"critique": AudioFormat.CRITIQUE,
"debate": AudioFormat.DEBATE,
}
length_map = {
"short": AudioLength.SHORT,
"default": AudioLength.DEFAULT,
"long": AudioLength.LONG,
}
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_audio(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description or None,
audio_format=format_map[audio_format],
audio_length=length_map[audio_length],
)
result = await generate_with_retry(_generate, max_retries, "audio", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "audio", wait, json_output
)
return _run()
@generate.command("video")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option(
"--format",
"video_format",
type=click.Choice(["explainer", "brief", "cinematic"]),
default="explainer",
)
@click.option(
"--style",
type=click.Choice(
[
"auto",
"classic",
"whiteboard",
"kawaii",
"anime",
"watercolor",
"retro-print",
"heritage",
"paper-craft",
]
),
default="auto",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_video(
ctx,
description,
notebook_id,
video_format,
style,
language,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate video overview.
Use --format cinematic for AI-generated documentary footage (Veo 3).
Cinematic videos ignore --style and take ~30-40 min (requires AI Ultra).
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate video "a funny explainer for kids age 5"
notebooklm generate video "professional presentation" --style classic
notebooklm generate video --format cinematic "documentary overview"
notebooklm generate video -s src_001 "from specific source"
"""
# Auto-select cinematic format when invoked as 'generate cinematic-video'
if ctx.info_name == "cinematic-video":
video_format = "cinematic"
nb_id = require_notebook(notebook_id)
format_map = {
"explainer": VideoFormat.EXPLAINER,
"brief": VideoFormat.BRIEF,
"cinematic": VideoFormat.CINEMATIC,
}
style_map = {
"auto": VideoStyle.AUTO_SELECT,
"classic": VideoStyle.CLASSIC,
"whiteboard": VideoStyle.WHITEBOARD,
"kawaii": VideoStyle.KAWAII,
"anime": VideoStyle.ANIME,
"watercolor": VideoStyle.WATERCOLOR,
"retro-print": VideoStyle.RETRO_PRINT,
"heritage": VideoStyle.HERITAGE,
"paper-craft": VideoStyle.PAPER_CRAFT,
}
is_cinematic = video_format == "cinematic"
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
if is_cinematic:
return await client.artifacts.generate_cinematic_video(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description or None,
)
return await client.artifacts.generate_video(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description or None,
video_format=format_map[video_format],
video_style=style_map[style],
)
timeout = 1800.0 if is_cinematic else 600.0
result = await generate_with_retry(_generate, max_retries, "video", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "video", wait, json_output, timeout=timeout
)
return _run()
# Convenience alias: 'generate cinematic-video' delegates to 'generate video --format cinematic'.
# Reuses generate_video's callback/params so changes stay in sync automatically.
_cinematic_video_gen_cmd = click.Command(
name="cinematic-video",
callback=generate_video.callback,
params=list(generate_video.params),
help=(
"Generate cinematic video overview (AI-generated documentary footage).\n\n"
"Alias for 'generate video --format cinematic'. Uses Veo 3 AI to create\n"
"documentary-style videos. Requires Google AI Ultra.\n\n"
"Example:\n"
' notebooklm generate cinematic-video "documentary about quantum physics"'
),
)
generate.add_command(_cinematic_video_gen_cmd)
@generate.command("slide-deck")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option(
"--format",
"deck_format",
type=click.Choice(["detailed", "presenter"]),
default="detailed",
)
@click.option(
"--length",
"deck_length",
type=click.Choice(["default", "short"]),
default="default",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_slide_deck(
ctx,
description,
notebook_id,
deck_format,
deck_length,
language,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate slide deck.
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate slide-deck "include speaker notes"
notebooklm generate slide-deck "executive summary" --format presenter --length short
"""
nb_id = require_notebook(notebook_id)
format_map = {
"detailed": SlideDeckFormat.DETAILED_DECK,
"presenter": SlideDeckFormat.PRESENTER_SLIDES,
}
length_map = {
"default": SlideDeckLength.DEFAULT,
"short": SlideDeckLength.SHORT,
}
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_slide_deck(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description or None,
slide_format=format_map[deck_format],
slide_length=length_map[deck_length],
)
result = await generate_with_retry(_generate, max_retries, "slide deck", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "slide deck", wait, json_output
)
return _run()
@generate.command("revise-slide")
@click.argument("description")
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option(
"-a",
"--artifact",
"artifact_id",
required=True,
help="Slide deck artifact ID to revise",
)
@click.option(
"--slide",
"slide_index",
type=int,
required=True,
help="Zero-based index of the slide to revise (0 = first slide)",
)
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_revise_slide(
ctx,
description,
notebook_id,
artifact_id,
slide_index,
wait,
max_retries,
json_output,
client_auth,
):
"""Revise an individual slide in an existing slide deck.
DESCRIPTION is the natural language prompt for the revision.
The slide deck must already be generated before using this command.
\b
Example:
notebooklm generate revise-slide "Move the title up" --artifact <id> --slide 0
notebooklm generate revise-slide "Remove taxonomy" --artifact <id> --slide 3 --wait
"""
nb_id = require_notebook(notebook_id)
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
async def _generate():
return await client.artifacts.revise_slide(
nb_id_resolved,
artifact_id=artifact_id,
slide_index=slide_index,
prompt=description,
)
result = await generate_with_retry(
_generate, max_retries, "slide revision", json_output
)
await handle_generation_result(
client, nb_id_resolved, result, "slide revision", wait, json_output
)
return _run()
@generate.command("quiz")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option("--quantity", type=click.Choice(["fewer", "standard", "more"]), default="standard")
@click.option("--difficulty", type=click.Choice(["easy", "medium", "hard"]), default="medium")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_quiz(
ctx,
description,
notebook_id,
quantity,
difficulty,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate quiz.
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate quiz "focus on vocabulary terms"
notebooklm generate quiz "test key concepts" --difficulty hard --quantity more
"""
nb_id = require_notebook(notebook_id)
quantity_map = {
"fewer": QuizQuantity.FEWER,
"standard": QuizQuantity.STANDARD,
"more": QuizQuantity.MORE,
}
difficulty_map = {
"easy": QuizDifficulty.EASY,
"medium": QuizDifficulty.MEDIUM,
"hard": QuizDifficulty.HARD,
}
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_quiz(
nb_id_resolved,
source_ids=sources,
instructions=description or None,
quantity=quantity_map[quantity],
difficulty=difficulty_map[difficulty],
)
result = await generate_with_retry(_generate, max_retries, "quiz", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "quiz", wait, json_output
)
return _run()
@generate.command("flashcards")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option("--quantity", type=click.Choice(["fewer", "standard", "more"]), default="standard")
@click.option("--difficulty", type=click.Choice(["easy", "medium", "hard"]), default="medium")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_flashcards(
ctx,
description,
notebook_id,
quantity,
difficulty,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate flashcards.
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate flashcards "vocabulary terms only"
notebooklm generate flashcards --quantity more --difficulty easy
"""
nb_id = require_notebook(notebook_id)
quantity_map = {
"fewer": QuizQuantity.FEWER,
"standard": QuizQuantity.STANDARD,
"more": QuizQuantity.MORE,
}
difficulty_map = {
"easy": QuizDifficulty.EASY,
"medium": QuizDifficulty.MEDIUM,
"hard": QuizDifficulty.HARD,
}
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_flashcards(
nb_id_resolved,
source_ids=sources,
instructions=description or None,
quantity=quantity_map[quantity],
difficulty=difficulty_map[difficulty],
)
result = await generate_with_retry(_generate, max_retries, "flashcards", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "flashcards", wait, json_output
)
return _run()
@generate.command("infographic")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option(
"--orientation",
type=click.Choice(["landscape", "portrait", "square"]),
default="landscape",
)
@click.option(
"--detail",
type=click.Choice(["concise", "standard", "detailed"]),
default="standard",
)
@click.option(
"--style",
type=click.Choice(list(_INFOGRAPHIC_STYLE_MAP)),
default="auto",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_infographic(
ctx,
description,
notebook_id,
orientation,
detail,
style,
language,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate infographic.
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate infographic "include statistics and key findings"
notebooklm generate infographic --orientation portrait --detail detailed
"""
nb_id = require_notebook(notebook_id)
orientation_map = {
"landscape": InfographicOrientation.LANDSCAPE,
"portrait": InfographicOrientation.PORTRAIT,
"square": InfographicOrientation.SQUARE,
}
detail_map = {
"concise": InfographicDetail.CONCISE,
"standard": InfographicDetail.STANDARD,
"detailed": InfographicDetail.DETAILED,
}
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_infographic(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description or None,
orientation=orientation_map[orientation],
detail_level=detail_map[detail],
style=_INFOGRAPHIC_STYLE_MAP[style],
)
result = await generate_with_retry(_generate, max_retries, "infographic", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "infographic", wait, json_output
)
return _run()
@generate.command("data-table")
@click.argument("description")
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@click.option("--wait/--no-wait", default=False, help="Wait for completion (default: no-wait)")
@retry_option
@json_option
@with_client
def generate_data_table(
ctx,
description,
notebook_id,
language,
source_ids,
wait,
max_retries,
json_output,
client_auth,
):
"""Generate data table.
\b
Use --json for machine-readable output.
\b
Example:
notebooklm generate data-table "comparison of key concepts"
notebooklm generate data-table -s src_001 "timeline of events"
"""
nb_id = require_notebook(notebook_id)
async def _run():
async with NotebookLMClient(client_auth) as client:
nb_id_resolved = await resolve_notebook_id(client, nb_id)
sources = await resolve_source_ids(client, nb_id_resolved, source_ids)
async def _generate():
return await client.artifacts.generate_data_table(
nb_id_resolved,
source_ids=sources,
language=resolve_language(language),
instructions=description,
)
result = await generate_with_retry(_generate, max_retries, "data table", json_output)
await handle_generation_result(
client, nb_id_resolved, result, "data table", wait, json_output
)
return _run()
@generate.command("mind-map")
@click.argument("description", default="", required=False)
@click.option(
"-n",
"--notebook",
"notebook_id",
default=None,
help="Notebook ID (uses current if not set)",
)
@click.option("--language", default=None, help="Output language (default: from config or 'en')")
@click.option("--source", "-s", "source_ids", multiple=True, help="Limit to specific source IDs")
@json_option