gws-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,879 @@
1
+ """Document conversion service (Markdown to Google Workspace formats)."""
2
+
3
+ import io
4
+ import re
5
+ import tempfile
6
+ import shutil
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from googleapiclient.discovery import build, Resource
11
+ from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
12
+ from googleapiclient.errors import HttpError
13
+
14
+ from gws.services.base import BaseService
15
+ from gws.output import output_success, output_error
16
+ from gws.exceptions import ExitCode
17
+ from gws.utils.diagrams import render_diagrams_in_markdown, find_diagram_blocks
18
+
19
+
20
+ class ConvertService(BaseService):
21
+ """Document conversion operations."""
22
+
23
+ SERVICE_NAME = "drive"
24
+ VERSION = "v3"
25
+
26
+ def __init__(self, **kwargs: Any):
27
+ super().__init__(**kwargs)
28
+ self._docs_service: Resource | None = None
29
+ self._slides_service: Resource | None = None
30
+
31
+ @property
32
+ def docs_service(self) -> Resource:
33
+ """Lazy-load Docs service for document manipulation."""
34
+ if self._docs_service is None:
35
+ credentials = self.auth_manager.get_credentials()
36
+ self._docs_service = build("docs", "v1", credentials=credentials)
37
+ return self._docs_service
38
+
39
+ @property
40
+ def slides_service(self) -> Resource:
41
+ """Lazy-load Slides service for presentation creation."""
42
+ if self._slides_service is None:
43
+ credentials = self.auth_manager.get_credentials()
44
+ self._slides_service = build("slides", "v1", credentials=credentials)
45
+ return self._slides_service
46
+
47
+ def _create_temp_folder(self) -> str:
48
+ """Create a temporary folder in Drive for diagram images.
49
+
50
+ Returns:
51
+ The folder ID
52
+ """
53
+ import uuid
54
+ folder_name = f"_gws_temp_{uuid.uuid4().hex[:8]}"
55
+ file_metadata = {
56
+ "name": folder_name,
57
+ "mimeType": "application/vnd.google-apps.folder",
58
+ }
59
+ folder = self.execute(
60
+ self.drive_service.files().create(body=file_metadata, fields="id")
61
+ )
62
+ return folder["id"]
63
+
64
+ def _delete_temp_folder(self, folder_id: str) -> None:
65
+ """Delete a temporary folder and all its contents.
66
+
67
+ Args:
68
+ folder_id: The folder ID to delete
69
+ """
70
+ try:
71
+ self.execute(self.drive_service.files().delete(fileId=folder_id))
72
+ except Exception:
73
+ pass # Ignore cleanup errors
74
+
75
+ def _set_pageless_mode(self, document_id: str) -> None:
76
+ """Set a document to pageless mode.
77
+
78
+ Args:
79
+ document_id: The Google Doc ID
80
+ """
81
+ requests = [{
82
+ "updateDocumentStyle": {
83
+ "documentStyle": {
84
+ "documentFormat": {
85
+ "documentMode": "PAGELESS",
86
+ }
87
+ },
88
+ "fields": "documentFormat",
89
+ }
90
+ }]
91
+
92
+ self.execute(
93
+ self.docs_service.documents().batchUpdate(
94
+ documentId=document_id, body={"requests": requests}
95
+ )
96
+ )
97
+
98
+ def _process_diagrams(
99
+ self,
100
+ markdown: str,
101
+ temp_dir: Path,
102
+ mermaid_theme: str = "default",
103
+ ) -> tuple[str, str | None]:
104
+ """Render diagrams and upload to Drive temp folder, returning modified markdown.
105
+
106
+ Args:
107
+ markdown: Original markdown content
108
+ temp_dir: Temporary directory for rendered images
109
+ mermaid_theme: Theme for Mermaid diagrams (default, neutral, dark, forest)
110
+
111
+ Returns:
112
+ Tuple of (modified markdown, temp folder ID for cleanup or None)
113
+ """
114
+ blocks = find_diagram_blocks(markdown)
115
+ if not blocks:
116
+ return markdown, None
117
+
118
+ # Create temp folder in Drive
119
+ temp_folder_id = self._create_temp_folder()
120
+
121
+ # Render diagrams locally
122
+ modified_md, rendered_paths = render_diagrams_in_markdown(
123
+ markdown, temp_dir, output_format="png", mermaid_theme=mermaid_theme
124
+ )
125
+
126
+ # Upload each rendered diagram to Drive temp folder and get public URLs
127
+ for path in rendered_paths:
128
+ # Upload to Drive temp folder
129
+ file_metadata = {"name": path.name, "parents": [temp_folder_id]}
130
+ media = MediaFileUpload(str(path), mimetype="image/png")
131
+ uploaded = self.execute(
132
+ self.drive_service.files()
133
+ .create(body=file_metadata, media_body=media, fields="id")
134
+ )
135
+ file_id = uploaded["id"]
136
+
137
+ # Make publicly accessible
138
+ self.execute(
139
+ self.drive_service.permissions().create(
140
+ fileId=file_id,
141
+ body={"type": "anyone", "role": "reader"},
142
+ )
143
+ )
144
+
145
+ # Get the web content link for embedding
146
+ # Use the direct image URL format
147
+ image_url = f"https://drive.google.com/uc?export=view&id={file_id}"
148
+
149
+ # Replace local path with Drive URL in markdown
150
+ modified_md = modified_md.replace(str(path.absolute()), image_url)
151
+
152
+ return modified_md, temp_folder_id
153
+
154
+ @staticmethod
155
+ def _preprocess_line_breaks(markdown: str) -> str:
156
+ """Convert soft line breaks to hard line breaks for Google Docs import.
157
+
158
+ Google's markdown import follows strict CommonMark where single newlines
159
+ within a paragraph are soft wraps (ignored). This adds trailing double-spaces
160
+ to create hard line breaks, preserving the source file's line structure.
161
+
162
+ Skips fenced code blocks and lines that already have hard break markers.
163
+ """
164
+ lines = markdown.split("\n")
165
+ result = []
166
+ in_code_block = False
167
+
168
+ for i, line in enumerate(lines):
169
+ stripped = line.strip()
170
+
171
+ # Track fenced code blocks
172
+ if stripped.startswith("```") or stripped.startswith("~~~"):
173
+ in_code_block = not in_code_block
174
+ result.append(line)
175
+ continue
176
+
177
+ if in_code_block:
178
+ result.append(line)
179
+ continue
180
+
181
+ is_last = i == len(lines) - 1
182
+ next_is_blank = is_last or lines[i + 1].strip() == ""
183
+
184
+ if (
185
+ stripped
186
+ and not next_is_blank
187
+ and not line.rstrip().endswith(" ")
188
+ and not line.rstrip().endswith("\\")
189
+ ):
190
+ result.append(line.rstrip() + " ")
191
+ else:
192
+ result.append(line)
193
+
194
+ return "\n".join(result)
195
+
196
+ def _prepare_markdown_upload(
197
+ self,
198
+ input_path: str,
199
+ operation: str,
200
+ render_diagrams: bool = False,
201
+ mermaid_theme: str = "default",
202
+ ) -> tuple[Path, Path, Path | None, str | None, int]:
203
+ """Validate and prepare markdown file for upload, optionally processing diagrams.
204
+
205
+ Args:
206
+ input_path: Path to markdown file
207
+ operation: Operation name for error messages
208
+ render_diagrams: If True, render Mermaid/PlantUML diagrams via Kroki
209
+ mermaid_theme: Theme for Mermaid diagrams
210
+
211
+ Returns:
212
+ Tuple of (source_path, upload_path, temp_dir, temp_folder_id, diagrams_rendered)
213
+
214
+ Raises:
215
+ SystemExit: If file not found
216
+ """
217
+ path = Path(input_path)
218
+ if not path.exists():
219
+ output_error(
220
+ error_code="FILE_NOT_FOUND",
221
+ operation=operation,
222
+ message=f"File not found: {input_path}",
223
+ )
224
+ raise SystemExit(ExitCode.INVALID_ARGS)
225
+
226
+ # Read and preprocess markdown (hard line breaks for Google import)
227
+ original_content = path.read_text(encoding="utf-8")
228
+ markdown_content = self._preprocess_line_breaks(original_content)
229
+
230
+ upload_path = path
231
+ temp_dir = None
232
+ temp_folder_id = None
233
+ diagrams_rendered = 0
234
+
235
+ if render_diagrams:
236
+ blocks = find_diagram_blocks(markdown_content)
237
+ diagrams_rendered = len(blocks)
238
+
239
+ if blocks:
240
+ temp_dir = Path(tempfile.mkdtemp(prefix="gws_diagrams_"))
241
+ markdown_content, temp_folder_id = self._process_diagrams(
242
+ markdown_content, temp_dir, mermaid_theme=mermaid_theme
243
+ )
244
+
245
+ # Write to temp file if content was modified (preprocessing or diagrams)
246
+ if markdown_content != original_content:
247
+ if temp_dir is None:
248
+ temp_dir = Path(tempfile.mkdtemp(prefix="gws_md_"))
249
+ temp_md = temp_dir / "converted.md"
250
+ temp_md.write_text(markdown_content, encoding="utf-8")
251
+ upload_path = temp_md
252
+
253
+ return path, upload_path, temp_dir, temp_folder_id, diagrams_rendered
254
+
255
+ def _cleanup_temp_resources(
256
+ self,
257
+ temp_dir: Path | None,
258
+ temp_folder_id: str | None,
259
+ ) -> None:
260
+ """Clean up temporary local directory and Drive folder.
261
+
262
+ Args:
263
+ temp_dir: Local temporary directory to remove
264
+ temp_folder_id: Drive folder ID to delete
265
+ """
266
+ if temp_dir and temp_dir.exists():
267
+ shutil.rmtree(temp_dir, ignore_errors=True)
268
+ if temp_folder_id:
269
+ self._delete_temp_folder(temp_folder_id)
270
+
271
+ def _resize_document_images(
272
+ self,
273
+ document_id: str,
274
+ max_width_pt: float = 450.0,
275
+ max_height_pt: float = 600.0,
276
+ ) -> int:
277
+ """Resize oversized images in a Google Doc by replacing them.
278
+
279
+ The Docs API doesn't support direct resizing of inline images,
280
+ so we find oversized images, delete them, and re-insert with correct size.
281
+
282
+ Args:
283
+ document_id: The Google Doc ID
284
+ max_width_pt: Maximum width in points (450pt ≈ 6 inches)
285
+ max_height_pt: Maximum height in points (600pt ≈ 8.3 inches)
286
+
287
+ Returns:
288
+ Number of images resized
289
+ """
290
+ # Get document structure
291
+ doc = self.execute(self.docs_service.documents().get(documentId=document_id))
292
+
293
+ # Find inline objects (images) that need resizing
294
+ inline_objects = doc.get("inlineObjects", {})
295
+ if not inline_objects:
296
+ return 0
297
+
298
+ # Collect images that need resizing with their info
299
+ images_to_resize = []
300
+ for obj_id, obj_data in inline_objects.items():
301
+ props = obj_data.get("inlineObjectProperties", {})
302
+ embedded = props.get("embeddedObject", {})
303
+ size = embedded.get("size", {})
304
+
305
+ width = size.get("width", {}).get("magnitude", 0)
306
+ height = size.get("height", {}).get("magnitude", 0)
307
+
308
+ # Check if image exceeds either dimension
309
+ needs_resize = (width > max_width_pt or height > max_height_pt) and width > 0 and height > 0
310
+
311
+ if needs_resize:
312
+ # Get the image URI
313
+ image_props = embedded.get("imageProperties", {})
314
+ content_uri = image_props.get("contentUri", "")
315
+ source_uri = image_props.get("sourceUri", "")
316
+ uri = source_uri or content_uri
317
+
318
+ if uri:
319
+ # Calculate scale factors for both dimensions
320
+ width_scale = max_width_pt / width if width > max_width_pt else 1.0
321
+ height_scale = max_height_pt / height if height > max_height_pt else 1.0
322
+
323
+ # Use the smaller scale to ensure both dimensions fit
324
+ scale = min(width_scale, height_scale)
325
+ new_width = width * scale
326
+ new_height = height * scale
327
+
328
+ images_to_resize.append({
329
+ "object_id": obj_id,
330
+ "uri": uri,
331
+ "new_width": new_width,
332
+ "new_height": new_height,
333
+ })
334
+
335
+ if not images_to_resize:
336
+ return 0
337
+
338
+ # Find positions of these images in the document body
339
+ body = doc.get("body", {}).get("content", [])
340
+ image_positions = {}
341
+
342
+ for element in body:
343
+ if "paragraph" in element:
344
+ para = element["paragraph"]
345
+ for pe in para.get("elements", []):
346
+ if "inlineObjectElement" in pe:
347
+ ioe = pe["inlineObjectElement"]
348
+ obj_id = ioe.get("inlineObjectId")
349
+ if obj_id:
350
+ # Get the start index of this element
351
+ start_index = pe.get("startIndex", 0)
352
+ image_positions[obj_id] = start_index
353
+
354
+ # Process each image - delete and re-insert with new size
355
+ # Process in reverse order to preserve indices
356
+ requests = []
357
+ for img_info in sorted(
358
+ images_to_resize,
359
+ key=lambda x: image_positions.get(x["object_id"], 0),
360
+ reverse=True,
361
+ ):
362
+ obj_id = img_info["object_id"]
363
+ if obj_id not in image_positions:
364
+ continue
365
+
366
+ position = image_positions[obj_id]
367
+
368
+ # Delete the old image
369
+ requests.append({
370
+ "deleteContentRange": {
371
+ "range": {
372
+ "startIndex": position,
373
+ "endIndex": position + 1,
374
+ }
375
+ }
376
+ })
377
+
378
+ # Insert new image with correct size
379
+ requests.append({
380
+ "insertInlineImage": {
381
+ "uri": img_info["uri"],
382
+ "location": {"index": position},
383
+ "objectSize": {
384
+ "width": {"magnitude": img_info["new_width"], "unit": "PT"},
385
+ "height": {"magnitude": img_info["new_height"], "unit": "PT"},
386
+ },
387
+ }
388
+ })
389
+
390
+ if requests:
391
+ self.execute(
392
+ self.docs_service.documents().batchUpdate(
393
+ documentId=document_id,
394
+ body={"requests": requests},
395
+ )
396
+ )
397
+
398
+ return len(images_to_resize)
399
+
400
+ def md_to_doc(
401
+ self,
402
+ input_path: str,
403
+ title: str | None = None,
404
+ folder_id: str | None = None,
405
+ render_diagrams: bool = False,
406
+ mermaid_theme: str = "default",
407
+ pageless: bool = True,
408
+ ) -> dict[str, Any]:
409
+ """Convert Markdown file to Google Doc.
410
+
411
+ Uses Google's native Markdown import (added July 2024).
412
+
413
+ Args:
414
+ input_path: Path to markdown file
415
+ title: Document title (defaults to filename)
416
+ folder_id: Optional folder to create document in
417
+ render_diagrams: If True, render Mermaid/PlantUML diagrams via Kroki
418
+ mermaid_theme: Theme for Mermaid diagrams (default, neutral, dark, forest)
419
+ pageless: If True (default), create document in pageless mode
420
+ """
421
+ temp_dir = None
422
+ temp_folder_id = None
423
+
424
+ try:
425
+ path, upload_path, temp_dir, temp_folder_id, diagrams_rendered = (
426
+ self._prepare_markdown_upload(
427
+ input_path, "convert.md_to_doc", render_diagrams, mermaid_theme
428
+ )
429
+ )
430
+
431
+ doc_title = title or path.stem
432
+
433
+ # Upload markdown file and convert to Google Doc
434
+ file_metadata: dict[str, Any] = {
435
+ "name": doc_title,
436
+ "mimeType": "application/vnd.google-apps.document",
437
+ }
438
+ if folder_id:
439
+ file_metadata["parents"] = [folder_id]
440
+
441
+ media = MediaFileUpload(
442
+ str(upload_path),
443
+ mimetype="text/markdown",
444
+ resumable=True,
445
+ )
446
+
447
+ file = self.execute(
448
+ self.drive_service.files().create(
449
+ body=file_metadata, media_body=media, fields="id,name,webViewLink"
450
+ )
451
+ )
452
+
453
+ # Resize any oversized images to fit the page
454
+ images_resized = self._resize_document_images(file["id"])
455
+
456
+ # Set pageless mode if requested
457
+ if pageless:
458
+ self._set_pageless_mode(file["id"])
459
+
460
+ result = {
461
+ "document_id": file["id"],
462
+ "title": file["name"],
463
+ "web_view_link": file["webViewLink"],
464
+ "source_file": str(path),
465
+ "pageless": pageless,
466
+ }
467
+ if diagrams_rendered > 0:
468
+ result["diagrams_rendered"] = diagrams_rendered
469
+ if images_resized > 0:
470
+ result["images_resized"] = images_resized
471
+
472
+ output_success(operation="convert.md_to_doc", **result)
473
+ return file
474
+
475
+ except HttpError as e:
476
+ output_error(
477
+ error_code="API_ERROR",
478
+ operation="convert.md_to_doc",
479
+ message=f"Drive API error: {e.reason}",
480
+ )
481
+ raise SystemExit(ExitCode.API_ERROR)
482
+ finally:
483
+ self._cleanup_temp_resources(temp_dir, temp_folder_id)
484
+
485
+ def md_to_pdf(
486
+ self,
487
+ input_path: str,
488
+ output_path: str,
489
+ title: str | None = None,
490
+ render_diagrams: bool = False,
491
+ mermaid_theme: str = "default",
492
+ ) -> dict[str, Any]:
493
+ """Convert Markdown to PDF via Google Docs.
494
+
495
+ 1. Upload Markdown as Google Doc (optionally rendering diagrams)
496
+ 2. Export as PDF
497
+ 3. Delete the temporary Doc and diagram images
498
+
499
+ Args:
500
+ input_path: Path to markdown file
501
+ output_path: Path for output PDF file
502
+ title: Temporary doc title
503
+ render_diagrams: If True, render Mermaid/PlantUML diagrams via Kroki
504
+ mermaid_theme: Theme for Mermaid diagrams (default, neutral, dark, forest)
505
+ """
506
+ temp_dir = None
507
+ temp_folder_id = None
508
+
509
+ try:
510
+ path, upload_path, temp_dir, temp_folder_id, diagrams_rendered = (
511
+ self._prepare_markdown_upload(
512
+ input_path, "convert.md_to_pdf", render_diagrams, mermaid_theme
513
+ )
514
+ )
515
+
516
+ doc_title = title or f"_temp_{path.stem}"
517
+
518
+ # Upload as Doc
519
+ file_metadata = {
520
+ "name": doc_title,
521
+ "mimeType": "application/vnd.google-apps.document",
522
+ }
523
+
524
+ media = MediaFileUpload(
525
+ str(upload_path),
526
+ mimetype="text/markdown",
527
+ resumable=True,
528
+ )
529
+
530
+ file = self.execute(
531
+ self.drive_service.files().create(
532
+ body=file_metadata, media_body=media, fields="id"
533
+ )
534
+ )
535
+ doc_id = file["id"]
536
+
537
+ try:
538
+ # Resize any oversized images to fit the page
539
+ self._resize_document_images(doc_id)
540
+
541
+ # Export as PDF
542
+ export_request = self.drive_service.files().export_media(
543
+ fileId=doc_id,
544
+ mimeType="application/pdf",
545
+ )
546
+
547
+ output_file = Path(output_path)
548
+ fh = io.FileIO(str(output_file), "wb")
549
+ downloader = MediaIoBaseDownload(fh, export_request)
550
+
551
+ done = False
552
+ while not done:
553
+ _, done = downloader.next_chunk()
554
+ fh.close()
555
+
556
+ result = {
557
+ "output_path": str(output_file),
558
+ "source_file": str(path),
559
+ "file_size": output_file.stat().st_size,
560
+ }
561
+ if diagrams_rendered > 0:
562
+ result["diagrams_rendered"] = diagrams_rendered
563
+
564
+ output_success(operation="convert.md_to_pdf", **result)
565
+ finally:
566
+ # Delete the temporary doc
567
+ self.execute(self.drive_service.files().delete(fileId=doc_id))
568
+ # Delete Drive temp folder (deletes folder and all diagram images)
569
+ if temp_folder_id:
570
+ self._delete_temp_folder(temp_folder_id)
571
+
572
+ return {"output_path": str(output_file)}
573
+ except HttpError as e:
574
+ output_error(
575
+ error_code="API_ERROR",
576
+ operation="convert.md_to_pdf",
577
+ message=f"Drive API error: {e.reason}",
578
+ )
579
+ raise SystemExit(ExitCode.API_ERROR)
580
+ finally:
581
+ # Cleanup local temp directory only (Drive folder cleaned in inner finally)
582
+ if temp_dir and temp_dir.exists():
583
+ shutil.rmtree(temp_dir, ignore_errors=True)
584
+
585
+ def md_to_slides(
586
+ self,
587
+ input_path: str,
588
+ title: str | None = None,
589
+ folder_id: str | None = None,
590
+ ) -> dict[str, Any]:
591
+ """Convert Markdown to Google Slides.
592
+
593
+ Parsing rules:
594
+ - # Heading → New slide with title
595
+ - ## Subheading → Subtitle
596
+ - Bullet lists → Slide bullet points
597
+ - --- → Slide break
598
+ """
599
+ try:
600
+ path = Path(input_path)
601
+ if not path.exists():
602
+ output_error(
603
+ error_code="FILE_NOT_FOUND",
604
+ operation="convert.md_to_slides",
605
+ message=f"File not found: {input_path}",
606
+ )
607
+ raise SystemExit(ExitCode.INVALID_ARGS)
608
+
609
+ pres_title = title or path.stem
610
+
611
+ # Read markdown content
612
+ content = path.read_text(encoding="utf-8")
613
+ slides_data = self._parse_markdown_to_slides(content)
614
+
615
+ # Create empty presentation
616
+ presentation = self.execute(
617
+ self.slides_service.presentations()
618
+ .create(body={"title": pres_title})
619
+ )
620
+ presentation_id = presentation["presentationId"]
621
+
622
+ try:
623
+ # Move to folder if specified
624
+ if folder_id:
625
+ file = self.execute(
626
+ self.drive_service.files().get(
627
+ fileId=presentation_id, fields="parents"
628
+ )
629
+ )
630
+ previous_parents = ",".join(file.get("parents", []))
631
+
632
+ self.execute(
633
+ self.drive_service.files().update(
634
+ fileId=presentation_id,
635
+ addParents=folder_id,
636
+ removeParents=previous_parents,
637
+ fields="id",
638
+ )
639
+ )
640
+
641
+ # Build slides from parsed content
642
+ requests = self._build_slide_requests(slides_data)
643
+
644
+ if requests:
645
+ self.execute(
646
+ self.slides_service.presentations().batchUpdate(
647
+ presentationId=presentation_id,
648
+ body={"requests": requests},
649
+ )
650
+ )
651
+
652
+ output_success(
653
+ operation="convert.md_to_slides",
654
+ presentation_id=presentation_id,
655
+ title=pres_title,
656
+ slide_count=len(slides_data),
657
+ web_view_link=f"https://docs.google.com/presentation/d/{presentation_id}/edit",
658
+ source_file=str(path),
659
+ )
660
+ return {"presentation_id": presentation_id}
661
+ except Exception:
662
+ # Clean up on error — best-effort delete
663
+ try:
664
+ self.execute(self.drive_service.files().delete(fileId=presentation_id))
665
+ except (HttpError, OSError):
666
+ pass
667
+ raise
668
+
669
+ except HttpError as e:
670
+ output_error(
671
+ error_code="API_ERROR",
672
+ operation="convert.md_to_slides",
673
+ message=f"API error: {e.reason}",
674
+ )
675
+ raise SystemExit(ExitCode.API_ERROR)
676
+
677
+ def _parse_markdown_to_slides(self, content: str) -> list[dict]:
678
+ """Parse markdown into slide structure."""
679
+ slides = []
680
+ current_slide: dict[str, Any] = {"title": "", "subtitle": "", "bullets": []}
681
+
682
+ lines = content.split("\n")
683
+ i = 0
684
+
685
+ while i < len(lines):
686
+ line = lines[i].rstrip()
687
+
688
+ # Slide break
689
+ if line == "---":
690
+ if current_slide["title"] or current_slide["bullets"]:
691
+ slides.append(current_slide)
692
+ current_slide = {"title": "", "subtitle": "", "bullets": []}
693
+ i += 1
694
+ continue
695
+
696
+ # H1 = new slide title
697
+ if line.startswith("# "):
698
+ if current_slide["title"] or current_slide["bullets"]:
699
+ slides.append(current_slide)
700
+ current_slide = {"title": "", "subtitle": "", "bullets": []}
701
+ current_slide["title"] = line[2:].strip()
702
+ i += 1
703
+ continue
704
+
705
+ # H2 = subtitle
706
+ if line.startswith("## "):
707
+ current_slide["subtitle"] = line[3:].strip()
708
+ i += 1
709
+ continue
710
+
711
+ # Bullet points
712
+ if line.startswith("- ") or line.startswith("* "):
713
+ current_slide["bullets"].append(line[2:].strip())
714
+ i += 1
715
+ continue
716
+
717
+ # Numbered list
718
+ match = re.match(r"^\d+\.\s+(.+)$", line)
719
+ if match:
720
+ current_slide["bullets"].append(match.group(1).strip())
721
+ i += 1
722
+ continue
723
+
724
+ i += 1
725
+
726
+ # Don't forget the last slide
727
+ if current_slide["title"] or current_slide["bullets"]:
728
+ slides.append(current_slide)
729
+
730
+ return slides
731
+
732
+ def _build_slide_requests(self, slides_data: list[dict]) -> list[dict]:
733
+ """Build Slides API requests from parsed content."""
734
+ import uuid
735
+ requests = []
736
+
737
+ for i, slide in enumerate(slides_data):
738
+ slide_id = f"slide_{uuid.uuid4().hex[:8]}"
739
+
740
+ # Create slide (skip first one since presentation comes with one)
741
+ if i > 0:
742
+ requests.append({
743
+ "createSlide": {
744
+ "objectId": slide_id,
745
+ "slideLayoutReference": {"predefinedLayout": "BLANK"},
746
+ }
747
+ })
748
+ else:
749
+ # Use the first slide (object id "p")
750
+ slide_id = "p"
751
+
752
+ # Add title text box
753
+ if slide["title"]:
754
+ title_id = f"title_{uuid.uuid4().hex[:8]}"
755
+ requests.extend([
756
+ {
757
+ "createShape": {
758
+ "objectId": title_id,
759
+ "shapeType": "TEXT_BOX",
760
+ "elementProperties": {
761
+ "pageObjectId": slide_id,
762
+ "size": {
763
+ "width": {"magnitude": 600, "unit": "PT"},
764
+ "height": {"magnitude": 50, "unit": "PT"},
765
+ },
766
+ "transform": {
767
+ "scaleX": 1, "scaleY": 1,
768
+ "translateX": 36, "translateY": 30,
769
+ "unit": "PT",
770
+ },
771
+ },
772
+ }
773
+ },
774
+ {
775
+ "insertText": {
776
+ "objectId": title_id,
777
+ "insertionIndex": 0,
778
+ "text": slide["title"],
779
+ }
780
+ },
781
+ {
782
+ "updateTextStyle": {
783
+ "objectId": title_id,
784
+ "style": {
785
+ "bold": True,
786
+ "fontSize": {"magnitude": 32, "unit": "PT"},
787
+ },
788
+ "textRange": {"type": "ALL"},
789
+ "fields": "bold,fontSize",
790
+ }
791
+ },
792
+ ])
793
+
794
+ # Add subtitle if present
795
+ if slide.get("subtitle"):
796
+ subtitle_id = f"subtitle_{uuid.uuid4().hex[:8]}"
797
+ requests.extend([
798
+ {
799
+ "createShape": {
800
+ "objectId": subtitle_id,
801
+ "shapeType": "TEXT_BOX",
802
+ "elementProperties": {
803
+ "pageObjectId": slide_id,
804
+ "size": {
805
+ "width": {"magnitude": 600, "unit": "PT"},
806
+ "height": {"magnitude": 30, "unit": "PT"},
807
+ },
808
+ "transform": {
809
+ "scaleX": 1, "scaleY": 1,
810
+ "translateX": 36, "translateY": 85,
811
+ "unit": "PT",
812
+ },
813
+ },
814
+ }
815
+ },
816
+ {
817
+ "insertText": {
818
+ "objectId": subtitle_id,
819
+ "insertionIndex": 0,
820
+ "text": slide["subtitle"],
821
+ }
822
+ },
823
+ {
824
+ "updateTextStyle": {
825
+ "objectId": subtitle_id,
826
+ "style": {
827
+ "fontSize": {"magnitude": 20, "unit": "PT"},
828
+ },
829
+ "textRange": {"type": "ALL"},
830
+ "fields": "fontSize",
831
+ }
832
+ },
833
+ ])
834
+
835
+ # Add bullets
836
+ if slide["bullets"]:
837
+ body_id = f"body_{uuid.uuid4().hex[:8]}"
838
+ bullet_text = "\n".join(f"• {bullet}" for bullet in slide["bullets"])
839
+ y_offset = 130 if slide.get("subtitle") else 100
840
+
841
+ requests.extend([
842
+ {
843
+ "createShape": {
844
+ "objectId": body_id,
845
+ "shapeType": "TEXT_BOX",
846
+ "elementProperties": {
847
+ "pageObjectId": slide_id,
848
+ "size": {
849
+ "width": {"magnitude": 600, "unit": "PT"},
850
+ "height": {"magnitude": 300, "unit": "PT"},
851
+ },
852
+ "transform": {
853
+ "scaleX": 1, "scaleY": 1,
854
+ "translateX": 36, "translateY": y_offset,
855
+ "unit": "PT",
856
+ },
857
+ },
858
+ }
859
+ },
860
+ {
861
+ "insertText": {
862
+ "objectId": body_id,
863
+ "insertionIndex": 0,
864
+ "text": bullet_text,
865
+ }
866
+ },
867
+ {
868
+ "updateTextStyle": {
869
+ "objectId": body_id,
870
+ "style": {
871
+ "fontSize": {"magnitude": 18, "unit": "PT"},
872
+ },
873
+ "textRange": {"type": "ALL"},
874
+ "fields": "fontSize",
875
+ }
876
+ },
877
+ ])
878
+
879
+ return requests