ReMe/reme2/component/file_parser/md_file_parser.py
jinli.yl ca5970c6b0 refactor(component): refactor base components and file store implementations
- Remove abstract methods from base component start/close
- Update BaseJob to remove name parameter and simplify initialization
- Change file modification time field from mtime_ms to modified_time in seconds
- Add type checking imports and improve typing annotations
- Implement LocalFileStore with JSONL persistence for file chunks
- Add MdFileParser with markdown and frontmatter support
- Simplify HttpClient call method with proper kwargs handling
- Remove unused ReMe class methods and create backup version
- Update StreamJob to use step_components instead of steps attribute
2026-04-23 17:44:25 +08:00

57 lines
1.5 KiB
Python

"""Markdown file parser."""
import asyncio
import os
from pathlib import Path
import frontmatter
from .base_file_parser import BaseFileParser
from ..component_registry import R
from ...schema import FileChunk, FileMetadata
from ...utils import hash_text, chunk_markdown
@R.register("md")
class MdFileParser(BaseFileParser):
"""Parser for Markdown files with YAML frontmatter support."""
suffixes = [".md", ".markdown"]
def __init__(self, encoding: str = "utf-8", **kwargs):
super().__init__(**kwargs)
self.encoding = encoding
async def parse(self, path: str) -> tuple[FileMetadata, list[FileChunk]]:
file_path = Path(path)
def _read_and_parse():
raw = file_path.read_text(encoding=self.encoding)
post = frontmatter.loads(raw)
stat = file_path.stat()
os.stat()
return stat, dict(post.metadata), post.content
stat, metadata, content = await asyncio.to_thread(_read_and_parse)
file_meta = FileMetadata(
hash=hash_text(content),
modified_time=stat.st_mtime,
size=stat.st_size,
path=str(file_path.absolute()),
content=content,
metadata=metadata,
)
chunks = (
chunk_markdown(
content,
file_meta.path,
self.chunk_tokens,
self.chunk_overlap,
)
or []
)
file_meta.chunk_count = len(chunks)
return file_meta, chunks