-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathhelpers.py
More file actions
754 lines (609 loc) · 24.5 KB
/
helpers.py
File metadata and controls
754 lines (609 loc) · 24.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
"""CLI helper utilities.
Provides common functionality for all CLI commands:
- Authentication handling (get_client)
- Async execution (run_async)
- Error handling
- JSON/Rich output formatting
- Context management (current notebook/conversation)
- @with_client decorator for command boilerplate reduction
"""
import asyncio
import json
import logging
import os
import time
from functools import wraps
from typing import TYPE_CHECKING
import click
from rich.console import Console
from rich.table import Table
from ..auth import (
AuthTokens,
fetch_tokens,
load_auth_from_storage,
)
from ..exceptions import RPCTimeoutError
from ..paths import get_context_path
from ..types import ArtifactType
if TYPE_CHECKING:
from ..types import Artifact
console = Console()
logger = logging.getLogger(__name__)
# CLI artifact type name aliases
_CLI_ARTIFACT_ALIASES = {
"flashcard": "flashcards", # CLI uses singular, enum uses plural
}
def cli_name_to_artifact_type(name: str) -> ArtifactType | None:
"""Convert CLI artifact type name to ArtifactType enum.
Args:
name: CLI artifact type name (e.g., "video", "slide-deck", "flashcard").
Use "all" to get None (no filter).
Returns:
ArtifactType enum member, or None if name is "all".
Raises:
KeyError: If name is not a valid artifact type.
"""
if name == "all":
return None
# Handle aliases
name = _CLI_ARTIFACT_ALIASES.get(name, name)
# Convert kebab-case to snake_case and uppercase for enum lookup
enum_name = name.upper().replace("-", "_")
return ArtifactType[enum_name]
# =============================================================================
# ASYNC EXECUTION
# =============================================================================
def run_async(coro):
"""Run async coroutine in sync context."""
return asyncio.run(coro)
def filter_unsupported_sources(sources: list[dict], *, json_output: bool = False) -> list[dict]:
"""Pre-filter sources that NotebookLM cannot import as web pages.
Removes direct PDF/document URLs and known bot-protected domains
that consistently result in error status after import.
"""
PDF_EXTENSIONS = (".pdf", ".docx", ".xlsx", ".pptx", ".zip")
BLOCKED_PATTERNS = ("/fileadmin/", "/download/", "/sites/default/files/", "/SharedDocs/Downloads/")
filtered = []
skipped = []
for s in sources:
url = (s.get("url") or "").lower()
if url.endswith(PDF_EXTENSIONS) or any(p in url for p in BLOCKED_PATTERNS):
skipped.append(s)
else:
filtered.append(s)
if skipped and not json_output:
console.print(
f"[dim]Skipping {len(skipped)} unsupported source(s) (PDFs/downloads) before import[/dim]"
)
return filtered
async def cleanup_error_sources(client, notebook_id: str, *, json_output: bool = False) -> int:
"""Delete all sources with error status from a notebook.
Returns the number of deleted sources.
"""
try:
sources = await client.sources.list(notebook_id)
error_ids = [s.get("id") for s in sources if s.get("status") == "error" and s.get("id")]
for source_id in error_ids:
try:
await client.sources.delete(notebook_id, source_id)
except Exception:
pass
if error_ids and not json_output:
console.print(f"[dim]Removed {len(error_ids)} failed source(s) after import[/dim]")
return len(error_ids)
except Exception:
return 0
async def import_with_retry(
client,
notebook_id: str,
task_id: str,
sources: list[dict],
*,
max_elapsed: float = 1800,
initial_delay: float = 5,
backoff_factor: float = 2,
max_delay: float = 60,
json_output: bool = False,
) -> list[dict[str, str]]:
"""Retry research import on RPC timeouts with exponential backoff.
This is intentionally CLI-only policy. Library consumers calling
`client.research.import_sources()` directly still get one-shot behavior.
"""
started_at = time.monotonic()
delay = initial_delay
attempt = 1
pending_sources = list(sources)
while True:
try:
return await client.research.import_sources(notebook_id, task_id, pending_sources)
except RPCTimeoutError:
elapsed = time.monotonic() - started_at
remaining = max_elapsed - elapsed
if remaining <= 0:
raise
sleep_for = min(delay, max_delay, remaining)
# Filter out sources already imported to avoid duplicates on retry
try:
existing = await client.sources.list(notebook_id)
existing_urls = {s.get("url") for s in existing if s.get("url")}
pending_sources = [s for s in pending_sources if s.get("url") not in existing_urls]
except Exception:
pass # If listing fails, retry with original list
logger.warning(
"IMPORT_RESEARCH timed out for notebook %s; retrying in %.1fs (attempt %d, %.1fs elapsed)",
notebook_id,
sleep_for,
attempt + 1,
elapsed,
)
if not json_output:
console.print(
f"[yellow]Import timed out; retrying in {sleep_for:.0f}s "
f"(attempt {attempt + 1})[/yellow]"
)
await asyncio.sleep(sleep_for)
delay = min(delay * backoff_factor, max_delay)
attempt += 1
# =============================================================================
# AUTHENTICATION
# =============================================================================
def get_client(ctx) -> tuple[dict, str, str]:
"""Get auth components from context.
Args:
ctx: Click context with optional storage_path in obj
Returns:
Tuple of (cookies, csrf_token, session_id)
Raises:
FileNotFoundError: If auth storage not found
"""
storage_path = ctx.obj.get("storage_path") if ctx.obj else None
cookies = load_auth_from_storage(storage_path)
csrf, session_id = run_async(fetch_tokens(cookies))
return cookies, csrf, session_id
def get_auth_tokens(ctx) -> AuthTokens:
"""Get AuthTokens object from context.
Args:
ctx: Click context
Returns:
AuthTokens ready for client construction
"""
cookies, csrf, session_id = get_client(ctx)
return AuthTokens(cookies=cookies, csrf_token=csrf, session_id=session_id)
# =============================================================================
# CONTEXT MANAGEMENT
# =============================================================================
def _get_context_value(key: str) -> str | None:
"""Read a single value from context.json."""
context_file = get_context_path()
if not context_file.exists():
return None
try:
data = json.loads(context_file.read_text(encoding="utf-8"))
return data.get(key)
except json.JSONDecodeError:
logger.warning(
"Context file %s is corrupted; cannot read '%s'. Run 'notebooklm clear' to reset.",
context_file,
key,
)
return None
except OSError as e:
logger.warning("Cannot read context file %s: %s", context_file, e)
return None
def _set_context_value(key: str, value: str | None) -> None:
"""Set or clear a single value in context.json."""
context_file = get_context_path()
if not context_file.exists():
return
try:
data = json.loads(context_file.read_text(encoding="utf-8"))
if value is not None:
data[key] = value
elif key in data:
del data[key]
context_file.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
except json.JSONDecodeError:
logger.warning(
"Context file %s is corrupted; cannot update '%s'. Run 'notebooklm clear' to reset.",
context_file,
key,
)
except OSError as e:
logger.warning("Failed to write context file %s for key '%s': %s", context_file, key, e)
def get_current_notebook() -> str | None:
"""Get the current notebook ID from context."""
return _get_context_value("notebook_id")
def set_current_notebook(
notebook_id: str,
title: str | None = None,
is_owner: bool | None = None,
created_at: str | None = None,
):
"""Set the current notebook context.
conversation_id is never preserved — the server owns the canonical ID per
notebook, and a stale local value would silently use the wrong UUID.
"""
context_file = get_context_path()
context_file.parent.mkdir(parents=True, exist_ok=True)
data: dict[str, str | bool] = {"notebook_id": notebook_id}
if title:
data["title"] = title
if is_owner is not None:
data["is_owner"] = is_owner
if created_at:
data["created_at"] = created_at
context_file.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
def clear_context():
"""Clear the current context."""
context_file = get_context_path()
if context_file.exists():
context_file.unlink()
def get_current_conversation() -> str | None:
"""Get the current conversation ID from context."""
return _get_context_value("conversation_id")
def set_current_conversation(conversation_id: str | None):
"""Set or clear the current conversation ID in context."""
_set_context_value("conversation_id", conversation_id)
def validate_id(entity_id: str, entity_name: str = "ID") -> str:
"""Validate and normalize an entity ID.
Args:
entity_id: The ID to validate
entity_name: Name for error messages (e.g., "notebook", "source")
Returns:
Stripped ID
Raises:
click.ClickException: If ID is empty or whitespace-only
"""
if not entity_id or not entity_id.strip():
raise click.ClickException(f"{entity_name} ID cannot be empty")
return entity_id.strip()
def require_notebook(notebook_id: str | None) -> str:
"""Get notebook ID from argument or context, raise if neither.
Args:
notebook_id: Optional notebook ID from command argument
Returns:
Notebook ID (from argument or context), validated and stripped
Raises:
SystemExit: If no notebook ID available
click.ClickException: If notebook ID is empty/whitespace
"""
if notebook_id:
return validate_id(notebook_id, "Notebook")
current = get_current_notebook()
if current:
return validate_id(current, "Notebook")
console.print(
"[red]No notebook specified. Use 'notebooklm use <id>' to set context or provide notebook_id.[/red]"
)
raise SystemExit(1)
async def _resolve_partial_id(
partial_id: str,
list_fn,
entity_name: str,
list_command: str,
) -> str:
"""Generic partial ID resolver.
Allows users to type partial IDs like 'abc' instead of full UUIDs.
Matches are case-insensitive prefix matches.
Args:
partial_id: Full or partial ID to resolve
list_fn: Async function that returns list of items with id/title attributes
entity_name: Name for error messages (e.g., "notebook", "source")
list_command: CLI command to list items (e.g., "list", "source list")
Returns:
Full ID of the matched item
Raises:
click.ClickException: If ID is empty, no match, or ambiguous match
"""
# Validate and normalize the ID
partial_id = validate_id(partial_id, entity_name)
# Skip resolution for IDs that look complete (20+ chars)
if len(partial_id) >= 20:
return partial_id
items = await list_fn()
matches = [item for item in items if item.id.lower().startswith(partial_id.lower())]
if len(matches) == 1:
if matches[0].id != partial_id:
title = matches[0].title or "(untitled)"
console.print(f"[dim]Matched: {matches[0].id[:12]}... ({title})[/dim]")
return matches[0].id
elif len(matches) == 0:
raise click.ClickException(
f"No {entity_name} found starting with '{partial_id}'. "
f"Run 'notebooklm {list_command}' to see available {entity_name}s."
)
else:
lines = [f"Ambiguous ID '{partial_id}' matches {len(matches)} {entity_name}s:"]
for item in matches[:5]:
title = item.title or "(untitled)"
lines.append(f" {item.id[:12]}... {title}")
if len(matches) > 5:
lines.append(f" ... and {len(matches) - 5} more")
lines.append("\nSpecify more characters to narrow down.")
raise click.ClickException("\n".join(lines))
async def resolve_notebook_id(client, partial_id: str) -> str:
"""Resolve partial notebook ID to full ID."""
return await _resolve_partial_id(
partial_id,
list_fn=lambda: client.notebooks.list(),
entity_name="notebook",
list_command="list",
)
async def resolve_source_id(client, notebook_id: str, partial_id: str) -> str:
"""Resolve partial source ID to full ID."""
return await _resolve_partial_id(
partial_id,
list_fn=lambda: client.sources.list(notebook_id),
entity_name="source",
list_command="source list",
)
async def resolve_artifact_id(client, notebook_id: str, partial_id: str) -> str:
"""Resolve partial artifact ID to full ID."""
return await _resolve_partial_id(
partial_id,
list_fn=lambda: client.artifacts.list(notebook_id),
entity_name="artifact",
list_command="artifact list",
)
async def resolve_note_id(client, notebook_id: str, partial_id: str) -> str:
"""Resolve partial note ID to full ID."""
return await _resolve_partial_id(
partial_id,
list_fn=lambda: client.notes.list(notebook_id),
entity_name="note",
list_command="note list",
)
async def resolve_source_ids(
client, notebook_id: str, source_ids: tuple[str, ...]
) -> list[str] | None:
"""Resolve multiple partial source IDs to full IDs.
Args:
client: NotebookLM client
notebook_id: Resolved notebook ID
source_ids: Tuple of partial source IDs from CLI
Returns:
List of resolved source IDs, or None if no source IDs provided
"""
if not source_ids:
return None
resolved = []
for sid in source_ids:
resolved.append(await resolve_source_id(client, notebook_id, sid))
return resolved
# =============================================================================
# ERROR HANDLING
# =============================================================================
def handle_error(e: Exception):
"""Handle and display errors consistently."""
console.print(f"[red]Error: {e}[/red]")
raise SystemExit(1)
def handle_auth_error(json_output: bool = False):
"""Handle authentication errors with helpful context."""
from ..paths import get_path_info, get_storage_path
path_info = get_path_info()
storage_path = get_storage_path()
has_env_var = bool(os.environ.get("NOTEBOOKLM_AUTH_JSON"))
has_home_env = bool(os.environ.get("NOTEBOOKLM_HOME"))
storage_source = path_info["home_source"]
if json_output:
json_error_response(
"AUTH_REQUIRED",
"Auth not found. Run 'notebooklm login' first.",
extra={
"checked_paths": {
"storage_file": str(storage_path),
"storage_source": storage_source,
"env_var": "NOTEBOOKLM_AUTH_JSON" if has_env_var else None,
},
"help": "Run 'notebooklm login' or set NOTEBOOKLM_AUTH_JSON",
},
)
else:
console.print("[red]Not logged in.[/red]\n")
console.print("[dim]Checked locations:[/dim]")
console.print(f" • Storage file: [cyan]{storage_path}[/cyan]")
if has_home_env:
console.print(" [dim](via $NOTEBOOKLM_HOME)[/dim]")
env_status = "[yellow]set but invalid[/yellow]" if has_env_var else "[dim]not set[/dim]"
console.print(f" • NOTEBOOKLM_AUTH_JSON: {env_status}")
console.print("\n[bold]Options to authenticate:[/bold]")
console.print(" 1. Run: [green]notebooklm login[/green]")
console.print(" 2. Set [cyan]NOTEBOOKLM_AUTH_JSON[/cyan] env var (for CI/CD)")
console.print(" 3. Use [cyan]--storage /path/to/file.json[/cyan] flag")
raise SystemExit(1)
# =============================================================================
# DECORATORS
# =============================================================================
def with_client(f):
"""Decorator that handles auth, async execution, and errors for CLI commands.
This decorator eliminates boilerplate from commands that need:
- Authentication (get AuthTokens from context)
- Async execution (run coroutine with asyncio.run)
- Error handling (auth errors, general exceptions)
The decorated function stays SYNC (Click doesn't support async) but returns
a coroutine. The decorator runs the coroutine and handles errors.
Usage:
@cli.command("list")
@click.option("--json", "json_output", is_flag=True)
@with_client
def list_notebooks(ctx, json_output, client_auth):
async def _run():
async with NotebookLMClient(client_auth) as client:
notebooks = await client.notebooks.list()
output_notebooks(notebooks, json_output)
return _run()
Args:
f: Function that accepts client_auth (AuthTokens) and returns a coroutine
Returns:
Decorated function with Click pass_context
"""
@wraps(f)
@click.pass_context
def wrapper(ctx, *args, **kwargs):
cmd_name = f.__name__
start = time.monotonic()
logger.debug("CLI command starting: %s", cmd_name)
json_output = kwargs.get("json_output", False)
def log_result(status: str, detail: str = "") -> float:
elapsed = time.monotonic() - start
if detail:
logger.debug("CLI command %s: %s (%.3fs) - %s", status, cmd_name, elapsed, detail)
else:
logger.debug("CLI command %s: %s (%.3fs)", status, cmd_name, elapsed)
return elapsed
try:
try:
auth = get_auth_tokens(ctx)
except FileNotFoundError:
log_result("failed", "not authenticated")
handle_auth_error(json_output)
return # unreachable (handle_auth_error raises SystemExit), but keeps mypy happy
coro = f(ctx, *args, client_auth=auth, **kwargs)
result = run_async(coro)
log_result("completed")
return result
except Exception as e:
log_result("failed", str(e))
if json_output:
json_error_response("ERROR", str(e))
else:
handle_error(e)
return wrapper
# =============================================================================
# OUTPUT FORMATTING
# =============================================================================
def json_output_response(data: dict) -> None:
"""Print JSON response (no colors for machine parsing)."""
click.echo(json.dumps(data, indent=2, default=str))
def json_error_response(code: str, message: str, extra: dict | None = None) -> None:
"""Print JSON error and exit (no colors for machine parsing).
Args:
code: Error code (e.g., "AUTH_REQUIRED", "ERROR")
message: Human-readable error message
extra: Optional additional data to include in response
"""
response = {"error": True, "code": code, "message": message}
if extra:
response.update(extra)
click.echo(json.dumps(response, indent=2))
raise SystemExit(1)
_RESULT_TYPE_LABELS = {
1: "Web",
2: "Drive",
5: "Report",
"web": "Web",
"drive": "Drive",
"report": "Report",
}
def display_research_sources(sources: list[dict], max_display: int = 10) -> None:
"""Display research sources in a formatted table.
Args:
sources: List of source dicts with 'title', 'url', and optional 'result_type' keys
max_display: Maximum sources to show before truncating (default 10)
"""
console.print(f"[bold]Found {len(sources)} sources[/bold]")
if sources:
# Only show Type column if any source has result_type
has_types = any("result_type" in s for s in sources)
table = Table(show_header=True, header_style="bold")
table.add_column("Title", style="cyan")
if has_types:
table.add_column("Type", style="yellow")
table.add_column("URL", style="dim")
for src in sources[:max_display]:
row = [src.get("title", "Untitled")[:50]]
if has_types:
rt: int | None = src.get("result_type")
label = (
_RESULT_TYPE_LABELS.get(rt, str(rt) if rt is not None else "")
if rt is not None
else ""
)
row.append(label)
row.append(src.get("url", "")[:60])
table.add_row(*row)
if len(sources) > max_display:
extra_row = [f"... and {len(sources) - max_display} more"]
if has_types:
extra_row.append("")
extra_row.append("")
table.add_row(*extra_row)
console.print(table)
def display_report(report: str, max_chars: int = 1000, json_hint: bool = True) -> None:
"""Display a research report, truncated for terminal output.
Args:
report: The report markdown text.
max_chars: Maximum characters to display (default 1000).
json_hint: Whether to suggest --json for full output in truncation message.
"""
if not report:
return
console.print("\n[bold]Report:[/bold]")
console.print(report[:max_chars], markup=False)
if len(report) > max_chars:
hint = " use --json for full report" if json_hint else ""
console.print(
f"[dim]... (truncated,{hint})[/dim]" if hint else "[dim]... (truncated)[/dim]"
)
# =============================================================================
# TYPE DISPLAY HELPERS
# =============================================================================
def get_artifact_type_display(artifact: "Artifact") -> str:
"""Get display string for artifact type.
Args:
artifact: Artifact object
Returns:
Display string with emoji
"""
from notebooklm import ArtifactType
kind = artifact.kind
# Map ArtifactType enum to display strings
display_map = {
ArtifactType.AUDIO: "🎧 Audio",
ArtifactType.VIDEO: "🎬 Video",
ArtifactType.QUIZ: "📝 Quiz",
ArtifactType.FLASHCARDS: "🃏 Flashcards",
ArtifactType.MIND_MAP: "🧠 Mind Map",
ArtifactType.INFOGRAPHIC: "🖼️ Infographic",
ArtifactType.SLIDE_DECK: "📊 Slide Deck",
ArtifactType.DATA_TABLE: "📈 Data Table",
}
# Handle report subtypes specially
if kind == ArtifactType.REPORT:
report_displays = {
"briefing_doc": "📋 Briefing Doc",
"study_guide": "📚 Study Guide",
"blog_post": "✍️ Blog Post",
"report": "📄 Report",
}
return report_displays.get(artifact.report_subtype or "report", "📄 Report")
return display_map.get(kind, f"Unknown ({kind})")
def get_source_type_display(source_type: str) -> str:
"""Get display string for source type.
Args:
source_type: Type string from Source.kind (SourceType str enum)
Returns:
Display string with emoji
"""
# Extract value if it's a SourceType enum, otherwise use as-is
type_str = source_type.value if hasattr(source_type, "value") else str(source_type)
type_map = {
# From SourceType str enum values (types.py)
"google_docs": "📄 Google Docs",
"google_slides": "📊 Google Slides",
"google_spreadsheet": "📊 Google Sheets",
"pdf": "📄 PDF",
"pasted_text": "📝 Pasted Text",
"docx": "📝 DOCX",
"web_page": "🌐 Web Page",
"markdown": "📝 Markdown",
"youtube": "🎬 YouTube",
"media": "🎵 Media",
"google_drive_audio": "🎧 Drive Audio",
"google_drive_video": "🎬 Drive Video",
"image": "🖼️ Image",
"csv": "📊 CSV",
"epub": "📕 EPUB",
"unknown": "❓ Unknown",
}
return type_map.get(type_str, f"❓ {type_str}")