### Install strip_markdown Library Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Use pip to install the strip_markdown library. This command is typically run in your terminal. ```bash pip install strip_markdown ``` -------------------------------- ### Fail-Fast Validation Example Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Demonstrates the fail-fast validation pattern by checking file existence before conversion. Note that .is_dir() returns False for non-existent paths. ```python if not markdown_fn.is_dir(): # Note: .is_dir() returns False for non-existent paths too raise MarkdownError(...) ``` -------------------------------- ### Basic Usage Example with try-except Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/markdown_error.md Demonstrates how to use a try-except block to catch MarkdownError when calling strip_markdown_file. This is useful for handling potential file I/O or conversion issues gracefully. ```python from pathlib import Path from strip_markdown import strip_markdown_file, MarkdownError try: strip_markdown_file(Path('readme.md'), Path('output.txt')) except MarkdownError as e: print(f'Error during conversion: {e}') # Handle the error appropriately ``` -------------------------------- ### Type-Safe Usage Example Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Shows an example of type-safe usage with `strip_markdown`, demonstrating how a type checker validates the handling of `Optional[str]`. ```python from pathlib import Path from typing import Optional from strip_markdown import strip_markdown, MarkdownError def process_markdown(md_text: str) -> Optional[str]: result: Optional[str] = strip_markdown(md_text) return result # Type checker validates that strip_markdown returns Optional[str] # and that we handle the None case appropriately ``` -------------------------------- ### CLI Error Handling Example Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/cli-reference.md Demonstrates the CLI output when attempting to convert a non-existent markdown file. The tool prints an error message and exits with a non-zero status code. ```bash $ python -m strip_markdown nonexistent.md Error: nonexistent.md does not exist ``` -------------------------------- ### Handle Markdown Conversion Errors Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Provides an example of how to catch and handle potential MarkdownError exceptions that may occur during file conversion. ```python from strip_markdown import strip_markdown_file, MarkdownError try: strip_markdown_file(path, output) except MarkdownError as e: print(f'Error: {e}') ``` -------------------------------- ### Package Initialization Export Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md The __init__.py file uses a wildcard re-export to make all public symbols from the core module available at the package level. ```python from .strip_markdown import * ``` -------------------------------- ### Using Path Objects for File Operations Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Demonstrates creating `Path` objects for input and output files and passing them to `strip_markdown_file`. ```python from pathlib import Path from strip_markdown import strip_markdown_file # Create Path objects for file operations input_path = Path('readme.md') output_path = Path('readme.txt') strip_markdown_file(input_path, output_path) ``` -------------------------------- ### Convert Markdown String and File Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Demonstrates basic usage of the strip_markdown library for converting strings and files. Includes error handling for file operations. ```python from strip_markdown import strip_markdown, strip_markdown_file, MarkdownError # Convert markdown string text = strip_markdown("# Title\n\n**Bold**") # Returns: "Title\n\nBold" # Convert markdown file strip_markdown_file(Path('readme.md'), Path('readme.txt')) # Handle errors try: strip_markdown_file(Path('input.md'), Path('output.txt')) except MarkdownError as e: print(f'Error: {e}') ``` -------------------------------- ### Use strip_markdown CLI Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Illustrates how to use the strip_markdown command-line interface to convert a markdown file to a text file. ```bash python -m strip_markdown readme.md readme.txt ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/cli-reference.md Converts a markdown file to plain text, automatically generating the output filename with a .txt extension. ```bash python -m strip_markdown readme.md # Creates: readme.txt ``` -------------------------------- ### File Path Output with Directory Creation Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Creates parent directories if they don't exist for the output file path, unless the parent is the current directory. ```python elif text_fn.parent != Path('.') and not text_fn.resolve().parent.is_dir(): text_fn.parent.mkdir(parents=True) ``` -------------------------------- ### Batch Convert Multiple Markdown Files Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Shows a pattern for iterating through multiple markdown files in a directory, converting each one, and handling potential errors. ```python from pathlib import Path from strip_markdown import strip_markdown_file, MarkdownError for md_file in Path('docs/').glob('*.md'): try: strip_markdown_file(md_file) except MarkdownError as e: print(f'Failed: {md_file}: {e}') ``` -------------------------------- ### CLI Conversion with Nested Output Directory Creation Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/cli-reference.md Converts a markdown file to plain text, creating any necessary nested directories in the specified output path before saving the file. ```bash python -m strip_markdown readme.md ./text_output/nested/directory/ # Creates: ./text_output/nested/directory/readme.txt ``` -------------------------------- ### Strip Markdown via Command Line Source: https://github.com/d3r3k23/strip_markdown/blob/master/README.md Execute the script from the command line, optionally specifying input and output filenames. If no output filename is provided, it defaults to `.txt`. ```bash $ python -m strip_markdown MD_fn [TXT_fn] ``` -------------------------------- ### Basic Usage of strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/strip_markdown.md Demonstrates the basic usage of the `strip_markdown` function with a sample markdown string. This function is useful for cleaning up markdown text into a readable plain text format. ```python import strip_markdown # Basic usage markdown_text = """# Title ## Section This is a line of text **Bold text** """ result = strip_markdown.strip_markdown(markdown_text) print(result) ``` -------------------------------- ### CLI Conversion to Specific Output Directory Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/cli-reference.md Converts a markdown file to plain text and saves it into a specified output directory, maintaining the original filename with a .txt extension. ```bash python -m strip_markdown readme.md ./output_dir/ # Creates: ./output_dir/readme.txt ``` -------------------------------- ### Convert Markdown File with strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Demonstrates converting a markdown file to plain text using the strip_markdown_file function. Requires importing Path from pathlib. ```python from pathlib import Path import strip_markdown strip_markdown.strip_markdown_file(Path('readme.md')) ``` -------------------------------- ### Specify a directory for output files Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md When converting files, you can specify a directory as the output target. The output file will be named after the input file's stem and placed in the specified directory. ```python from pathlib import Path from strip_markdown import strip_markdown_file # Input: readme.md # Output: text_files/readme.txt strip_markdown_file(Path('readme.md'), Path('text_files/')) # Input: docs/api.md # Output: text_files/api.txt # (only the filename stem is used, not the directory path) strip_markdown_file(Path('docs/api.md'), Path('text_files/')) ``` -------------------------------- ### Basic CLI Conversion Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Convert markdown files to plain text using the command-line interface. Specify input and output file paths, or an output directory for batch conversions. ```bash # readme.md -> readme.txt python -m strip_markdown readme.md # input.md -> output.txt python -m strip_markdown input.md output.txt # docs/readme.md -> output_dir/readme.txt python -m strip_markdown docs/readme.md output_dir/ ``` -------------------------------- ### Directory Output Path Resolution Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Places the output file in a specified directory with the input filename's stem. The parent directory is not created if it's the current directory. ```python elif text_fn.is_dir(): text_fn = Path(text_fn) / markdown_fn.stem.with_suffix('.txt') ``` -------------------------------- ### CLI Conversion to Specific Output File Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/cli-reference.md Converts a markdown file to plain text and saves it to a specified output file path. ```bash python -m strip_markdown input.md output.txt # Creates: output.txt ``` -------------------------------- ### String Conversion Data Flow Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Illustrates the step-by-step process of converting a Markdown string to plain text using markdown.markdown() and BeautifulSoup. ```text markdown string (str) ↓ markdown.markdown() → HTML string ↓ BeautifulSoup(html) → HTML parse tree ↓ .get_text() → plain text ↓ plain text (str) or None ``` -------------------------------- ### Convert Markdown String with strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/README.md Shows how to import and use the strip_markdown function to convert a markdown formatted string to plain text. ```python import strip_markdown text = strip_markdown.strip_markdown("# Title\n**bold**") ``` -------------------------------- ### Run strip_markdown CLI Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/INDEX.md Execute the strip_markdown command-line interface using Python's module execution. This is the primary way to use the tool from the terminal. ```bash python -m strip_markdown ``` -------------------------------- ### Convert Markdown File Tree Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Recursively convert all markdown files within a source directory to a target directory using strip_markdown_file. Includes error handling for individual file conversions. ```python from pathlib import Path from strip_markdown import strip_markdown_file, MarkdownError def convert_markdown_tree(source_dir, target_dir): """Recursively convert all .md files in a directory tree.""" source = Path(source_dir) target = Path(target_dir) for md_file in source.rglob('*.md'): try: strip_markdown_file(md_file, target) except MarkdownError as e: print(f'Warning: Failed to convert {md_file}: {e}') # Convert docs/content -> output/text convert_markdown_tree('docs/content', 'output/text') ``` -------------------------------- ### Default Output Path Resolution Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md When no output path is specified, this code changes the file extension from .md to .txt, keeping the same directory. ```python if text_fn is None: text_fn = markdown_fn.with_suffix('.txt') ``` -------------------------------- ### Public Symbol Equivalence Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Demonstrates equivalent import statements for accessing public symbols from the strip_markdown package. ```python # These are equivalent: from strip_markdown.strip_markdown import strip_markdown from strip_markdown import strip_markdown ``` -------------------------------- ### Optional Type Usage Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Illustrates the usage of `Optional[str]` to handle cases where a function might return a string or `None`. ```python # Optional[str] means: str or None result: Optional[str] = strip_markdown(md) if result is not None: # result is definitely a str here text = result else: # conversion failed pass ``` -------------------------------- ### Internal Function Type Hints Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Provides type hints for internal library functions, `_read_file` and `_write_file`, indicating their parameters and return types. ```python def _read_file(filename: Path) -> Optional[str]: # Returns file content (str) or None on I/O error ... def _write_file(filename: Path, text: str) -> bool: # Returns True on success, False on I/O error ... ``` -------------------------------- ### Import Path from pathlib Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Imports the `Path` object from the `pathlib` module, used for representing filesystem paths. ```python from pathlib import Path ``` -------------------------------- ### Auto-generate output paths for file conversion Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md When no output path is specified, `strip_markdown_file` automatically generates a `.txt` file with the same name and in the same directory as the input markdown file. ```python from pathlib import Path from strip_markdown import strip_markdown_file # Input: docs/readme.md # Output: docs/readme.txt strip_markdown_file(Path('docs/readme.md')) # Input: documentation.md # Output: documentation.txt strip_markdown_file(Path('documentation.md')) ``` -------------------------------- ### Convert Markdown to Text and Handle Conversion Errors Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Converts markdown source to plain text and raises a MarkdownError if the conversion fails. Conversion failures result in descriptive error messages. ```python text = strip_markdown(markdown_src) if text is None: raise MarkdownError(f'Could not convert to text') ``` -------------------------------- ### Store Plain Text Version in Database Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Convert markdown content to plain text using strip_markdown and store it in a database. Handles cases where plain text extraction fails. ```python from strip_markdown import strip_markdown def store_plaintext_version(markdown_doc, db): """Store both markdown and plain text versions in database.""" plain_text = strip_markdown(markdown_doc['content']) if plain_text is None: print(f"Warning: Could not extract plain text from {markdown_doc['id']}") return False # Store converted text db.store_text(markdown_doc['id'], plain_text) return True ``` -------------------------------- ### CLI Usage for strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/INDEX.md Convert markdown to plain text using the command-line interface. The first argument is the input markdown file, and the optional second argument is the output text file. ```bash python -m strip_markdown MD_FN [TXT_FN] ``` -------------------------------- ### strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Converts a markdown-formatted string to plain text. Returns None if the conversion fails. ```APIDOC ## strip_markdown(md: str) -> Optional[str] ### Description Converts a markdown-formatted string to plain text by removing all formatting, syntax, and markup. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **md** (str) - Required - The markdown-formatted string to convert. ### Response #### Success Response (200) - **Optional[str]** - The plain text string with markdown formatting removed, or None if conversion fails. ### Request Example ```python from strip_markdown import strip_markdown markdown_text = "# Hello, **World**!\nThis is *italic* text." plain_text = strip_markdown(markdown_text) print(plain_text) ``` ### Response Example ``` Hello, World! This is italic text. ``` ``` -------------------------------- ### File Conversion Data Flow Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Outlines the data flow for converting a Markdown file to plain text, including file reading, processing, and writing. ```text input file path (Path) ↓ _read_file() → markdown content (str) or None ↓ strip_markdown() → plain text (str) or None ↓ [resolve output path] ↓ [create parent directories if needed] ↓ _write_file() → success (bool) ↓ return None or raise MarkdownError ``` -------------------------------- ### Handle None return from strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md When converting markdown strings, always check if the result is `None` to handle potential conversion failures gracefully. ```python from strip_markdown import strip_markdown result = strip_markdown(markdown_text) if result is not None: # Process the plain text print(result) else: # Handle conversion failure print('Conversion failed') ``` -------------------------------- ### strip_markdown_file() Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Strips markdown formatting from a file and writes the plain text to another file. It takes the input markdown file path and an optional output text file path. ```APIDOC ## strip_markdown_file() ### Description Strips markdown formatting from a file and writes the plain text to another file. It takes the input markdown file path and an optional output text file path. ### Method `def` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **markdown_fn** (`Path`) - File path object from `pathlib.Path` - **text_fn** (`Optional[Path]`) - File path object or `None` for auto-naming ### Response #### Success Response - **Return type**: `None` — No return value; writes file as side effect ### Request Example ```python from pathlib import Path from strip_markdown import strip_markdown_file input_path = Path('my_document.md') output_path = Path('my_document.txt') # Assuming 'my_document.md' exists and contains markdown strip_markdown_file(input_path, output_path) # If output_path is None, a name will be auto-generated # strip_markdown_file(input_path) ``` ### Response Example ```json { "example": "Success: File processed and written." } ``` ``` -------------------------------- ### Catching MarkdownError Exceptions Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/errors.md Demonstrates how to catch and handle specific MarkdownError exceptions raised during file processing. It checks the error message to determine the type of failure and prints a user-friendly message. ```python from pathlib import Path from strip_markdown import strip_markdown_file, MarkdownError try: strip_markdown_file(Path('input.md'), Path('output.txt')) except MarkdownError as e: error_message = str(e) # Handle specific error cases if 'does not exist' in error_message: print('Input file not found') elif 'Could not load' in error_message: print('File read error (permissions?)') elif 'Could not convert' in error_message: print('Markdown conversion failed') ``` -------------------------------- ### Validate File Existence Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Checks if the provided markdown file path exists before proceeding. This fails fast to prevent unnecessary operations. ```python if not markdown_fn.is_dir(): raise MarkdownError(f'{markdown_fn} does not exist') ``` -------------------------------- ### strip_markdown_file Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Converts a markdown file to a plain text file. Supports automatic output path generation and directory specification. ```APIDOC ## strip_markdown_file(markdown_fn: Path, text_fn: Optional[Path]=None) ### Description Reads a markdown file from disk, converts its content to plain text, and writes the result to a specified text file or a file with an auto-generated name. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **markdown_fn** (Path) - Required - The path to the input markdown file. * **text_fn** (Optional[Path]) - Optional - The path to the output text file, a directory to save the output file in, or None to auto-generate the output path. ### Response #### Success Response (200) This function does not return a value upon success. It raises `MarkdownError` on failure. ### Request Example ```python from pathlib import Path from strip_markdown import strip_markdown_file # Example 1: Specify output file path markdown_file = Path("input.md") text_file = Path("output.txt") # Assume input.md exists # strip_markdown_file(markdown_file, text_file) # Example 2: Specify output directory output_dir = Path("output_directory") # Assume input.md exists # strip_markdown_file(markdown_file, output_dir) # Example 3: Auto-generate output path # Assume input.md exists # strip_markdown_file(markdown_file) ``` ### Error Handling Raises `MarkdownError` on any file I/O or conversion failures. ``` -------------------------------- ### Import Public Symbols from strip_markdown Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Import the main functions and exception class directly from the strip_markdown package. These are re-exported at the package level for easy access. ```python from strip_markdown import strip_markdown, strip_markdown_file, MarkdownError ``` -------------------------------- ### Strip Markdown from File Source: https://github.com/d3r3k23/strip_markdown/blob/master/README.md Use `strip_markdown_file` to convert a markdown file to a text file. The output filename defaults to the input filename with a .txt extension. If an output directory is specified, the .txt file will be placed there. ```python >>> strip_markdown.strip_markdown_file(MD_fn: Path, TXT_fn: Optional[Path]) ``` -------------------------------- ### Custom Markdown Conversion Function Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Provides an alternative way to convert markdown to text by allowing a custom HTML generator function. This function takes markdown input and an optional HTML generator, returning the extracted text. ```python def strip_markdown_custom(md: str, html_generator=None) -> Optional[str]: html = (html_generator or markdown.markdown)(md) soup = BeautifulSoup(html, features='html.parser') return soup.get_text() ``` -------------------------------- ### MarkdownError Exception Details Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/markdown_error.md Details about the MarkdownError exception, including its class signature, inheritance, and conditions under which it is raised. ```APIDOC ## MarkdownError Exception ### Overview `MarkdownError` is the custom exception raised by the strip_markdown library for all conversion and file operation failures. ### Class Signature ```python class MarkdownError(Exception): pass ``` ### Inheritance - Parent class: `Exception` (Python built-in) - Can be caught with standard exception handling ### Error Conditions | Condition | |-----------| | Input markdown file does not exist | | Markdown file cannot be read | | Markdown-to-text conversion fails | ### When Raised - `strip_markdown_file()` raises `MarkdownError` when: - The input markdown file path does not exist or is not accessible - The markdown file cannot be read due to I/O errors - The markdown-to-text conversion process fails - `strip_markdown()` function (string conversion) does not raise `MarkdownError`; it returns `None` on failure ### Usage Example ```python from pathlib import Path from strip_markdown import strip_markdown_file, MarkdownError try: strip_markdown_file(Path('readme.md'), Path('output.txt')) except MarkdownError as e: print(f'Error during conversion: {e}') # Handle the error appropriately ``` ### Exception Handling Pattern ```python from strip_markdown import strip_markdown_file, MarkdownError def safe_convert_markdown(input_path, output_path): try: strip_markdown_file(input_path, output_path) return True except MarkdownError as e: print(f'Conversion error: {e}') return False ``` ``` -------------------------------- ### Convert Markdown File to Text Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/strip_markdown_file.md Use this function to convert a markdown file to plain text. If no output path is provided, the output file will have the same name as the input file but with a .txt extension. ```python from pathlib import Path import strip_markdown # Convert with auto-generated output path (test.md -> test.txt) strip_markdown.strip_markdown_file(Path('test.md')) ``` ```python # Convert to specific file path strip_markdown.strip_markdown_file( Path('readme.md'), Path('output.txt') ) ``` ```python # Convert to specific directory strip_markdown.strip_markdown_file( Path('readme.md'), Path('output_texts/') ) ``` -------------------------------- ### Convert Markdown File to Text File Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md This function is for batch file processing and disk I/O. It reads a markdown file, converts its content to plain text, and writes the result to a specified output file or a generated path. Raises MarkdownError on any failure. ```python def strip_markdown_file(markdown_fn: Path, text_fn: Optional[Path]=None): # Convert markdown file to text file pass ``` -------------------------------- ### Write Text to File Safely Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/internal-functions.md Writes text content to a file, overwriting existing content. Returns True on success and False if the file cannot be written due to any I/O error, such as permission denied or disk full. This function suppresses exceptions. ```python def _write_file(filename: Path, text: str) -> bool: # Opens file in write mode ('w'), overwriting any existing file # Catches OSError and IOError exceptions # Returns True on success, False on any I/O error # Does not handle specific error types differently # Creates the file if it does not exist pass # Internal use in strip_markdown_file(): _write_file(text_fn, text) # If parent directories don't exist, this must be called after mkdir() ``` -------------------------------- ### strip_markdown Function Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/strip_markdown.md Converts markdown-formatted text to plain text by parsing the markdown to HTML and extracting the text content, removing all formatting. ```APIDOC ## strip_markdown(md: str) -> Optional[str] ### Description Converts markdown-formatted text to plain text by parsing the markdown to HTML and extracting the text content, removing all formatting. ### Parameters #### Path Parameters - **md** (str) - Required - Markdown-formatted text to convert ### Return Type `Optional[str]` - Plain text with all markdown formatting removed, or `None` if conversion fails ### Usage Example ```python import strip_markdown markdown_text = """# Title ## Section This is a line of text **Bold text** """ result = strip_markdown.strip_markdown(markdown_text) print(result) # Output: # Title # Section # This is a line of text # Bold text ``` ``` -------------------------------- ### Error Handling in Shell Scripts Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Integrate markdown conversion into shell scripts to check for success or failure using exit codes. ```bash #!/bin/bash if python -m strip_markdown readme.md; then echo "Conversion succeeded" else echo "Conversion failed with exit code $?" fi ``` -------------------------------- ### strip_markdown_file Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/strip_markdown_file.md Converts a markdown file on disk to plain text. It handles automatic or explicit output path specification and creates parent directories if needed. The function raises MarkdownError for various file or conversion issues. ```APIDOC ## strip_markdown_file Function ### Description Converts a markdown file on disk to plain text, with automatic or explicit output path specification. ### Function Signature ```python def strip_markdown_file(markdown_fn: Path, text_fn: Optional[Path]=None): ``` ### Parameters #### Path Parameters - **markdown_fn** (Path) - Required - Path to the markdown input file - **text_fn** (Optional[Path]) - Optional - Output path for the text file. If None, uses `.txt`. If a directory, places output as `.txt` in that directory ### Return Type `None` — Writes output file as a side effect ### Raises - **MarkdownError** - Markdown file does not exist - **MarkdownError** - Markdown file cannot be read (I/O error) - **MarkdownError** - Markdown-to-text conversion fails ### Description Processes a markdown file by reading it, converting content using `strip_markdown()`, and writing the plain text result to the specified output path. Parent directories are created if needed. ### Output Path Resolution - If `text_fn` is `None`: Output filename is the input filename with `.txt` extension (e.g., `input.md` → `input.txt`). - If `text_fn` is a directory: Output file is placed in that directory with the input filename's stem and `.txt` extension. - If `text_fn` is a file path with non-existent parent directories: Parent directories are created automatically. - If `text_fn` is the current directory (`.`): Treated as a literal path, not a directory context. ### Usage Example ```python from pathlib import Path import strip_markdown # Convert with auto-generated output path (test.md -> test.txt) strip_markdown.strip_markdown_file(Path('test.md')) # Convert to specific file path strip_markdown.strip_markdown_file( Path('readme.md'), Path('output.txt') ) # Convert to specific directory strip_markdown.strip_markdown_file( Path('readme.md'), Path('output_texts/') ) # Handle errors from strip_markdown import MarkdownError try: strip_markdown.strip_markdown_file(Path('input.md'), Path('output.txt')) except MarkdownError as e: print(f'Conversion failed: {e}') ``` ### Behavior - The input file must exist and be readable; raises `MarkdownError` if not. - Output directories are created automatically if they don't exist. - Overwrites the output file if it already exists. - Returns normally if conversion succeeds. - Raises `MarkdownError` for all failure conditions. ``` -------------------------------- ### Convert a markdown file to plain text Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Use `strip_markdown_file` to convert a markdown file to plain text. You can specify an output file or directory. ```python from pathlib import Path from strip_markdown import strip_markdown_file # Convert readme.md to readme.txt strip_markdown_file(Path('readme.md')) # Convert to a specific output file strip_markdown_file(Path('readme.md'), Path('output.txt')) # Convert to a specific output directory strip_markdown_file(Path('readme.md'), Path('output_dir/')) ``` -------------------------------- ### Read File and Handle I/O Errors Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/architecture.md Reads the content of a markdown file and converts potential I/O errors into a MarkdownError. File read/write errors are suppressed at the I/O layer. ```python markdown_src = _read_file(markdown_fn) if markdown_src is None: raise MarkdownError(f'Could not load {markdown_fn}') ``` -------------------------------- ### Convert Markdown String to Plain Text Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Use this function for in-memory text processing. It takes a markdown-formatted string and returns a plain text string with all formatting removed. Returns None if conversion fails. ```python def strip_markdown(md: str) -> Optional[str]: # Convert markdown text string to plain text pass ``` -------------------------------- ### Safe Markdown Conversion Function Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/markdown_error.md Provides a reusable function 'safe_convert_markdown' that wraps the strip_markdown_file call within a try-except block to handle MarkdownError, returning a boolean indicating success or failure. ```python from strip_markdown import strip_markdown_file, MarkdownError def safe_convert_markdown(input_path, output_path): try: strip_markdown_file(input_path, output_path) return True except MarkdownError as e: print(f'Conversion error: {e}') return False ``` -------------------------------- ### strip_markdown() Function Signature Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Defines the signature for the `strip_markdown` function, indicating it accepts a string and returns an optional string. ```python def strip_markdown(md: str) -> Optional[str]: ``` -------------------------------- ### strip_markdown_file() Function Signature Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/types.md Defines the signature for the `strip_markdown_file` function, which takes a Path object for the markdown file and an optional Path object for the text file. ```python def strip_markdown_file(markdown_fn: Path, text_fn: Optional[Path]=None): ``` -------------------------------- ### MarkdownError Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Custom exception class for handling errors during markdown conversion or file operations. ```APIDOC ## MarkdownError ### Description A custom exception class that subclasses Python's built-in `Exception`. It is used to signal and handle errors that occur during markdown file processing or text conversion. ### Usage This exception is raised by the `strip_markdown_file()` function when any file I/O or conversion process fails. It is not raised by the `strip_markdown()` function, which returns `None` on failure. ### Example ```python from strip_markdown import strip_markdown_file, MarkdownError from pathlib import Path try: strip_markdown_file(Path("non_existent_file.md")) except MarkdownError as e: print(f"An error occurred: {e}") ``` ``` -------------------------------- ### Read File Content Safely Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/internal-functions.md Reads the complete content of a text file. Returns None if the file cannot be read due to any I/O error, such as file not found or permission denied. This function suppresses exceptions. ```python def _read_file(filename: Path) -> Optional[str]: # Opens file in read mode ('r') # Catches OSError and IOError exceptions # Returns None for any I/O error condition # Does not handle specific error types differently pass # Internal use in strip_markdown_file(): markdown_src = _read_file(markdown_fn) if markdown_src is None: raise MarkdownError(f'Could not load {markdown_fn}') ``` -------------------------------- ### Internal Function to Write File Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Internal utility function for writing text content to a file. It returns True on successful write and False if an I/O error occurs. This function is not part of the public API. ```python def _write_file(filename: Path, text: str) -> bool: # Write file content, return False on I/O error pass ``` -------------------------------- ### Convert a markdown string to plain text Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Use the `strip_markdown` function to convert a markdown formatted string into plain text. Ensure the markdown string is correctly formatted. ```python from strip_markdown import strip_markdown markdown_text = """# Hello World This is **bold** and this is *italic*. - List item 1 - List item 2 """ plain_text = strip_markdown(markdown_text) print(plain_text) ``` -------------------------------- ### Internal Function to Read File Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md Internal utility function for reading file content. It returns the file's content as a string or None if an I/O error occurs. This function is not part of the public API. ```python def _read_file(filename: Path) -> Optional[str]: # Read file content, return None on I/O error pass ``` -------------------------------- ### Extract Plain Text from Markdown Content Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/usage-guide.md Use the strip_markdown function to extract plain text from markdown content within Python. Handles cases where conversion might return None. ```python from strip_markdown import strip_markdown def extract_markdown_text(markdown_content): """Extract plain text from markdown for indexing/analysis.""" plain_text = strip_markdown(markdown_content) if plain_text is None: return "" return plain_text.strip() # Use in a processing pipeline text_content = extract_markdown_text(readme_markdown) words = text_content.split() word_count = len(words) ``` -------------------------------- ### MarkdownError Class Definition Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/api-reference/markdown_error.md Defines the custom MarkdownError exception class, inheriting from Python's built-in Exception. ```python class MarkdownError(Exception): pass ``` -------------------------------- ### Custom Exception for Failures Source: https://github.com/d3r3k23/strip_markdown/blob/master/_autodocs/module-overview.md MarkdownError is a custom exception class that subclasses Python's Exception. It is raised by strip_markdown_file() for file I/O and conversion errors, but not by strip_markdown() which returns None instead. ```python class MarkdownError(Exception): # Custom exception for all conversion and file operation failures pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.