Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Implement all parse module files: image_parser, web_parser, code_parser, email_parser, media_parser, structured_data_parser

KaifAhmad1ead993924461
diff --git a/libs/semantica/normalize/encoding_handler.py b/libs/semantica/normalize/encoding_handler.py
index 872727c9..82d4c5e0 100644
--- a/libs/semantica/normalize/encoding_handler.py
+++ b/libs/semantica/normalize/encoding_handler.py
@@ -5,10 +5,255 @@ This module provides encoding detection, conversion, and handling
for UTF-8 conversion and BOM handling.
"""
-# TODO: Implement encoding handling functionality
-# - Automatic encoding detection
-# - UTF-8 conversion and normalization
-# - BOM (Byte Order Mark) handling
-# - Encoding error recovery and fallback
-# - Batch encoding conversion
-# - Performance optimization for large files
+import chardet
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+class EncodingHandler:
+ """Encoding handling utilities."""
+
+ def __init__(self, **config):
+ """
+ Initialize encoding handler.
+
+ Args:
+ **config: Configuration options
+ """
+ self.logger = get_logger("encoding_handler")
+ self.config = config
+ self.default_encoding = config.get("default_encoding", "utf-8")
+ self.fallback_encodings = config.get("fallback_encodings", ["latin-1", "cp1252", "iso-8859-1"])
+
+ def detect(self, data: Union[str, bytes], **options) -> Tuple[str, float]:
+ """
+ Detect encoding of data.
+
+ Args:
+ data: Input data (string or bytes)
+ **options: Detection options
+
+ Returns:
+ tuple: (encoding, confidence)
+ """
+ if isinstance(data, str):
+ data = data.encode('utf-8')
+
+ if not data:
+ return (self.default_encoding, 0.0)
+
+ try:
+ result = chardet.detect(data)
+ if result:
+ encoding = result.get('encoding', self.default_encoding)
+ confidence = result.get('confidence', 0.0)
+ return (encoding, confidence)
+ else:
+ return (self.default_encoding, 0.0)
+ except Exception as e:
+ self.logger.warning(f"Failed to detect encoding: {e}")
+ return (self.default_encoding, 0.0)
+
+ def detect_file(self, file_path: Union[str, Path], **options) -> Tuple[str, float]:
+ """
+ Detect encoding of file.
+
+ Args:
+ file_path: Path to file
+ **options: Detection options
+
+ Returns:
+ tuple: (encoding, confidence)
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"File not found: {file_path}")
+
+ # Read sample bytes for detection
+ sample_size = options.get("sample_size", 10000)
+
+ try:
+ with open(file_path, 'rb') as f:
+ sample = f.read(sample_size)
+
+ return self.detect(sample, **options)
+ except Exception as e:
+ self.logger.error(f"Failed to detect file encoding: {e}")
+ raise ProcessingError(f"Failed to detect file encoding: {e}")
+
+ def convert_to_utf8(self, data: Union[str, bytes], source_encoding: Optional[str] = None, **options) -> str:
+ """
+ Convert data to UTF-8.
+
+ Args:
+ data: Input data
+ source_encoding: Source encoding (auto-detected if None)
+ **options: Conversion options
+
+ Returns:
+ str: UTF-8 encoded string
+ """
+ if isinstance(data, str):
+ # Already a string, just ensure it's valid UTF-8
+ return data.encode('utf-8', errors='replace').decode('utf-8')
+
+ if source_encoding is None:
+ source_encoding, _ = self.detect(data, **options)
+
+ # Try to decode with detected encoding
+ try:
+ return data.decode(source_encoding, errors='replace')
+ except (UnicodeDecodeError, LookupError):
+ # Try fallback encodings
+ for encoding in self.fallback_encodings:
+ try:
+ return data.decode(encoding, errors='replace')
+ except (UnicodeDecodeError, LookupError):
+ continue
+
+ # Final fallback: decode with errors replaced
+ self.logger.warning(f"Failed to decode with detected encoding, using errors='replace'")
+ return data.decode(self.default_encoding, errors='replace')
+
+ def convert_file_to_utf8(
+ self,
+ file_path: Union[str, Path],
+ output_path: Optional[Union[str, Path]] = None,
+ **options
+ ) -> str:
+ """
+ Convert file to UTF-8.
+
+ Args:
+ file_path: Path to input file
+ output_path: Path to output file (overwrites if None)
+ **options: Conversion options
+
+ Returns:
+ str: Converted content as string
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"File not found: {file_path}")
+
+ # Detect encoding
+ source_encoding, _ = self.detect_file(file_path, **options)
+
+ # Read file with detected encoding
+ try:
+ with open(file_path, 'r', encoding=source_encoding, errors='replace') as f:
+ content = f.read()
+ except Exception as e:
+ # Try fallback encodings
+ content = None
+ for encoding in self.fallback_encodings:
+ try:
+ with open(file_path, 'r', encoding=encoding, errors='replace') as f:
+ content = f.read()
+ break
+ except Exception:
+ continue
+
+ if content is None:
+ self.logger.error(f"Failed to read file with any encoding: {e}")
+ raise ProcessingError(f"Failed to read file: {e}")
+
+ # Ensure content is UTF-8
+ utf8_content = content.encode('utf-8', errors='replace').decode('utf-8')
+
+ # Write to output file if specified
+ if output_path:
+ output_path = Path(output_path)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+
+ with open(output_path, 'w', encoding='utf-8', errors='replace') as f:
+ f.write(utf8_content)
+
+ return utf8_content
+
+ def remove_bom(self, data: Union[str, bytes]) -> Union[str, bytes]:
+ """
+ Remove BOM (Byte Order Mark) from data.
+
+ Args:
+ data: Input data
+
+ Returns:
+ Data without BOM
+ """
+ if isinstance(data, bytes):
+ # Remove UTF-8 BOM
+ if data.startswith(b'\xef\xbb\xbf'):
+ return data[3:]
+ # Remove UTF-16 BOMs
+ elif data.startswith(b'\xff\xfe'):
+ return data[2:]
+ elif data.startswith(b'\xfe\xff'):
+ return data[2:]
+ else:
+ return data
+ else:
+ # String data - remove if present
+ if data.startswith('\ufeff'):
+ return data[1:]
+ else:
+ return data
+
+ def handle_encoding_error(self, data: bytes, **options) -> str:
+ """
+ Handle encoding errors gracefully.
+
+ Args:
+ data: Input bytes data
+ **options: Error handling options
+
+ Returns:
+ str: Decoded string with errors handled
+ """
+ error_strategy = options.get("error_strategy", "replace")
+
+ # Try detected encoding first
+ encoding, _ = self.detect(data, **options)
+
+ try:
+ return data.decode(encoding, errors=error_strategy)
+ except Exception:
+ # Try fallback encodings
+ for fallback_encoding in self.fallback_encodings:
+ try:
+ return data.decode(fallback_encoding, errors=error_strategy)
+ except Exception:
+ continue
+
+ # Final fallback
+ return data.decode(self.default_encoding, errors=error_strategy)
+
+ def validate_encoding(self, data: Union[str, bytes], encoding: str, **options) -> bool:
+ """
+ Validate that data can be decoded with given encoding.
+
+ Args:
+ data: Input data
+ encoding: Encoding to validate
+ **options: Validation options
+
+ Returns:
+ bool: True if encoding is valid for data
+ """
+ if isinstance(data, str):
+ try:
+ data.encode(encoding)
+ return True
+ except Exception:
+ return False
+ else:
+ try:
+ data.decode(encoding, errors='strict')
+ return True
+ except Exception:
+ return False
diff --git a/libs/semantica/normalize/language_detector.py b/libs/semantica/normalize/language_detector.py
index fd4da7e4..3de20392 100644
--- a/libs/semantica/normalize/language_detector.py
+++ b/libs/semantica/normalize/language_detector.py
@@ -5,10 +5,189 @@ This module provides multi-language detection capabilities
using langdetect and other language identification libraries.
"""
-# TODO: Implement language detection functionality
-# - Multi-language text detection
-# - Confidence scoring for language identification
-# - Batch processing for multiple documents
-# - Language-specific preprocessing
-# - Fallback handling for unknown languages
-# - Performance optimization for large texts
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from langdetect import detect, detect_langs
+from langdetect.lang_detect_exception import LangDetectException
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+
+
+class LanguageDetector:
+ """Language detection utilities."""
+
+ def __init__(self, **config):
+ """
+ Initialize language detector.
+
+ Args:
+ **config: Configuration options
+ """
+ self.logger = get_logger("language_detector")
+ self.config = config
+ self.default_language = config.get("default_language", "en")
+ self.min_confidence = config.get("min_confidence", 0.5)
+
+ def detect(self, text: str, **options) -> str:
+ """
+ Detect language of text.
+
+ Args:
+ text: Input text
+ **options: Detection options
+
+ Returns:
+ str: Detected language code
+ """
+ if not text or len(text.strip()) < 10:
+ return self.default_language
+
+ try:
+ language = detect(text)
+ return language
+ except LangDetectException:
+ self.logger.warning(f"Failed to detect language, using default: {self.default_language}")
+ return self.default_language
+ except Exception as e:
+ self.logger.error(f"Language detection error: {e}")
+ return self.default_language
+
+ def detect_with_confidence(self, text: str, **options) -> Tuple[str, float]:
+ """
+ Detect language with confidence score.
+
+ Args:
+ text: Input text
+ **options: Detection options
+
+ Returns:
+ tuple: (language_code, confidence_score)
+ """
+ if not text or len(text.strip()) < 10:
+ return (self.default_language, 0.0)
+
+ try:
+ languages = detect_langs(text)
+ if languages:
+ top_language = languages[0]
+ if top_language.prob >= self.min_confidence:
+ return (top_language.lang, top_language.prob)
+ else:
+ return (self.default_language, top_language.prob)
+ else:
+ return (self.default_language, 0.0)
+ except LangDetectException:
+ self.logger.warning(f"Failed to detect language, using default: {self.default_language}")
+ return (self.default_language, 0.0)
+ except Exception as e:
+ self.logger.error(f"Language detection error: {e}")
+ return (self.default_language, 0.0)
+
+ def detect_multiple(self, text: str, top_n: int = 3, **options) -> List[Tuple[str, float]]:
+ """
+ Detect top N languages with confidence scores.
+
+ Args:
+ text: Input text
+ top_n: Number of top languages to return
+ **options: Detection options
+
+ Returns:
+ list: List of (language_code, confidence_score) tuples
+ """
+ if not text or len(text.strip()) < 10:
+ return [(self.default_language, 0.0)]
+
+ try:
+ languages = detect_langs(text)
+ if languages:
+ return [(lang.lang, lang.prob) for lang in languages[:top_n]]
+ else:
+ return [(self.default_language, 0.0)]
+ except LangDetectException:
+ self.logger.warning(f"Failed to detect languages, using default: {self.default_language}")
+ return [(self.default_language, 0.0)]
+ except Exception as e:
+ self.logger.error(f"Language detection error: {e}")
+ return [(self.default_language, 0.0)]
+
+ def detect_batch(self, texts: List[str], **options) -> List[str]:
+ """
+ Detect languages for multiple texts in batch.
+
+ Args:
+ texts: List of texts to analyze
+ **options: Detection options
+
+ Returns:
+ list: List of detected language codes
+ """
+ return [self.detect(text, **options) for text in texts]
+
+ def detect_batch_with_confidence(self, texts: List[str], **options) -> List[Tuple[str, float]]:
+ """
+ Detect languages with confidence for multiple texts.
+
+ Args:
+ texts: List of texts to analyze
+ **options: Detection options
+
+ Returns:
+ list: List of (language_code, confidence_score) tuples
+ """
+ return [self.detect_with_confidence(text, **options) for text in texts]
+
+ def is_language(self, text: str, target_language: str, **options) -> bool:
+ """
+ Check if text is in target language.
+
+ Args:
+ text: Input text
+ target_language: Target language code
+ **options: Detection options
+
+ Returns:
+ bool: True if text is in target language
+ """
+ detected, confidence = self.detect_with_confidence(text, **options)
+ min_confidence = options.get("min_confidence", self.min_confidence)
+ return detected == target_language and confidence >= min_confidence
+
+ def get_language_name(self, language_code: str) -> str:
+ """
+ Get language name from code.
+
+ Args:
+ language_code: Language code (e.g., 'en', 'fr')
+
+ Returns:
+ str: Language name
+ """
+ language_names = {
+ 'en': 'English',
+ 'fr': 'French',
+ 'de': 'German',
+ 'es': 'Spanish',
+ 'it': 'Italian',
+ 'pt': 'Portuguese',
+ 'ru': 'Russian',
+ 'zh': 'Chinese',
+ 'ja': 'Japanese',
+ 'ko': 'Korean',
+ 'ar': 'Arabic',
+ 'hi': 'Hindi',
+ 'nl': 'Dutch',
+ 'sv': 'Swedish',
+ 'da': 'Danish',
+ 'no': 'Norwegian',
+ 'fi': 'Finnish',
+ 'pl': 'Polish',
+ 'tr': 'Turkish',
+ 'cs': 'Czech',
+ 'hu': 'Hungarian',
+ 'ro': 'Romanian',
+ 'th': 'Thai',
+ 'vi': 'Vietnamese'
+ }
+ return language_names.get(language_code, language_code.upper())
diff --git a/libs/semantica/normalize/text_cleaner.py b/libs/semantica/normalize/text_cleaner.py
index 457d7073..1be62499 100644
--- a/libs/semantica/normalize/text_cleaner.py
+++ b/libs/semantica/normalize/text_cleaner.py
@@ -5,10 +5,241 @@ This module provides text cleaning and preprocessing functions
for HTML removal, whitespace normalization, and text sanitization.
"""
-# TODO: Implement text cleaning functionality
-# - HTML tag removal and cleaning
-# - Whitespace normalization and trimming
-# - Special character handling and encoding
-# - Text sanitization and security
-# - Unicode normalization
-# - Language-specific cleaning rules
+import re
+import unicodedata
+from typing import Any, Dict, List, Optional, Union
+
+from bs4 import BeautifulSoup
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+
+
+class TextCleaner:
+ """Text cleaning utilities."""
+
+ def __init__(self, **config):
+ """
+ Initialize text cleaner.
+
+ Args:
+ **config: Configuration options
+ """
+ self.logger = get_logger("text_cleaner")
+ self.config = config
+
+ def clean(
+ self,
+ text: str,
+ remove_html: bool = True,
+ normalize_whitespace: bool = True,
+ normalize_unicode: bool = True,
+ remove_special_chars: bool = False,
+ **options
+ ) -> str:
+ """
+ Clean text with various options.
+
+ Args:
+ text: Input text to clean
+ remove_html: Whether to remove HTML tags
+ normalize_whitespace: Whether to normalize whitespace
+ normalize_unicode: Whether to normalize unicode
+ remove_special_chars: Whether to remove special characters
+ **options: Additional cleaning options
+
+ Returns:
+ str: Cleaned text
+ """
+ if not text:
+ return ""
+
+ cleaned = text
+
+ # Remove HTML tags
+ if remove_html:
+ cleaned = self.remove_html(cleaned)
+
+ # Normalize unicode
+ if normalize_unicode:
+ cleaned = self.normalize_unicode(cleaned, form=options.get("unicode_form", "NFC"))
+
+ # Normalize whitespace
+ if normalize_whitespace:
+ cleaned = self.normalize_whitespace(cleaned)
+
+ # Remove special characters
+ if remove_special_chars:
+ cleaned = self.remove_special_chars(cleaned, allow_spaces=options.get("allow_spaces", True))
+
+ return cleaned.strip()
+
+ def remove_html(self, text: str, preserve_structure: bool = False) -> str:
+ """
+ Remove HTML tags from text.
+
+ Args:
+ text: Input text with HTML
+ preserve_structure: Whether to preserve structure (use BeautifulSoup)
+
+ Returns:
+ str: Text without HTML tags
+ """
+ if not text:
+ return ""
+
+ if preserve_structure:
+ try:
+ soup = BeautifulSoup(text, 'html.parser')
+ return soup.get_text(separator='\n', strip=True)
+ except Exception:
+ # Fallback to regex if BeautifulSoup fails
+ pass
+
+ # Remove HTML tags using regex
+ text = re.sub(r'<[^>]+>', '', text)
+
+ # Decode HTML entities
+ text = text.replace('&nbsp;', ' ')
+ text = text.replace('&amp;', '&')
+ text = text.replace('&lt;', '<')
+ text = text.replace('&gt;', '>')
+ text = text.replace('&quot;', '"')
+ text = text.replace('&#39;', "'")
+
+ # Remove remaining HTML entities
+ text = re.sub(r'&#?\w+;', '', text)
+
+ return text
+
+ def normalize_whitespace(self, text: str) -> str:
+ """
+ Normalize whitespace in text.
+
+ Args:
+ text: Input text
+
+ Returns:
+ str: Text with normalized whitespace
+ """
+ if not text:
+ return ""
+
+ # Replace tabs and newlines with spaces
+ text = re.sub(r'[\t\n\r]+', ' ', text)
+
+ # Replace multiple spaces with single space
+ text = re.sub(r' +', ' ', text)
+
+ return text.strip()
+
+ def normalize_unicode(self, text: str, form: str = "NFC") -> str:
+ """
+ Normalize unicode characters.
+
+ Args:
+ text: Input text
+ form: Normalization form (NFC, NFD, NFKC, NFKD)
+
+ Returns:
+ str: Normalized text
+ """
+ if not text:
+ return ""
+
+ try:
+ return unicodedata.normalize(form, text)
+ except Exception as e:
+ self.logger.warning(f"Failed to normalize unicode: {e}")
+ return text
+
+ def remove_special_chars(self, text: str, allow_spaces: bool = True, allow_newlines: bool = False) -> str:
+ """
+ Remove special characters from text.
+
+ Args:
+ text: Input text
+ allow_spaces: Whether to allow spaces
+ allow_newlines: Whether to allow newlines
+
+ Returns:
+ str: Text without special characters
+ """
+ if not text:
+ return ""
+
+ if allow_spaces and allow_newlines:
+ # Keep alphanumeric, spaces, and newlines
+ pattern = r'[^a-zA-Z0-9\s]'
+ elif allow_spaces:
+ # Keep alphanumeric and spaces
+ pattern = r'[^a-zA-Z0-9 ]'
+ else:
+ # Keep only alphanumeric
+ pattern = r'[^a-zA-Z0-9]'
+
+ return re.sub(pattern, '', text)
+
+ def sanitize(self, text: str, **options) -> str:
+ """
+ Sanitize text for security.
+
+ Args:
+ text: Input text
+ **options: Sanitization options
+
+ Returns:
+ str: Sanitized text
+ """
+ if not text:
+ return ""
+
+ # Remove potential script tags
+ text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.IGNORECASE | re.DOTALL)
+ text = re.sub(r'<iframe[^>]*>.*?</iframe>', '', text, flags=re.IGNORECASE | re.DOTALL)
+
+ # Remove javascript: URLs
+ text = re.sub(r'javascript:', '', text, flags=re.IGNORECASE)
+
+ # Remove data: URLs if requested
+ if options.get("remove_data_urls", False):
+ text = re.sub(r'data:[^;]*;base64,', '', text, flags=re.IGNORECASE)
+
+ return text
+
+ def trim(self, text: str, **options) -> str:
+ """
+ Trim text.
+
+ Args:
+ text: Input text
+ **options: Trimming options
+
+ Returns:
+ str: Trimmed text
+ """
+ if not text:
+ return ""
+
+ # Remove leading/trailing whitespace
+ text = text.strip()
+
+ # Remove empty lines if requested
+ if options.get("remove_empty_lines", False):
+ lines = [line for line in text.split('\n') if line.strip()]
+ text = '\n'.join(lines)
+
+ return text
+
+ def clean_batch(self, texts: List[str], **options) -> List[str]:
+ """
+ Clean multiple texts in batch.
+
+ Args:
+ texts: List of texts to clean
+ **options: Cleaning options
+
+ Returns:
+ list: List of cleaned texts
+ """
+ return [self.clean(text, **options) for text in texts]
diff --git a/libs/semantica/parse/code_parser.py b/libs/semantica/parse/code_parser.py
index 0f2f5f0e..799353af 100644
--- a/libs/semantica/parse/code_parser.py
+++ b/libs/semantica/parse/code_parser.py
@@ -17,6 +17,36 @@ Main Classes:
- DependencyAnalyzer: Code dependency analyzer
"""
+import ast
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class CodeStructure:
+ """Code structure representation."""
+
+ functions: List[Dict[str, Any]] = field(default_factory=list)
+ classes: List[Dict[str, Any]] = field(default_factory=list)
+ imports: List[str] = field(default_factory=list)
+ variables: List[str] = field(default_factory=list)
+ constants: List[str] = field(default_factory=list)
+
+
+@dataclass
+class CodeComment:
+ """Code comment representation."""
+
+ text: str
+ line_number: int
+ type: str # "inline", "block", "docstring"
+ language: str
+
class CodeParser:
"""
@@ -28,18 +58,6 @@ class CodeParser:
• Analyzes code dependencies
• Handles various code formats
• Supports batch code processing
-
- Attributes:
- • syntax_parser: Syntax tree parser
- • comment_extractor: Comment processor
- • dependency_analyzer: Dependency analyzer
- • supported_languages: List of supported languages
-
- Methods:
- • parse_code(): Parse source code file
- • extract_structure(): Extract code structure
- • extract_comments(): Extract code comments
- • analyze_dependencies(): Analyze code dependencies
"""
def __init__(self, config=None, **kwargs):
@@ -52,56 +70,124 @@ class CodeParser:
• Setup dependency analysis
• Configure batch processing
"""
- pass
+ self.logger = get_logger("code_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize sub-parsers
+ self.syntax_parser = SyntaxTreeParser(**self.config.get("syntax", {}))
+ self.comment_extractor = CommentExtractor(**self.config.get("comments", {}))
+ self.dependency_analyzer = DependencyAnalyzer(**self.config.get("dependencies", {}))
+
+ # Supported languages
+ self.supported_languages = {
+ '.py': 'python',
+ '.js': 'javascript',
+ '.java': 'java',
+ '.cpp': 'cpp',
+ '.c': 'c',
+ '.cs': 'csharp',
+ '.rb': 'ruby',
+ '.go': 'go',
+ '.rs': 'rust',
+ '.php': 'php'
+ }
- def parse_code(self, file_path, language=None):
+ def parse_code(self, file_path: Union[str, Path], language: Optional[str] = None, **options) -> Dict[str, Any]:
"""
Parse source code file.
- • Detect programming language
- • Parse code syntax structure
- • Extract code elements
- • Process comments and docs
- • Analyze code patterns
- • Return parsed code object
- """
- pass
+ Args:
+ file_path: Path to code file
+ language: Programming language (auto-detected if None)
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed code data
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Code file not found: {file_path}")
+
+ # Detect language if not specified
+ if language is None:
+ language = self._detect_language(file_path)
+
+ if language not in self.supported_languages.values():
+ self.logger.warning(f"Language {language} may not be fully supported")
+
+ try:
+ # Read code content
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
+ code_content = f.read()
+
+ # Extract structure
+ structure = self.extract_structure(code_content, language)
+
+ # Extract comments
+ comments = self.extract_comments(code_content, language)
+
+ # Analyze dependencies
+ dependencies = self.analyze_dependencies(code_content, language)
+
+ return {
+ "file_path": str(file_path),
+ "language": language,
+ "structure": structure.__dict__,
+ "comments": [c.__dict__ for c in comments],
+ "dependencies": dependencies,
+ "line_count": len(code_content.splitlines()),
+ "size": len(code_content)
+ }
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse code {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse code: {e}")
- def extract_structure(self, code_content, language):
+ def extract_structure(self, code_content: str, language: str) -> CodeStructure:
"""
Extract code structure and elements.
- • Parse syntax tree
- • Extract functions and classes
- • Identify variables and imports
- • Analyze code organization
- • Return structure information
- """
- pass
+ Args:
+ code_content: Code content as string
+ language: Programming language
+
+ Returns:
+ CodeStructure: Code structure
+ """
+ return self.syntax_parser.extract_elements(code_content, language)
- def extract_comments(self, code_content, language):
+ def extract_comments(self, code_content: str, language: str) -> List[CodeComment]:
"""
Extract comments and documentation.
- • Find comment blocks
- • Extract docstrings
- • Process inline comments
- • Parse documentation
- • Return comment collection
- """
- pass
+ Args:
+ code_content: Code content as string
+ language: Programming language
+
+ Returns:
+ list: List of comments
+ """
+ return self.comment_extractor.extract_comments(code_content, language)
- def analyze_dependencies(self, code_content, language):
+ def analyze_dependencies(self, code_content: str, language: str) -> Dict[str, Any]:
"""
Analyze code dependencies and imports.
- • Parse import statements
- • Identify external dependencies
- • Map internal dependencies
- • Analyze dependency relationships
- • Return dependency analysis
- """
- pass
+ Args:
+ code_content: Code content as string
+ language: Programming language
+
+ Returns:
+ dict: Dependency analysis
+ """
+ return self.dependency_analyzer.analyze_dependencies(code_content, language)
+
+ def _detect_language(self, file_path: Path) -> str:
+ """Detect programming language from file extension."""
+ suffix = file_path.suffix.lower()
+ return self.supported_languages.get(suffix, "unknown")
class SyntaxTreeParser:
@@ -116,49 +202,163 @@ class SyntaxTreeParser:
"""
def __init__(self, **config):
- """
- Initialize syntax tree parser.
-
- • Setup language parsers
- • Configure tree analysis
- • Initialize element extractors
- • Setup error handling
- """
- pass
+ """Initialize syntax tree parser."""
+ self.logger = get_logger("syntax_tree_parser")
+ self.config = config
- def parse_syntax_tree(self, code_content, language):
+ def parse_syntax_tree(self, code_content: str, language: str) -> Any:
"""
Parse code into syntax tree.
- • Parse code with language parser
- • Build syntax tree structure
- • Validate tree integrity
- • Return syntax tree object
- """
- pass
+ Args:
+ code_content: Code content
+ language: Programming language
+
+ Returns:
+ Syntax tree object
+ """
+ if language == "python":
+ try:
+ return ast.parse(code_content)
+ except SyntaxError as e:
+ self.logger.warning(f"Syntax error in Python code: {e}")
+ return None
+ else:
+ # For other languages, return None (would need language-specific parsers)
+ return None
- def extract_elements(self, syntax_tree):
+ def extract_elements(self, code_content: str, language: str) -> CodeStructure:
"""
Extract code elements from syntax tree.
- • Traverse syntax tree
- • Extract functions and classes
- • Identify variables and constants
- • Extract control structures
- • Return element collection
- """
- pass
+ Args:
+ code_content: Code content
+ language: Programming language
+
+ Returns:
+ CodeStructure: Extracted structure
+ """
+ structure = CodeStructure()
+
+ if language == "python":
+ try:
+ tree = ast.parse(code_content)
+
+ # Extract functions and classes
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef):
+ structure.functions.append({
+ "name": node.name,
+ "line_number": node.lineno,
+ "args": [arg.arg for arg in node.args.args],
+ "decorators": [ast.unparse(d) for d in node.decorator_list]
+ })
+ elif isinstance(node, ast.ClassDef):
+ structure.classes.append({
+ "name": node.name,
+ "line_number": node.lineno,
+ "bases": [ast.unparse(b) for b in node.bases]
+ })
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ structure.imports.append(alias.name)
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ for alias in node.names:
+ structure.imports.append(f"{module}.{alias.name}")
+
+ except SyntaxError:
+ # Fallback to regex-based extraction
+ structure = self._extract_with_regex(code_content, language)
+ else:
+ # Use regex-based extraction for other languages
+ structure = self._extract_with_regex(code_content, language)
+
+ return structure
- def analyze_structure(self, syntax_tree):
+ def _extract_with_regex(self, code_content: str, language: str) -> CodeStructure:
+ """Extract code elements using regex patterns."""
+ structure = CodeStructure()
+
+ # Extract imports (common patterns)
+ import_patterns = {
+ "python": r'^import\s+(\S+)|^from\s+(\S+)\s+import',
+ "javascript": r'^import\s+.*?from\s+[\'"](\S+)[\'"]|^require\([\'"](\S+)[\'"]',
+ "java": r'^import\s+(\S+);',
+ "c": r'^#include\s+[<"](\S+)[>"]'
+ }
+
+ pattern = import_patterns.get(language, r'import|require|include')
+ for line in code_content.splitlines():
+ match = re.search(pattern, line, re.IGNORECASE)
+ if match:
+ structure.imports.append(match.group(1) or match.group(2) or match.group(0))
+
+ # Extract functions (common patterns)
+ func_patterns = {
+ "python": r'^def\s+(\w+)',
+ "javascript": r'^function\s+(\w+)|^(\w+)\s*=\s*function',
+ "java": r'^\s*(?:public|private|protected)?\s*\w+\s+(\w+)\s*\(',
+ "c": r'^\w+\s+(\w+)\s*\('
+ }
+
+ pattern = func_patterns.get(language, r'function|def')
+ for i, line in enumerate(code_content.splitlines(), 1):
+ match = re.search(pattern, line, re.IGNORECASE)
+ if match:
+ func_name = match.group(1) or match.group(2) or f"function_{i}"
+ structure.functions.append({
+ "name": func_name,
+ "line_number": i
+ })
+
+ # Extract classes (common patterns)
+ class_patterns = {
+ "python": r'^class\s+(\w+)',
+ "javascript": r'^class\s+(\w+)',
+ "java": r'^public\s+class\s+(\w+)',
+ "c": r'^struct\s+(\w+)|^class\s+(\w+)'
+ }
+
+ pattern = class_patterns.get(language, r'class|struct')
+ for i, line in enumerate(code_content.splitlines(), 1):
+ match = re.search(pattern, line, re.IGNORECASE)
+ if match:
+ class_name = match.group(1) or match.group(2) or f"class_{i}"
+ structure.classes.append({
+ "name": class_name,
+ "line_number": i
+ })
+
+ return structure
+
+ def analyze_structure(self, syntax_tree: Any) -> Dict[str, Any]:
"""
Analyze code structure and organization.
- • Analyze code hierarchy
- • Identify patterns and conventions
- • Calculate complexity metrics
- • Return structure analysis
- """
- pass
+ Args:
+ syntax_tree: Syntax tree object
+
+ Returns:
+ dict: Structure analysis
+ """
+ if syntax_tree is None:
+ return {}
+
+ # For Python AST
+ if isinstance(syntax_tree, ast.Module):
+ functions = sum(1 for node in ast.walk(syntax_tree) if isinstance(node, ast.FunctionDef))
+ classes = sum(1 for node in ast.walk(syntax_tree) if isinstance(node, ast.ClassDef))
+ imports = sum(1 for node in ast.walk(syntax_tree) if isinstance(node, (ast.Import, ast.ImportFrom)))
+
+ return {
+ "function_count": functions,
+ "class_count": classes,
+ "import_count": imports,
+ "complexity": "low" if functions + classes < 10 else "medium" if functions + classes < 50 else "high"
+ }
+
+ return {}
class CommentExtractor:
@@ -173,49 +373,74 @@ class CommentExtractor:
"""
def __init__(self, **config):
- """
- Initialize comment extractor.
-
- • Setup comment pattern matching
- • Configure documentation parsing
- • Initialize content analysis
- • Setup metadata extraction
- """
- pass
+ """Initialize comment extractor."""
+ self.logger = get_logger("comment_extractor")
+ self.config = config
- def extract_comments(self, code_content, language):
+ def extract_comments(self, code_content: str, language: str) -> List[CodeComment]:
"""
Extract all comments from code.
- • Find comment patterns
- • Extract comment content
- • Process different comment types
- • Clean comment text
- • Return comment collection
- """
- pass
-
- def extract_docstrings(self, code_content, language):
- """
- Extract documentation strings.
+ Args:
+ code_content: Code content
+ language: Programming language
+
+ Returns:
+ list: List of comments
+ """
+ comments = []
- • Find docstring patterns
- • Extract docstring content
- • Parse documentation structure
- • Return docstring collection
- """
- pass
+ # Comment patterns by language
+ patterns = {
+ "python": [
+ (r'#(.+?)$', 'inline'),
+ (r'"""(.*?)"""', 'docstring'),
+ (r"'''(.*?)'''", 'docstring')
+ ],
+ "javascript": [
+ (r'//(.+?)$', 'inline'),
+ (r'/\*(.*?)\*/', 'block')
+ ],
+ "java": [
+ (r'//(.+?)$', 'inline'),
+ (r'/\*(.*?)\*/', 'block')
+ ],
+ "c": [
+ (r'//(.+?)$', 'inline'),
+ (r'/\*(.*?)\*/', 'block')
+ ]
+ }
+
+ patterns_list = patterns.get(language, [(r'//(.+?)$', 'inline'), (r'/\*(.*?)\*/', 'block')])
+
+ for i, line in enumerate(code_content.splitlines(), 1):
+ for pattern, comment_type in patterns_list:
+ matches = re.finditer(pattern, line, re.MULTILINE | re.DOTALL)
+ for match in matches:
+ comment_text = match.group(1).strip()
+ if comment_text:
+ comments.append(CodeComment(
+ text=comment_text,
+ line_number=i,
+ type=comment_type,
+ language=language
+ ))
+
+ return comments
- def analyze_comment_content(self, comments):
+ def extract_docstrings(self, code_content: str, language: str) -> List[CodeComment]:
"""
- Analyze comment content and patterns.
+ Extract documentation strings.
- • Analyze comment topics
- • Identify documentation patterns
- • Extract metadata
- • Return analysis results
- """
- pass
+ Args:
+ code_content: Code content
+ language: Programming language
+
+ Returns:
+ list: List of docstrings
+ """
+ comments = self.extract_comments(code_content, language)
+ return [c for c in comments if c.type == "docstring"]
class DependencyAnalyzer:
@@ -230,46 +455,68 @@ class DependencyAnalyzer:
"""
def __init__(self, **config):
- """
- Initialize dependency analyzer.
-
- • Setup dependency detection
- • Configure version tracking
- • Initialize conflict detection
- • Setup dependency mapping
- """
- pass
+ """Initialize dependency analyzer."""
+ self.logger = get_logger("dependency_analyzer")
+ self.config = config
- def analyze_dependencies(self, code_content, language):
+ def analyze_dependencies(self, code_content: str, language: str) -> Dict[str, Any]:
"""
Analyze code dependencies.
- • Parse import statements
- • Identify external packages
- • Map internal dependencies
- • Analyze dependency relationships
- • Return dependency analysis
- """
- pass
-
- def detect_conflicts(self, dependencies):
- """
- Detect dependency conflicts.
+ Args:
+ code_content: Code content
+ language: Programming language
+
+ Returns:
+ dict: Dependency analysis
+ """
+ dependencies = {
+ "imports": [],
+ "external": [],
+ "internal": [],
+ "standard_library": []
+ }
- • Compare dependency versions
- • Identify version conflicts
- • Analyze compatibility issues
- • Return conflict report
- """
- pass
-
- def map_dependency_tree(self, dependencies):
- """
- Map dependency tree structure.
+ if language == "python":
+ try:
+ tree = ast.parse(code_content)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ dependencies["imports"].append(alias.name)
+ if self._is_standard_library(alias.name):
+ dependencies["standard_library"].append(alias.name)
+ else:
+ dependencies["external"].append(alias.name)
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ for alias in node.names:
+ full_name = f"{module}.{alias.name}" if module else alias.name
+ dependencies["imports"].append(full_name)
+ if self._is_standard_library(module or alias.name):
+ dependencies["standard_library"].append(full_name)
+ else:
+ dependencies["external"].append(full_name)
+ except SyntaxError:
+ # Fallback to regex
+ pass
- • Build dependency graph
- • Identify dependency chains
- • Analyze dependency depth
- • Return dependency tree
- """
- pass
+ # Regex fallback
+ import_pattern = r'(?:import|from|require|include)\s+[\'"](.*?)[\'"]|(?:import|from)\s+(\S+)'
+ for line in code_content.splitlines():
+ matches = re.finditer(import_pattern, line, re.IGNORECASE)
+ for match in matches:
+ dep = match.group(1) or match.group(2)
+ if dep:
+ dependencies["imports"].append(dep)
+
+ return dependencies
+
+ def _is_standard_library(self, module_name: str) -> bool:
+ """Check if module is from Python standard library."""
+ stdlib_modules = [
+ 'os', 'sys', 'json', 'csv', 'xml', 'html', 'urllib', 'http',
+ 'email', 'datetime', 'time', 're', 'math', 'random', 'collections',
+ 'itertools', 'functools', 'operator', 'pathlib', 'shutil'
+ ]
+ return any(module_name.startswith(mod) for mod in stdlib_modules)
diff --git a/libs/semantica/parse/csv_parser.py b/libs/semantica/parse/csv_parser.py
index 3397aabd..a6117a87 100644
--- a/libs/semantica/parse/csv_parser.py
+++ b/libs/semantica/parse/csv_parser.py
@@ -1,14 +1,158 @@
"""
-CSV/TSV file parser for Semantica framework.
+CSV document parser for Semantica framework.
-This module handles CSV and TSV file parsing using pandas and csv
-for structured data extraction.
+This module handles CSV file parsing for structured data extraction.
"""
-# TODO: Implement CSV parsing functionality
-# - CSV/TSV data extraction
-# - Delimiter detection and handling
-# - Header recognition and processing
-# - Data type inference
-# - Encoding detection and handling
-# - Large file streaming support
+import csv
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class CSVData:
+ """CSV data representation."""
+
+ headers: List[str]
+ rows: List[Dict[str, Any]]
+ row_count: int
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class CSVParser:
+ """CSV document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize CSV parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("csv_parser")
+ self.config = config
+
+ def parse(
+ self,
+ file_path: Union[str, Path],
+ delimiter: str = ',',
+ **options
+ ) -> CSVData:
+ """
+ Parse CSV file.
+
+ Args:
+ file_path: Path to CSV file
+ delimiter: CSV delimiter (default: ',')
+ **options: Parsing options:
+ - 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
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"CSV file not found: {file_path}")
+
+ has_header = options.get("has_header", True)
+ encoding = options.get("encoding", "utf-8")
+ skip_rows = options.get("skip_rows", 0)
+ max_rows = options.get("max_rows")
+
+ try:
+ with open(file_path, 'r', encoding=encoding, errors='ignore', newline='') as f:
+ # Detect delimiter if not specified
+ sample = f.read(1024)
+ f.seek(0)
+
+ if delimiter is None:
+ sniffer = csv.Sniffer()
+ delimiter = sniffer.sniff(sample).delimiter
+
+ reader = csv.DictReader(f, delimiter=delimiter) if has_header else csv.reader(f, delimiter=delimiter)
+
+ headers = []
+ rows = []
+
+ # Get headers
+ if has_header:
+ headers = reader.fieldnames or []
+ else:
+ # Read first row as headers
+ try:
+ first_row = next(reader)
+ headers = [f"Column_{i+1}" for i in range(len(first_row))]
+ rows.append(dict(zip(headers, first_row)))
+ except StopIteration:
+ pass
+
+ # Skip rows if requested
+ for _ in range(skip_rows):
+ try:
+ next(reader)
+ except StopIteration:
+ break
+
+ # Read rows
+ for idx, row in enumerate(reader):
+ if max_rows and idx >= max_rows:
+ break
+
+ if has_header:
+ rows.append(row)
+ else:
+ rows.append(dict(zip(headers, row if isinstance(row, list) else [row])))
+
+ metadata = {
+ "file_path": str(file_path),
+ "delimiter": delimiter,
+ "encoding": encoding,
+ "has_header": has_header
+ }
+
+ return CSVData(
+ headers=headers,
+ rows=rows,
+ row_count=len(rows),
+ metadata=metadata
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse CSV {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse CSV: {e}")
+
+ def parse_to_dict(self, file_path: Union[str, Path], **options) -> List[Dict[str, Any]]:
+ """
+ Parse CSV to list of dictionaries.
+
+ Args:
+ file_path: Path to CSV file
+ **options: Parsing options
+
+ Returns:
+ list: List of row dictionaries
+ """
+ csv_data = self.parse(file_path, **options)
+ return csv_data.rows
+
+ def parse_to_list(self, file_path: Union[str, Path], **options) -> List[List[Any]]:
+ """
+ Parse CSV to list of lists.
+
+ Args:
+ file_path: Path to CSV file
+ **options: Parsing options
+
+ Returns:
+ list: List of row lists
+ """
+ csv_data = self.parse(file_path, **options)
+ return [[row.get(header, '') for header in csv_data.headers] for row in csv_data.rows]
diff --git a/libs/semantica/parse/document_parser.py b/libs/semantica/parse/document_parser.py
index 9f18eaff..f53c50ee 100644
--- a/libs/semantica/parse/document_parser.py
+++ b/libs/semantica/parse/document_parser.py
@@ -12,11 +12,17 @@ Key Features:
Main Classes:
- DocumentParser: Main document parsing class
- - PDFParser: PDF-specific parser
- - DOCXParser: DOCX-specific parser
- - HTMLParser: HTML content parser
"""
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .pdf_parser import PDFParser
+from .docx_parser import DOCXParser
+from .html_parser import HTMLParser
+
class DocumentParser:
"""
@@ -53,9 +59,27 @@ class DocumentParser:
• Setup error handling
• Configure batch processing
"""
- pass
+ self.logger = get_logger("document_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize format-specific parsers
+ self.pdf_parser = PDFParser(**self.config.get("pdf", {}))
+ self.docx_parser = DOCXParser(**self.config.get("docx", {}))
+ self.html_parser = HTMLParser(**self.config.get("html", {}))
+
+ # Supported formats
+ self.supported_formats = {
+ '.pdf': 'pdf',
+ '.docx': 'docx',
+ '.doc': 'docx',
+ '.html': 'html',
+ '.htm': 'html',
+ '.txt': 'text',
+ '.text': 'text'
+ }
- def parse_document(self, file_path, file_type=None):
+ def parse_document(self, file_path: Union[str, Path], file_type: Optional[str] = None, **options) -> Dict[str, Any]:
"""
Parse document of any supported format.
@@ -65,10 +89,42 @@ class DocumentParser:
• Extract metadata and properties
• Handle parsing errors gracefully
• Return parsed document object
- """
- pass
-
- def extract_text(self, file_path, **options):
+
+ Args:
+ file_path: Path to document file
+ file_type: Document type (auto-detected if None)
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed document data
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Document file not found: {file_path}")
+
+ # Detect file type if not specified
+ if file_type is None:
+ file_type = self._detect_file_type(file_path)
+
+ # Route to appropriate parser
+ try:
+ if file_type == 'pdf':
+ return self.pdf_parser.parse(file_path, **options)
+ elif file_type == 'docx':
+ return self.docx_parser.parse(file_path, **options)
+ elif file_type == 'html':
+ return self.html_parser.parse(file_path, **options)
+ elif file_type == 'text':
+ return self._parse_text(file_path, **options)
+ else:
+ raise ValidationError(f"Unsupported document format: {file_type}")
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse document {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse document: {e}")
+
+ def extract_text(self, file_path: Union[str, Path], **options) -> str:
"""
Extract text content from document.
@@ -78,10 +134,29 @@ class DocumentParser:
• Handle special characters and encoding
• Clean and normalize text
• Return extracted text content
- """
- pass
-
- def extract_metadata(self, file_path):
+
+ Args:
+ file_path: Path to document file
+ **options: Parsing options
+
+ Returns:
+ str: Extracted text content
+ """
+ file_path = Path(file_path)
+ file_type = self._detect_file_type(file_path)
+
+ if file_type == 'pdf':
+ return self.pdf_parser.extract_text(file_path, **options)
+ elif file_type == 'docx':
+ return self.docx_parser.extract_text(file_path)
+ elif file_type == 'html':
+ return self.html_parser.extract_text(file_path, clean=options.get("clean", True))
+ elif file_type == 'text':
+ return self._parse_text(file_path, **options).get("text", "")
+ else:
+ raise ValidationError(f"Unsupported document format: {file_type}")
+
+ def extract_metadata(self, file_path: Union[str, Path]) -> Dict[str, Any]:
"""
Extract document metadata and properties.
@@ -90,10 +165,20 @@ class DocumentParser:
• Get author and title information
• Extract document statistics
• Return metadata dictionary
+
+ Args:
+ file_path: Path to document file
+
+ Returns:
+ dict: Document metadata
"""
- pass
+ file_path = Path(file_path)
+ file_type = self._detect_file_type(file_path)
+
+ result = self.parse_document(file_path, file_type=file_type, extract_tables=False, extract_images=False)
+ return result.get("metadata", {})
- def parse_batch(self, file_paths, **options):
+ def parse_batch(self, file_paths: List[Union[str, Path]], **options) -> Dict[str, Any]:
"""
Parse multiple documents in batch.
@@ -102,178 +187,69 @@ class DocumentParser:
• Handle individual file errors
• Collect parsing results
• Return batch processing results
- """
- pass
-
-
-class PDFParser:
- """
- PDF document parsing engine.
-
- • Extracts text from PDF documents
- • Handles various PDF formats and versions
- • Processes PDF metadata and properties
- • Extracts images and embedded content
- • Handles password-protected PDFs
- """
-
- def __init__(self, **config):
- """
- Initialize PDF parser.
- • Setup PDF processing libraries
- • Configure text extraction options
- • Initialize metadata extractors
- • Setup image extraction tools
- """
- pass
-
- def parse_pdf(self, file_path, **options):
- """
- Parse PDF document.
-
- • Open and validate PDF file
- • Extract text from all pages
- • Process page structure and layout
- • Extract images and embedded content
- • Handle password protection if needed
- • Return parsed PDF content
- """
- pass
-
- def extract_text_from_pdf(self, file_path):
- """
- Extract text content from PDF.
-
- • Process each PDF page
- • Extract text with positioning
- • Preserve text flow and structure
- • Handle special characters
- • Return extracted text
- """
- pass
-
- def extract_images_from_pdf(self, file_path):
- """
- Extract images from PDF document.
-
- • Identify image objects in PDF
- • Extract image data and metadata
- • Save images to temporary storage
- • Return image information
- """
- pass
-
-
-class DOCXParser:
- """
- DOCX document parsing engine.
-
- • Extracts content from DOCX files
- • Handles document structure and formatting
- • Processes tables and embedded objects
- • Extracts styles and formatting information
- """
-
- def __init__(self, **config):
- """
- Initialize DOCX parser.
-
- • Setup DOCX processing libraries
- • Configure content extraction
- • Initialize structure analyzers
- • Setup formatting extractors
- """
- pass
-
- def parse_docx(self, file_path, **options):
- """
- Parse DOCX document.
-
- • Open and validate DOCX file
- • Extract document structure
- • Process paragraphs and formatting
- • Extract tables and embedded content
- • Return parsed DOCX content
- """
- pass
-
- def extract_paragraphs(self, file_path):
- """
- Extract paragraphs from DOCX.
-
- • Process document paragraphs
- • Extract text and formatting
- • Preserve paragraph structure
- • Return paragraph collection
- """
- pass
-
- def extract_tables(self, file_path):
- """
- Extract tables from DOCX.
-
- • Identify table elements
- • Extract table structure and data
- • Process table formatting
- • Return table data collection
- """
- pass
-
-
-class HTMLParser:
- """
- HTML content parsing engine.
-
- • Parses HTML documents and fragments
- • Extracts text content and structure
- • Handles various HTML versions
- • Processes embedded content and links
- • Cleans and normalizes HTML content
- """
-
- def __init__(self, **config):
- """
- Initialize HTML parser.
-
- • Setup HTML parsing libraries
- • Configure content extraction
- • Initialize text cleaners
- • Setup link and image extractors
- """
- pass
-
- def parse_html(self, html_content, **options):
- """
- Parse HTML content.
-
- • Parse HTML structure
- • Extract text content
- • Process embedded elements
- • Clean and normalize content
- • Return parsed HTML object
- """
- pass
-
- def extract_text_from_html(self, html_content):
- """
- Extract clean text from HTML.
-
- • Remove HTML tags and scripts
- • Extract text content
- • Preserve text structure
- • Clean whitespace and formatting
- • Return clean text content
- """
- pass
-
- def extract_links_from_html(self, html_content):
- """
- Extract links from HTML.
-
- • Find all link elements
- • Extract URL and text
- • Resolve relative URLs
- • Return link collection
- """
- pass
+ Args:
+ file_paths: List of document file paths
+ **options: Parsing options:
+ - max_workers: Maximum parallel workers
+ - continue_on_error: Continue on errors (default: True)
+
+ Returns:
+ dict: Batch processing results
+ """
+ results = {
+ "successful": [],
+ "failed": [],
+ "total": len(file_paths)
+ }
+
+ continue_on_error = options.get("continue_on_error", True)
+
+ for file_path in file_paths:
+ try:
+ result = self.parse_document(file_path, **options)
+ results["successful"].append({
+ "file_path": str(file_path),
+ "result": result
+ })
+ except Exception as e:
+ error_info = {
+ "file_path": str(file_path),
+ "error": str(e),
+ "error_type": type(e).__name__
+ }
+ results["failed"].append(error_info)
+
+ if not continue_on_error:
+ raise ProcessingError(f"Batch processing failed at {file_path}: {e}")
+
+ results["success_count"] = len(results["successful"])
+ results["failure_count"] = len(results["failed"])
+
+ return results
+
+ def _detect_file_type(self, file_path: Path) -> str:
+ """Detect document file type from extension."""
+ suffix = file_path.suffix.lower()
+ return self.supported_formats.get(suffix, 'unknown')
+
+ def _parse_text(self, file_path: Path, **options) -> Dict[str, Any]:
+ """Parse plain text file."""
+ encoding = options.get("encoding", "utf-8")
+
+ try:
+ with open(file_path, 'r', encoding=encoding, errors='ignore') as f:
+ text = f.read()
+
+ return {
+ "text": text,
+ "metadata": {
+ "file_path": str(file_path),
+ "encoding": encoding,
+ "size": len(text)
+ },
+ "full_text": text
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to parse text file {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse text file: {e}")
diff --git a/libs/semantica/parse/docx_parser.py b/libs/semantica/parse/docx_parser.py
index b597ee62..db3dba7b 100644
--- a/libs/semantica/parse/docx_parser.py
+++ b/libs/semantica/parse/docx_parser.py
@@ -5,10 +5,255 @@ This module handles DOCX document parsing using python-docx
for text, formatting, and structure extraction.
"""
-# TODO: Implement DOCX parsing functionality
-# - Text extraction from Word documents
-# - Paragraph and section structure recognition
-# - Table extraction and formatting preservation
-# - Image and embedded object handling
-# - Style and formatting information extraction
-# - Comments and track changes processing
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from docx import Document
+from docx.document import Document as DocxDocument
+from docx.oxml.text.paragraph import CT_P
+from docx.oxml.table import CT_Tbl
+from docx.table import Table
+from docx.text.paragraph import Paragraph
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class DocxSection:
+ """Document section representation."""
+
+ heading: str
+ level: int
+ content: str
+ paragraphs: List[str] = field(default_factory=list)
+ tables: List[Dict[str, Any]] = field(default_factory=list)
+
+
+@dataclass
+class DocxMetadata:
+ """Document metadata representation."""
+
+ title: Optional[str] = None
+ author: Optional[str] = None
+ subject: Optional[str] = None
+ keywords: Optional[str] = None
+ comments: Optional[str] = None
+ category: Optional[str] = None
+ created: Optional[str] = None
+ modified: Optional[str] = None
+ last_modified_by: Optional[str] = None
+
+
+class DOCXParser:
+ """DOCX document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize DOCX parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("docx_parser")
+ self.config = config
+
+ def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:
+ """
+ Parse DOCX document.
+
+ Args:
+ file_path: Path to DOCX file
+ **options: Parsing options:
+ - 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 document data
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"DOCX file not found: {file_path}")
+
+ if not file_path.suffix.lower() in ['.docx', '.doc']:
+ raise ValidationError(f"File is not a DOCX: {file_path}")
+
+ try:
+ doc = Document(str(file_path))
+
+ # Extract metadata
+ metadata = self._extract_metadata(doc)
+
+ # Extract paragraphs
+ paragraphs = []
+ for para in doc.paragraphs:
+ if para.text.strip():
+ paragraphs.append(para.text.strip())
+
+ # Extract tables
+ tables = []
+ if options.get("extract_tables", True):
+ for table in doc.tables:
+ table_data = self._extract_table(table)
+ tables.append(table_data)
+
+ # Extract structure
+ sections = self._extract_sections(doc, options)
+
+ # Extract comments if requested
+ comments = []
+ if options.get("extract_comments", False):
+ comments = self._extract_comments(doc)
+
+ # Extract formatting if requested
+ formatting_info = None
+ if options.get("extract_formatting", False):
+ formatting_info = self._extract_formatting(doc)
+
+ return {
+ "metadata": metadata.__dict__,
+ "full_text": "\n\n".join(paragraphs),
+ "paragraphs": paragraphs,
+ "tables": tables,
+ "sections": [s.__dict__ for s in sections],
+ "comments": comments,
+ "formatting": formatting_info,
+ "total_paragraphs": len(paragraphs),
+ "total_tables": len(tables)
+ }
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse DOCX {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse DOCX: {e}")
+
+ def extract_text(self, file_path: Union[str, Path]) -> str:
+ """
+ Extract text from DOCX.
+
+ Args:
+ file_path: Path to DOCX file
+
+ Returns:
+ str: Extracted text
+ """
+ result = self.parse(file_path, extract_tables=False, extract_comments=False, extract_formatting=False)
+ return result["full_text"]
+
+ def extract_tables(self, file_path: Union[str, Path]) -> List[Dict[str, Any]]:
+ """
+ Extract tables from DOCX.
+
+ Args:
+ file_path: Path to DOCX file
+
+ Returns:
+ list: Extracted tables
+ """
+ result = self.parse(file_path, extract_formatting=False, extract_comments=False)
+ return result["tables"]
+
+ def _extract_table(self, table: Table) -> Dict[str, Any]:
+ """Extract data from table."""
+ table_data = {
+ "rows": [],
+ "row_count": len(table.rows),
+ "col_count": len(table.columns) if table.rows else 0
+ }
+
+ for row in table.rows:
+ row_data = []
+ for cell in row.cells:
+ row_data.append(cell.text.strip())
+ table_data["rows"].append(row_data)
+
+ return table_data
+
+ def _extract_sections(self, doc: DocxDocument, options: Dict[str, Any]) -> List[DocxSection]:
+ """Extract document sections based on headings."""
+ sections = []
+ current_section = None
+
+ for para in doc.paragraphs:
+ # Check if paragraph is a heading
+ if para.style.name.startswith('Heading'):
+ # Get heading level
+ level = int(para.style.name.split()[-1]) if para.style.name.split()[-1].isdigit() else 1
+
+ # Save previous section if exists
+ if current_section:
+ sections.append(current_section)
+
+ # Create new section
+ current_section = DocxSection(
+ heading=para.text.strip(),
+ level=level,
+ content="",
+ paragraphs=[],
+ tables=[]
+ )
+ elif current_section:
+ # Add paragraph to current section
+ if para.text.strip():
+ current_section.paragraphs.append(para.text.strip())
+ current_section.content += para.text.strip() + "\n\n"
+
+ # Add last section
+ if current_section:
+ sections.append(current_section)
+
+ return sections
+
+ def _extract_metadata(self, doc: DocxDocument) -> DocxMetadata:
+ """Extract document metadata."""
+ core_props = doc.core_properties
+
+ return DocxMetadata(
+ title=core_props.title,
+ author=core_props.author,
+ subject=core_props.subject,
+ keywords=core_props.keywords,
+ comments=core_props.comments,
+ category=core_props.category,
+ created=str(core_props.created) if core_props.created else None,
+ modified=str(core_props.modified) if core_props.modified else None,
+ last_modified_by=core_props.last_modified_by
+ )
+
+ def _extract_comments(self, doc: DocxDocument) -> List[Dict[str, Any]]:
+ """Extract comments from document."""
+ comments = []
+ # Note: python-docx doesn't directly support comments
+ # This would require additional processing
+ return comments
+
+ def _extract_formatting(self, doc: DocxDocument) -> Dict[str, Any]:
+ """Extract formatting information."""
+ formatting = {
+ "paragraphs": []
+ }
+
+ for para in doc.paragraphs:
+ para_formatting = {
+ "text": para.text,
+ "style": para.style.name,
+ "alignment": str(para.alignment) if para.alignment else None,
+ "runs": []
+ }
+
+ for run in para.runs:
+ run_formatting = {
+ "text": run.text,
+ "bold": run.bold,
+ "italic": run.italic,
+ "underline": run.underline,
+ "font_name": run.font.name if run.font.name else None,
+ "font_size": run.font.size.pt if run.font.size else None
+ }
+ para_formatting["runs"].append(run_formatting)
+
+ formatting["paragraphs"].append(para_formatting)
+
+ return formatting
diff --git a/libs/semantica/parse/email_parser.py b/libs/semantica/parse/email_parser.py
index 17efb08f..27b8e0bf 100644
--- a/libs/semantica/parse/email_parser.py
+++ b/libs/semantica/parse/email_parser.py
@@ -16,6 +16,51 @@ Main Classes:
- EmailThreadAnalyzer: Email thread processor
"""
+import email
+from dataclasses import dataclass, field
+from email import message_from_string, message_from_bytes
+from email.header import decode_header
+from email.utils import parsedate_to_datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class EmailHeaders:
+ """Email headers representation."""
+
+ subject: Optional[str] = None
+ from_address: Optional[str] = None
+ to_addresses: List[str] = field(default_factory=list)
+ cc_addresses: List[str] = field(default_factory=list)
+ bcc_addresses: List[str] = field(default_factory=list)
+ date: Optional[str] = None
+ message_id: Optional[str] = None
+ in_reply_to: Optional[str] = None
+ references: List[str] = field(default_factory=list)
+ custom_headers: Dict[str, str] = field(default_factory=dict)
+
+
+@dataclass
+class EmailBody:
+ """Email body representation."""
+
+ text: Optional[str] = None
+ html: Optional[str] = None
+ attachments: List[Dict[str, Any]] = field(default_factory=list)
+
+
+@dataclass
+class EmailData:
+ """Email data representation."""
+
+ headers: EmailHeaders
+ body: EmailBody
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
class EmailParser:
"""
@@ -27,191 +72,296 @@ class EmailParser:
• Handles email attachments
• Analyzes email threads and conversations
• Supports various email formats
-
- Attributes:
- • mime_parser: MIME message parser
- • thread_analyzer: Email thread analyzer
- • attachment_processor: Attachment handler
- • header_parser: Email header parser
-
- Methods:
- • parse_email(): Parse email message
- • extract_headers(): Extract email headers
- • extract_body(): Extract email body
- • analyze_thread(): Analyze email thread
"""
def __init__(self, config=None, **kwargs):
- """
- Initialize email parser.
+ """Initialize email parser."""
+ self.logger = get_logger("email_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
- • Setup MIME parsing library
- • Configure email processing
- • Initialize thread analysis
- • Setup attachment handling
- • Configure header parsing
- """
- pass
+ self.mime_parser = MIMEParser(**self.config.get("mime", {}))
+ self.thread_analyzer = EmailThreadAnalyzer(**self.config.get("thread", {}))
- def parse_email(self, email_content, **options):
+ def parse_email(self, email_content: Union[str, bytes, Path], **options) -> EmailData:
"""
Parse email message content.
- • Parse email structure
- • Extract headers and metadata
- • Process MIME parts
- • Extract body content
- • Handle attachments
- • Return parsed email object
+ Args:
+ email_content: Email content (string, bytes, or file path)
+ **options: Parsing options:
+ - extract_attachments: Whether to extract attachments (default: True)
+
+ Returns:
+ EmailData: Parsed email data
"""
- pass
+ # Load email content
+ if isinstance(email_content, Path) or (isinstance(email_content, str) and Path(email_content).exists()):
+ file_path = Path(email_content)
+ if not file_path.exists():
+ raise ValidationError(f"Email file not found: {file_path}")
+
+ with open(file_path, 'rb') as f:
+ email_bytes = f.read()
+ email_msg = message_from_bytes(email_bytes)
+ elif isinstance(email_content, bytes):
+ email_msg = message_from_bytes(email_content)
+ else:
+ email_msg = message_from_string(email_content)
+
+ try:
+ # Extract headers
+ headers = self.extract_headers(email_msg)
+
+ # Extract body
+ body = self.extract_body(email_msg, extract_attachments=options.get("extract_attachments", True))
+
+ return EmailData(
+ headers=headers,
+ body=body,
+ metadata={
+ "message_id": headers.message_id,
+ "date": headers.date
+ }
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse email: {e}")
+ raise ProcessingError(f"Failed to parse email: {e}")
- def extract_headers(self, email_message):
+ def extract_headers(self, email_message: email.message.Message) -> EmailHeaders:
"""
Extract email headers and metadata.
- • Parse email headers
- • Extract sender and recipient info
- • Process date and subject
- • Extract custom headers
- • Return header dictionary
+ Args:
+ email_message: Email message object
+
+ Returns:
+ EmailHeaders: Extracted headers
"""
- pass
+ def decode_header_value(value):
+ """Decode email header value."""
+ if value is None:
+ return None
+
+ decoded_parts = decode_header(value)
+ decoded_str = ""
+ for part, encoding in decoded_parts:
+ if isinstance(part, bytes):
+ decoded_str += part.decode(encoding or 'utf-8', errors='ignore')
+ else:
+ decoded_str += part
+ return decoded_str.strip()
+
+ headers = EmailHeaders()
+
+ # Extract standard headers
+ headers.subject = decode_header_value(email_message.get('Subject'))
+ headers.from_address = decode_header_value(email_message.get('From'))
+
+ # Extract recipients
+ to_header = email_message.get('To', '')
+ if to_header:
+ headers.to_addresses = [addr.strip() for addr in str(to_header).split(',')]
+
+ cc_header = email_message.get('Cc', '')
+ if cc_header:
+ headers.cc_addresses = [addr.strip() for addr in str(cc_header).split(',')]
+
+ bcc_header = email_message.get('Bcc', '')
+ if bcc_header:
+ headers.bcc_addresses = [addr.strip() for addr in str(bcc_header).split(',')]
+
+ # Extract dates
+ date_str = email_message.get('Date')
+ if date_str:
+ try:
+ date_obj = parsedate_to_datetime(date_str)
+ headers.date = date_obj.isoformat() if date_obj else str(date_str)
+ except Exception:
+ headers.date = str(date_str)
+
+ # Extract message IDs
+ headers.message_id = email_message.get('Message-ID')
+ headers.in_reply_to = email_message.get('In-Reply-To')
+
+ # Extract references
+ references = email_message.get('References', '')
+ if references:
+ headers.references = [ref.strip() for ref in str(references).split()]
+
+ # Extract custom headers
+ for header_name, header_value in email_message.items():
+ if header_name not in ['Subject', 'From', 'To', 'Cc', 'Bcc', 'Date', 'Message-ID', 'In-Reply-To', 'References']:
+ headers.custom_headers[header_name] = decode_header_value(header_value)
+
+ return headers
- def extract_body(self, email_message):
+ def extract_body(self, email_message: email.message.Message, extract_attachments: bool = True) -> EmailBody:
"""
Extract email body content.
- • Process MIME multipart structure
- • Extract text and HTML content
- • Handle content encoding
- • Clean and normalize content
- • Return body content
+ Args:
+ email_message: Email message object
+ extract_attachments: Whether to extract attachments
+
+ Returns:
+ EmailBody: Extracted body content
"""
- pass
+ body = EmailBody()
+
+ # Process MIME message
+ if email_message.is_multipart():
+ for part in email_message.walk():
+ content_type = part.get_content_type()
+ content_disposition = part.get("Content-Disposition", "")
+
+ # Check if it's an attachment
+ if "attachment" in content_disposition and extract_attachments:
+ attachment = self._extract_attachment(part)
+ if attachment:
+ body.attachments.append(attachment)
+
+ # Extract text content
+ elif content_type == "text/plain":
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or 'utf-8'
+ body.text = payload.decode(charset, errors='ignore')
+
+ # Extract HTML content
+ elif content_type == "text/html":
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or 'utf-8'
+ body.html = payload.decode(charset, errors='ignore')
+ else:
+ # Single part message
+ content_type = email_message.get_content_type()
+ payload = email_message.get_payload(decode=True)
+
+ if payload:
+ charset = email_message.get_content_charset() or 'utf-8'
+ if content_type == "text/html":
+ body.html = payload.decode(charset, errors='ignore')
+ else:
+ body.text = payload.decode(charset, errors='ignore')
+
+ return body
+
+ def _extract_attachment(self, part: email.message.Message) -> Optional[Dict[str, Any]]:
+ """Extract attachment from email part."""
+ try:
+ filename = part.get_filename()
+ if not filename:
+ return None
+
+ # Decode filename
+ decoded_parts = decode_header(filename)
+ decoded_filename = ""
+ for part_bytes, encoding in decoded_parts:
+ if isinstance(part_bytes, bytes):
+ decoded_filename += part_bytes.decode(encoding or 'utf-8', errors='ignore')
+ else:
+ decoded_filename += part_bytes
+
+ payload = part.get_payload(decode=True)
+
+ return {
+ "filename": decoded_filename,
+ "content_type": part.get_content_type(),
+ "size": len(payload) if payload else 0,
+ "data": payload
+ }
+ except Exception as e:
+ self.logger.warning(f"Failed to extract attachment: {e}")
+ return None
- def analyze_thread(self, emails):
+ def analyze_thread(self, emails: List[EmailData]) -> Dict[str, Any]:
"""
Analyze email thread structure.
- • Group related emails
- • Identify thread participants
- • Analyze conversation flow
- • Extract thread metadata
- • Return thread analysis
+ Args:
+ emails: List of email data objects
+
+ Returns:
+ dict: Thread analysis
"""
- pass
+ return self.thread_analyzer.analyze_thread(emails)
class MIMEParser:
- """
- MIME message parsing engine.
-
- • Parses MIME multipart messages
- • Handles various content types
- • Processes email attachments
- • Manages content encoding
- • Extracts embedded content
- """
+ """MIME message parsing engine."""
def __init__(self, **config):
- """
- Initialize MIME parser.
-
- • Setup MIME parsing library
- • Configure content handling
- • Initialize attachment processing
- • Setup encoding detection
- """
- pass
+ """Initialize MIME parser."""
+ self.logger = get_logger("mime_parser")
+ self.config = config
- def parse_mime_message(self, message_content):
+ def parse_mime_message(self, message_content: Union[str, bytes]) -> email.message.Message:
"""
Parse MIME message structure.
- • Parse MIME headers
- • Process multipart structure
- • Extract content parts
- • Handle content encoding
- • Return parsed MIME object
- """
- pass
-
- def extract_content_parts(self, mime_message):
- """
- Extract content from MIME parts.
-
- • Process each MIME part
- • Extract text and binary content
- • Handle different content types
- • Process attachments
- • Return content collection
- """
- pass
-
- def decode_content(self, content, encoding):
+ Args:
+ message_content: MIME message content
+
+ Returns:
+ Email message object
"""
- Decode content with specified encoding.
-
- • Apply content decoding
- • Handle encoding errors
- • Return decoded content
- """
- pass
+ if isinstance(message_content, bytes):
+ return message_from_bytes(message_content)
+ else:
+ return message_from_string(message_content)
class EmailThreadAnalyzer:
- """
- Email thread analysis engine.
-
- • Analyzes email conversations
- • Identifies thread participants
- • Tracks conversation flow
- • Extracts thread metadata
- • Handles thread reconstruction
- """
+ """Email thread analysis engine."""
def __init__(self, **config):
- """
- Initialize email thread analyzer.
-
- • Setup thread analysis algorithms
- • Configure participant detection
- • Initialize conversation tracking
- • Setup metadata extraction
- """
- pass
+ """Initialize email thread analyzer."""
+ self.logger = get_logger("email_thread_analyzer")
+ self.config = config
- def analyze_thread(self, emails):
+ def analyze_thread(self, emails: List[EmailData]) -> Dict[str, Any]:
"""
Analyze email thread structure.
- • Group emails by thread
- • Identify thread participants
- • Analyze conversation flow
- • Extract thread metadata
- • Return thread analysis
- """
- pass
-
- def identify_participants(self, emails):
+ Args:
+ emails: List of email data objects
+
+ Returns:
+ dict: Thread analysis
"""
- Identify thread participants.
+ analysis = {
+ "thread_count": len(emails),
+ "participants": set(),
+ "messages_by_date": {},
+ "reply_chains": []
+ }
- • Extract sender and recipient info
- • Identify unique participants
- • Analyze participation patterns
- • Return participant list
- """
- pass
-
- def track_conversation_flow(self, emails):
- """
- Track conversation flow and patterns.
+ # Extract participants
+ for email_data in emails:
+ if email_data.headers.from_address:
+ analysis["participants"].add(email_data.headers.from_address)
+ analysis["participants"].update(email_data.headers.to_addresses)
+ analysis["participants"].update(email_data.headers.cc_addresses)
- • Analyze email sequence
- • Identify response patterns
- • Track topic changes
- • Return flow analysis
- """
- pass
+ analysis["participants"] = list(analysis["participants"])
+
+ # Group by date
+ for email_data in emails:
+ if email_data.headers.date:
+ date_key = email_data.headers.date[:10] if len(email_data.headers.date) >= 10 else email_data.headers.date
+ if date_key not in analysis["messages_by_date"]:
+ analysis["messages_by_date"][date_key] = []
+ analysis["messages_by_date"][date_key].append(email_data.headers.message_id)
+
+ # Identify reply chains
+ for email_data in emails:
+ if email_data.headers.in_reply_to:
+ analysis["reply_chains"].append({
+ "message_id": email_data.headers.message_id,
+ "in_reply_to": email_data.headers.in_reply_to
+ })
+
+ return analysis
diff --git a/libs/semantica/parse/excel_parser.py b/libs/semantica/parse/excel_parser.py
index f89b1bab..c6709569 100644
--- a/libs/semantica/parse/excel_parser.py
+++ b/libs/semantica/parse/excel_parser.py
@@ -1,14 +1,236 @@
"""
-Excel spreadsheet parser for Semantica framework.
+Excel document parser for Semantica framework.
This module handles Excel file parsing using openpyxl and pandas
-for data extraction and structure recognition.
+for spreadsheet data extraction.
"""
-# TODO: Implement Excel parsing functionality
-# - Worksheet data extraction
-# - Cell formatting and data type recognition
-# - Formula and calculation handling
-# - Chart and graph data extraction
-# - Pivot table processing
-# - Multiple sheet handling
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+import pandas as pd
+from openpyxl import load_workbook
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class ExcelSheet:
+ """Excel sheet representation."""
+
+ name: str
+ data: List[Dict[str, Any]]
+ row_count: int
+ column_count: int
+ headers: List[str] = field(default_factory=list)
+
+
+@dataclass
+class ExcelData:
+ """Excel workbook representation."""
+
+ sheet_names: List[str]
+ sheets: Dict[str, ExcelSheet]
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class ExcelParser:
+ """Excel document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize Excel parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("excel_parser")
+ self.config = config
+
+ def parse(
+ self,
+ file_path: Union[str, Path],
+ sheet_name: Optional[str] = None,
+ **options
+ ) -> Union[ExcelData, ExcelSheet]:
+ """
+ Parse Excel file.
+
+ Args:
+ file_path: Path to Excel file
+ sheet_name: Specific sheet name (None = all sheets)
+ **options: Parsing options:
+ - header_row: Row number to use as header (default: 0)
+ - skip_rows: Number of rows to skip
+ - max_rows: Maximum number of rows to read per sheet
+ - engine: Parser engine ('pandas' or 'openpyxl', default: 'pandas')
+
+ Returns:
+ ExcelData or ExcelSheet: Parsed Excel data
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Excel file not found: {file_path}")
+
+ if not file_path.suffix.lower() in ['.xlsx', '.xls', '.xlsm']:
+ raise ValidationError(f"File is not an Excel file: {file_path}")
+
+ try:
+ engine = options.get("engine", "pandas")
+
+ if engine == "pandas":
+ return self._parse_with_pandas(file_path, sheet_name, **options)
+ else:
+ return self._parse_with_openpyxl(file_path, sheet_name, **options)
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse Excel {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse Excel: {e}")
+
+ def _parse_with_pandas(
+ self,
+ file_path: Path,
+ sheet_name: Optional[str],
+ **options
+ ) -> Union[ExcelData, ExcelSheet]:
+ """Parse Excel using pandas."""
+ header_row = options.get("header_row", 0)
+ skip_rows = options.get("skip_rows", 0)
+ max_rows = options.get("max_rows")
+
+ # Read all sheets or specific sheet
+ if sheet_name:
+ df = pd.read_excel(
+ file_path,
+ sheet_name=sheet_name,
+ header=header_row,
+ skiprows=skip_rows,
+ nrows=max_rows
+ )
+
+ # Convert to list of dictionaries
+ rows = df.fillna("").to_dict('records')
+
+ return ExcelSheet(
+ name=sheet_name,
+ data=rows,
+ row_count=len(rows),
+ column_count=len(df.columns),
+ headers=list(df.columns)
+ )
+ else:
+ # Read all sheets
+ excel_file = pd.ExcelFile(file_path)
+ sheets = {}
+
+ for sheet_name in excel_file.sheet_names:
+ df = pd.read_excel(
+ excel_file,
+ sheet_name=sheet_name,
+ header=header_row,
+ skiprows=skip_rows,
+ nrows=max_rows
+ )
+
+ rows = df.fillna("").to_dict('records')
+
+ sheets[sheet_name] = ExcelSheet(
+ name=sheet_name,
+ data=rows,
+ row_count=len(rows),
+ column_count=len(df.columns),
+ headers=list(df.columns)
+ )
+
+ return ExcelData(
+ sheet_names=excel_file.sheet_names,
+ sheets=sheets,
+ metadata={
+ "file_path": str(file_path),
+ "total_sheets": len(excel_file.sheet_names)
+ }
+ )
+
+ def _parse_with_openpyxl(
+ self,
+ file_path: Path,
+ sheet_name: Optional[str],
+ **options
+ ) -> Union[ExcelData, ExcelSheet]:
+ """Parse Excel using openpyxl."""
+ wb = load_workbook(file_path, data_only=True)
+
+ header_row = options.get("header_row", 0)
+ skip_rows = options.get("skip_rows", 0)
+ max_rows = options.get("max_rows")
+
+ if sheet_name:
+ ws = wb[sheet_name]
+ return self._parse_sheet(ws, header_row, skip_rows, max_rows)
+ else:
+ sheets = {}
+ for sheet_name in wb.sheetnames:
+ ws = wb[sheet_name]
+ sheets[sheet_name] = self._parse_sheet(ws, header_row, skip_rows, max_rows)
+
+ return ExcelData(
+ sheet_names=wb.sheetnames,
+ sheets=sheets,
+ metadata={
+ "file_path": str(file_path),
+ "total_sheets": len(wb.sheetnames)
+ }
+ )
+
+ def _parse_sheet(self, worksheet, header_row: int, skip_rows: int, max_rows: Optional[int]) -> ExcelSheet:
+ """Parse individual worksheet."""
+ rows_data = []
+
+ # Get headers
+ headers = []
+ if worksheet.max_row > header_row:
+ header_cells = list(worksheet.iter_rows(min_row=header_row+1, max_row=header_row+1, values_only=True))[0]
+ headers = [str(cell) if cell is not None else f"Column_{i+1}" for i, cell in enumerate(header_cells)]
+
+ # Get data rows
+ start_row = header_row + skip_rows + 2 if headers else skip_rows + 1
+ end_row = start_row + max_rows if max_rows else worksheet.max_row + 1
+
+ for row in worksheet.iter_rows(min_row=start_row, max_row=end_row-1, values_only=True):
+ row_dict = {}
+ for idx, cell_value in enumerate(row):
+ header = headers[idx] if idx < len(headers) else f"Column_{idx+1}"
+ row_dict[header] = str(cell_value) if cell_value is not None else ""
+ rows_data.append(row_dict)
+
+ return ExcelSheet(
+ name=worksheet.title,
+ data=rows_data,
+ row_count=len(rows_data),
+ column_count=len(headers) if headers else 0,
+ headers=headers
+ )
+
+ def extract_sheet(self, file_path: Union[str, Path], sheet_name: str, **options) -> ExcelSheet:
+ """
+ Extract specific sheet from Excel.
+
+ Args:
+ file_path: Path to Excel file
+ sheet_name: Sheet name to extract
+ **options: Parsing options
+
+ Returns:
+ ExcelSheet: Extracted sheet data
+ """
+ result = self.parse(file_path, sheet_name=sheet_name, **options)
+ if isinstance(result, ExcelSheet):
+ return result
+ else:
+ if sheet_name in result.sheets:
+ return result.sheets[sheet_name]
+ else:
+ raise ValidationError(f"Sheet '{sheet_name}' not found in Excel file")
diff --git a/libs/semantica/parse/html_parser.py b/libs/semantica/parse/html_parser.py
index 46343afb..5d9cf2af 100644
--- a/libs/semantica/parse/html_parser.py
+++ b/libs/semantica/parse/html_parser.py
@@ -5,10 +5,327 @@ This module handles HTML parsing using BeautifulSoup and lxml
for content extraction and structure analysis.
"""
-# TODO: Implement HTML parsing functionality
-# - HTML content extraction and cleaning
-# - DOM structure analysis
-# - Link and reference extraction
-# - Meta tag and metadata processing
-# - Form and interactive element handling
-# - CSS and styling information extraction
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+from urllib.parse import urljoin
+
+from bs4 import BeautifulSoup
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class HTMLMetadata:
+ """HTML metadata representation."""
+
+ title: Optional[str] = None
+ description: Optional[str] = None
+ keywords: Optional[str] = None
+ author: Optional[str] = None
+ og_title: Optional[str] = None
+ og_description: Optional[str] = None
+ og_image: Optional[str] = None
+ og_url: Optional[str] = None
+ twitter_card: Optional[str] = None
+ canonical_url: Optional[str] = None
+
+
+@dataclass
+class HTMLElement:
+ """HTML element representation."""
+
+ tag: str
+ text: str
+ attributes: Dict[str, str] = field(default_factory=dict)
+ children: List['HTMLElement'] = field(default_factory=list)
+
+
+class HTMLParser:
+ """HTML document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize HTML parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("html_parser")
+ self.config = config
+
+ def parse(self, html_content: Union[str, Path], base_url: Optional[str] = None, **options) -> Dict[str, Any]:
+ """
+ Parse HTML content.
+
+ Args:
+ html_content: HTML content as string or file path
+ base_url: Base URL for resolving relative links
+ **options: Parsing options:
+ - extract_links: Whether to extract links (default: True)
+ - extract_images: Whether to extract images (default: True)
+ - extract_forms: Whether to extract forms (default: False)
+ - extract_tables: Whether to extract tables (default: True)
+ - clean_text: Whether to clean extracted text (default: True)
+
+ Returns:
+ dict: Parsed HTML data
+ """
+ # Load HTML content
+ if isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):
+ with open(html_content, 'r', encoding='utf-8', errors='ignore') as f:
+ html_string = f.read()
+ else:
+ html_string = html_content
+
+ try:
+ soup = BeautifulSoup(html_string, 'html.parser')
+
+ # Extract metadata
+ metadata = self._extract_metadata(soup)
+
+ # Extract text content
+ if options.get("clean_text", True):
+ text = self._extract_clean_text(soup)
+ else:
+ text = soup.get_text()
+
+ # Extract links
+ links = []
+ if options.get("extract_links", True):
+ links = self._extract_links(soup, base_url)
+
+ # Extract images
+ images = []
+ if options.get("extract_images", True):
+ images = self._extract_images(soup, base_url)
+
+ # Extract forms
+ forms = []
+ if options.get("extract_forms", False):
+ forms = self._extract_forms(soup)
+
+ # Extract tables
+ tables = []
+ if options.get("extract_tables", True):
+ tables = self._extract_tables(soup)
+
+ # Extract structure
+ structure = self._extract_structure(soup)
+
+ return {
+ "metadata": metadata.__dict__,
+ "text": text,
+ "html": html_string,
+ "links": links,
+ "images": images,
+ "forms": forms,
+ "tables": tables,
+ "structure": structure
+ }
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse HTML: {e}")
+ raise ProcessingError(f"Failed to parse HTML: {e}")
+
+ def extract_text(self, html_content: Union[str, Path], clean: bool = True) -> str:
+ """
+ Extract text from HTML.
+
+ Args:
+ html_content: HTML content or file path
+ clean: Whether to clean extracted text
+
+ Returns:
+ str: Extracted text
+ """
+ result = self.parse(html_content, extract_links=False, extract_images=False, extract_forms=False, extract_tables=False, clean_text=clean)
+ return result["text"]
+
+ def extract_links(self, html_content: Union[str, Path], base_url: Optional[str] = None) -> List[Dict[str, Any]]:
+ """
+ Extract links from HTML.
+
+ Args:
+ html_content: HTML content or file path
+ base_url: Base URL for resolving relative links
+
+ Returns:
+ list: Extracted links
+ """
+ result = self.parse(html_content, base_url=base_url, extract_images=False, extract_forms=False, extract_tables=False)
+ return result["links"]
+
+ def _extract_metadata(self, soup: BeautifulSoup) -> HTMLMetadata:
+ """Extract metadata from HTML."""
+ metadata = HTMLMetadata()
+
+ # Extract title
+ title_tag = soup.find('title')
+ if title_tag:
+ metadata.title = title_tag.get_text().strip()
+
+ # Extract meta tags
+ for meta_tag in soup.find_all('meta'):
+ name = meta_tag.get('name') or meta_tag.get('property', '')
+ content = meta_tag.get('content', '')
+
+ if name.lower() == 'description':
+ metadata.description = content
+ elif name.lower() == 'keywords':
+ metadata.keywords = content
+ elif name.lower() == 'author':
+ metadata.author = content
+ elif name == 'og:title':
+ metadata.og_title = content
+ elif name == 'og:description':
+ metadata.og_description = content
+ elif name == 'og:image':
+ metadata.og_image = content
+ elif name == 'og:url':
+ metadata.og_url = content
+ elif name == 'twitter:card':
+ metadata.twitter_card = content
+
+ # Extract canonical URL
+ canonical = soup.find('link', rel='canonical')
+ if canonical:
+ metadata.canonical_url = canonical.get('href')
+
+ return metadata
+
+ def _extract_clean_text(self, soup: BeautifulSoup) -> str:
+ """Extract clean text from HTML."""
+ # Remove script and style elements
+ for element in soup(['script', 'style', 'noscript']):
+ element.decompose()
+
+ # Get text
+ text = soup.get_text()
+
+ # Clean whitespace
+ lines = (line.strip() for line in text.splitlines())
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
+ text = ' '.join(chunk for chunk in chunks if chunk)
+
+ return text
+
+ def _extract_links(self, soup: BeautifulSoup, base_url: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Extract links from HTML."""
+ links = []
+
+ for link_tag in soup.find_all('a', href=True):
+ href = link_tag['href']
+
+ # Resolve relative URLs
+ if base_url:
+ url = urljoin(base_url, href)
+ else:
+ url = href
+
+ link_info = {
+ "url": url,
+ "text": link_tag.get_text().strip(),
+ "title": link_tag.get('title'),
+ "rel": link_tag.get('rel')
+ }
+ links.append(link_info)
+
+ return links
+
+ def _extract_images(self, soup: BeautifulSoup, base_url: Optional[str] = None) -> List[Dict[str, Any]]:
+ """Extract images from HTML."""
+ images = []
+
+ for img_tag in soup.find_all('img'):
+ src = img_tag.get('src')
+ if src:
+ # Resolve relative URLs
+ if base_url:
+ url = urljoin(base_url, src)
+ else:
+ url = src
+
+ img_info = {
+ "url": url,
+ "alt": img_tag.get('alt', ''),
+ "title": img_tag.get('title'),
+ "width": img_tag.get('width'),
+ "height": img_tag.get('height')
+ }
+ images.append(img_info)
+
+ return images
+
+ def _extract_forms(self, soup: BeautifulSoup) -> List[Dict[str, Any]]:
+ """Extract forms from HTML."""
+ forms = []
+
+ for form_tag in soup.find_all('form'):
+ form_info = {
+ "action": form_tag.get('action', ''),
+ "method": form_tag.get('method', 'get').lower(),
+ "fields": []
+ }
+
+ # Extract form fields
+ for input_tag in form_tag.find_all(['input', 'textarea', 'select']):
+ field_info = {
+ "name": input_tag.get('name'),
+ "type": input_tag.get('type') or input_tag.name,
+ "value": input_tag.get('value', ''),
+ "required": input_tag.has_attr('required')
+ }
+ form_info["fields"].append(field_info)
+
+ forms.append(form_info)
+
+ return forms
+
+ def _extract_tables(self, soup: BeautifulSoup) -> List[Dict[str, Any]]:
+ """Extract tables from HTML."""
+ tables = []
+
+ for table_tag in soup.find_all('table'):
+ table_data = {
+ "headers": [],
+ "rows": []
+ }
+
+ # Extract headers
+ thead = table_tag.find('thead')
+ if thead:
+ for th in thead.find_all(['th', 'td']):
+ table_data["headers"].append(th.get_text().strip())
+
+ # Extract rows
+ tbody = table_tag.find('tbody') or table_tag
+ for row in tbody.find_all('tr'):
+ cells = []
+ for cell in row.find_all(['td', 'th']):
+ cells.append(cell.get_text().strip())
+ if cells:
+ table_data["rows"].append(cells)
+
+ tables.append(table_data)
+
+ return tables
+
+ def _extract_structure(self, soup: BeautifulSoup) -> Dict[str, Any]:
+ """Extract document structure."""
+ structure = {
+ "headings": [],
+ "sections": []
+ }
+
+ # Extract headings
+ for level in range(1, 7):
+ for heading in soup.find_all(f'h{level}'):
+ structure["headings"].append({
+ "level": level,
+ "text": heading.get_text().strip(),
+ "id": heading.get('id')
+ })
+
+ return structure
diff --git a/libs/semantica/parse/image_parser.py b/libs/semantica/parse/image_parser.py
index b0eb2429..f26e714c 100644
--- a/libs/semantica/parse/image_parser.py
+++ b/libs/semantica/parse/image_parser.py
@@ -5,10 +5,240 @@ This module handles image parsing using Tesseract OCR and PIL
for text extraction and image analysis.
"""
-# TODO: Implement image parsing functionality
-# - OCR text extraction using Tesseract
-# - Image preprocessing and enhancement
-# - Multiple language OCR support
-# - Layout analysis and text structure recognition
-# - Image metadata extraction
-# - Batch processing capabilities
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from PIL import Image, ExifTags
+from PIL.Image import Image as PILImage
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+try:
+ import pytesseract
+ TESSERACT_AVAILABLE = True
+except ImportError:
+ TESSERACT_AVAILABLE = False
+
+
+@dataclass
+class ImageMetadata:
+ """Image metadata representation."""
+
+ format: Optional[str] = None
+ mode: Optional[str] = None
+ size: tuple = (0, 0)
+ width: int = 0
+ height: int = 0
+ exif: Dict[str, Any] = field(default_factory=dict)
+ info: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class OCRResult:
+ """OCR result representation."""
+
+ text: str
+ confidence: float = 0.0
+ language: str = "eng"
+ boxes: List[Dict[str, Any]] = field(default_factory=list)
+
+
+class ImageParser:
+ """Image parser for OCR and metadata extraction."""
+
+ def __init__(self, **config):
+ """
+ Initialize image parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("image_parser")
+ self.config = config
+ self.tesseract_path = config.get("tesseract_path")
+ if self.tesseract_path:
+ pytesseract.pytesseract.tesseract_cmd = self.tesseract_path
+
+ def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:
+ """
+ Parse image file.
+
+ Args:
+ file_path: Path to image file
+ **options: Parsing options:
+ - 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
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Image file not found: {file_path}")
+
+ # Validate image file
+ try:
+ with Image.open(file_path) as img:
+ img.verify()
+ except Exception as e:
+ raise ValidationError(f"Invalid image file: {e}")
+
+ try:
+ with Image.open(file_path) as img:
+ # Extract metadata
+ metadata = None
+ if options.get("extract_metadata", True):
+ metadata = self._extract_metadata(img, file_path)
+
+ # Extract text using OCR
+ ocr_result = None
+ if options.get("extract_text", False) and TESSERACT_AVAILABLE:
+ ocr_result = self.extract_text(file_path, language=options.get("ocr_language", "eng"))
+
+ return {
+ "metadata": metadata.__dict__ if metadata else None,
+ "ocr": ocr_result.__dict__ if ocr_result else None,
+ "text": ocr_result.text if ocr_result else None
+ }
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse image {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse image: {e}")
+
+ def extract_text(self, file_path: Union[str, Path], language: str = "eng", **options) -> OCRResult:
+ """
+ Extract text from image using OCR.
+
+ Args:
+ file_path: Path to image file
+ language: OCR language code
+ **options: OCR options
+
+ Returns:
+ OCRResult: Extracted text and confidence
+ """
+ if not TESSERACT_AVAILABLE:
+ raise ProcessingError("Tesseract OCR is not available. Install pytesseract and tesseract.")
+
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Image file not found: {file_path}")
+
+ try:
+ # Extract text
+ text = pytesseract.image_to_string(str(file_path), lang=language)
+
+ # Get detailed data with boxes
+ data = pytesseract.image_to_data(str(file_path), lang=language, output_type=pytesseract.Output.DICT)
+
+ # Calculate average confidence
+ confidences = [conf for conf in data['conf'] if conf != -1]
+ avg_confidence = sum(confidences) / len(confidences) if confidences else 0.0
+
+ # Extract boxes
+ boxes = []
+ n_boxes = len(data['level'])
+ for i in range(n_boxes):
+ if data['text'][i].strip():
+ boxes.append({
+ "text": data['text'][i],
+ "confidence": data['conf'][i],
+ "left": data['left'][i],
+ "top": data['top'][i],
+ "width": data['width'][i],
+ "height": data['height'][i]
+ })
+
+ return OCRResult(
+ text=text.strip(),
+ confidence=avg_confidence / 100.0,
+ language=language,
+ boxes=boxes
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to extract text from image {file_path}: {e}")
+ raise ProcessingError(f"Failed to extract text from image: {e}")
+
+ def extract_metadata(self, file_path: Union[str, Path]) -> ImageMetadata:
+ """
+ Extract metadata from image.
+
+ Args:
+ file_path: Path to image file
+
+ Returns:
+ ImageMetadata: Image metadata
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"Image file not found: {file_path}")
+
+ try:
+ with Image.open(file_path) as img:
+ # Extract EXIF data
+ exif_data = {}
+ if hasattr(img, '_getexif') and img._getexif():
+ exif_dict = img._getexif()
+ for tag_id, value in exif_dict.items():
+ tag = ExifTags.TAGS.get(tag_id, tag_id)
+ exif_data[str(tag)] = str(value)
+
+ return ImageMetadata(
+ format=img.format,
+ mode=img.mode,
+ size=img.size,
+ width=img.width,
+ height=img.height,
+ exif=exif_data,
+ info=img.info or {}
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to extract metadata from image {file_path}: {e}")
+ raise ProcessingError(f"Failed to extract metadata from image: {e}")
+
+ def preprocess_image(self, file_path: Union[str, Path], **options) -> Path:
+ """
+ Preprocess image for better OCR results.
+
+ Args:
+ file_path: Path to image file
+ **options: Preprocessing options:
+ - resize: Resize factor
+ - grayscale: Convert to grayscale
+ - enhance_contrast: Enhance contrast
+
+ Returns:
+ Path: Path to preprocessed image
+ """
+ file_path = Path(file_path)
+
+ with Image.open(file_path) as img:
+ # Convert to grayscale if requested
+ if options.get("grayscale", True):
+ img = img.convert('L')
+
+ # Resize if requested
+ if options.get("resize"):
+ resize_factor = options["resize"]
+ new_size = (int(img.width * resize_factor), int(img.height * resize_factor))
+ img = img.resize(new_size, Image.Resampling.LANCZOS)
+
+ # Enhance contrast if requested
+ if options.get("enhance_contrast", True):
+ from PIL import ImageEnhance
+ enhancer = ImageEnhance.Contrast(img)
+ img = enhancer.enhance(1.5)
+
+ # Save preprocessed image
+ output_path = file_path.parent / f"{file_path.stem}_preprocessed{file_path.suffix}"
+ img.save(output_path)
+
+ return output_path
diff --git a/libs/semantica/parse/json_parser.py b/libs/semantica/parse/json_parser.py
index b317a6b7..0e42fdaf 100644
--- a/libs/semantica/parse/json_parser.py
+++ b/libs/semantica/parse/json_parser.py
@@ -1,14 +1,233 @@
"""
-JSON/JSONL file parser for Semantica framework.
+JSON document parser for Semantica framework.
-This module handles JSON and JSONL file parsing for structured
-data extraction and processing.
+This module handles JSON file parsing for structured data extraction.
"""
-# TODO: Implement JSON parsing functionality
-# - JSON document parsing and validation
-# - JSONL (JSON Lines) streaming processing
-# - Nested object and array handling
-# - Schema validation and type checking
-# - Large JSON file streaming support
-# - Error handling for malformed JSON
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class JSONData:
+ """JSON data representation."""
+
+ data: Any
+ type: str # object, array, string, number, boolean, null
+ metadata: Dict[str, Any]
+
+
+class JSONParser:
+ """JSON document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize JSON parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("json_parser")
+ self.config = config
+
+ def parse(self, file_path: Union[str, Path], **options) -> JSONData:
+ """
+ Parse JSON file.
+
+ Args:
+ file_path: Path to JSON file or JSON string
+ **options: Parsing options:
+ - 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
+ """
+ encoding = options.get("encoding", "utf-8")
+
+ # Check if input is a file path or JSON string
+ if isinstance(file_path, Path) or (isinstance(file_path, str) and Path(file_path).exists()):
+ file_path_obj = Path(file_path)
+ if not file_path_obj.exists():
+ raise ValidationError(f"JSON file not found: {file_path_obj}")
+
+ try:
+ with open(file_path_obj, 'r', encoding=encoding) as f:
+ data = json.load(f)
+ source = str(file_path_obj)
+ except json.JSONDecodeError as e:
+ raise ValidationError(f"Invalid JSON file: {e}")
+ else:
+ # Assume it's a JSON string
+ try:
+ data = json.loads(file_path)
+ source = "string"
+ except json.JSONDecodeError as e:
+ raise ValidationError(f"Invalid JSON string: {e}")
+
+ # Determine data type
+ data_type = self._determine_type(data)
+
+ # Flatten if requested
+ if options.get("flatten", False):
+ data = self._flatten(data)
+
+ # Extract paths if requested
+ paths = None
+ if options.get("extract_paths", False):
+ paths = self._extract_paths(data)
+
+ metadata = {
+ "source": source,
+ "type": data_type,
+ "paths": paths
+ }
+
+ return JSONData(
+ data=data,
+ type=data_type,
+ metadata=metadata
+ )
+
+ def parse_to_dict(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:
+ """
+ Parse JSON to dictionary.
+
+ Args:
+ file_path: Path to JSON file or JSON string
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed JSON as dictionary
+ """
+ json_data = self.parse(file_path, **options)
+
+ if json_data.type == "object":
+ return json_data.data
+ elif json_data.type == "array" and len(json_data.data) > 0 and isinstance(json_data.data[0], dict):
+ # Return first element if array of objects
+ return json_data.data[0] if len(json_data.data) == 1 else {"items": json_data.data}
+ else:
+ return {"data": json_data.data}
+
+ def parse_to_list(self, file_path: Union[str, Path], **options) -> List[Any]:
+ """
+ Parse JSON to list.
+
+ Args:
+ file_path: Path to JSON file or JSON string
+ **options: Parsing options
+
+ Returns:
+ list: Parsed JSON as list
+ """
+ json_data = self.parse(file_path, **options)
+
+ if json_data.type == "array":
+ return json_data.data
+ elif json_data.type == "object":
+ return [json_data.data]
+ else:
+ return [json_data.data]
+
+ def extract_values(self, file_path: Union[str, Path], key_path: str, **options) -> List[Any]:
+ """
+ Extract values from JSON using key path.
+
+ Args:
+ file_path: Path to JSON file or JSON string
+ key_path: Dot-separated key path (e.g., "user.name")
+ **options: Parsing options
+
+ Returns:
+ list: Extracted values
+ """
+ json_data = self.parse(file_path, **options)
+ return self._extract_by_path(json_data.data, key_path)
+
+ def _determine_type(self, data: Any) -> str:
+ """Determine JSON data type."""
+ if isinstance(data, dict):
+ return "object"
+ elif isinstance(data, list):
+ return "array"
+ elif isinstance(data, str):
+ return "string"
+ elif isinstance(data, (int, float)):
+ return "number"
+ elif isinstance(data, bool):
+ return "boolean"
+ elif data is None:
+ return "null"
+ else:
+ return "unknown"
+
+ def _flatten(self, data: Any, parent_key: str = "", separator: str = ".") -> Dict[str, Any]:
+ """Flatten nested JSON structure."""
+ items = []
+
+ if isinstance(data, dict):
+ for key, value in data.items():
+ new_key = f"{parent_key}{separator}{key}" if parent_key else key
+ if isinstance(value, (dict, list)):
+ items.extend(self._flatten(value, new_key, separator).items())
+ else:
+ items.append((new_key, value))
+ elif isinstance(data, list):
+ for idx, value in enumerate(data):
+ new_key = f"{parent_key}{separator}{idx}" if parent_key else str(idx)
+ if isinstance(value, (dict, list)):
+ items.extend(self._flatten(value, new_key, separator).items())
+ else:
+ items.append((new_key, value))
+ else:
+ items.append((parent_key, data))
+
+ return dict(items)
+
+ def _extract_paths(self, data: Any, prefix: str = "") -> List[str]:
+ """Extract all JSON paths."""
+ paths = []
+
+ if isinstance(data, dict):
+ for key, value in data.items():
+ current_path = f"{prefix}.{key}" if prefix else key
+ paths.append(current_path)
+ if isinstance(value, (dict, list)):
+ paths.extend(self._extract_paths(value, current_path))
+ elif isinstance(data, list):
+ for idx, value in enumerate(data):
+ current_path = f"{prefix}[{idx}]" if prefix else f"[{idx}]"
+ paths.append(current_path)
+ if isinstance(value, (dict, list)):
+ paths.extend(self._extract_paths(value, current_path))
+
+ return paths
+
+ def _extract_by_path(self, data: Any, key_path: str) -> List[Any]:
+ """Extract values by key path."""
+ keys = key_path.split('.')
+ results = []
+
+ def extract_recursive(obj: Any, remaining_keys: List[str], current_path: List[str]):
+ if not remaining_keys:
+ results.append(obj)
+ return
+
+ key = remaining_keys[0]
+
+ if isinstance(obj, dict):
+ if key in obj:
+ extract_recursive(obj[key], remaining_keys[1:], current_path + [key])
+ elif isinstance(obj, list):
+ for idx, item in enumerate(obj):
+ extract_recursive(item, remaining_keys, current_path + [str(idx)])
+
+ extract_recursive(data, keys, [])
+ return results
diff --git a/libs/semantica/parse/media_parser.py b/libs/semantica/parse/media_parser.py
index 2d51fbe4..9483bda8 100644
--- a/libs/semantica/parse/media_parser.py
+++ b/libs/semantica/parse/media_parser.py
@@ -17,6 +17,13 @@ Main Classes:
- VideoParser: Video file parser
"""
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .image_parser import ImageParser
+
class MediaParser:
"""
@@ -28,255 +35,181 @@ class MediaParser:
• Handles different media types
• Supports batch media processing
• Analyzes media characteristics
-
- Attributes:
- • image_parser: Image file parser
- • audio_parser: Audio file parser
- • video_parser: Video file parser
- • metadata_extractor: Metadata extraction tools
- • supported_formats: List of supported formats
-
- Methods:
- • parse_media(): Parse media file
- • extract_metadata(): Extract media metadata
- • analyze_content(): Analyze media content
- • process_batch(): Process multiple media files
"""
def __init__(self, config=None, **kwargs):
- """
- Initialize media parser.
-
- • Setup format-specific parsers
- • Configure metadata extraction
- • Initialize content analysis
- • Setup batch processing
- • Configure error handling
- """
- pass
-
- def parse_media(self, file_path, media_type=None):
+ """Initialize media parser."""
+ self.logger = get_logger("media_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize parsers
+ self.image_parser = ImageParser(**self.config.get("image", {}))
+
+ # Supported formats
+ self.supported_formats = {
+ # Image formats
+ '.jpg': 'image',
+ '.jpeg': 'image',
+ '.png': 'image',
+ '.gif': 'image',
+ '.bmp': 'image',
+ '.tiff': 'image',
+ '.webp': 'image',
+ # Audio formats (would need additional libraries)
+ '.mp3': 'audio',
+ '.wav': 'audio',
+ '.flac': 'audio',
+ '.aac': 'audio',
+ # Video formats (would need additional libraries)
+ '.mp4': 'video',
+ '.avi': 'video',
+ '.mov': 'video',
+ '.mkv': 'video',
+ '.webm': 'video'
+ }
+
+ def parse_media(self, file_path: Union[str, Path], media_type: Optional[str] = None, **options) -> Dict[str, Any]:
"""
Parse media file of any supported type.
- • Detect media type if not specified
- • Route to appropriate parser
- • Extract metadata and properties
- • Analyze media content
- • Handle parsing errors
- • Return parsed media object
- """
- pass
-
- def extract_metadata(self, file_path, media_type):
- """
- Extract metadata from media file.
-
- • Parse media file headers
- • Extract technical properties
- • Get creation and modification info
- • Extract embedded metadata
- • Return metadata dictionary
- """
- pass
-
- def analyze_content(self, file_path, media_type):
- """
- Analyze media content characteristics.
-
- • Analyze media properties
- • Calculate content metrics
- • Identify content features
- • Assess content quality
- • Return content analysis
- """
- pass
-
- def process_batch(self, file_paths, **options):
- """
- Process multiple media files in batch.
-
- • Process files concurrently
- • Track processing progress
- • Handle individual file errors
- • Collect processing results
- • Return batch results
- """
- pass
-
-
-class ImageParser:
- """
- Image file parsing engine.
-
- • Parses various image formats
- • Extracts image metadata
- • Analyzes image properties
- • Processes image content
- • Handles image transformations
- """
-
- def __init__(self, **config):
+ Args:
+ file_path: Path to media file
+ media_type: Media type (auto-detected if None)
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed media data
"""
- Initialize image parser.
+ file_path = Path(file_path)
- • Setup image processing library
- • Configure metadata extraction
- • Initialize content analysis
- • Setup format handlers
- """
- pass
-
- def parse_image(self, file_path):
- """
- Parse image file and extract information.
+ if not file_path.exists():
+ raise ValidationError(f"Media file not found: {file_path}")
- • Load image file
- • Extract image properties
- • Process image metadata
- • Analyze image content
- • Return image information
- """
- pass
-
- def extract_metadata(self, file_path):
- """
- Extract image metadata and EXIF data.
+ # Detect media type if not specified
+ if media_type is None:
+ media_type = self._detect_media_type(file_path)
- • Parse image headers
- • Extract EXIF information
- • Get technical properties
- • Extract creation metadata
- • Return metadata dictionary
- """
- pass
+ if media_type == "image":
+ return self.image_parser.parse(file_path, **options)
+ elif media_type == "audio":
+ return self._parse_audio(file_path, **options)
+ elif media_type == "video":
+ return self._parse_video(file_path, **options)
+ else:
+ raise ValidationError(f"Unsupported media type: {media_type}")
- def analyze_properties(self, file_path):
+ def extract_metadata(self, file_path: Union[str, Path], media_type: Optional[str] = None) -> Dict[str, Any]:
"""
- Analyze image properties and characteristics.
-
- • Calculate image dimensions
- • Analyze color properties
- • Assess image quality
- • Identify image features
- • Return property analysis
- """
- pass
-
-
-class AudioParser:
- """
- Audio file parsing engine.
-
- • Parses various audio formats
- • Extracts audio metadata
- • Analyzes audio properties
- • Processes audio content
- • Handles audio information
- """
-
- def __init__(self, **config):
- """
- Initialize audio parser.
-
- • Setup audio processing library
- • Configure metadata extraction
- • Initialize content analysis
- • Setup format handlers
- """
- pass
-
- def parse_audio(self, file_path):
- """
- Parse audio file and extract information.
-
- • Load audio file
- • Extract audio properties
- • Process audio metadata
- • Analyze audio content
- • Return audio information
- """
- pass
-
- def extract_metadata(self, file_path):
- """
- Extract audio metadata and tags.
-
- • Parse audio headers
- • Extract ID3 tags
- • Get technical properties
- • Extract creation metadata
- • Return metadata dictionary
- """
- pass
-
- def analyze_properties(self, file_path):
- """
- Analyze audio properties and characteristics.
-
- • Calculate audio duration
- • Analyze audio quality
- • Assess bitrate and sample rate
- • Identify audio features
- • Return property analysis
- """
- pass
-
-
-class VideoParser:
- """
- Video file parsing engine.
-
- • Parses various video formats
- • Extracts video metadata
- • Analyzes video properties
- • Processes video content
- • Handles video information
- """
-
- def __init__(self, **config):
- """
- Initialize video parser.
-
- • Setup video processing library
- • Configure metadata extraction
- • Initialize content analysis
- • Setup format handlers
- """
- pass
-
- def parse_video(self, file_path):
- """
- Parse video file and extract information.
-
- • Load video file
- • Extract video properties
- • Process video metadata
- • Analyze video content
- • Return video information
- """
- pass
-
- def extract_metadata(self, file_path):
- """
- Extract video metadata and properties.
-
- • Parse video headers
- • Extract technical properties
- • Get creation metadata
- • Extract embedded information
- • Return metadata dictionary
- """
- pass
-
- def analyze_properties(self, file_path):
- """
- Analyze video properties and characteristics.
+ Extract metadata from media file.
- • Calculate video dimensions
- • Analyze video quality
- • Assess frame rate and bitrate
- • Identify video features
- • Return property analysis
- """
- pass
+ Args:
+ file_path: Path to media file
+ media_type: Media type (auto-detected if None)
+
+ Returns:
+ dict: Media metadata
+ """
+ file_path = Path(file_path)
+
+ if media_type is None:
+ media_type = self._detect_media_type(file_path)
+
+ if media_type == "image":
+ return self.image_parser.extract_metadata(file_path).__dict__
+ elif media_type == "audio":
+ return self._extract_audio_metadata(file_path)
+ elif media_type == "video":
+ return self._extract_video_metadata(file_path)
+ else:
+ return {}
+
+ def _detect_media_type(self, file_path: Path) -> str:
+ """Detect media type from file extension."""
+ suffix = file_path.suffix.lower()
+ return self.supported_formats.get(suffix, "unknown")
+
+ def _parse_audio(self, file_path: Path, **options) -> Dict[str, Any]:
+ """Parse audio file."""
+ metadata = self._extract_audio_metadata(file_path)
+
+ return {
+ "metadata": metadata,
+ "type": "audio"
+ }
+
+ def _parse_video(self, file_path: Path, **options) -> Dict[str, Any]:
+ """Parse video file."""
+ metadata = self._extract_video_metadata(file_path)
+
+ return {
+ "metadata": metadata,
+ "type": "video"
+ }
+
+ def _extract_audio_metadata(self, file_path: Path) -> Dict[str, Any]:
+ """Extract audio metadata."""
+ metadata = {
+ "file_path": str(file_path),
+ "file_size": file_path.stat().st_size,
+ "format": file_path.suffix.lower()
+ }
+
+ # Try to extract metadata using mutagen if available
+ try:
+ from mutagen import File
+ audio_file = File(str(file_path))
+ if audio_file:
+ metadata.update({
+ "title": audio_file.get("TIT2", [None])[0] or audio_file.get("TITLE", [None])[0],
+ "artist": audio_file.get("TPE1", [None])[0] or audio_file.get("ARTIST", [None])[0],
+ "album": audio_file.get("TALB", [None])[0] or audio_file.get("ALBUM", [None])[0],
+ "duration": audio_file.info.length if hasattr(audio_file.info, 'length') else None,
+ "bitrate": audio_file.info.bitrate if hasattr(audio_file.info, 'bitrate') else None,
+ "sample_rate": audio_file.info.sample_rate if hasattr(audio_file.info, 'sample_rate') else None
+ })
+ except ImportError:
+ self.logger.warning("mutagen not available for audio metadata extraction")
+ except Exception as e:
+ self.logger.warning(f"Failed to extract audio metadata: {e}")
+
+ return metadata
+
+ def _extract_video_metadata(self, file_path: Path) -> Dict[str, Any]:
+ """Extract video metadata."""
+ metadata = {
+ "file_path": str(file_path),
+ "file_size": file_path.stat().st_size,
+ "format": file_path.suffix.lower()
+ }
+
+ # Try to extract metadata using ffmpeg if available
+ try:
+ import subprocess
+ result = subprocess.run(
+ ['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', str(file_path)],
+ capture_output=True,
+ text=True
+ )
+
+ if result.returncode == 0:
+ import json
+ video_data = json.loads(result.stdout)
+
+ if 'streams' in video_data:
+ for stream in video_data['streams']:
+ if stream.get('codec_type') == 'video':
+ metadata.update({
+ "width": stream.get("width"),
+ "height": stream.get("height"),
+ "duration": float(video_data.get('format', {}).get('duration', 0)),
+ "codec": stream.get("codec_name"),
+ "fps": eval(stream.get("r_frame_rate", "0/1")) if stream.get("r_frame_rate") else None
+ })
+ break
+ except FileNotFoundError:
+ self.logger.warning("ffprobe not available for video metadata extraction")
+ except Exception as e:
+ self.logger.warning(f"Failed to extract video metadata: {e}")
+
+ return metadata
diff --git a/libs/semantica/parse/pdf_parser.py b/libs/semantica/parse/pdf_parser.py
index 24731c6e..9b54ed32 100644
--- a/libs/semantica/parse/pdf_parser.py
+++ b/libs/semantica/parse/pdf_parser.py
@@ -5,11 +5,219 @@ This module handles PDF document parsing using PyPDF2 and pdfplumber
for text, table, and image extraction.
"""
-# TODO: Implement PDF parsing functionality
-# - Text extraction from PDF documents
-# - Table extraction and structure recognition
-# - Image extraction and OCR processing
-# - Metadata extraction (author, title, creation date)
-# - Page-by-page processing
-# - Handling encrypted PDFs
-# - Support for different PDF versions
+import io
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+import pdfplumber
+from PIL import Image
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class PDFPage:
+ """PDF page representation."""
+
+ page_number: int
+ text: str
+ width: float
+ height: float
+ images: List[Dict[str, Any]] = field(default_factory=list)
+ tables: List[Dict[str, Any]] = field(default_factory=list)
+
+
+@dataclass
+class PDFMetadata:
+ """PDF metadata representation."""
+
+ title: Optional[str] = None
+ author: Optional[str] = None
+ subject: Optional[str] = None
+ creator: Optional[str] = None
+ producer: Optional[str] = None
+ creation_date: Optional[str] = None
+ modification_date: Optional[str] = None
+ page_count: int = 0
+
+
+class PDFParser:
+ """PDF document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize PDF parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("pdf_parser")
+ self.config = config
+
+ def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:
+ """
+ Parse PDF document.
+
+ Args:
+ file_path: Path to PDF file
+ **options: Parsing options:
+ - 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
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"PDF file not found: {file_path}")
+
+ if not file_path.suffix.lower() == '.pdf':
+ raise ValidationError(f"File is not a PDF: {file_path}")
+
+ try:
+ with pdfplumber.open(str(file_path)) as pdf:
+ # Extract metadata
+ metadata = self._extract_metadata(pdf)
+ metadata.page_count = len(pdf.pages)
+
+ # Extract pages
+ pages = []
+ page_numbers = options.get("pages", range(len(pdf.pages)))
+
+ for page_num in page_numbers:
+ if page_num < len(pdf.pages):
+ page_data = self._parse_page(
+ pdf.pages[page_num],
+ page_num + 1,
+ options
+ )
+ pages.append(page_data)
+
+ return {
+ "metadata": metadata.__dict__,
+ "pages": [page.__dict__ for page in pages],
+ "full_text": "\n\n".join(page.text for page in pages),
+ "total_pages": len(pdf.pages)
+ }
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse PDF {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse PDF: {e}")
+
+ def extract_text(self, file_path: Union[str, Path], pages: Optional[List[int]] = None) -> str:
+ """
+ Extract text from PDF.
+
+ Args:
+ file_path: Path to PDF file
+ pages: Specific page numbers (None = all pages)
+
+ Returns:
+ str: Extracted text
+ """
+ result = self.parse(file_path, extract_tables=False, extract_images=False, pages=pages)
+ return result["full_text"]
+
+ def extract_tables(self, file_path: Union[str, Path], pages: Optional[List[int]] = None) -> List[Dict[str, Any]]:
+ """
+ Extract tables from PDF.
+
+ Args:
+ file_path: Path to PDF file
+ pages: Specific page numbers (None = all pages)
+
+ Returns:
+ list: Extracted tables
+ """
+ result = self.parse(file_path, extract_text=False, extract_images=False, pages=pages)
+
+ all_tables = []
+ for page in result["pages"]:
+ for table in page.get("tables", []):
+ table["page_number"] = page["page_number"]
+ all_tables.append(table)
+
+ return all_tables
+
+ def extract_images(self, file_path: Union[str, Path], output_dir: Optional[Path] = None) -> List[Dict[str, Any]]:
+ """
+ Extract images from PDF.
+
+ Args:
+ file_path: Path to PDF file
+ output_dir: Directory to save extracted images
+
+ Returns:
+ list: Extracted image information
+ """
+ result = self.parse(file_path, extract_text=False, extract_tables=False, extract_images=True)
+
+ all_images = []
+ for page in result["pages"]:
+ for img in page.get("images", []):
+ img["page_number"] = page["page_number"]
+ all_images.append(img)
+
+ return all_images
+
+ def _parse_page(self, page, page_number: int, options: Dict[str, Any]) -> PDFPage:
+ """Parse individual PDF page."""
+ page_data = PDFPage(
+ page_number=page_number,
+ text="",
+ width=page.width,
+ height=page.height
+ )
+
+ # Extract text
+ if options.get("extract_text", True):
+ page_data.text = page.extract_text() or ""
+
+ # Extract tables
+ if options.get("extract_tables", True):
+ tables = page.extract_tables()
+ if tables:
+ page_data.tables = [
+ {
+ "data": table,
+ "bbox": None # pdfplumber doesn't provide bbox for tables directly
+ }
+ for table in tables
+ ]
+
+ # Extract images
+ if options.get("extract_images", False):
+ images = page.images
+ if images:
+ page_data.images = [
+ {
+ "x0": img.get("x0", 0),
+ "y0": img.get("y0", 0),
+ "x1": img.get("x1", 0),
+ "y1": img.get("y1", 0),
+ "width": img.get("width", 0),
+ "height": img.get("height", 0)
+ }
+ for img in images
+ ]
+
+ return page_data
+
+ def _extract_metadata(self, pdf) -> PDFMetadata:
+ """Extract PDF metadata."""
+ metadata = pdf.metadata or {}
+
+ return PDFMetadata(
+ title=metadata.get("Title"),
+ author=metadata.get("Author"),
+ subject=metadata.get("Subject"),
+ creator=metadata.get("Creator"),
+ producer=metadata.get("Producer"),
+ creation_date=str(metadata.get("CreationDate", "")),
+ modification_date=str(metadata.get("ModDate", ""))
+ )
diff --git a/libs/semantica/parse/pptx_parser.py b/libs/semantica/parse/pptx_parser.py
index 292048ef..c685bc3d 100644
--- a/libs/semantica/parse/pptx_parser.py
+++ b/libs/semantica/parse/pptx_parser.py
@@ -1,14 +1,211 @@
"""
-PowerPoint presentation parser for Semantica framework.
+PowerPoint document parser for Semantica framework.
-This module handles PPTX presentation parsing using python-pptx
-for slide content, text, and structure extraction.
+This module handles PPTX file parsing using python-pptx
+for presentation content extraction.
"""
-# TODO: Implement PPTX parsing functionality
-# - Slide content extraction
-# - Text extraction from slides and notes
-# - Image and media handling
-# - Slide layout and structure recognition
-# - Animation and transition information
-# - Master slide and template processing
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from pptx import Presentation
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class SlideContent:
+ """Slide content representation."""
+
+ slide_number: int
+ title: str
+ text: str
+ notes: str = ""
+ shapes: List[Dict[str, Any]] = field(default_factory=list)
+ images: List[Dict[str, Any]] = field(default_factory=list)
+
+
+@dataclass
+class PPTXData:
+ """PPTX presentation representation."""
+
+ title: str
+ slides: List[SlideContent]
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class PPTXParser:
+ """PPTX document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize PPTX parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("pptx_parser")
+ self.config = config
+
+ def parse(self, file_path: Union[str, Path], **options) -> PPTXData:
+ """
+ Parse PPTX file.
+
+ Args:
+ file_path: Path to PPTX file
+ **options: Parsing options:
+ - extract_images: Whether to extract images (default: False)
+ - extract_notes: Whether to extract speaker notes (default: True)
+ - extract_shapes: Whether to extract shape information (default: False)
+
+ Returns:
+ PPTXData: Parsed presentation data
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise ValidationError(f"PPTX file not found: {file_path}")
+
+ if not file_path.suffix.lower() == '.pptx':
+ raise ValidationError(f"File is not a PPTX: {file_path}")
+
+ try:
+ prs = Presentation(str(file_path))
+
+ # Extract metadata
+ metadata = self._extract_metadata(prs)
+
+ # Extract slides
+ slides = []
+ for idx, slide in enumerate(prs.slides, 1):
+ slide_content = self._parse_slide(slide, idx, options)
+ slides.append(slide_content)
+
+ # Get presentation title (from first slide or core properties)
+ title = metadata.get("title", f"Presentation_{file_path.stem}")
+ if slides and slides[0].title:
+ title = slides[0].title
+
+ return PPTXData(
+ title=title,
+ slides=slides,
+ metadata={
+ **metadata,
+ "total_slides": len(slides),
+ "file_path": str(file_path)
+ }
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse PPTX {file_path}: {e}")
+ raise ProcessingError(f"Failed to parse PPTX: {e}")
+
+ def extract_text(self, file_path: Union[str, Path]) -> str:
+ """
+ Extract text from PPTX.
+
+ Args:
+ file_path: Path to PPTX file
+
+ Returns:
+ str: Extracted text from all slides
+ """
+ result = self.parse(file_path, extract_images=False, extract_shapes=False)
+ return "\n\n".join([f"Slide {s.slide_number}: {s.title}\n{s.text}" for s in result.slides])
+
+ def extract_slides(self, file_path: Union[str, Path], **options) -> List[SlideContent]:
+ """
+ Extract slides from PPTX.
+
+ Args:
+ file_path: Path to PPTX file
+ **options: Parsing options
+
+ Returns:
+ list: List of slide contents
+ """
+ result = self.parse(file_path, **options)
+ return result.slides
+
+ def _parse_slide(self, slide, slide_number: int, options: Dict[str, Any]) -> SlideContent:
+ """Parse individual slide."""
+ title = ""
+ text_parts = []
+ notes = ""
+ shapes = []
+ images = []
+
+ # Extract title and text from shapes
+ for shape in slide.shapes:
+ # Extract title
+ if hasattr(shape, "is_placeholder") and shape.is_placeholder:
+ if shape.placeholder_format.idx == 0: # Title placeholder
+ if hasattr(shape, "text"):
+ title = shape.text.strip()
+
+ # Extract text from text boxes
+ if hasattr(shape, "text") and shape.text.strip():
+ text_parts.append(shape.text.strip())
+
+ # Extract images
+ if options.get("extract_images", False) and hasattr(shape, "image"):
+ try:
+ image_info = {
+ "width": shape.width,
+ "height": shape.height,
+ "format": shape.image.ext
+ }
+ images.append(image_info)
+ except Exception:
+ pass
+
+ # Extract shape information
+ if options.get("extract_shapes", False):
+ shape_info = {
+ "type": shape.shape_type,
+ "has_text": hasattr(shape, "text")
+ }
+ shapes.append(shape_info)
+
+ # Extract notes
+ if options.get("extract_notes", True) and slide.has_notes_slide:
+ notes_slide = slide.notes_slide
+ if hasattr(notes_slide, "notes_text_frame"):
+ notes = notes_slide.notes_text_frame.text
+
+ # Get title from first text part if not found
+ if not title and text_parts:
+ title = text_parts[0]
+ text_parts = text_parts[1:]
+
+ return SlideContent(
+ slide_number=slide_number,
+ title=title,
+ text="\n".join(text_parts),
+ notes=notes,
+ shapes=shapes,
+ images=images
+ )
+
+ def _extract_metadata(self, prs: Presentation) -> Dict[str, Any]:
+ """Extract presentation metadata."""
+ metadata = {}
+
+ try:
+ core_props = prs.core_properties
+ metadata = {
+ "title": core_props.title,
+ "author": core_props.author,
+ "subject": core_props.subject,
+ "keywords": core_props.keywords,
+ "comments": core_props.comments,
+ "created": str(core_props.created) if core_props.created else None,
+ "modified": str(core_props.modified) if core_props.modified else None,
+ "last_modified_by": core_props.last_modified_by
+ }
+ except Exception:
+ pass
+
+ return metadata
diff --git a/libs/semantica/parse/structured_data_parser.py b/libs/semantica/parse/structured_data_parser.py
index a411d072..cce08803 100644
--- a/libs/semantica/parse/structured_data_parser.py
+++ b/libs/semantica/parse/structured_data_parser.py
@@ -12,11 +12,19 @@ Key Features:
Main Classes:
- StructuredDataParser: Main structured data parser
- - JSONParser: JSON data parser
- - CSVParser: CSV data parser
- - YAMLParser: YAML data parser
"""
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+import yaml
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .csv_parser import CSVParser
+from .json_parser import JSONParser
+from .xml_parser import XMLParser
+
class StructuredDataParser:
"""
@@ -28,250 +36,293 @@ class StructuredDataParser:
• Handles nested and complex structures
• Processes large datasets efficiently
• Supports various encoding formats
-
- Attributes:
- • json_parser: JSON parsing engine
- • csv_parser: CSV parsing engine
- • xml_parser: XML parsing engine
- • yaml_parser: YAML parsing engine
- • data_validator: Data validation tools
-
- Methods:
- • parse_data(): Parse any structured data format
- • validate_data(): Validate data structure
- • convert_data(): Convert data between formats
- • extract_schema(): Extract data schema
"""
def __init__(self, config=None, **kwargs):
- """
- Initialize structured data parser.
+ """Initialize structured data parser."""
+ self.logger = get_logger("structured_data_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
- • Setup format-specific parsers
- • Configure data validation
- • Initialize type converters
- • Setup schema extraction
- • Configure error handling
- """
- pass
+ # Initialize parsers
+ self.json_parser = JSONParser(**self.config.get("json", {}))
+ self.csv_parser = CSVParser(**self.config.get("csv", {}))
+ self.xml_parser = XMLParser(**self.config.get("xml", {}))
- def parse_data(self, data, data_format, **options):
+ def parse_data(self, data: Union[str, Path], data_format: Optional[str] = None, **options) -> Dict[str, Any]:
"""
Parse structured data of any supported format.
- • Detect data format if not specified
- • Route to appropriate parser
- • Parse data structure
- • Validate data integrity
- • Handle parsing errors
- • Return parsed data object
- """
- pass
+ Args:
+ data: Data content or file path
+ data_format: Data format (auto-detected if None)
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed data
+ """
+ # Detect format if not specified
+ if data_format is None:
+ data_format = self._detect_format(data)
+
+ # Route to appropriate parser
+ if data_format == "json":
+ return self.json_parser.parse(data, **options).__dict__
+ elif data_format == "csv":
+ return self.csv_parser.parse(data, **options).__dict__
+ elif data_format == "xml":
+ return self.xml_parser.parse(data, **options).__dict__
+ elif data_format == "yaml":
+ return self._parse_yaml(data, **options)
+ else:
+ raise ValidationError(f"Unsupported data format: {data_format}")
- def validate_data(self, data, schema=None):
+ def validate_data(self, data: Any, schema: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Validate structured data against schema.
- • Load validation schema
- • Check data structure
- • Validate data types
- • Report validation errors
- • Return validation result
- """
- pass
+ Args:
+ data: Data to validate
+ schema: Validation schema
+
+ Returns:
+ dict: Validation result
+ """
+ result = {
+ "valid": True,
+ "errors": []
+ }
+
+ if schema is None:
+ result["valid"] = True
+ result["message"] = "No schema provided, skipping validation"
+ return result
+
+ # Basic schema validation
+ if isinstance(data, dict):
+ # Check required fields
+ required_fields = schema.get("required", [])
+ for field in required_fields:
+ if field not in data:
+ result["valid"] = False
+ result["errors"].append(f"Missing required field: {field}")
+
+ # Check field types
+ properties = schema.get("properties", {})
+ for field, value in data.items():
+ if field in properties:
+ expected_type = properties[field].get("type")
+ actual_type = type(value).__name__
+
+ type_mapping = {
+ "string": "str",
+ "number": ("int", "float"),
+ "integer": "int",
+ "boolean": "bool",
+ "array": "list",
+ "object": "dict"
+ }
+
+ expected_types = type_mapping.get(expected_type, [expected_type])
+ if isinstance(expected_types, tuple):
+ if actual_type not in expected_types:
+ result["valid"] = False
+ result["errors"].append(f"Field {field}: expected {expected_type}, got {actual_type}")
+ elif actual_type != expected_types:
+ result["valid"] = False
+ result["errors"].append(f"Field {field}: expected {expected_type}, got {actual_type}")
+
+ return result
- def convert_data(self, data, from_format, to_format):
+ def convert_data(self, data: Any, from_format: str, to_format: str) -> Any:
"""
Convert data between different formats.
- • Parse data from source format
- • Transform data structure
- • Serialize to target format
- • Handle type conversions
- • Return converted data
- """
- pass
+ Args:
+ data: Input data
+ from_format: Source format
+ to_format: Target format
+
+ Returns:
+ Converted data
+ """
+ # Parse from source format
+ if isinstance(data, (str, Path)):
+ parsed = self.parse_data(data, data_format=from_format)
+ if isinstance(parsed, dict) and "data" in parsed:
+ parsed = parsed["data"]
+ else:
+ parsed = data
+
+ # Convert to target format
+ if to_format == "json":
+ import json
+ return json.dumps(parsed, indent=2)
+ elif to_format == "csv":
+ return self._convert_to_csv(parsed)
+ elif to_format == "xml":
+ return self._convert_to_xml(parsed)
+ elif to_format == "yaml":
+ return yaml.dump(parsed, default_flow_style=False)
+ else:
+ raise ValidationError(f"Unsupported target format: {to_format}")
- def extract_schema(self, data):
+ def extract_schema(self, data: Any) -> Dict[str, Any]:
"""
Extract schema from structured data.
- • Analyze data structure
- • Identify data types
- • Extract field definitions
- • Generate schema representation
- • Return data schema
- """
- pass
-
-
-class JSONParser:
- """
- JSON data parsing engine.
-
- • Parses JSON documents and fragments
- • Validates JSON structure
- • Handles nested objects and arrays
- • Processes JSON schemas
- • Manages large JSON files
- """
-
- def __init__(self, **config):
- """
- Initialize JSON parser.
+ Args:
+ data: Structured data
+
+ Returns:
+ dict: Extracted schema
+ """
+ schema = {
+ "type": "object" if isinstance(data, dict) else "array" if isinstance(data, list) else type(data).__name__,
+ "properties": {}
+ }
- • Setup JSON parsing library
- • Configure parsing options
- • Initialize validation tools
- • Setup streaming for large files
- """
- pass
-
- def parse_json(self, json_content, **options):
- """
- Parse JSON content.
+ if isinstance(data, dict):
+ for key, value in data.items():
+ schema["properties"][key] = self._infer_type(value)
+ elif isinstance(data, list) and len(data) > 0:
+ schema["items"] = self._infer_type(data[0])
- • Parse JSON structure
- • Validate JSON format
- • Handle parsing errors
- • Return parsed JSON object
- """
- pass
+ return schema
- def validate_json(self, json_content, schema=None):
- """
- Validate JSON against schema.
+ def _detect_format(self, data: Union[str, Path]) -> str:
+ """Detect data format from content or extension."""
+ # Check if it's a file path
+ if isinstance(data, Path) or (isinstance(data, str) and Path(data).exists()):
+ file_path = Path(data)
+ suffix = file_path.suffix.lower()
+ format_map = {
+ '.json': 'json',
+ '.csv': 'csv',
+ '.xml': 'xml',
+ '.yaml': 'yaml',
+ '.yml': 'yaml'
+ }
+ if suffix in format_map:
+ return format_map[suffix]
- • Parse JSON content
- • Load JSON schema
- • Validate structure and types
- • Report validation errors
- • Return validation result
- """
- pass
-
- def extract_values(self, json_data, key_path):
- """
- Extract values using key path.
+ # Check content if string
+ if isinstance(data, str):
+ data_str = data.strip()
+ if data_str.startswith('{') or data_str.startswith('['):
+ return 'json'
+ elif data_str.startswith('<'):
+ return 'xml'
+ elif ',' in data_str and '\n' in data_str:
+ return 'csv'
- • Navigate JSON structure
- • Extract values by path
- • Handle nested objects
- • Return extracted values
- """
- pass
-
-
-class CSVParser:
- """
- CSV data parsing engine.
-
- • Parses CSV files and data
- • Handles various CSV formats
- • Detects delimiters and encodings
- • Processes headers and data types
- • Manages large CSV files
- """
+ return "unknown"
- def __init__(self, **config):
- """
- Initialize CSV parser.
+ def _parse_yaml(self, data: Union[str, Path], **options) -> Dict[str, Any]:
+ """Parse YAML data."""
+ if isinstance(data, Path) or (isinstance(data, str) and Path(data).exists()):
+ file_path = Path(data)
+ with open(file_path, 'r', encoding='utf-8') as f:
+ yaml_data = yaml.safe_load(f)
+ else:
+ yaml_data = yaml.safe_load(data)
- • Setup CSV parsing library
- • Configure delimiter detection
- • Initialize encoding detection
- • Setup data type inference
- """
- pass
+ return {
+ "data": yaml_data,
+ "type": type(yaml_data).__name__,
+ "metadata": {
+ "format": "yaml"
+ }
+ }
- def parse_csv(self, csv_content, **options):
- """
- Parse CSV content.
+ def _convert_to_csv(self, data: Any) -> str:
+ """Convert data to CSV format."""
+ import csv
+ import io
- • Detect CSV format parameters
- • Parse CSV structure
- • Process headers and data
- • Handle encoding issues
- • Return parsed CSV object
- """
- pass
+ if isinstance(data, dict):
+ # Convert dict to CSV (single row)
+ output = io.StringIO()
+ writer = csv.DictWriter(output, fieldnames=data.keys())
+ writer.writeheader()
+ writer.writerow(data)
+ return output.getvalue()
+ elif isinstance(data, list):
+ if not data:
+ return ""
+
+ output = io.StringIO()
+ if isinstance(data[0], dict):
+ writer = csv.DictWriter(output, fieldnames=data[0].keys())
+ writer.writeheader()
+ writer.writerows(data)
+ else:
+ writer = csv.writer(output)
+ writer.writerows(data)
+ return output.getvalue()
+ else:
+ return str(data)
- def detect_format(self, csv_content):
- """
- Detect CSV format parameters.
+ def _convert_to_xml(self, data: Any, root_tag: str = "root") -> str:
+ """Convert data to XML format."""
+ from xml.etree.ElementTree import Element, tostring
+ import xml.dom.minidom
- • Analyze CSV structure
- • Detect delimiter character
- • Identify encoding format
- • Determine quote character
- • Return format parameters
- """
- pass
-
- def infer_types(self, csv_data):
- """
- Infer data types from CSV content.
+ def dict_to_xml(d: Dict[str, Any], parent: Element):
+ for key, value in d.items():
+ elem = Element(key)
+ if isinstance(value, dict):
+ dict_to_xml(value, elem)
+ elif isinstance(value, list):
+ for item in value:
+ if isinstance(item, dict):
+ dict_to_xml(item, elem)
+ else:
+ child = Element("item")
+ child.text = str(item)
+ elem.append(child)
+ else:
+ elem.text = str(value)
+ parent.append(elem)
- • Analyze column data
- • Detect data types
- • Handle type conversion
- • Return type information
- """
- pass
-
-
-class YAMLParser:
- """
- YAML data parsing engine.
-
- • Parses YAML documents and fragments
- • Validates YAML structure
- • Handles YAML schemas
- • Processes configuration files
- • Manages YAML transformations
- """
-
- def __init__(self, **config):
- """
- Initialize YAML parser.
+ root = Element(root_tag)
+ if isinstance(data, dict):
+ dict_to_xml(data, root)
+ elif isinstance(data, list):
+ for item in data:
+ if isinstance(item, dict):
+ dict_to_xml(item, root)
+ else:
+ elem = Element("item")
+ elem.text = str(item)
+ root.append(elem)
+ else:
+ root.text = str(data)
- • Setup YAML parsing library
- • Configure parsing options
- • Initialize validation tools
- • Setup transformation utilities
- """
- pass
+ # Pretty print
+ rough_string = tostring(root, encoding='unicode')
+ reparsed = xml.dom.minidom.parseString(rough_string)
+ return reparsed.toprettyxml(indent=" ")
- def parse_yaml(self, yaml_content, **options):
- """
- Parse YAML content.
+ def _infer_type(self, value: Any) -> Dict[str, Any]:
+ """Infer JSON Schema type from Python value."""
+ type_mapping = {
+ str: "string",
+ int: "integer",
+ float: "number",
+ bool: "boolean",
+ list: "array",
+ dict: "object"
+ }
- • Parse YAML structure
- • Validate YAML format
- • Handle parsing errors
- • Return parsed YAML object
- """
- pass
-
- def validate_yaml(self, yaml_content, schema=None):
- """
- Validate YAML against schema.
+ python_type = type(value)
+ json_type = type_mapping.get(python_type, "string")
- • Parse YAML content
- • Load validation schema
- • Validate structure and types
- • Report validation errors
- • Return validation result
- """
- pass
-
- def extract_config(self, yaml_content, config_path):
- """
- Extract configuration values.
+ result = {"type": json_type}
- • Parse YAML structure
- • Navigate configuration path
- • Extract configuration values
- • Return configuration object
- """
- pass
+ if json_type == "array" and isinstance(value, list) and len(value) > 0:
+ result["items"] = self._infer_type(value[0])
+ elif json_type == "object" and isinstance(value, dict):
+ result["properties"] = {k: self._infer_type(v) for k, v in value.items()}
+
+ return result
diff --git a/libs/semantica/parse/web_parser.py b/libs/semantica/parse/web_parser.py
index 3bf01d51..c284c37c 100644
--- a/libs/semantica/parse/web_parser.py
+++ b/libs/semantica/parse/web_parser.py
@@ -13,10 +13,20 @@ Key Features:
Main Classes:
- WebParser: Main web content parser
- HTMLContentParser: HTML-specific parser
- - XMLParser: XML document parser
- JavaScriptRenderer: JavaScript rendering engine
"""
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+from urllib.parse import urljoin, urlparse
+
+from bs4 import BeautifulSoup
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .html_parser import HTMLParser
+from .xml_parser import XMLParser
+
class WebParser:
"""
@@ -28,19 +38,6 @@ class WebParser:
• Processes web scraping results
• Cleans and normalizes web content
• Supports various web formats
-
- Attributes:
- • html_parser: HTML parsing engine
- • xml_parser: XML parsing engine
- • js_renderer: JavaScript rendering engine
- • content_cleaner: Content cleaning tools
- • link_extractor: Link extraction utilities
-
- Methods:
- • parse_web_content(): Parse web content
- • extract_text(): Extract text from web content
- • extract_links(): Extract links from content
- • render_javascript(): Render JavaScript content
"""
def __init__(self, config=None, **kwargs):
@@ -53,61 +50,83 @@ class WebParser:
• Setup content cleaning tools
• Configure link extraction
"""
- pass
+ self.logger = get_logger("web_parser")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize parsers
+ self.html_parser = HTMLParser(**self.config.get("html", {}))
+ self.xml_parser = XMLParser(**self.config.get("xml", {}))
+ self.js_renderer = JavaScriptRenderer(**self.config.get("js", {}))
- def parse_web_content(self, content, content_type="html", **options):
+ def parse_web_content(self, content: Union[str, Path], content_type: str = "html", base_url: Optional[str] = None, **options) -> Dict[str, Any]:
"""
Parse web content of various types.
- • Detect content type if not specified
- • Route to appropriate parser
- • Extract structured content
- • Process embedded elements
- • Clean and normalize content
- • Return parsed content object
- """
- pass
+ Args:
+ content: Web content or file path
+ content_type: Content type ("html", "xml")
+ base_url: Base URL for resolving relative links
+ **options: Parsing options
+
+ Returns:
+ dict: Parsed content data
+ """
+ if content_type == "html":
+ return self.html_parser.parse(content, base_url=base_url, **options)
+ elif content_type == "xml":
+ return self.xml_parser.parse(content, **options)
+ else:
+ raise ValidationError(f"Unsupported content type: {content_type}")
- def extract_text(self, web_content, **options):
+ def extract_text(self, web_content: Union[str, Path], **options) -> str:
"""
Extract clean text from web content.
- • Parse web content structure
- • Extract text from all elements
- • Remove scripts and styles
- • Clean whitespace and formatting
- • Preserve text hierarchy
- • Return clean text content
- """
- pass
+ Args:
+ web_content: Web content or file path
+ **options: Extraction options
+
+ Returns:
+ str: Extracted text
+ """
+ content_type = options.get("content_type", "html")
+
+ # Handle JavaScript rendering if requested
+ if options.get("render_javascript", False):
+ html_content = self.js_renderer.render_page(web_content, **options)
+ return self.html_parser.extract_text(html_content, clean=options.get("clean", True))
+ else:
+ return self.html_parser.extract_text(web_content, clean=options.get("clean", True))
- def extract_links(self, web_content, base_url=None):
+ def extract_links(self, web_content: Union[str, Path], base_url: Optional[str] = None) -> List[Dict[str, Any]]:
"""
Extract links from web content.
- • Find all link elements
- • Extract URLs and anchor text
- • Resolve relative URLs
- • Validate link URLs
- • Categorize link types
- • Return link collection
- """
- pass
+ Args:
+ web_content: Web content or file path
+ base_url: Base URL for resolving relative links
+
+ Returns:
+ list: Extracted links
+ """
+ return self.html_parser.extract_links(web_content, base_url=base_url)
- def render_javascript(self, html_content, **options):
+ def render_javascript(self, html_content: Union[str, Path], **options) -> str:
"""
Render JavaScript content in HTML.
- • Execute JavaScript code
- • Wait for page load completion
- • Extract rendered content
- • Handle dynamic content loading
- • Return rendered HTML content
- """
- pass
+ Args:
+ html_content: HTML content or file path
+ **options: Rendering options
+
+ Returns:
+ str: Rendered HTML content
+ """
+ return self.js_renderer.render_page(html_content, **options)
-class HTMLContentParser:
+class HTMLContentParser(HTMLParser):
"""
HTML content parsing engine.
@@ -118,111 +137,102 @@ class HTMLContentParser:
• Cleans and validates HTML content
"""
- def __init__(self, **config):
+ def extract_structured_content(self, html_content: Union[str, Path], **options) -> Dict[str, Any]:
"""
- Initialize HTML content parser.
+ Extract structured content from HTML.
- • Setup HTML parsing library
- • Configure parsing options
- • Initialize content extractors
- • Setup validation tools
- """
- pass
-
- def parse_html(self, html_content, **options):
- """
- Parse HTML content.
+ Args:
+ html_content: HTML content or file path
+ **options: Extraction options
+
+ Returns:
+ dict: Structured content
+ """
+ parsed = self.parse(html_content, **options)
- • Parse HTML structure
- • Extract document elements
- • Process embedded content
- • Validate HTML structure
- • Return parsed HTML object
- """
- pass
-
- def extract_structured_content(self, html_content):
- """
- Extract structured content from HTML.
+ structure = {
+ "headings": [],
+ "paragraphs": [],
+ "lists": [],
+ "tables": parsed.get("tables", []),
+ "forms": parsed.get("forms", [])
+ }
- • Identify content sections
- • Extract headings and paragraphs
- • Process lists and tables
- • Extract forms and inputs
- • Return structured content
- """
- pass
+ # Load HTML for structure extraction
+ if isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):
+ with open(html_content, 'r', encoding='utf-8', errors='ignore') as f:
+ html_string = f.read()
+ else:
+ html_string = html_content
+
+ soup = BeautifulSoup(html_string, 'html.parser')
+
+ # Extract headings
+ for level in range(1, 7):
+ for heading in soup.find_all(f'h{level}'):
+ structure["headings"].append({
+ "level": level,
+ "text": heading.get_text().strip(),
+ "id": heading.get('id')
+ })
+
+ # Extract paragraphs
+ for para in soup.find_all('p'):
+ text = para.get_text().strip()
+ if text:
+ structure["paragraphs"].append(text)
+
+ # Extract lists
+ for list_elem in soup.find_all(['ul', 'ol']):
+ items = []
+ for item in list_elem.find_all('li'):
+ items.append(item.get_text().strip())
+ if items:
+ structure["lists"].append({
+ "type": list_elem.name,
+ "items": items
+ })
+
+ return structure
- def clean_html(self, html_content):
+ def clean_html(self, html_content: Union[str, Path], **options) -> str:
"""
Clean and normalize HTML content.
- • Remove unnecessary tags
- • Clean up formatting
- • Normalize whitespace
- • Remove scripts and styles
- • Return cleaned HTML
- """
- pass
-
-
-class XMLParser:
- """
- XML document parsing engine.
-
- • Parses XML documents and fragments
- • Validates XML structure
- • Extracts XML data and attributes
- • Handles namespaces and schemas
- • Processes XML transformations
- """
-
- def __init__(self, **config):
- """
- Initialize XML parser.
+ Args:
+ html_content: HTML content or file path
+ **options: Cleaning options
+
+ Returns:
+ str: Cleaned HTML
+ """
+ if isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):
+ with open(html_content, 'r', encoding='utf-8', errors='ignore') as f:
+ html_string = f.read()
+ else:
+ html_string = html_content
- • Setup XML parsing library
- • Configure validation options
- • Initialize namespace handlers
- • Setup transformation tools
- """
- pass
-
- def parse_xml(self, xml_content, **options):
- """
- Parse XML content.
+ soup = BeautifulSoup(html_string, 'html.parser')
- • Parse XML structure
- • Validate XML format
- • Extract elements and attributes
- • Process namespaces
- • Return parsed XML object
- """
- pass
-
- def extract_xml_data(self, xml_content, xpath=None):
- """
- Extract data from XML using XPath.
+ # Remove scripts and styles
+ if options.get("remove_scripts", True):
+ for script in soup(["script", "style", "noscript"]):
+ script.decompose()
- • Parse XML content
- • Apply XPath expressions
- • Extract matching elements
- • Process extracted data
- • Return data collection
- """
- pass
-
- def validate_xml(self, xml_content, schema=None):
- """
- Validate XML against schema.
+ # Remove comments
+ if options.get("remove_comments", True):
+ from bs4 import Comment
+ comments = soup.find_all(string=lambda text: isinstance(text, Comment))
+ for comment in comments:
+ comment.extract()
- • Parse XML content
- • Load validation schema
- • Validate XML structure
- • Report validation errors
- • Return validation result
- """
- pass
+ # Normalize whitespace
+ if options.get("normalize_whitespace", True):
+ for elem in soup.find_all(string=True):
+ if elem.parent.name not in ['pre', 'code']:
+ elem.replace_with(' '.join(elem.split()))
+
+ return str(soup)
class JavaScriptRenderer:
@@ -245,38 +255,143 @@ class JavaScriptRenderer:
• Initialize content extraction
• Setup error handling
"""
- pass
+ self.logger = get_logger("js_renderer")
+ self.config = config
+ self.use_selenium = config.get("use_selenium", False)
+
+ # Initialize Selenium if requested
+ if self.use_selenium:
+ try:
+ from selenium import webdriver
+ from selenium.webdriver.chrome.options import Options
+
+ self.driver_options = Options()
+ self.driver_options.add_argument('--headless')
+ self.driver_options.add_argument('--no-sandbox')
+ self.driver_options.add_argument('--disable-dev-shm-usage')
+
+ self.driver = None # Initialize on first use
+ self.logger.info("Selenium WebDriver configured")
+ except ImportError:
+ self.logger.warning("Selenium not available, JavaScript rendering disabled")
+ self.use_selenium = False
- def render_page(self, html_content, **options):
+ def render_page(self, html_content: Union[str, Path], **options) -> str:
"""
Render HTML page with JavaScript.
- • Load HTML content in browser
- • Execute JavaScript code
- • Wait for page completion
- • Extract rendered content
- • Return final HTML content
- """
- pass
+ Args:
+ html_content: HTML content or file path
+ **options: Rendering options:
+ - wait_time: Time to wait for page load (default: 5)
+ - wait_for_selector: CSS selector to wait for
+
+ Returns:
+ str: Rendered HTML content
+ """
+ if not self.use_selenium:
+ self.logger.warning("JavaScript rendering not available (Selenium not configured)")
+ # Return original content if JavaScript rendering is not available
+ if isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):
+ with open(html_content, 'r', encoding='utf-8', errors='ignore') as f:
+ return f.read()
+ return html_content
+
+ try:
+ # Initialize driver if needed
+ if self.driver is None:
+ from selenium import webdriver
+ from selenium.webdriver.chrome.options import Options
+
+ self.driver = webdriver.Chrome(options=self.driver_options)
+
+ # Load HTML content
+ if isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):
+ file_path = Path(html_content)
+ url = f"file://{file_path.absolute()}"
+ else:
+ # Create temporary HTML file
+ import tempfile
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f:
+ f.write(html_content)
+ url = f"file://{f.name}"
+
+ # Load page
+ self.driver.get(url)
+
+ # Wait for page load
+ wait_time = options.get("wait_time", 5)
+ self.wait_for_content(timeout=wait_time)
+
+ # Wait for specific selector if requested
+ if options.get("wait_for_selector"):
+ from selenium.webdriver.support.ui import WebDriverWait
+ from selenium.webdriver.support import expected_conditions as EC
+ from selenium.webdriver.common.by import By
+
+ WebDriverWait(self.driver, wait_time).until(
+ EC.presence_of_element_located((By.CSS_SELECTOR, options["wait_for_selector"]))
+ )
+
+ # Get rendered HTML
+ rendered_html = self.driver.page_source
+
+ return rendered_html
+
+ except Exception as e:
+ self.logger.error(f"Failed to render JavaScript: {e}")
+ raise ProcessingError(f"Failed to render JavaScript: {e}")
- def execute_script(self, script, **context):
+ def execute_script(self, script: str, **context: Any) -> Any:
"""
Execute JavaScript code.
- • Setup execution context
- • Execute JavaScript code
- • Handle errors and exceptions
- • Return execution results
- """
- pass
+ Args:
+ script: JavaScript code to execute
+ **context: Execution context
+
+ Returns:
+ Result of JavaScript execution
+ """
+ if not self.use_selenium or self.driver is None:
+ raise ProcessingError("JavaScript execution requires Selenium WebDriver")
+
+ try:
+ return self.driver.execute_script(script)
+ except Exception as e:
+ self.logger.error(f"Failed to execute script: {e}")
+ raise ProcessingError(f"Failed to execute script: {e}")
- def wait_for_content(self, condition, timeout=30):
+ def wait_for_content(self, condition: Optional[str] = None, timeout: int = 30) -> bool:
"""
Wait for specific content to load.
- • Monitor page state
- • Wait for condition to be met
- • Handle timeout scenarios
- • Return wait result
- """
- pass
+ Args:
+ condition: Condition to wait for
+ timeout: Timeout in seconds
+
+ Returns:
+ bool: True if condition met
+ """
+ if not self.use_selenium or self.driver is None:
+ return False
+
+ try:
+ from selenium.webdriver.support.ui import WebDriverWait
+ from selenium.webdriver.support import expected_conditions as EC
+
+ WebDriverWait(self.driver, timeout).until(
+ lambda driver: driver.execute_script('return document.readyState') == 'complete'
+ )
+ return True
+ except Exception as e:
+ self.logger.warning(f"Wait timeout: {e}")
+ return False
+
+ def __del__(self):
+ """Cleanup WebDriver on deletion."""
+ if hasattr(self, 'driver') and self.driver:
+ try:
+ self.driver.quit()
+ except Exception:
+ pass
diff --git a/libs/semantica/parse/xml_parser.py b/libs/semantica/parse/xml_parser.py
index d5d63c8f..bf93cd58 100644
--- a/libs/semantica/parse/xml_parser.py
+++ b/libs/semantica/parse/xml_parser.py
@@ -1,14 +1,259 @@
"""
XML document parser for Semantica framework.
-This module handles XML parsing using lxml and xmltodict
-for structured data extraction and validation.
+This module handles XML file parsing using lxml and xml.etree
+for structured data extraction.
"""
-# TODO: Implement XML parsing functionality
-# - XML document parsing and validation
-# - Namespace handling and processing
-# - XPath query support
-# - Schema validation (XSD)
-# - Large XML file streaming support
-# - Error handling for malformed XML
+import io
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from lxml import etree
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class XMLElement:
+ """XML element representation."""
+
+ tag: str
+ text: str
+ attributes: Dict[str, str] = field(default_factory=dict)
+ children: List['XMLElement'] = field(default_factory=list)
+ namespace: Optional[str] = None
+
+
+@dataclass
+class XMLData:
+ """XML document representation."""
+
+ root: XMLElement
+ namespaces: Dict[str, str] = field(default_factory=dict)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class XMLParser:
+ """XML document parser."""
+
+ def __init__(self, **config):
+ """
+ Initialize XML parser.
+
+ Args:
+ **config: Parser configuration
+ """
+ self.logger = get_logger("xml_parser")
+ self.config = config
+
+ def parse(
+ self,
+ file_path: Union[str, Path],
+ **options
+ ) -> XMLData:
+ """
+ Parse XML file.
+
+ Args:
+ file_path: Path to XML file or XML string
+ **options: Parsing options:
+ - engine: Parser engine ('etree' or 'lxml', default: 'lxml')
+ - validate: Whether to validate XML (default: False)
+ - schema: XSD schema for validation
+ - extract_namespaces: Whether to extract namespaces (default: True)
+
+ Returns:
+ XMLData: Parsed XML data
+ """
+ engine = options.get("engine", "lxml")
+
+ # Load XML content
+ if isinstance(file_path, Path) or (isinstance(file_path, str) and Path(file_path).exists()):
+ file_path_obj = Path(file_path)
+ if not file_path_obj.exists():
+ raise ValidationError(f"XML file not found: {file_path_obj}")
+
+ with open(file_path_obj, 'r', encoding='utf-8', errors='ignore') as f:
+ xml_string = f.read()
+ source = str(file_path_obj)
+ else:
+ xml_string = file_path
+ source = "string"
+
+ try:
+ if engine == "lxml":
+ return self._parse_with_lxml(xml_string, source, options)
+ else:
+ return self._parse_with_etree(xml_string, source, options)
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse XML: {e}")
+ raise ProcessingError(f"Failed to parse XML: {e}")
+
+ def _parse_with_lxml(self, xml_string: str, source: str, options: Dict[str, Any]) -> XMLData:
+ """Parse XML using lxml."""
+ parser = etree.XMLParser(remove_blank_text=True)
+ root = etree.fromstring(xml_string.encode('utf-8'), parser)
+
+ # Extract namespaces
+ namespaces = {}
+ if options.get("extract_namespaces", True):
+ namespaces = root.nsmap or {}
+
+ # Convert to XMLElement
+ root_element = self._element_to_xml_element(root)
+
+ return XMLData(
+ root=root_element,
+ namespaces=namespaces,
+ metadata={"source": source, "engine": "lxml"}
+ )
+
+ def _parse_with_etree(self, xml_string: str, source: str, options: Dict[str, Any]) -> XMLData:
+ """Parse XML using xml.etree.ElementTree."""
+ root = ET.fromstring(xml_string)
+
+ # Extract namespaces
+ namespaces = {}
+ if options.get("extract_namespaces", True):
+ # Extract from root element
+ for prefix, uri in ET.iterparse(io.StringIO(xml_string), events=['start-ns']):
+ namespaces[prefix or 'default'] = uri
+
+ # Convert to XMLElement
+ root_element = self._etree_element_to_xml_element(root)
+
+ return XMLData(
+ root=root_element,
+ namespaces=namespaces,
+ metadata={"source": source, "engine": "etree"}
+ )
+
+ def _element_to_xml_element(self, element) -> XMLElement:
+ """Convert lxml element to XMLElement."""
+ tag = element.tag
+ if '}' in tag:
+ namespace, tag = tag.split('}', 1)
+ namespace = namespace[1:]
+ else:
+ namespace = None
+
+ xml_elem = XMLElement(
+ tag=tag,
+ text=(element.text or "").strip(),
+ attributes=dict(element.attrib),
+ namespace=namespace
+ )
+
+ # Process children
+ for child in element:
+ xml_elem.children.append(self._element_to_xml_element(child))
+
+ return xml_elem
+
+ def _etree_element_to_xml_element(self, element: ET.Element) -> XMLElement:
+ """Convert ElementTree element to XMLElement."""
+ tag = element.tag
+ if '}' in tag:
+ namespace, tag = tag.split('}', 1)
+ namespace = namespace[1:]
+ else:
+ namespace = None
+
+ xml_elem = XMLElement(
+ tag=tag,
+ text=(element.text or "").strip(),
+ attributes=dict(element.attrib),
+ namespace=namespace
+ )
+
+ # Process children
+ for child in element:
+ xml_elem.children.append(self._etree_element_to_xml_element(child))
+
+ return xml_elem
+
+ def find_elements(self, file_path: Union[str, Path], xpath: str, **options) -> List[XMLElement]:
+ """
+ Find elements using XPath.
+
+ Args:
+ file_path: Path to XML file or XML string
+ xpath: XPath expression
+ **options: Parsing options
+
+ Returns:
+ list: Found XML elements
+ """
+ xml_data = self.parse(file_path, **options)
+
+ # Use lxml for XPath queries
+ xml_string = file_path if isinstance(file_path, str) and not Path(file_path).exists() else Path(file_path).read_text()
+ root = etree.fromstring(xml_string.encode('utf-8'))
+
+ # Register namespaces for XPath
+ namespaces = xml_data.namespaces
+ elements = root.xpath(xpath, namespaces=namespaces)
+
+ return [self._element_to_xml_element(elem) for elem in elements]
+
+ def extract_by_tag(self, file_path: Union[str, Path], tag_name: str, **options) -> List[XMLElement]:
+ """
+ Extract elements by tag name.
+
+ Args:
+ file_path: Path to XML file or XML string
+ tag_name: Tag name to find
+ **options: Parsing options
+
+ Returns:
+ list: Found XML elements
+ """
+ xml_data = self.parse(file_path, **options)
+
+ def find_by_tag(element: XMLElement, tag: str, results: List[XMLElement]):
+ if element.tag == tag:
+ results.append(element)
+ for child in element.children:
+ find_by_tag(child, tag, results)
+
+ results = []
+ find_by_tag(xml_data.root, tag_name, results)
+ return results
+
+ def to_dict(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:
+ """
+ Convert XML to dictionary.
+
+ Args:
+ file_path: Path to XML file or XML string
+ **options: Parsing options
+
+ Returns:
+ dict: XML data as dictionary
+ """
+ xml_data = self.parse(file_path, **options)
+ return self._element_to_dict(xml_data.root)
+
+ def _element_to_dict(self, element: XMLElement) -> Dict[str, Any]:
+ """Convert XMLElement to dictionary."""
+ result = {
+ "tag": element.tag,
+ "text": element.text,
+ "attributes": element.attributes
+ }
+
+ if element.children:
+ # Group children by tag
+ children_dict = {}
+ for child in element.children:
+ if child.tag not in children_dict:
+ children_dict[child.tag] = []
+ children_dict[child.tag].append(self._element_to_dict(child))
+ result["children"] = children_dict
+
+ return result