Transform %pip install commands using regex for efficiency.
(markdown_content)
| 56 | |
| 57 | |
| 58 | def process_pip_installations(markdown_content): |
| 59 | """Transform %pip install commands using regex for efficiency.""" |
| 60 | # Extract all packages from pip install commands |
| 61 | packages = [] |
| 62 | for match in re.finditer(r"%pip install\s+([^\n#]+)", markdown_content): |
| 63 | packages.extend(match.group(1).strip().split()) |
| 64 | |
| 65 | if not packages: |
| 66 | return markdown_content |
| 67 | |
| 68 | # Deduplicate packages |
| 69 | unique_packages = " ".join(sorted(set(packages))) |
| 70 | |
| 71 | # Remove code blocks containing pip installs |
| 72 | content = re.sub(r"```python\n(?:[^`])*?%pip install[^\n]*\n(?:[^`])*?```\n?", "", markdown_content) |
| 73 | |
| 74 | # Find insertion point for installation section |
| 75 | first_pip_pos = markdown_content.find("%pip install") |
| 76 | if first_pip_pos == -1: |
| 77 | return markdown_content |
| 78 | |
| 79 | # Calculate line position and insert installation section |
| 80 | line_pos = markdown_content[:first_pip_pos].count("\n") |
| 81 | lines = content.split("\n") |
| 82 | |
| 83 | installation_section = f"""## Installation |
| 84 | <CodeGroup> |
| 85 | ```bash pip |
| 86 | pip install {unique_packages} |
| 87 | ``` |
| 88 | ```bash poetry |
| 89 | poetry add {unique_packages} |
| 90 | ``` |
| 91 | ```bash uv |
| 92 | uv add {unique_packages} |
| 93 | ``` |
| 94 | </CodeGroup> |
| 95 | """ |
| 96 | |
| 97 | lines.insert(line_pos, installation_section) |
| 98 | return "\n".join(lines) |
| 99 | |
| 100 | |
| 101 | def get_existing_frontmatter(mdx_path): |