Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Standardize parse module: Add methods.py, registry.py, config.py, update __init__.py, and create parse_usage.md

KaifAhmad16c73c59dd29b
diff --git a/semantica/parse/__init__.py b/semantica/parse/__init__.py
index b2270b1e..136e5e82 100644
--- a/semantica/parse/__init__.py
+++ b/semantica/parse/__init__.py
@@ -5,35 +5,109 @@ This module provides comprehensive data parsing capabilities for various file fo
enabling extraction of text, metadata, and structured data from documents, web content,
emails, code files, and media files.
+Algorithms Used:
+
+Document Parsing:
+ - PDF Parsing: pdfplumber integration (pdfplumber.PDF()) for text extraction, PyPDF2.PdfReader() fallback, table extraction (pdfplumber.extract_tables()), image extraction, metadata extraction (title, author, dates via pdf.metadata), page-level processing (page iteration)
+ - DOCX Parsing: python-docx integration (docx.Document()), paragraph extraction (document.paragraphs), table extraction (docx.table.Table), section/heading detection (paragraph.style), metadata extraction (core_properties), formatting extraction
+ - PPTX Parsing: python-pptx integration (pptx.Presentation()), slide extraction (presentation.slides), shape extraction, notes extraction, metadata extraction
+ - Excel Parsing: openpyxl integration (openpyxl.load_workbook()), pandas integration (pandas.read_excel()), sheet iteration, cell value extraction, formula extraction, metadata extraction
+ - HTML Parsing: BeautifulSoup integration (BeautifulSoup(html, 'html.parser')), text extraction (soup.get_text()), link extraction (find_all('a')), metadata extraction (meta tags), structure analysis
+ - Text Parsing: Plain text file reading (open().read()), encoding detection, line-by-line processing
+
+Web Content Parsing:
+ - HTML Parsing: BeautifulSoup integration, content cleaning (soup.get_text(separator=' ', strip=True)), link extraction (find_all('a', href=True)), media extraction (find_all('img', 'video', 'audio')), JavaScript rendering support (Selenium WebDriver, Playwright)
+ - XML Parsing: xml.etree.ElementTree integration (ElementTree.parse()), lxml integration (lxml.etree.parse()), element traversal (iter(), findall()), attribute extraction (element.attrib), namespace handling, XPath support
+ - JavaScript Rendering: Selenium WebDriver integration (webdriver.Chrome()), Playwright integration, headless browser rendering, dynamic content extraction (driver.page_source)
+
+Structured Data Parsing:
+ - JSON Parsing: json.load()/json.loads() integration, nested structure handling (recursive traversal), JSON path extraction, structure flattening, type validation
+ - CSV Parsing: csv.reader()/csv.DictReader() integration, delimiter detection (csv.Sniffer()), header detection, encoding handling, type conversion
+ - XML Parsing: xml.etree.ElementTree integration, lxml integration, element traversal (iter(), findall()), attribute extraction, namespace handling, XPath support
+ - YAML Parsing: yaml.safe_load() integration, nested structure handling, type preservation
+
+Email Parsing:
+ - MIME Parsing: email.message_from_string()/message_from_bytes() integration, multipart message handling (message.is_multipart()), header decoding (email.header.decode_header()), attachment extraction (message.get_payload())
+ - Header Parsing: From/To/CC/BCC extraction (message.get('From')), Subject decoding, Date parsing (email.utils.parsedate_to_datetime), Message-ID extraction
+ - Body Extraction: Plain text extraction (message.get_payload(decode=True)), HTML body extraction, multipart alternative handling
+ - Thread Analysis: In-Reply-To tracking (message.get('In-Reply-To')), References header analysis (message.get('References')), conversation threading
+
+Code Parsing:
+ - AST Parsing: ast.parse() integration (Python), syntax tree traversal (ast.walk()), function/class extraction (ast.FunctionDef, ast.ClassDef), import statement parsing (ast.Import, ast.ImportFrom)
+ - Comment Extraction: Regex-based comment detection (# for Python, // for JavaScript, /* */ for C-style), docstring extraction (ast.get_docstring()), inline/block comment distinction
+ - Dependency Analysis: Import statement parsing, dependency graph construction, cross-file dependency tracking
+ - Multi-Language Support: Language-specific parsers (Python, JavaScript, Java, etc.), syntax tree analysis per language
+
+Media Parsing:
+ - Image Parsing: PIL/Pillow integration (PIL.Image.open()), EXIF data extraction (PIL.ExifTags), metadata extraction (image.format, image.size, image.mode), image analysis
+ - OCR Processing: Tesseract OCR integration (pytesseract.image_to_string()), text extraction from images, confidence scoring (pytesseract.image_to_data()), language support, bounding box extraction
+ - Audio/Video Parsing: Metadata extraction (format, duration, codec), file information extraction (future support)
+
+Format-Specific Parsers:
+ - PDFParser: pdfplumber.PDF() for text/tables, PyPDF2.PdfReader() fallback, page iteration (pdf.pages), metadata extraction
+ - DOCXParser: docx.Document() for document loading, paragraph iteration, table extraction, core_properties access
+ - PPTXParser: pptx.Presentation() for presentation loading, slide iteration, shape extraction
+ - ExcelParser: openpyxl.load_workbook() for workbook loading, pandas.read_excel() for data extraction, sheet iteration
+ - HTMLParser: BeautifulSoup() for HTML parsing, element traversal, metadata extraction
+ - JSONParser: json.load()/json.loads(), recursive structure traversal, path extraction
+ - CSVParser: csv.DictReader() for row-by-row processing, delimiter detection, header handling
+ - XMLParser: xml.etree.ElementTree.parse(), lxml.etree.parse(), element iteration, attribute access
+ - ImageParser: PIL.Image.open(), EXIF extraction, pytesseract.image_to_string() for OCR
+
Key Features:
- Document format parsing (PDF, DOCX, PPTX, HTML, TXT)
- Web content parsing (HTML, XML, JavaScript-rendered content)
- Structured data parsing (JSON, CSV, XML, YAML)
- Email content parsing (headers, body, attachments, threads)
- Source code parsing (multi-language, syntax trees, dependencies)
- - Media content parsing (images, audio, video metadata)
+ - Media content parsing (images with OCR, audio, video metadata)
- Batch processing support
- Metadata extraction
- Content structure analysis
+ - Method registry for custom parsing methods
+ - Configuration management via environment variables and config files
Main Classes:
- - DocumentParser: Document format parsing (PDF, DOCX, etc.)
- - WebParser: Web content parsing (HTML, XML, etc.)
- - StructuredDataParser: Structured data parsing (JSON, CSV, etc.)
- - EmailParser: Email content parsing
- - CodeParser: Source code parsing
- - MediaParser: Media content parsing
- - PDFParser: PDF document parser
- - DOCXParser: Word document parser
- - PPTXParser: PowerPoint parser
- - ExcelParser: Excel spreadsheet parser
- - HTMLParser: HTML document parser
- - JSONParser: JSON data parser
- - CSVParser: CSV data parser
- - XMLParser: XML document parser
- - ImageParser: Image file parser with OCR
+ - DocumentParser: Document format parsing (PDF, DOCX, PPTX, HTML, TXT)
+ - WebParser: Web content parsing (HTML, XML, JavaScript-rendered)
+ - StructuredDataParser: Structured data parsing (JSON, CSV, XML, YAML)
+ - EmailParser: Email content parsing (headers, body, attachments, threads)
+ - CodeParser: Source code parsing (multi-language, AST, comments, dependencies)
+ - MediaParser: Media content parsing (images, audio, video)
+ - PDFParser: PDF document parser with text, table, and image extraction
+ - DOCXParser: Word document parser with structure and metadata extraction
+ - PPTXParser: PowerPoint parser with slide and notes extraction
+ - ExcelParser: Excel spreadsheet parser with multi-sheet support
+ - HTMLParser: HTML document parser with metadata and link extraction
+ - JSONParser: JSON data parser with nested structure handling
+ - CSVParser: CSV data parser with delimiter detection and type conversion
+ - XMLParser: XML document parser with namespace and XPath support
+ - ImageParser: Image file parser with OCR and metadata extraction
+ - MethodRegistry: Registry for custom parsing methods
+ - ParseConfig: Configuration manager for parsing operations
+
+Convenience Functions:
+ - parse_document: Parse any document format (PDF, DOCX, HTML, TXT)
+ - parse_web_content: Parse web content (HTML, XML, JavaScript-rendered)
+ - parse_structured_data: Parse structured data (JSON, CSV, XML, YAML)
+ - parse_email: Parse email messages (headers, body, attachments)
+ - parse_code: Parse source code files (multi-language, AST, comments)
+ - parse_media: Parse media files (images with OCR, audio, video)
+ - parse_pdf: Parse PDF documents
+ - parse_docx: Parse DOCX documents
+ - parse_json: Parse JSON files
+ - parse_csv: Parse CSV files
+ - parse_xml: Parse XML files
+ - parse_image: Parse image files with OCR
+ - get_parse_method: Get parsing method by task and name
+ - list_available_methods: List registered parsing methods
Example Usage:
+ >>> from semantica.parse import parse_document, parse_web_content, parse_json
+ >>> doc = parse_document("document.pdf", method="default")
+ >>> web = parse_web_content("https://example.com", method="default")
+ >>> data = parse_json("data.json", method="default")
+
>>> from semantica.parse import DocumentParser, WebParser, StructuredDataParser
>>> doc_parser = DocumentParser()
>>> text = doc_parser.parse_document("document.pdf")
@@ -61,6 +135,24 @@ from .json_parser import JSONParser, JSONData
from .csv_parser import CSVParser, CSVData
from .xml_parser import XMLParser, XMLElement, XMLData
from .image_parser import ImageParser, ImageMetadata, OCRResult
+from .methods import (
+ parse_document,
+ parse_web_content,
+ parse_structured_data,
+ parse_email,
+ parse_code,
+ parse_media,
+ parse_pdf,
+ parse_docx,
+ parse_json,
+ parse_csv,
+ parse_xml,
+ parse_image,
+ get_parse_method,
+ list_available_methods,
+)
+from .registry import method_registry, MethodRegistry
+from .config import parse_config, ParseConfig
__all__ = [
# Main parsers
@@ -108,4 +200,24 @@ __all__ = [
"ImageParser",
"ImageMetadata",
"OCRResult",
+ # Registry and config
+ "MethodRegistry",
+ "method_registry",
+ "ParseConfig",
+ "parse_config",
+ # Convenience functions
+ "parse_document",
+ "parse_web_content",
+ "parse_structured_data",
+ "parse_email",
+ "parse_code",
+ "parse_media",
+ "parse_pdf",
+ "parse_docx",
+ "parse_json",
+ "parse_csv",
+ "parse_xml",
+ "parse_image",
+ "get_parse_method",
+ "list_available_methods",
]
diff --git a/semantica/parse/config.py b/semantica/parse/config.py
new file mode 100644
index 00000000..e4c308ab
--- /dev/null
+++ b/semantica/parse/config.py
@@ -0,0 +1,161 @@
+"""
+Configuration Management Module for Parse
+
+This module provides centralized configuration management for data parsing operations,
+supporting multiple configuration sources including environment variables, config files,
+and programmatic configuration.
+
+Supported Configuration Sources:
+ - Environment variables: PARSE_DEFAULT_ENCODING, PARSE_OCR_LANGUAGE, PARSE_EXTRACT_TABLES, etc.
+ - Config files: YAML, JSON, TOML formats
+ - Programmatic: Python API for setting parsing configurations
+
+Algorithms Used:
+ - Environment Variable Parsing: OS-level environment variable access
+ - YAML Parsing: YAML parser for configuration file loading
+ - JSON Parsing: JSON parser for configuration file loading
+ - TOML Parsing: TOML parser for configuration file loading
+ - Fallback Chain: Priority-based configuration resolution
+ - Dictionary Merging: Deep merge algorithms for configuration updates
+
+Key Features:
+ - Environment variable support for parsing parameters
+ - Config file support (YAML, JSON, TOML formats)
+ - Programmatic configuration via Python API
+ - Method-specific configuration management
+ - Automatic fallback chain (config file -> environment -> defaults)
+ - Global config instance for easy access
+
+Main Classes:
+ - ParseConfig: Main configuration manager class for parse module
+
+Example Usage:
+ >>> from semantica.parse.config import parse_config
+ >>> encoding = parse_config.get("default_encoding", default="utf-8")
+ >>> parse_config.set("default_encoding", "utf-8")
+ >>> method_config = parse_config.get_method_config("document")
+"""
+
+import os
+from typing import Optional, Dict, Any
+from pathlib import Path
+
+from ..utils.logging import get_logger
+
+
+class ParseConfig:
+ """Configuration manager for parse module - supports .env files, environment variables, and programmatic config."""
+
+ def __init__(self, config_file: Optional[str] = None):
+ self.logger = get_logger("parse_config")
+ self._configs: Dict[str, Any] = {}
+ self._method_configs: Dict[str, Dict] = {}
+ self._load_config_file(config_file)
+ self._load_env_vars()
+
+ def _load_config_file(self, config_file: Optional[str]):
+ if config_file and Path(config_file).exists():
+ try:
+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):
+ import yaml
+ with open(config_file, 'r') as f:
+ data = yaml.safe_load(f) or {}
+ self._configs.update(data.get("parse", {}))
+ self._method_configs.update(data.get("parse_methods", {}))
+ elif config_file.endswith('.json'):
+ import json
+ with open(config_file, 'r') as f:
+ data = json.load(f) or {}
+ self._configs.update(data.get("parse", {}))
+ self._method_configs.update(data.get("parse_methods", {}))
+ elif config_file.endswith('.toml'):
+ import toml
+ with open(config_file, 'r') as f:
+ data = toml.load(f) or {}
+ if "parse" in data:
+ self._configs.update(data["parse"])
+ if "parse_methods" in data:
+ self._method_configs.update(data["parse_methods"])
+ self.logger.info(f"Loaded parse config from {config_file}")
+ except Exception as e:
+ self.logger.warning(f"Failed to load config file {config_file}: {e}")
+
+ def _load_env_vars(self):
+ env_mappings = {
+ "PARSE_DEFAULT_ENCODING": ("default_encoding", str),
+ "PARSE_OCR_LANGUAGE": ("ocr_language", str),
+ "PARSE_EXTRACT_TABLES": ("extract_tables", bool),
+ "PARSE_EXTRACT_IMAGES": ("extract_images", bool),
+ "PARSE_EXTRACT_METADATA": ("extract_metadata", bool),
+ "PARSE_JS_RENDERING": ("js_rendering", bool),
+ }
+
+ for env_key, (config_key, type_func) in env_mappings.items():
+ value = os.getenv(env_key)
+ if value:
+ try:
+ if type_func == bool:
+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")
+ else:
+ self._configs[config_key] = type_func(value)
+ except (ValueError, TypeError):
+ self.logger.warning(f"Failed to parse {env_key}={value}")
+
+ env_prefix = "PARSE_"
+ for key, value in os.environ.items():
+ if key.startswith(env_prefix) and key not in env_mappings:
+ config_key = key[len(env_prefix):].lower()
+ if value.lower() in ('true', 'false'):
+ self._configs[config_key] = value.lower() == 'true'
+ elif value.isdigit():
+ self._configs[config_key] = int(value)
+ else:
+ try:
+ self._configs[config_key] = float(value)
+ except ValueError:
+ self._configs[config_key] = value
+
+ def set(self, key: str, value: Any):
+ """Set configuration value programmatically."""
+ self._configs[key] = value
+
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get configuration value with fallback chain: config -> env -> default."""
+ if key in self._configs:
+ return self._configs[key]
+
+ env_key = f"PARSE_{key.upper()}"
+ value = os.getenv(env_key)
+ if value:
+ try:
+ if isinstance(default, int):
+ return int(value)
+ elif isinstance(default, float):
+ return float(value)
+ elif isinstance(default, bool):
+ return value.lower() in ("true", "1", "yes", "on")
+ return value
+ except (ValueError, TypeError):
+ pass
+
+ return default
+
+ def set_method_config(self, method: str, **config):
+ """Set method-specific configuration."""
+ self._method_configs[method] = config
+
+ def get_method_config(self, method: str) -> Dict:
+ """Get method-specific configuration."""
+ return self._method_configs.get(method, {})
+
+ def get_all(self) -> Dict[str, Any]:
+ """Get all configuration."""
+ return {
+ "config": self._configs.copy(),
+ "method_configs": self._method_configs.copy()
+ }
+
+
+# Global config instance
+parse_config = ParseConfig()
+
diff --git a/semantica/parse/methods.py b/semantica/parse/methods.py
new file mode 100644
index 00000000..d5aafc2d
--- /dev/null
+++ b/semantica/parse/methods.py
@@ -0,0 +1,735 @@
+"""
+Data Parsing Methods Module
+
+This module provides all parsing operations as simple, reusable functions for
+document parsing, web content parsing, structured data parsing, email parsing,
+code parsing, and media parsing. It supports multiple approaches and integrates
+with the method registry for extensibility.
+
+Supported Methods:
+
+Document Parsing:
+ - "default": Default document parsing using DocumentParser
+ - "pdf": PDF-focused parsing
+ - "docx": DOCX-focused parsing
+ - "html": HTML-focused parsing
+
+Web Content Parsing:
+ - "default": Default web parsing using WebParser
+ - "html": HTML-focused parsing
+ - "xml": XML-focused parsing
+ - "javascript": JavaScript-rendered content parsing
+
+Structured Data Parsing:
+ - "default": Default structured data parsing using StructuredDataParser
+ - "json": JSON-focused parsing
+ - "csv": CSV-focused parsing
+ - "xml": XML-focused parsing
+ - "yaml": YAML-focused parsing
+
+Email Parsing:
+ - "default": Default email parsing using EmailParser
+ - "headers": Header-only parsing
+ - "body": Body-only parsing
+ - "thread": Thread analysis parsing
+
+Code Parsing:
+ - "default": Default code parsing using CodeParser
+ - "ast": AST-focused parsing
+ - "comments": Comment-focused parsing
+ - "dependencies": Dependency-focused parsing
+
+Media Parsing:
+ - "default": Default media parsing using MediaParser
+ - "image": Image-focused parsing with OCR
+ - "audio": Audio-focused parsing
+ - "video": Video-focused parsing
+
+Algorithms Used:
+
+Document Parsing:
+ - PDF Parsing: pdfplumber integration (pdfplumber.PDF()) for text extraction, PyPDF2.PdfReader() fallback, table extraction (pdfplumber.extract_tables()), image extraction, metadata extraction (title, author, dates via pdf.metadata), page-level processing (page iteration)
+ - DOCX Parsing: python-docx integration (docx.Document()), paragraph extraction (document.paragraphs), table extraction (docx.table.Table), section/heading detection (paragraph.style), metadata extraction (core_properties), formatting extraction
+ - HTML Parsing: BeautifulSoup integration (BeautifulSoup(html, 'html.parser')), text extraction (soup.get_text()), link extraction (find_all('a')), metadata extraction (meta tags), structure analysis
+ - Text Parsing: Plain text file reading (open().read()), encoding detection, line-by-line processing
+
+Web Content Parsing:
+ - HTML Parsing: BeautifulSoup integration, content cleaning (soup.get_text(separator=' ', strip=True)), link extraction (find_all('a', href=True)), media extraction (find_all('img', 'video', 'audio')), JavaScript rendering support (Selenium WebDriver, Playwright)
+ - XML Parsing: xml.etree.ElementTree integration (ElementTree.parse()), element traversal (iter(), findall()), attribute extraction (element.attrib), namespace handling, XPath support
+ - JavaScript Rendering: Selenium WebDriver integration (webdriver.Chrome()), Playwright integration, headless browser rendering, dynamic content extraction (driver.page_source)
+
+Structured Data Parsing:
+ - JSON Parsing: json.load()/json.loads() integration, nested structure handling (recursive traversal), JSON path extraction, structure flattening, type validation
+ - CSV Parsing: csv.reader()/csv.DictReader() integration, delimiter detection (csv.Sniffer()), header detection, encoding handling, type conversion
+ - XML Parsing: xml.etree.ElementTree integration, element traversal (iter(), findall()), attribute extraction, namespace handling, XPath support
+ - YAML Parsing: yaml.safe_load() integration, nested structure handling, type preservation
+
+Email Parsing:
+ - MIME Parsing: email.message_from_string()/message_from_bytes() integration, multipart message handling (message.is_multipart()), header decoding (email.header.decode_header()), attachment extraction (message.get_payload())
+ - Header Parsing: From/To/CC/BCC extraction (message.get('From')), Subject decoding, Date parsing (email.utils.parsedate_to_datetime), Message-ID extraction
+ - Body Extraction: Plain text extraction (message.get_payload(decode=True)), HTML body extraction, multipart alternative handling
+ - Thread Analysis: In-Reply-To tracking (message.get('In-Reply-To')), References header analysis (message.get('References')), conversation threading
+
+Code Parsing:
+ - AST Parsing: ast.parse() integration (Python), syntax tree traversal (ast.walk()), function/class extraction (ast.FunctionDef, ast.ClassDef), import statement parsing (ast.Import, ast.ImportFrom)
+ - Comment Extraction: Regex-based comment detection (# for Python, // for JavaScript, /* */ for C-style), docstring extraction (ast.get_docstring()), inline/block comment distinction
+ - Dependency Analysis: Import statement parsing, dependency graph construction, cross-file dependency tracking
+ - Multi-Language Support: Language-specific parsers (Python, JavaScript, Java, etc.), syntax tree analysis per language
+
+Media Parsing:
+ - Image Parsing: PIL/Pillow integration (PIL.Image.open()), EXIF data extraction (PIL.ExifTags), metadata extraction (image.format, image.size, image.mode), image analysis
+ - OCR Processing: Tesseract OCR integration (pytesseract.image_to_string()), text extraction from images, confidence scoring (pytesseract.image_to_data()), language support, bounding box extraction
+ - Audio/Video Parsing: Metadata extraction (format, duration, codec), file information extraction (future support)
+
+Format-Specific Parsers:
+ - PDFParser: pdfplumber.PDF() for text/tables, PyPDF2.PdfReader() fallback, page iteration (pdf.pages), metadata extraction
+ - DOCXParser: docx.Document() for document loading, paragraph iteration, table extraction, core_properties access
+ - JSONParser: json.load()/json.loads(), recursive structure traversal, path extraction
+ - CSVParser: csv.DictReader() for row-by-row processing, delimiter detection, header handling
+ - XMLParser: xml.etree.ElementTree.parse(), element iteration, attribute access
+ - ImageParser: PIL.Image.open(), EXIF extraction, pytesseract.image_to_string() for OCR
+
+Key Features:
+ - Multiple parsing operation methods
+ - Parsing operations with method dispatch
+ - Method dispatchers with registry support
+ - Custom method registration capability
+ - Consistent interface across all methods
+
+Main Functions:
+ - parse_document: Document parsing wrapper
+ - parse_web_content: Web content parsing wrapper
+ - parse_structured_data: Structured data parsing wrapper
+ - parse_email: Email parsing wrapper
+ - parse_code: Code parsing wrapper
+ - parse_media: Media parsing wrapper
+ - parse_pdf: PDF parsing wrapper
+ - parse_docx: DOCX parsing wrapper
+ - parse_json: JSON parsing wrapper
+ - parse_csv: CSV parsing wrapper
+ - parse_xml: XML parsing wrapper
+ - parse_image: Image parsing wrapper
+ - get_parse_method: Get parsing method by name
+ - list_available_methods: List registered methods
+
+Example Usage:
+ >>> from semantica.parse.methods import parse_document, parse_web_content, parse_json
+ >>> doc = parse_document("document.pdf", method="default")
+ >>> web = parse_web_content("https://example.com", method="default")
+ >>> data = parse_json("data.json", method="default")
+"""
+
+from typing import Any, Dict, List, Optional, Callable, Union
+from pathlib import Path
+
+from ..utils.logging import get_logger
+from ..utils.exceptions import ProcessingError, ConfigurationError
+from .document_parser import DocumentParser
+from .web_parser import WebParser
+from .structured_data_parser import StructuredDataParser
+from .email_parser import EmailParser
+from .code_parser import CodeParser
+from .media_parser import MediaParser
+from .pdf_parser import PDFParser
+from .docx_parser import DOCXParser
+from .json_parser import JSONParser
+from .csv_parser import CSVParser
+from .xml_parser import XMLParser
+from .image_parser import ImageParser
+from .registry import method_registry
+from .config import parse_config
+
+logger = get_logger("parse_methods")
+
+
+def parse_document(
+ file_path: Union[str, Path],
+ file_type: Optional[str] = None,
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse document of any supported format (convenience function).
+
+ This is a user-friendly wrapper that parses documents using the specified method.
+
+ Args:
+ file_path: Path to document file
+ file_type: Document type (auto-detected if None)
+ method: Parsing method (default: "default")
+ - "default": Use DocumentParser with default settings
+ - "pdf": PDF-focused parsing
+ - "docx": DOCX-focused parsing
+ - "html": HTML-focused parsing
+ **kwargs: Additional options passed to DocumentParser
+ - extract_text: Whether to extract text (default: True)
+ - extract_tables: Whether to extract tables (default: True)
+ - extract_images: Whether to extract images (default: False)
+
+ Returns:
+ dict: Parsed document data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_document
+ >>> doc = parse_document("document.pdf", method="default")
+ >>> text = parse_document("document.pdf", method="default", extract_text=True)
+ """
+ custom_method = method_registry.get("document", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, file_type, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("document")
+ config.update(kwargs)
+
+ parser = DocumentParser(**config)
+ return parser.parse_document(file_path, file_type=file_type, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse document: {e}")
+ raise
+
+
+def parse_web_content(
+ content: Union[str, Path],
+ content_type: str = "html",
+ base_url: Optional[str] = None,
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse web content (convenience function).
+
+ This is a user-friendly wrapper that parses web content using the specified method.
+
+ Args:
+ content: Web content or file path
+ content_type: Content type ("html", "xml")
+ base_url: Base URL for resolving relative links
+ method: Parsing method (default: "default")
+ - "default": Use WebParser with default settings
+ - "html": HTML-focused parsing
+ - "xml": XML-focused parsing
+ - "javascript": JavaScript-rendered content parsing
+ **kwargs: Additional options passed to WebParser
+ - render_javascript: Whether to render JavaScript (default: False)
+ - clean: Whether to clean HTML (default: True)
+
+ Returns:
+ dict: Parsed web content data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_web_content
+ >>> web = parse_web_content("https://example.com", method="default")
+ >>> html = parse_web_content("page.html", content_type="html", method="default")
+ """
+ custom_method = method_registry.get("web", method)
+ if custom_method:
+ try:
+ return custom_method(content, content_type, base_url, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("web")
+ config.update(kwargs)
+
+ parser = WebParser(**config)
+ return parser.parse_web_content(content, content_type=content_type, base_url=base_url, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse web content: {e}")
+ raise
+
+
+def parse_structured_data(
+ data: Union[str, Path],
+ data_format: Optional[str] = None,
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse structured data (convenience function).
+
+ This is a user-friendly wrapper that parses structured data using the specified method.
+
+ Args:
+ data: Data content or file path
+ data_format: Data format (auto-detected if None)
+ method: Parsing method (default: "default")
+ - "default": Use StructuredDataParser with default settings
+ - "json": JSON-focused parsing
+ - "csv": CSV-focused parsing
+ - "xml": XML-focused parsing
+ - "yaml": YAML-focused parsing
+ **kwargs: Additional options passed to StructuredDataParser
+ - encoding: File encoding (default: 'utf-8')
+ - delimiter: CSV delimiter (for CSV parsing)
+ - flatten: Whether to flatten nested structures (for JSON)
+
+ Returns:
+ dict: Parsed data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_structured_data
+ >>> json_data = parse_structured_data("data.json", method="default")
+ >>> csv_data = parse_structured_data("data.csv", data_format="csv", method="default")
+ """
+ custom_method = method_registry.get("structured", method)
+ if custom_method:
+ try:
+ return custom_method(data, data_format, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("structured")
+ config.update(kwargs)
+
+ parser = StructuredDataParser(**config)
+ return parser.parse_data(data, data_format=data_format, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse structured data: {e}")
+ raise
+
+
+def parse_email(
+ email_content: Union[str, bytes, Path],
+ method: str = "default",
+ **kwargs
+) -> Any:
+ """
+ Parse email message (convenience function).
+
+ This is a user-friendly wrapper that parses emails using the specified method.
+
+ Args:
+ email_content: Email content (string, bytes, or file path)
+ method: Parsing method (default: "default")
+ - "default": Use EmailParser with default settings
+ - "headers": Header-only parsing
+ - "body": Body-only parsing
+ - "thread": Thread analysis parsing
+ **kwargs: Additional options passed to EmailParser
+ - extract_attachments: Whether to extract attachments (default: True)
+
+ Returns:
+ EmailData: Parsed email data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_email
+ >>> email = parse_email("email.eml", method="default")
+ >>> headers = parse_email("email.eml", method="headers")
+ """
+ custom_method = method_registry.get("email", method)
+ if custom_method:
+ try:
+ return custom_method(email_content, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("email")
+ config.update(kwargs)
+
+ parser = EmailParser(**config)
+ return parser.parse_email(email_content, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse email: {e}")
+ raise
+
+
+def parse_code(
+ file_path: Union[str, Path],
+ language: Optional[str] = None,
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse source code file (convenience function).
+
+ This is a user-friendly wrapper that parses code using the specified method.
+
+ Args:
+ file_path: Path to code file
+ language: Programming language (auto-detected if None)
+ method: Parsing method (default: "default")
+ - "default": Use CodeParser with default settings
+ - "ast": AST-focused parsing
+ - "comments": Comment-focused parsing
+ - "dependencies": Dependency-focused parsing
+ **kwargs: Additional options passed to CodeParser
+
+ Returns:
+ dict: Parsed code data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_code
+ >>> code = parse_code("script.py", method="default")
+ >>> structure = parse_code("script.py", method="ast")
+ """
+ custom_method = method_registry.get("code", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, language, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("code")
+ config.update(kwargs)
+
+ parser = CodeParser(**config)
+ return parser.parse_code(file_path, language=language, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse code: {e}")
+ raise
+
+
+def parse_media(
+ file_path: Union[str, Path],
+ media_type: Optional[str] = None,
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse media file (convenience function).
+
+ This is a user-friendly wrapper that parses media using the specified method.
+
+ Args:
+ file_path: Path to media file
+ media_type: Media type (auto-detected if None)
+ method: Parsing method (default: "default")
+ - "default": Use MediaParser with default settings
+ - "image": Image-focused parsing with OCR
+ - "audio": Audio-focused parsing
+ - "video": Video-focused parsing
+ **kwargs: Additional options passed to MediaParser
+ - extract_text: Whether to extract text using OCR (for images, default: False)
+ - extract_metadata: Whether to extract metadata (default: True)
+ - ocr_language: OCR language code (for images, default: "eng")
+
+ Returns:
+ dict: Parsed media data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_media
+ >>> image = parse_media("image.jpg", method="default", extract_text=True)
+ >>> video = parse_media("video.mp4", method="default")
+ """
+ custom_method = method_registry.get("media", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, media_type, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("media")
+ config.update(kwargs)
+
+ parser = MediaParser(**config)
+ return parser.parse_media(file_path, media_type=media_type, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse media: {e}")
+ raise
+
+
+def parse_pdf(
+ file_path: Union[str, Path],
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse PDF document (convenience function).
+
+ This is a user-friendly wrapper that parses PDFs using the specified method.
+
+ Args:
+ file_path: Path to PDF file
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to PDFParser
+ - extract_text: Whether to extract text (default: True)
+ - extract_tables: Whether to extract tables (default: True)
+ - extract_images: Whether to extract images (default: False)
+ - pages: Specific page numbers to parse (None = all pages)
+
+ Returns:
+ dict: Parsed PDF data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_pdf
+ >>> pdf = parse_pdf("document.pdf", method="default")
+ >>> pages = parse_pdf("document.pdf", method="default", pages=[1, 2, 3])
+ """
+ custom_method = method_registry.get("document", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("document")
+ config.update(kwargs)
+
+ parser = PDFParser(**config)
+ return parser.parse(file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse PDF: {e}")
+ raise
+
+
+def parse_docx(
+ file_path: Union[str, Path],
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse DOCX document (convenience function).
+
+ This is a user-friendly wrapper that parses DOCX files using the specified method.
+
+ Args:
+ file_path: Path to DOCX file
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to DOCXParser
+ - extract_formatting: Whether to extract formatting (default: False)
+ - extract_tables: Whether to extract tables (default: True)
+ - extract_comments: Whether to extract comments (default: False)
+
+ Returns:
+ dict: Parsed DOCX data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_docx
+ >>> docx = parse_docx("document.docx", method="default")
+ """
+ custom_method = method_registry.get("document", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("document")
+ config.update(kwargs)
+
+ parser = DOCXParser(**config)
+ return parser.parse(file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse DOCX: {e}")
+ raise
+
+
+def parse_json(
+ file_path: Union[str, Path],
+ method: str = "default",
+ **kwargs
+) -> Any:
+ """
+ Parse JSON file (convenience function).
+
+ This is a user-friendly wrapper that parses JSON using the specified method.
+
+ Args:
+ file_path: Path to JSON file or JSON string
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to JSONParser
+ - encoding: File encoding (default: 'utf-8')
+ - flatten: Whether to flatten nested structures (default: False)
+ - extract_paths: Whether to extract JSON paths (default: False)
+
+ Returns:
+ JSONData: Parsed JSON data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_json
+ >>> json_data = parse_json("data.json", method="default")
+ >>> flattened = parse_json("data.json", method="default", flatten=True)
+ """
+ custom_method = method_registry.get("structured", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("structured")
+ config.update(kwargs)
+
+ parser = JSONParser(**config)
+ return parser.parse(file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse JSON: {e}")
+ raise
+
+
+def parse_csv(
+ file_path: Union[str, Path],
+ delimiter: str = ',',
+ method: str = "default",
+ **kwargs
+) -> Any:
+ """
+ Parse CSV file (convenience function).
+
+ This is a user-friendly wrapper that parses CSV using the specified method.
+
+ Args:
+ file_path: Path to CSV file
+ delimiter: CSV delimiter (default: ',')
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to CSVParser
+ - has_header: Whether CSV has header row (default: True)
+ - encoding: File encoding (default: 'utf-8')
+ - skip_rows: Number of rows to skip
+ - max_rows: Maximum number of rows to read
+
+ Returns:
+ CSVData: Parsed CSV data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_csv
+ >>> csv_data = parse_csv("data.csv", method="default")
+ >>> tab_separated = parse_csv("data.tsv", delimiter="\t", method="default")
+ """
+ custom_method = method_registry.get("structured", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, delimiter, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("structured")
+ config.update(kwargs)
+
+ parser = CSVParser(**config)
+ return parser.parse(file_path, delimiter=delimiter, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse CSV: {e}")
+ raise
+
+
+def parse_xml(
+ file_path: Union[str, Path],
+ method: str = "default",
+ **kwargs
+) -> Any:
+ """
+ Parse XML file (convenience function).
+
+ This is a user-friendly wrapper that parses XML using the specified method.
+
+ Args:
+ file_path: Path to XML file or XML string
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to XMLParser
+
+ Returns:
+ XMLData: Parsed XML data
+
+ Examples:
+ >>> from semantica.parse.methods import parse_xml
+ >>> xml_data = parse_xml("data.xml", method="default")
+ """
+ custom_method = method_registry.get("structured", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("structured")
+ config.update(kwargs)
+
+ parser = XMLParser(**config)
+ return parser.parse(file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse XML: {e}")
+ raise
+
+
+def parse_image(
+ file_path: Union[str, Path],
+ method: str = "default",
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Parse image file with OCR support (convenience function).
+
+ This is a user-friendly wrapper that parses images using the specified method.
+
+ Args:
+ file_path: Path to image file
+ method: Parsing method (default: "default")
+ **kwargs: Additional options passed to ImageParser
+ - extract_text: Whether to extract text using OCR (default: False)
+ - ocr_language: OCR language code (default: "eng")
+ - extract_metadata: Whether to extract metadata (default: True)
+
+ Returns:
+ dict: Parsed image data containing:
+ - metadata: ImageMetadata object
+ - ocr_result: OCRResult object (if extract_text=True)
+ - text: Extracted text (if extract_text=True)
+
+ Examples:
+ >>> from semantica.parse.methods import parse_image
+ >>> image = parse_image("image.jpg", method="default", extract_text=True)
+ >>> ocr_text = image.get("ocr_result", {}).get("text", "")
+ """
+ custom_method = method_registry.get("media", method)
+ if custom_method:
+ try:
+ return custom_method(file_path, **kwargs)
+ except Exception as e:
+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")
+
+ try:
+ config = parse_config.get_method_config("media")
+ config.update(kwargs)
+
+ parser = ImageParser(**config)
+ return parser.parse(file_path, **kwargs)
+
+ except Exception as e:
+ logger.error(f"Failed to parse image: {e}")
+ raise
+
+
+def get_parse_method(task: str, name: str) -> Optional[Callable]:
+ """Get parsing method by task and name."""
+ return method_registry.get(task, name)
+
+
+def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
+ """List all registered parsing methods."""
+ return method_registry.list_all(task)
+
+
+# Register default methods
+method_registry.register("document", "default", parse_document)
+method_registry.register("web", "default", parse_web_content)
+method_registry.register("structured", "default", parse_structured_data)
+method_registry.register("email", "default", parse_email)
+method_registry.register("code", "default", parse_code)
+method_registry.register("media", "default", parse_media)
+
diff --git a/semantica/parse/parse_usage.md b/semantica/parse/parse_usage.md
new file mode 100644
index 00000000..e0271acb
--- /dev/null
+++ b/semantica/parse/parse_usage.md
@@ -0,0 +1,1034 @@
+# Data Parsing Module Usage Guide
+
+This comprehensive guide demonstrates how to use the data parsing module for document parsing, web content parsing, structured data parsing, email parsing, code parsing, and media parsing. The module supports parsing various file formats including PDF, DOCX, PPTX, HTML, JSON, CSV, XML, images, and more.
+
+## Table of Contents
+
+1. [Basic Usage](#basic-usage)
+2. [Document Parsing](#document-parsing)
+3. [Web Content Parsing](#web-content-parsing)
+4. [Structured Data Parsing](#structured-data-parsing)
+5. [Email Parsing](#email-parsing)
+6. [Code Parsing](#code-parsing)
+7. [Media Parsing](#media-parsing)
+8. [Format-Specific Parsers](#format-specific-parsers)
+9. [Using Methods](#using-methods)
+10. [Using Registry](#using-registry)
+11. [Configuration](#configuration)
+12. [Advanced Examples](#advanced-examples)
+
+## Basic Usage
+
+### Using the Convenience Functions
+
+```python
+from semantica.parse import parse_document, parse_web_content, parse_json
+
+# Parse a PDF document
+doc = parse_document("document.pdf", method="default")
+print(f"Text: {doc.get('full_text', '')}")
+print(f"Pages: {doc.get('total_pages', 0)}")
+
+# Parse web content
+web = parse_web_content("https://example.com", method="default")
+print(f"Content: {web.get('text', '')}")
+
+# Parse JSON data
+data = parse_json("data.json", method="default")
+print(f"Data: {data.data}")
+```
+
+### Using Main Classes
+
+```python
+from semantica.parse import DocumentParser, WebParser, StructuredDataParser
+
+# Create parsers
+doc_parser = DocumentParser()
+web_parser = WebParser()
+data_parser = StructuredDataParser()
+
+# Parse document
+doc = doc_parser.parse_document("document.pdf")
+print(f"Text: {doc.get('full_text', '')}")
+
+# Parse web content
+web = web_parser.parse_web_content("https://example.com", content_type="html")
+print(f"Content: {web.get('text', '')}")
+
+# Parse structured data
+data = data_parser.parse_data("data.json", data_format="json")
+print(f"Data: {data}")
+```
+
+## Document Parsing
+
+### PDF Parsing
+
+```python
+from semantica.parse import parse_pdf, PDFParser
+
+# Using convenience function
+pdf = parse_pdf("document.pdf", method="default", extract_tables=True)
+print(f"Text: {pdf.get('full_text', '')}")
+print(f"Pages: {pdf.get('total_pages', 0)}")
+print(f"Tables: {pdf.get('pages', [{}])[0].get('tables', [])}")
+
+# Using PDFParser directly
+pdf_parser = PDFParser()
+pdf_data = pdf_parser.parse("document.pdf", extract_text=True, extract_tables=True)
+
+# Extract specific pages
+pdf_pages = pdf_parser.parse("document.pdf", pages=[1, 2, 3])
+
+# Extract only text
+text = pdf_parser.extract_text("document.pdf")
+
+# Extract only tables
+tables = pdf_parser.extract_tables("document.pdf")
+```
+
+### DOCX Parsing
+
+```python
+from semantica.parse import parse_docx, DOCXParser
+
+# Using convenience function
+docx = parse_docx("document.docx", method="default")
+print(f"Text: {docx.get('text', '')}")
+print(f"Sections: {docx.get('sections', [])}")
+
+# Using DOCXParser directly
+docx_parser = DOCXParser()
+docx_data = docx_parser.parse("document.docx", extract_tables=True)
+
+# Extract sections
+sections = docx_parser.extract_sections("document.docx")
+
+# Extract metadata
+metadata = docx_parser.extract_metadata("document.docx")
+print(f"Author: {metadata.author}")
+print(f"Title: {metadata.title}")
+```
+
+### PPTX Parsing
+
+```python
+from semantica.parse import PPTXParser
+
+pptx_parser = PPTXParser()
+pptx_data = pptx_parser.parse("presentation.pptx")
+
+print(f"Title: {pptx_data.title}")
+print(f"Slides: {len(pptx_data.slides)}")
+
+for slide in pptx_data.slides:
+ print(f"Slide {slide.slide_number}: {slide.title}")
+ print(f" Text: {slide.text}")
+ print(f" Notes: {slide.notes}")
+```
+
+### Excel Parsing
+
+```python
+from semantica.parse import ExcelParser
+
+excel_parser = ExcelParser()
+excel_data = excel_parser.parse("spreadsheet.xlsx")
+
+print(f"Sheets: {excel_data.sheet_names}")
+
+for sheet_name, sheet in excel_data.sheets.items():
+ print(f"Sheet: {sheet_name}")
+ print(f" Rows: {sheet.row_count}")
+ print(f" Columns: {sheet.column_count}")
+ print(f" Headers: {sheet.headers}")
+```
+
+### HTML Document Parsing
+
+```python
+from semantica.parse import parse_document, HTMLParser
+
+# Using convenience function
+html_doc = parse_document("page.html", method="default")
+print(f"Text: {html_doc.get('text', '')}")
+
+# Using HTMLParser directly
+html_parser = HTMLParser()
+html_data = html_parser.parse("page.html", extract_links=True, extract_images=True)
+
+# Extract metadata
+metadata = html_parser.extract_metadata("page.html")
+print(f"Title: {metadata.title}")
+print(f"Description: {metadata.description}")
+
+# Extract links
+links = html_parser.extract_links("page.html")
+for link in links:
+ print(f"Link: {link.get('href', '')} - {link.get('text', '')}")
+```
+
+### Text File Parsing
+
+```python
+from semantica.parse import parse_document
+
+# Parse plain text file
+text_doc = parse_document("document.txt", method="default")
+print(f"Text: {text_doc.get('text', '')}")
+```
+
+## Web Content Parsing
+
+### HTML Content Parsing
+
+```python
+from semantica.parse import parse_web_content, WebParser
+
+# Using convenience function
+web = parse_web_content("https://example.com", content_type="html", method="default")
+print(f"Text: {web.get('text', '')}")
+
+# Using WebParser directly
+web_parser = WebParser()
+html_data = web_parser.parse_web_content("https://example.com", content_type="html")
+
+# Extract text
+text = web_parser.extract_text("https://example.com")
+
+# Extract links
+links = web_parser.extract_links("https://example.com")
+for link in links:
+ print(f"Link: {link.get('href', '')}")
+
+# Render JavaScript content
+rendered = web_parser.render_javascript("https://example.com", wait_time=5)
+```
+
+### XML Content Parsing
+
+```python
+from semantica.parse import parse_web_content, XMLParser
+
+# Using convenience function
+xml_data = parse_web_content("data.xml", content_type="xml", method="default")
+
+# Using XMLParser directly
+xml_parser = XMLParser()
+xml_data = xml_parser.parse("data.xml")
+
+# Find elements using XPath
+elements = xml_parser.find_elements("data.xml", "//item")
+for element in elements:
+ print(f"Element: {element.tag} - {element.text}")
+```
+
+### JavaScript-Rendered Content
+
+```python
+from semantica.parse import WebParser, JavaScriptRenderer
+
+# Using JavaScript renderer
+js_renderer = JavaScriptRenderer()
+rendered_html = js_renderer.render_page("https://example.com", wait_time=5)
+
+# Using WebParser with JavaScript rendering
+web_parser = WebParser()
+rendered_content = web_parser.parse_web_content(
+ "https://example.com",
+ content_type="html",
+ render_javascript=True,
+ wait_time=5
+)
+```
+
+## Structured Data Parsing
+
+### JSON Parsing
+
+```python
+from semantica.parse import parse_json, JSONParser
+
+# Using convenience function
+json_data = parse_json("data.json", method="default")
+print(f"Data: {json_data.data}")
+print(f"Type: {json_data.type}")
+
+# Using JSONParser directly
+json_parser = JSONParser()
+json_data = json_parser.parse("data.json", flatten=True)
+
+# Extract JSON paths
+paths = json_parser.extract_paths("data.json")
+for path in paths:
+ print(f"Path: {path}")
+```
+
+### CSV Parsing
+
+```python
+from semantica.parse import parse_csv, CSVParser
+
+# Using convenience function
+csv_data = parse_csv("data.csv", delimiter=",", method="default")
+print(f"Headers: {csv_data.headers}")
+print(f"Rows: {csv_data.row_count}")
+
+# Using CSVParser directly
+csv_parser = CSVParser()
+csv_data = csv_parser.parse("data.csv", delimiter=",", has_header=True)
+
+# Parse to dictionary list
+rows = csv_parser.parse_to_dict("data.csv")
+for row in rows:
+ print(f"Row: {row}")
+```
+
+### XML Parsing
+
+```python
+from semantica.parse import parse_xml, XMLParser
+
+# Using convenience function
+xml_data = parse_xml("data.xml", method="default")
+print(f"Root: {xml_data.root.tag}")
+
+# Using XMLParser directly
+xml_parser = XMLParser()
+xml_data = xml_parser.parse("data.xml", engine="lxml")
+
+# Find elements
+elements = xml_parser.find_elements("data.xml", "//item")
+for element in elements:
+ print(f"Element: {element.tag} - {element.text}")
+```
+
+### YAML Parsing
+
+```python
+from semantica.parse import StructuredDataParser
+
+data_parser = StructuredDataParser()
+yaml_data = data_parser.parse_data("config.yaml", data_format="yaml")
+print(f"Data: {yaml_data}")
+```
+
+## Email Parsing
+
+### Basic Email Parsing
+
+```python
+from semantica.parse import parse_email, EmailParser
+
+# Using convenience function
+email = parse_email("email.eml", method="default")
+print(f"Subject: {email.headers.subject}")
+print(f"From: {email.headers.from_address}")
+print(f"To: {email.headers.to_addresses}")
+print(f"Body: {email.body.text}")
+
+# Using EmailParser directly
+email_parser = EmailParser()
+email_data = email_parser.parse_email("email.eml", extract_attachments=True)
+
+# Extract headers only
+headers = email_parser.parse_headers("email.eml")
+print(f"Subject: {headers.subject}")
+print(f"Date: {headers.date}")
+
+# Extract body only
+body = email_parser.extract_body("email.eml")
+print(f"Text: {body.text}")
+print(f"HTML: {body.html}")
+```
+
+### Email Thread Analysis
+
+```python
+from semantica.parse import EmailParser
+
+email_parser = EmailParser()
+
+# Analyze email thread
+thread = email_parser.analyze_thread("email.eml")
+print(f"Thread ID: {thread.thread_id}")
+print(f"Messages: {len(thread.messages)}")
+print(f"Subject: {thread.subject}")
+
+# Parse multiple emails in a thread
+for email_file in ["email1.eml", "email2.eml", "email3.eml"]:
+ email = email_parser.parse_email(email_file)
+ print(f"Email: {email.headers.subject}")
+```
+
+### Email Attachment Extraction
+
+```python
+from semantica.parse import EmailParser
+
+email_parser = EmailParser()
+email_data = email_parser.parse_email("email.eml", extract_attachments=True)
+
+# Access attachments
+for attachment in email_data.body.attachments:
+ print(f"Filename: {attachment.get('filename', '')}")
+ print(f"Content Type: {attachment.get('content_type', '')}")
+ print(f"Size: {attachment.get('size', 0)}")
+```
+
+## Code Parsing
+
+### Basic Code Parsing
+
+```python
+from semantica.parse import parse_code, CodeParser
+
+# Using convenience function
+code = parse_code("script.py", method="default")
+print(f"Functions: {code.get('structure', {}).get('functions', [])}")
+print(f"Classes: {code.get('structure', {}).get('classes', [])}")
+print(f"Imports: {code.get('structure', {}).get('imports', [])}")
+
+# Using CodeParser directly
+code_parser = CodeParser()
+code_data = code_parser.parse_code("script.py", language="python")
+
+# Extract structure
+structure = code_parser.extract_structure("script.py", language="python")
+print(f"Functions: {structure.functions}")
+print(f"Classes: {structure.classes}")
+
+# Extract comments
+comments = code_parser.extract_comments("script.py", language="python")
+for comment in comments:
+ print(f"Comment: {comment.text} (Line {comment.line_number})")
+
+# Analyze dependencies
+dependencies = code_parser.analyze_dependencies("script.py", language="python")
+print(f"Dependencies: {dependencies}")
+```
+
+### AST Parsing
+
+```python
+from semantica.parse import CodeParser, SyntaxTreeParser
+
+code_parser = CodeParser()
+syntax_parser = SyntaxTreeParser()
+
+# Parse syntax tree
+tree = syntax_parser.parse_syntax_tree("script.py", language="python")
+
+# Extract functions
+functions = syntax_parser.extract_functions("script.py", language="python")
+for func in functions:
+ print(f"Function: {func.get('name', '')}")
+
+# Extract classes
+classes = syntax_parser.extract_classes("script.py", language="python")
+for cls in classes:
+ print(f"Class: {cls.get('name', '')}")
+
+# Extract imports
+imports = syntax_parser.extract_imports("script.py", language="python")
+for imp in imports:
+ print(f"Import: {imp}")
+```
+
+### Multi-Language Code Parsing
+
+```python
+from semantica.parse import CodeParser
+
+code_parser = CodeParser()
+
+# Parse Python code
+python_code = code_parser.parse_code("script.py", language="python")
+
+# Parse JavaScript code
+js_code = code_parser.parse_code("script.js", language="javascript")
+
+# Parse Java code
+java_code = code_parser.parse_code("Main.java", language="java")
+```
+
+## Media Parsing
+
+### Image Parsing with OCR
+
+```python
+from semantica.parse import parse_image, ImageParser
+
+# Using convenience function
+image = parse_image("image.jpg", method="default", extract_text=True)
+print(f"Format: {image.get('metadata', {}).get('format', '')}")
+print(f"Size: {image.get('metadata', {}).get('size', (0, 0))}")
+
+# Extract OCR text
+if "ocr_result" in image:
+ print(f"OCR Text: {image['ocr_result'].text}")
+ print(f"Confidence: {image['ocr_result'].confidence}")
+
+# Using ImageParser directly
+image_parser = ImageParser()
+image_data = image_parser.parse("image.jpg", extract_text=True, ocr_language="eng")
+
+# Extract metadata only
+metadata = image_parser.extract_metadata("image.jpg")
+print(f"Format: {metadata.format}")
+print(f"Size: {metadata.size}")
+print(f"EXIF: {metadata.exif}")
+
+# Extract text with OCR
+ocr_result = image_parser.extract_text("image.jpg", language="eng")
+print(f"Text: {ocr_result.text}")
+print(f"Confidence: {ocr_result.confidence}")
+```
+
+### Media File Parsing
+
+```python
+from semantica.parse import parse_media, MediaParser
+
+# Using convenience function
+media = parse_media("video.mp4", method="default")
+print(f"Type: {media.get('media_type', '')}")
+print(f"Metadata: {media.get('metadata', {})}")
+
+# Using MediaParser directly
+media_parser = MediaParser()
+media_data = media_parser.parse_media("image.jpg", media_type="image")
+
+# Get supported formats
+formats = media_parser.get_supported_formats()
+print(f"Supported formats: {formats}")
+```
+
+## Format-Specific Parsers
+
+### PDF Parser
+
+```python
+from semantica.parse import PDFParser, PDFPage, PDFMetadata
+
+pdf_parser = PDFParser()
+
+# Parse PDF
+pdf_data = pdf_parser.parse("document.pdf", extract_text=True, extract_tables=True)
+
+# Access pages
+for page_dict in pdf_data.get("pages", []):
+ page = PDFPage(**page_dict)
+ print(f"Page {page.page_number}: {len(page.text)} characters")
+ print(f" Tables: {len(page.tables)}")
+ print(f" Images: {len(page.images)}")
+
+# Access metadata
+metadata = PDFMetadata(**pdf_data.get("metadata", {}))
+print(f"Title: {metadata.title}")
+print(f"Author: {metadata.author}")
+print(f"Page Count: {metadata.page_count}")
+```
+
+### DOCX Parser
+
+```python
+from semantica.parse import DOCXParser, DocxSection, DocxMetadata
+
+docx_parser = DOCXParser()
+
+# Parse DOCX
+docx_data = docx_parser.parse("document.docx", extract_tables=True)
+
+# Access sections
+for section_dict in docx_data.get("sections", []):
+ section = DocxSection(**section_dict)
+ print(f"Section: {section.heading} (Level {section.level})")
+ print(f" Content: {section.content[:100]}...")
+
+# Access metadata
+metadata = DocxMetadata(**docx_data.get("metadata", {}))
+print(f"Title: {metadata.title}")
+print(f"Author: {metadata.author}")
+```
+
+### JSON Parser
+
+```python
+from semantica.parse import JSONParser, JSONData
+
+json_parser = JSONParser()
+
+# Parse JSON
+json_data = json_parser.parse("data.json", flatten=True)
+
+# Access data
+print(f"Type: {json_data.type}")
+print(f"Data: {json_data.data}")
+print(f"Metadata: {json_data.metadata}")
+
+# Extract paths
+paths = json_parser.extract_paths("data.json")
+for path in paths:
+ print(f"Path: {path}")
+```
+
+### CSV Parser
+
+```python
+from semantica.parse import CSVParser, CSVData
+
+csv_parser = CSVParser()
+
+# Parse CSV
+csv_data = csv_parser.parse("data.csv", delimiter=",", has_header=True)
+
+# Access data
+print(f"Headers: {csv_data.headers}")
+print(f"Row Count: {csv_data.row_count}")
+
+# Access rows
+for row in csv_data.rows:
+ print(f"Row: {row}")
+
+# Parse to dictionary list
+rows = csv_parser.parse_to_dict("data.csv")
+for row in rows:
+ print(f"Row: {row}")
+```
+
+### XML Parser
+
+```python
+from semantica.parse import XMLParser, XMLData, XMLElement
+
+xml_parser = XMLParser()
+
+# Parse XML
+xml_data = xml_parser.parse("data.xml", engine="lxml")
+
+# Access root element
+root = xml_data.root
+print(f"Root Tag: {root.tag}")
+print(f"Root Text: {root.text}")
+
+# Access children
+for child in root.children:
+ print(f"Child: {child.tag} - {child.text}")
+
+# Find elements
+elements = xml_parser.find_elements("data.xml", "//item")
+for element in elements:
+ print(f"Element: {element.tag} - {element.text}")
+```
+
+### Image Parser
+
+```python
+from semantica.parse import ImageParser, ImageMetadata, OCRResult
+
+image_parser = ImageParser()
+
+# Parse image
+image_data = image_parser.parse("image.jpg", extract_text=True, ocr_language="eng")
+
+# Access metadata
+metadata = ImageMetadata(**image_data.get("metadata", {}))
+print(f"Format: {metadata.format}")
+print(f"Size: {metadata.size}")
+print(f"EXIF: {metadata.exif}")
+
+# Access OCR result
+if "ocr_result" in image_data:
+ ocr = OCRResult(**image_data["ocr_result"])
+ print(f"OCR Text: {ocr.text}")
+ print(f"Confidence: {ocr.confidence}")
+ print(f"Language: {ocr.language}")
+```
+
+## Using Methods
+
+### Method Selection
+
+```python
+from semantica.parse import parse_document, parse_web_content, parse_json
+
+# Use default method
+doc = parse_document("document.pdf", method="default")
+
+# Use specific method (if registered)
+doc = parse_document("document.pdf", method="custom_pdf_parser")
+
+# List available methods
+from semantica.parse import list_available_methods
+
+methods = list_available_methods("document")
+print(f"Available document methods: {methods}")
+```
+
+### Custom Method Registration
+
+```python
+from semantica.parse import method_registry, parse_document
+
+# Define custom parsing method
+def custom_document_parser(file_path, file_type=None, **kwargs):
+ # Custom parsing logic
+ return {"text": "Custom parsed text", "metadata": {}}
+
+# Register custom method
+method_registry.register("document", "custom", custom_document_parser)
+
+# Use custom method
+doc = parse_document("document.pdf", method="custom")
+```
+
+## Using Registry
+
+### Registering Custom Methods
+
+```python
+from semantica.parse import method_registry
+
+# Register document parsing method
+def my_document_parser(file_path, file_type=None, **kwargs):
+ # Custom implementation
+ return {"text": "Parsed", "metadata": {}}
+
+method_registry.register("document", "my_parser", my_document_parser)
+
+# Register web parsing method
+def my_web_parser(content, content_type="html", base_url=None, **kwargs):
+ # Custom implementation
+ return {"text": "Parsed", "links": []}
+
+method_registry.register("web", "my_parser", my_web_parser)
+```
+
+### Listing Registered Methods
+
+```python
+from semantica.parse import method_registry
+
+# List all methods
+all_methods = method_registry.list_all()
+print(f"All methods: {all_methods}")
+
+# List methods for specific task
+document_methods = method_registry.list_all("document")
+print(f"Document methods: {document_methods}")
+
+web_methods = method_registry.list_all("web")
+print(f"Web methods: {web_methods}")
+```
+
+### Getting Methods
+
+```python
+from semantica.parse import method_registry, get_parse_method
+
+# Get method directly
+method = method_registry.get("document", "default")
+if method:
+ result = method("document.pdf")
+
+# Using convenience function
+method = get_parse_method("document", "default")
+if method:
+ result = method("document.pdf")
+```
+
+### Unregistering Methods
+
+```python
+from semantica.parse import method_registry
+
+# Unregister specific method
+method_registry.unregister("document", "custom")
+
+# Clear all methods for a task
+method_registry.clear("document")
+
+# Clear all methods
+method_registry.clear()
+```
+
+## Configuration
+
+### Environment Variables
+
+```python
+import os
+
+# Set environment variables
+os.environ["PARSE_DEFAULT_ENCODING"] = "utf-8"
+os.environ["PARSE_OCR_LANGUAGE"] = "eng"
+os.environ["PARSE_EXTRACT_TABLES"] = "true"
+os.environ["PARSE_EXTRACT_IMAGES"] = "false"
+os.environ["PARSE_EXTRACT_METADATA"] = "true"
+os.environ["PARSE_JS_RENDERING"] = "false"
+```
+
+### Config File
+
+Create a `config.yaml` file:
+
+```yaml
+parse:
+ default_encoding: "utf-8"
+ ocr_language: "eng"
+ extract_tables: true
+ extract_images: false
+ extract_metadata: true
+ js_rendering: false
+
+parse_methods:
+ document:
+ extract_tables: true
+ extract_images: false
+ web:
+ render_javascript: false
+ structured:
+ encoding: "utf-8"
+```
+
+Load config:
+
+```python
+from semantica.parse.config import ParseConfig
+
+# Load from config file
+parse_config = ParseConfig(config_file="config.yaml")
+
+# Access configuration
+encoding = parse_config.get("default_encoding", default="utf-8")
+ocr_lang = parse_config.get("ocr_language", default="eng")
+```
+
+### Programmatic Configuration
+
+```python
+from semantica.parse import parse_config
+
+# Set configuration
+parse_config.set("default_encoding", "utf-8")
+parse_config.set("ocr_language", "eng")
+parse_config.set("extract_tables", True)
+
+# Get configuration
+encoding = parse_config.get("default_encoding", default="utf-8")
+ocr_lang = parse_config.get("ocr_language", default="eng")
+
+# Method-specific configuration
+parse_config.set_method_config("document", extract_tables=True, extract_images=False)
+parse_config.set_method_config("web", render_javascript=False)
+
+# Get method configuration
+doc_config = parse_config.get_method_config("document")
+web_config = parse_config.get_method_config("web")
+
+# Get all configuration
+all_config = parse_config.get_all()
+print(f"All config: {all_config}")
+```
+
+## Advanced Examples
+
+### Batch Document Processing
+
+```python
+from semantica.parse import parse_document
+from pathlib import Path
+
+# Process multiple documents
+documents = ["doc1.pdf", "doc2.docx", "doc3.html"]
+results = []
+
+for doc_path in documents:
+ try:
+ result = parse_document(doc_path, method="default")
+ results.append({
+ "file": doc_path,
+ "text": result.get("full_text", ""),
+ "metadata": result.get("metadata", {})
+ })
+ except Exception as e:
+ print(f"Error parsing {doc_path}: {e}")
+
+# Process all PDFs in a directory
+pdf_dir = Path("documents")
+pdf_files = list(pdf_dir.glob("*.pdf"))
+
+for pdf_file in pdf_files:
+ result = parse_document(pdf_file, method="default")
+ print(f"Processed: {pdf_file.name} ({result.get('total_pages', 0)} pages)")
+```
+
+### Multi-Format Data Extraction
+
+```python
+from semantica.parse import (
+ parse_document, parse_json, parse_csv, parse_xml
+)
+
+# Extract data from multiple formats
+files = {
+ "document.pdf": parse_document,
+ "data.json": parse_json,
+ "data.csv": parse_csv,
+ "data.xml": parse_xml,
+}
+
+extracted_data = {}
+
+for file_path, parser_func in files.items():
+ try:
+ data = parser_func(file_path, method="default")
+ extracted_data[file_path] = data
+ except Exception as e:
+ print(f"Error parsing {file_path}: {e}")
+
+# Process extracted data
+for file_path, data in extracted_data.items():
+ print(f"File: {file_path}")
+ if isinstance(data, dict):
+ print(f" Keys: {list(data.keys())}")
+```
+
+### Email Thread Reconstruction
+
+```python
+from semantica.parse import EmailParser
+from pathlib import Path
+
+email_parser = EmailParser()
+
+# Process email thread
+email_files = ["email1.eml", "email2.eml", "email3.eml"]
+thread_messages = []
+
+for email_file in email_files:
+ email = email_parser.parse_email(email_file)
+ thread_messages.append({
+ "subject": email.headers.subject,
+ "from": email.headers.from_address,
+ "date": email.headers.date,
+ "body": email.body.text,
+ "in_reply_to": email.headers.in_reply_to,
+ "references": email.headers.references
+ })
+
+# Sort by date
+thread_messages.sort(key=lambda x: x["date"] or "")
+
+# Display thread
+for i, msg in enumerate(thread_messages, 1):
+ print(f"Message {i}:")
+ print(f" From: {msg['from']}")
+ print(f" Subject: {msg['subject']}")
+ print(f" Date: {msg['date']}")
+ print(f" Body: {msg['body'][:100]}...")
+```
+
+### Code Repository Analysis
+
+```python
+from semantica.parse import CodeParser
+from pathlib import Path
+
+code_parser = CodeParser()
+
+# Analyze code repository
+repo_path = Path("repository")
+code_files = list(repo_path.rglob("*.py"))
+
+all_functions = []
+all_classes = []
+all_imports = []
+
+for code_file in code_files:
+ try:
+ code_data = code_parser.parse_code(code_file, language="python")
+ structure = code_data.get("structure", {})
+
+ all_functions.extend(structure.get("functions", []))
+ all_classes.extend(structure.get("classes", []))
+ all_imports.extend(structure.get("imports", []))
+ except Exception as e:
+ print(f"Error parsing {code_file}: {e}")
+
+print(f"Total functions: {len(all_functions)}")
+print(f"Total classes: {len(all_classes)}")
+print(f"Total imports: {len(set(all_imports))}")
+```
+
+### OCR Batch Processing
+
+```python
+from semantica.parse import parse_image
+from pathlib import Path
+
+# Process all images in a directory
+image_dir = Path("images")
+image_files = list(image_dir.glob("*.jpg")) + list(image_dir.glob("*.png"))
+
+ocr_results = []
+
+for image_file in image_files:
+ try:
+ image_data = parse_image(image_file, method="default", extract_text=True)
+
+ if "ocr_result" in image_data:
+ ocr_results.append({
+ "file": image_file.name,
+ "text": image_data["ocr_result"].text,
+ "confidence": image_data["ocr_result"].confidence
+ })
+ except Exception as e:
+ print(f"Error processing {image_file}: {e}")
+
+# Display results
+for result in ocr_results:
+ print(f"File: {result['file']}")
+ print(f" Text: {result['text'][:100]}...")
+ print(f" Confidence: {result['confidence']:.2f}")
+```
+
+### Custom Parser Pipeline
+
+```python
+from semantica.parse import (
+ parse_document, parse_json, parse_csv,
+ method_registry
+)
+
+# Define custom pipeline
+def pipeline_parser(file_path, file_type=None, **kwargs):
+ # Step 1: Parse document
+ doc = parse_document(file_path, file_type=file_type, **kwargs)
+
+ # Step 2: Extract structured data if available
+ structured_data = {}
+ if "json" in str(file_path):
+ structured_data = parse_json(file_path, **kwargs)
+ elif "csv" in str(file_path):
+ structured_data = parse_csv(file_path, **kwargs)
+
+ # Step 3: Combine results
+ return {
+ "document": doc,
+ "structured": structured_data,
+ "combined_text": doc.get("full_text", "") + str(structured_data)
+ }
+
+# Register pipeline
+method_registry.register("document", "pipeline", pipeline_parser)
+
+# Use pipeline
+result = parse_document("document.pdf", method="pipeline")
+print(f"Combined text: {result['combined_text']}")
+```
+
+This comprehensive guide covers all major features of the data parsing module. For more specific use cases or advanced scenarios, refer to the individual parser class documentation or explore the source code.
+
diff --git a/semantica/parse/registry.py b/semantica/parse/registry.py
new file mode 100644
index 00000000..ecaafada
--- /dev/null
+++ b/semantica/parse/registry.py
@@ -0,0 +1,130 @@
+"""
+Method Registry Module for Parse
+
+This module provides a method registry system for registering custom parsing methods,
+enabling extensibility and community contributions to the parsing toolkit.
+
+Supported Registration Types:
+ - Method Registry: Register custom parsing methods for:
+ * "document": Document parsing methods (PDF, DOCX, PPTX, HTML, TXT)
+ * "web": Web content parsing methods (HTML, XML, JavaScript)
+ * "structured": Structured data parsing methods (JSON, CSV, XML, YAML)
+ * "email": Email parsing methods
+ * "code": Code parsing methods
+ * "media": Media parsing methods (images, audio, video)
+
+Algorithms Used:
+ - Registry Pattern: Dictionary-based registration and lookup
+ - Dynamic Registration: Runtime function registration
+ - Type Checking: Type validation for registered components
+ - Lookup Algorithms: Hash-based O(1) lookup for methods
+ - Task-based Organization: Hierarchical organization by task type
+
+Key Features:
+ - Method registry for custom parsing methods
+ - Task-based method organization (document, web, structured, email, code, media)
+ - Dynamic registration and unregistration
+ - Easy discovery of available methods
+ - Support for community-contributed extensions
+
+Main Classes:
+ - MethodRegistry: Registry for custom parsing methods
+
+Global Instances:
+ - method_registry: Global method registry instance
+
+Example Usage:
+ >>> from semantica.parse.registry import method_registry
+ >>> method_registry.register("document", "custom_method", custom_document_parsing_function)
+ >>> available = method_registry.list_all("document")
+"""
+
+from typing import Dict, Callable, Any, List, Optional
+
+
+class MethodRegistry:
+ """Registry for custom parsing methods."""
+
+ _methods: Dict[str, Dict[str, Callable]] = {
+ "document": {},
+ "web": {},
+ "structured": {},
+ "email": {},
+ "code": {},
+ "media": {},
+ }
+
+ @classmethod
+ def register(cls, task: str, name: str, method_func: Callable):
+ """
+ Register a custom parsing method.
+
+ Args:
+ task: Task type ("document", "web", "structured", "email", "code", "media")
+ name: Method name
+ method_func: Method function
+ """
+ if task not in cls._methods:
+ cls._methods[task] = {}
+ cls._methods[task][name] = method_func
+
+ @classmethod
+ def get(cls, task: str, name: str) -> Optional[Callable]:
+ """
+ Get method by task and name.
+
+ Args:
+ task: Task type ("document", "web", "structured", "email", "code", "media")
+ name: Method name
+
+ Returns:
+ Method function or None
+ """
+ return cls._methods.get(task, {}).get(name)
+
+ @classmethod
+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:
+ """
+ List all registered methods.
+
+ Args:
+ task: Optional task type to filter by
+
+ Returns:
+ Dictionary mapping task types to method names
+ """
+ if task:
+ return {task: list(cls._methods.get(task, {}).keys())}
+ return {t: list(m.keys()) for t, m in cls._methods.items()}
+
+ @classmethod
+ def unregister(cls, task: str, name: str):
+ """
+ Unregister a method.
+
+ Args:
+ task: Task type ("document", "web", "structured", "email", "code", "media")
+ name: Method name
+ """
+ if task in cls._methods and name in cls._methods[task]:
+ del cls._methods[task][name]
+
+ @classmethod
+ def clear(cls, task: Optional[str] = None):
+ """
+ Clear all registered methods for a task or all tasks.
+
+ Args:
+ task: Optional task type to clear (clears all if None)
+ """
+ if task:
+ if task in cls._methods:
+ cls._methods[task].clear()
+ else:
+ for task_dict in cls._methods.values():
+ task_dict.clear()
+
+
+# Global registry
+method_registry = MethodRegistry()
+