from pathlib import Path def pdf_source_for_markdown(source: str | None) -> str: if not source: return "" md_path = Path(source) if md_path.suffix.lower() != ".md": return "" pdf_path = md_path.parent.parent / "pdf" / f"{md_path.stem}.pdf" return str(pdf_path) if pdf_path.exists() else "" def source_after_data_pdf(source: str) -> str: parts = Path(source).parts lowered = [part.lower() for part in parts] for index in range(len(lowered) - 1): if lowered[index] == "data" and lowered[index + 1] == "pdf": return str(Path(*parts[index + 2 :])) if index + 2 < len(parts) else "" return source def display_source_from_metadata(metadata: dict) -> str: source = ( metadata.get("source_display_path") or metadata.get("source_pdf_path") or metadata.get("source") ) if not source: return "Không có nguồn" pdf_source = pdf_source_for_markdown(str(source)) or str(source) return source_after_data_pdf(pdf_source)