diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c69f3de..2a247c4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -26,7 +26,7 @@ jobs: run: python -m pip install -e . - name: Compile Python files - run: python -m py_compile main.py chatgpt_share_exporter.py tests/test_exporter.py + run: python -m py_compile main.py chatgpt_share_exporter.py chatgpt_pdf_converter.py tests/test_exporter.py tests/test_pdf_converter.py - name: Run tests run: python -m unittest discover -s tests diff --git a/.gitignore b/.gitignore index 4b0d0de..364b255 100644 --- a/.gitignore +++ b/.gitignore @@ -26,5 +26,8 @@ dist/ # Generated exports and local scratch files exports/ +screenshots/ +pdf_exports/ +output/pdf/ *.html *.log diff --git a/README.md b/README.md index 45cf870..3393636 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,10 @@ The exporter reads the structured conversation data embedded in ChatGPT share pa - includes conversation metadata such as title, source URL, conversation ID, timestamps, and model slug - includes per-message metadata such as author, message ID, created/updated time, status, channel, recipient, model, request ID, and turn ID - records uploaded image/file metadata such as name, MIME type, size, dimensions, and source pointer +- converts Markdown exports to clean PDF files +- supports RTL PDF layout for Persian/Arabic chats +- supports custom PDF font family, font file, font size, page size, and margins - can include hidden/system/internal nodes when requested -- uses only the Python standard library ## Requirements @@ -36,6 +38,8 @@ python3 -m pip install -e . chatgpt-share-exporter "https://chatgpt.com/share/YOUR_SHARE_ID" ``` +This installs the PDF dependencies too. + ## Options ```bash @@ -54,6 +58,52 @@ chatgpt-share-exporter URL -o my_exports --overwrite - `--html-file`: parse an already downloaded share page instead of fetching the URL - `--timeout`: set the download timeout in seconds +## Convert Exports To PDF + +Convert every Markdown export in `exports/`: + +```bash +chatgpt-share-exporter pdf exports +``` + +or use the dedicated command: + +```bash +chatgpt-export-to-pdf exports +``` + +Generate an RTL PDF: + +```bash +chatgpt-share-exporter pdf exports --rtl +``` + +Use a custom font and size: + +```bash +chatgpt-share-exporter pdf exports \ + --font-family Vazirmatn \ + --font-path ./fonts/Vazirmatn-Regular.ttf \ + --font-size 14 +``` + +PDF options: + +- `--direction auto|ltr|rtl`: choose PDF text direction. Default: `auto` +- `--rtl`: shortcut for `--direction rtl` +- `--ltr`: shortcut for `--direction ltr` +- `--font-family`: preferred body font family. Default: `Vazirmatn` +- `--font-path`: explicit `.ttf` or `.otf` font file path +- `--font-size`: base font size in points. Default: `14` +- `--page-size A4|Letter`: PDF page size. Default: `A4` +- `--margin-mm`: page margin in millimeters. Default: `16` +- `--recursive`: convert Markdown files in nested export directories +- `--overwrite`: replace existing PDF files + +Generated PDFs are written to `pdf_exports/`, which is ignored by Git. + +For best Persian output, install Vazirmatn locally or pass its font file with `--font-path`. If Vazirmatn is not installed, the converter searches for common system fallbacks such as Arial Unicode, Tahoma, DejaVu Sans, and Noto Arabic fonts. + ## Development Run tests: @@ -65,7 +115,7 @@ python3 -m unittest discover -s tests Run a syntax check: ```bash -python3 -m py_compile main.py chatgpt_share_exporter.py tests/test_exporter.py +python3 -m py_compile main.py chatgpt_share_exporter.py chatgpt_pdf_converter.py tests/test_exporter.py tests/test_pdf_converter.py ``` ## Notes diff --git a/chatgpt_pdf_converter.py b/chatgpt_pdf_converter.py new file mode 100644 index 0000000..9fcf2f2 --- /dev/null +++ b/chatgpt_pdf_converter.py @@ -0,0 +1,953 @@ +from __future__ import annotations + +import argparse +import html +import os +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple + +try: + import arabic_reshaper + from bidi.algorithm import get_display + from reportlab.lib import colors + from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT + from reportlab.lib.pagesizes import A4, LETTER + from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet + from reportlab.lib.units import mm + from reportlab.pdfbase import pdfmetrics + from reportlab.pdfbase.ttfonts import TTFont + from reportlab.platypus import ( + HRFlowable, + PageBreak, + Paragraph, + Preformatted, + SimpleDocTemplate, + Spacer, + Table, + TableStyle, + ) +except ImportError as exc: # pragma: no cover - exercised when deps are absent. + _IMPORT_ERROR = exc +else: + _IMPORT_ERROR = None + + +RTL_RE = re.compile(r"[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]") +PROTECTED_LTR_RE = re.compile( + r"(https?://\S+|[A-Za-z0-9][A-Za-z0-9._:/?&=#%+\-@]*[A-Za-z0-9]?)" +) +INLINE_MARKUP_RE = re.compile( + r"`([^`]+)`|\*\*(.+?)\*\*|(? Path: + _ensure_pdf_dependencies() + if not markdown_path.exists(): + raise PdfConversionError(f"Input file does not exist: {markdown_path}") + if markdown_path.suffix.lower() != ".md": + raise PdfConversionError(f"Input file is not Markdown: {markdown_path}") + + text = markdown_path.read_text(encoding="utf-8") + direction = detect_direction(text) if options.direction == "auto" else options.direction + font_config = resolve_font(options.font_family, options.font_path) + + options.output_dir.mkdir(parents=True, exist_ok=True) + output_path = options.output_dir / f"{markdown_path.stem}.pdf" + if not options.overwrite: + output_path = unique_path(output_path) + + render_pdf( + markdown_text=text, + output_path=output_path, + title=title_from_markdown(text) or markdown_path.stem, + direction=direction, + font_config=font_config, + font_size=options.font_size, + page_size=page_size_for_name(options.page_size), + margin_mm=options.margin_mm, + ) + return output_path + + +def convert_inputs(paths: Sequence[Path], options: PdfOptions) -> List[Path]: + markdown_files: List[Path] = [] + for path in paths: + if path.is_dir(): + pattern = "**/*.md" if options.recursive else "*.md" + markdown_files.extend(sorted(path.glob(pattern))) + elif path.is_file(): + markdown_files.append(path) + else: + raise PdfConversionError(f"Input path does not exist: {path}") + + if not markdown_files: + raise PdfConversionError("No Markdown files found to convert.") + + outputs = [] + for markdown_file in markdown_files: + outputs.append(convert_markdown_file(markdown_file, options)) + return outputs + + +def render_pdf( + markdown_text: str, + output_path: Path, + title: str, + direction: str, + font_config: FontConfig, + font_size: float, + page_size: Tuple[float, float], + margin_mm: float, +) -> None: + base_margin = margin_mm * mm + doc = SimpleDocTemplate( + str(output_path), + pagesize=page_size, + rightMargin=base_margin, + leftMargin=base_margin, + topMargin=base_margin, + bottomMargin=base_margin + 8 * mm, + title=title, + author="chatgpt-share-exporter", + ) + styles = build_styles(font_config, font_size, direction) + blocks = parse_markdown(markdown_text) + story = blocks_to_flowables(blocks, styles, direction, doc.width) + if not story: + story = [Paragraph("No content.", styles["Body"])] + doc.build( + story, + onFirstPage=page_footer(title, font_config, direction), + onLaterPages=page_footer(title, font_config, direction), + ) + + +def parse_markdown(markdown_text: str) -> List[Mapping[str, Any]]: + lines = strip_frontmatter(markdown_text).splitlines() + blocks: List[Mapping[str, Any]] = [] + index = 0 + + while index < len(lines): + line = lines[index] + stripped = line.strip() + if not stripped: + index += 1 + continue + + fence_match = FENCE_RE.match(stripped) + if fence_match: + fence = fence_match.group(1) + code_lines: List[str] = [] + index += 1 + while index < len(lines) and not lines[index].strip().startswith(fence): + code_lines.append(lines[index]) + index += 1 + if index < len(lines): + index += 1 + blocks.append({"type": "code", "text": "\n".join(code_lines)}) + continue + + if stripped in {"---", "***", "___"}: + blocks.append({"type": "hr"}) + index += 1 + continue + + heading_match = HEADING_RE.match(stripped) + if heading_match: + blocks.append( + { + "type": "heading", + "level": len(heading_match.group(1)), + "text": heading_match.group(2).strip(), + } + ) + index += 1 + continue + + if is_table_start(lines, index): + table_lines = [lines[index], lines[index + 1]] + index += 2 + while index < len(lines) and lines[index].strip().startswith("|"): + table_lines.append(lines[index]) + index += 1 + blocks.append({"type": "table", "rows": parse_table(table_lines)}) + continue + + unordered_match = UNORDERED_LIST_RE.match(line) + ordered_match = ORDERED_LIST_RE.match(line) + if unordered_match or ordered_match: + ordered = bool(ordered_match) + items: List[Tuple[str, str]] = [] + while index < len(lines): + current = lines[index] + current_unordered = UNORDERED_LIST_RE.match(current) + current_ordered = ORDERED_LIST_RE.match(current) + if ordered and current_ordered: + items.append((current_ordered.group(1) + ".", current_ordered.group(2).strip())) + elif not ordered and current_unordered: + items.append(("-", current_unordered.group(1).strip())) + else: + break + index += 1 + blocks.append({"type": "list", "ordered": ordered, "items": items}) + continue + + if stripped.startswith(">"): + quote_lines: List[str] = [] + while index < len(lines) and lines[index].strip().startswith(">"): + quote_lines.append(lines[index].strip()[1:].strip()) + index += 1 + blocks.append({"type": "quote", "text": " ".join(quote_lines)}) + continue + + paragraph_lines = [line.strip()] + index += 1 + while index < len(lines): + current = lines[index] + current_stripped = current.strip() + if ( + not current_stripped + or FENCE_RE.match(current_stripped) + or current_stripped in {"---", "***", "___"} + or HEADING_RE.match(current_stripped) + or is_table_start(lines, index) + or UNORDERED_LIST_RE.match(current) + or ORDERED_LIST_RE.match(current) + or current_stripped.startswith(">") + ): + break + paragraph_lines.append(current_stripped) + index += 1 + blocks.append({"type": "paragraph", "text": " ".join(paragraph_lines)}) + + return blocks + + +def blocks_to_flowables( + blocks: Sequence[Mapping[str, Any]], + styles: Mapping[str, ParagraphStyle], + direction: str, + available_width: float, +) -> List[Any]: + story: List[Any] = [] + for block in blocks: + block_type = block.get("type") + if block_type == "heading": + level = int(block.get("level") or 1) + style = styles.get(f"H{min(level, 4)}", styles["H4"]) + story.append(Paragraph(inline_markup(str(block.get("text") or ""), direction), style)) + story.append(Spacer(1, style.fontSize * 0.45)) + elif block_type == "paragraph": + story.append(Paragraph(inline_markup(str(block.get("text") or ""), direction), styles["Body"])) + story.append(Spacer(1, styles["Body"].fontSize * 0.55)) + elif block_type == "quote": + story.append(Paragraph(inline_markup(str(block.get("text") or ""), direction), styles["Quote"])) + story.append(Spacer(1, styles["Body"].fontSize * 0.6)) + elif block_type == "list": + for marker, item in block.get("items", []): + text = f"{marker} {item}" if direction == "ltr" else f"{item} {marker}" + story.append(Paragraph(inline_markup(text, direction), styles["List"])) + story.append(Spacer(1, styles["Body"].fontSize * 0.45)) + elif block_type == "code": + code = str(block.get("text") or "") + story.append(code_block(code, styles["Code"])) + story.append(Spacer(1, styles["Body"].fontSize * 0.65)) + elif block_type == "table": + rows = block.get("rows") or [] + if rows: + story.append(table_flowable(rows, styles, direction, available_width)) + story.append(Spacer(1, styles["Body"].fontSize * 0.75)) + elif block_type == "hr": + story.append(Spacer(1, styles["Body"].fontSize * 0.4)) + story.append(HRFlowable(width="100%", color=colors.HexColor("#d7d7d7"), thickness=0.7)) + story.append(Spacer(1, styles["Body"].fontSize * 0.7)) + elif block_type == "page_break": + story.append(PageBreak()) + return story + + +def build_styles(font_config: FontConfig, font_size: float, direction: str) -> Mapping[str, ParagraphStyle]: + base = getSampleStyleSheet() + alignment = TA_RIGHT if direction == "rtl" else TA_LEFT + word_wrap = "RTL" if direction == "rtl" else None + body_leading = font_size * 1.65 + + styles = { + "Body": ParagraphStyle( + "Body", + parent=base["BodyText"], + fontName=font_config.body_font, + fontSize=font_size, + leading=body_leading, + alignment=alignment, + wordWrap=word_wrap, + textColor=colors.HexColor("#1f2328"), + spaceAfter=0, + ), + "H1": ParagraphStyle( + "H1", + parent=base["Heading1"], + fontName=font_config.bold_font, + fontSize=font_size * 1.85, + leading=font_size * 2.25, + alignment=alignment, + wordWrap=word_wrap, + textColor=colors.HexColor("#111827"), + spaceBefore=font_size * 0.6, + ), + "H2": ParagraphStyle( + "H2", + parent=base["Heading2"], + fontName=font_config.bold_font, + fontSize=font_size * 1.45, + leading=font_size * 1.85, + alignment=alignment, + wordWrap=word_wrap, + textColor=colors.HexColor("#111827"), + spaceBefore=font_size * 0.45, + ), + "H3": ParagraphStyle( + "H3", + parent=base["Heading3"], + fontName=font_config.bold_font, + fontSize=font_size * 1.2, + leading=font_size * 1.6, + alignment=alignment, + wordWrap=word_wrap, + textColor=colors.HexColor("#111827"), + spaceBefore=font_size * 0.35, + ), + "H4": ParagraphStyle( + "H4", + parent=base["Heading4"], + fontName=font_config.bold_font, + fontSize=font_size * 1.05, + leading=font_size * 1.45, + alignment=alignment, + wordWrap=word_wrap, + textColor=colors.HexColor("#111827"), + spaceBefore=font_size * 0.25, + ), + "Quote": ParagraphStyle( + "Quote", + parent=base["BodyText"], + fontName=font_config.body_font, + fontSize=font_size, + leading=body_leading, + alignment=alignment, + wordWrap=word_wrap, + leftIndent=10 * mm if direction == "ltr" else 0, + rightIndent=10 * mm if direction == "rtl" else 0, + textColor=colors.HexColor("#4b5563"), + borderColor=colors.HexColor("#d1d5db"), + borderWidth=0.7, + borderPadding=6, + backColor=colors.HexColor("#f9fafb"), + ), + "List": ParagraphStyle( + "List", + parent=base["BodyText"], + fontName=font_config.body_font, + fontSize=font_size, + leading=body_leading, + alignment=alignment, + wordWrap=word_wrap, + leftIndent=8 * mm if direction == "ltr" else 0, + rightIndent=8 * mm if direction == "rtl" else 0, + ), + "Code": ParagraphStyle( + "Code", + parent=base["Code"], + fontName=font_config.code_font, + fontSize=max(font_size * 0.85, 9), + leading=max(font_size * 1.25, 12), + alignment=TA_LEFT, + wordWrap="CJK", + textColor=colors.HexColor("#111827"), + ), + "TableCell": ParagraphStyle( + "TableCell", + parent=base["BodyText"], + fontName=font_config.body_font, + fontSize=max(font_size * 0.84, 9), + leading=max(font_size * 1.18, 12), + alignment=alignment, + wordWrap=word_wrap or "CJK", + textColor=colors.HexColor("#1f2328"), + ), + "TableHeader": ParagraphStyle( + "TableHeader", + parent=base["BodyText"], + fontName=font_config.bold_font, + fontSize=max(font_size * 0.84, 9), + leading=max(font_size * 1.18, 12), + alignment=alignment, + wordWrap=word_wrap or "CJK", + textColor=colors.HexColor("#111827"), + ), + "Footer": ParagraphStyle( + "Footer", + parent=base["BodyText"], + fontName=font_config.body_font, + fontSize=8, + leading=10, + alignment=TA_CENTER, + textColor=colors.HexColor("#6b7280"), + ), + } + return styles + + +def table_flowable( + rows: Sequence[Sequence[str]], + styles: Mapping[str, ParagraphStyle], + direction: str, + available_width: float, +) -> Table: + header = rows[0] + body = rows[1:] + ordered_rows = [header] + body + column_widths = content_aware_column_widths(ordered_rows, available_width) + if direction == "rtl": + ordered_rows = [list(reversed(row)) for row in ordered_rows] + column_widths = list(reversed(column_widths)) + + table_data: List[List[Paragraph]] = [] + for row_index, row in enumerate(ordered_rows): + style = styles["TableHeader"] if row_index == 0 else styles["TableCell"] + table_data.append([Paragraph(inline_markup(cell, direction), style) for cell in row]) + + table = Table( + table_data, + colWidths=column_widths, + repeatRows=1, + splitByRow=1, + hAlign="RIGHT" if direction == "rtl" else "LEFT", + ) + table.setStyle( + TableStyle( + [ + ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f3f4f6")), + ("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#111827")), + ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#d1d5db")), + ("VALIGN", (0, 0), (-1, -1), "TOP"), + ("LEFTPADDING", (0, 0), (-1, -1), 6), + ("RIGHTPADDING", (0, 0), (-1, -1), 6), + ("TOPPADDING", (0, 0), (-1, -1), 5), + ("BOTTOMPADDING", (0, 0), (-1, -1), 5), + ] + ) + ) + return table + + +def content_aware_column_widths(rows: Sequence[Sequence[str]], available_width: float) -> List[float]: + column_count = max((len(row) for row in rows), default=0) + if column_count == 0: + return [] + + columns = [ + [str(row[index]) if index < len(row) else "" for row in rows] + for index in range(column_count) + ] + minimums = [minimum_column_width(column) for column in columns] + scores = [column_width_score(column, minimum) for column, minimum in zip(columns, minimums)] + minimum_sum = sum(minimums) + + if minimum_sum >= available_width: + scale = available_width / minimum_sum + return [max(width * scale, 24) for width in minimums] + + extra = available_width - minimum_sum + flex_values = [max(score - minimum, 1.0) for score, minimum in zip(scores, minimums)] + flex_sum = sum(flex_values) + return [ + minimum + extra * (flex / flex_sum) + for minimum, flex in zip(minimums, flex_values) + ] + + +def minimum_column_width(cells: Sequence[str]) -> float: + values = [cell.strip() for cell in cells if cell and cell.strip()] + if not values: + return 42.0 + + joined = " ".join(values) + max_length = max(display_length(value) for value in values) + if "://" in joined: + return 160.0 + if any(is_uuid_like(value) for value in values): + return 130.0 + if any(is_filename_like(value) for value in values): + return 105.0 + if any("/" in value and not has_rtl(value) for value in values): + return 82.0 + if any(re.search(r"\d+x\d+", value) for value in values): + return 78.0 + if max_length <= 5: + return 44.0 + if max_length <= 12: + return 64.0 + return 88.0 + + +def column_width_score(cells: Sequence[str], minimum: float) -> float: + values = [cell.strip() for cell in cells if cell and cell.strip()] + if not values: + return minimum + + max_length = max(display_length(value) for value in values) + joined = " ".join(values) + if "://" in joined: + return max(minimum, 310.0) + if any(is_uuid_like(value) for value in values): + return max(minimum, 230.0) + return max(minimum, min(max_length * 5.6, 230.0)) + + +def display_length(value: str) -> int: + return sum(1 if ord(char) < 128 else 2 for char in value) + + +def is_uuid_like(value: str) -> bool: + return bool(re.search(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F-]{12,}\b", value)) + + +def is_filename_like(value: str) -> bool: + return bool(re.search(r"\b[\w.-]+\.[A-Za-z0-9]{2,5}\b", value)) + + +def code_block(code: str, style: ParagraphStyle) -> Table: + preformatted = Preformatted(code or " ", style, maxLineLength=95) + table = Table([[preformatted]], colWidths=["*"], hAlign="LEFT") + table.setStyle( + TableStyle( + [ + ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f6f8fa")), + ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#d1d5db")), + ("LEFTPADDING", (0, 0), (-1, -1), 8), + ("RIGHTPADDING", (0, 0), (-1, -1), 8), + ("TOPPADDING", (0, 0), (-1, -1), 8), + ("BOTTOMPADDING", (0, 0), (-1, -1), 8), + ] + ) + ) + return table + + +def inline_markup(text: str, direction: str) -> str: + if direction == "rtl": + return rtl_inline_markup(text) + + placeholders: List[str] = [] + + def code_replacement(match: re.Match[str]) -> str: + placeholders.append(html.escape(match.group(1))) + return f"@@CODE{len(placeholders) - 1}@@" + + escaped = html.escape(text) + escaped = INLINE_CODE_RE.sub(code_replacement, text) + escaped = html.escape(escaped, quote=False) + escaped = escaped.replace("<font name=\"Courier\">", "") + escaped = escaped.replace("</font>", "") + escaped = re.sub(r"\*\*(.+?)\*\*", r"\1", escaped) + escaped = re.sub(r"(?\1", escaped) + + for index, value in enumerate(placeholders): + escaped = escaped.replace(f"@@CODE{index}@@", value) + return escaped + + +def rtl_inline_markup(text: str) -> str: + placeholders: List[Tuple[str, str]] = [] + + def new_placeholder(replacement: str) -> str: + placeholder = chr(0xE000 + len(placeholders)) + placeholders.append((placeholder, replacement)) + return placeholder + + def markup_replacement(match: re.Match[str]) -> str: + code_text, bold_text, italic_text = match.groups() + if code_text is not None: + replacement = html.escape(code_text, quote=False) + elif bold_text is not None: + replacement = escape_rtl_fragment(bold_text) + else: + replacement = escape_rtl_fragment(italic_text or "") + return new_placeholder(replacement) + + protected = INLINE_MARKUP_RE.sub(markup_replacement, text) + + def ltr_replacement(match: re.Match[str]) -> str: + return new_placeholder(html.escape(match.group(0), quote=False)) + + protected = PROTECTED_LTR_RE.sub(ltr_replacement, protected) + shaped = get_display(arabic_reshaper.reshape(protected)) if has_rtl(protected) else protected + escaped = html.escape(shaped, quote=False) + + for placeholder, replacement in placeholders: + escaped = escaped.replace(html.escape(placeholder, quote=False), replacement) + escaped = escaped.replace(placeholder, replacement) + return escaped + + +def escape_rtl_fragment(text: str) -> str: + if has_rtl(text): + return reshape_plain_text(text) + return html.escape(text, quote=False) + + +def reshape_plain_text(text: str) -> str: + placeholders: List[Tuple[str, str]] = [] + + def ltr_replacement(match: re.Match[str]) -> str: + placeholder = chr(0xE000 + len(placeholders)) + placeholders.append((placeholder, match.group(0))) + return placeholder + + protected = PROTECTED_LTR_RE.sub(ltr_replacement, text) + shaped = get_display(arabic_reshaper.reshape(protected)) if has_rtl(protected) else protected + for placeholder, replacement in placeholders: + shaped = shaped.replace(placeholder, replacement) + return html.escape(shaped, quote=False) + + +def parse_table(lines: Sequence[str]) -> List[List[str]]: + rows = [] + for index, line in enumerate(lines): + if index == 1 and TABLE_SEPARATOR_RE.match(line): + continue + cells = split_table_row(line) + rows.append(cells) + + max_columns = max((len(row) for row in rows), default=0) + return [row + [""] * (max_columns - len(row)) for row in rows] + + +def split_table_row(line: str) -> List[str]: + line = line.strip() + if line.startswith("|"): + line = line[1:] + if line.endswith("|"): + line = line[:-1] + + cells: List[str] = [] + current = [] + escaped = False + for char in line: + if char == "\\" and not escaped: + escaped = True + continue + if char == "|" and not escaped: + cells.append("".join(current).strip()) + current = [] + continue + if escaped: + current.append("\\") + current.append(char) + escaped = False + cells.append("".join(current).strip()) + return cells + + +def is_table_start(lines: Sequence[str], index: int) -> bool: + return ( + index + 1 < len(lines) + and lines[index].strip().startswith("|") + and TABLE_SEPARATOR_RE.match(lines[index + 1].strip()) is not None + ) + + +def strip_frontmatter(markdown_text: str) -> str: + lines = markdown_text.splitlines() + if lines and lines[0].strip() == "---": + for index in range(1, len(lines)): + if lines[index].strip() == "---": + return "\n".join(lines[index + 1 :]) + return markdown_text + + +def title_from_markdown(markdown_text: str) -> str: + for line in strip_frontmatter(markdown_text).splitlines(): + match = HEADING_RE.match(line.strip()) + if match and len(match.group(1)) == 1: + return match.group(2).strip() + return "" + + +def detect_direction(text: str) -> str: + letters = [char for char in text if char.isalpha()] + if not letters: + return "ltr" + rtl_count = sum(1 for char in letters if has_rtl(char)) + return "rtl" if rtl_count / max(len(letters), 1) >= 0.18 else "ltr" + + +def has_rtl(text: str) -> bool: + return RTL_RE.search(text) is not None + + +def resolve_font(font_family: str, font_path: Optional[Path]) -> FontConfig: + if font_path: + if not font_path.exists(): + raise PdfConversionError(f"Font path does not exist: {font_path}") + body_font = register_font("BodyFont", font_path) + return FontConfig(body_font=body_font, bold_font=body_font, code_font="Courier", source_path=font_path) + + if font_family in BUILTIN_FONTS: + return FontConfig(body_font=font_family, bold_font=font_family, code_font="Courier", source_path=None) + + found = find_font_file(font_family) or first_existing_font(DEFAULT_FALLBACK_FONTS) + if not found: + if has_rtl(font_family): + raise PdfConversionError("No TrueType font was found for RTL output. Use --font-path.") + return FontConfig(body_font="Helvetica", bold_font="Helvetica-Bold", code_font="Courier", source_path=None) + + body_font = register_font("BodyFont", found) + return FontConfig(body_font=body_font, bold_font=body_font, code_font="Courier", source_path=found) + + +def register_font(name: str, path: Path) -> str: + try: + pdfmetrics.registerFont(TTFont(name, str(path))) + except Exception as exc: + raise PdfConversionError(f"Could not load font {path}: {exc}") from exc + pdfmetrics.registerFontFamily(name, normal=name, bold=name, italic=name, boldItalic=name) + return name + + +def find_font_file(font_family: str) -> Optional[Path]: + normalized_family = normalize_font_name(font_family) + search_roots = [ + Path.cwd() / "fonts", + Path.home() / "Library" / "Fonts", + Path("/Library/Fonts"), + Path("/System/Library/Fonts"), + Path("/System/Library/Fonts/Supplemental"), + Path("/usr/share/fonts"), + Path("/usr/local/share/fonts"), + ] + for root in search_roots: + if not root.exists(): + continue + for candidate in root.rglob("*"): + if candidate.suffix.lower() in FONT_EXTENSIONS and normalized_family in normalize_font_name(candidate.stem): + return candidate + return None + + +def normalize_font_name(value: str) -> str: + return re.sub(r"[^a-z0-9]+", "", value.lower()) + + +def first_existing_font(paths: Sequence[str]) -> Optional[Path]: + for path in paths: + candidate = Path(os.path.expanduser(path)) + if candidate.exists(): + return candidate + return None + + +def page_size_for_name(name: str) -> Tuple[float, float]: + normalized = name.upper() + if normalized == "A4": + return A4 + if normalized in {"LETTER", "US-LETTER"}: + return LETTER + raise PdfConversionError(f"Unsupported page size: {name}") + + +def page_footer(title: str, font_config: FontConfig, direction: str): + def draw(canvas, doc): + canvas.saveState() + canvas.setFont(font_config.body_font, 8) + canvas.setFillColor(colors.HexColor("#6b7280")) + page_width, _page_height = doc.pagesize + footer = f"{title} - Page {doc.page}" + if direction == "rtl" and has_rtl(footer): + footer = get_display(arabic_reshaper.reshape(footer)) + canvas.drawCentredString(page_width / 2, 9 * mm, footer[:140]) + canvas.restoreState() + + return draw + + +def unique_path(path: Path) -> Path: + if not path.exists(): + return path + counter = 2 + while True: + candidate = path.with_name(f"{path.stem}-{counter}{path.suffix}") + if not candidate.exists(): + return candidate + counter += 1 + + +def _ensure_pdf_dependencies() -> None: + if _IMPORT_ERROR is not None: + raise PdfConversionError( + "PDF dependencies are not installed. Run: python3 -m pip install -e ." + ) from _IMPORT_ERROR + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser( + description="Convert ChatGPT Markdown exports to clean PDF files." + ) + parser.add_argument("inputs", nargs="+", type=Path, help="Markdown file(s) or export directory.") + parser.add_argument( + "-o", + "--output-dir", + type=Path, + default=Path("pdf_exports"), + help="Directory for generated PDFs. Default: pdf_exports", + ) + parser.add_argument( + "--direction", + choices=["auto", "ltr", "rtl"], + default="auto", + help="Text direction. Default: auto", + ) + parser.add_argument( + "--rtl", + action="store_true", + help="Shortcut for --direction rtl.", + ) + parser.add_argument( + "--ltr", + action="store_true", + help="Shortcut for --direction ltr.", + ) + parser.add_argument( + "--font-family", + default="Vazirmatn", + help="Preferred body font family. Default: Vazirmatn", + ) + parser.add_argument( + "--font-path", + type=Path, + help="Path to a .ttf/.otf font file. Use this for Vazirmatn if it is not installed.", + ) + parser.add_argument( + "--font-size", + type=float, + default=14.0, + help="Base font size in points. Default: 14", + ) + parser.add_argument( + "--page-size", + choices=["A4", "Letter"], + default="A4", + help="PDF page size. Default: A4", + ) + parser.add_argument( + "--margin-mm", + type=float, + default=16.0, + help="Page margin in millimeters. Default: 16", + ) + parser.add_argument( + "--recursive", + action="store_true", + help="When an input is a directory, convert Markdown files recursively.", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="Overwrite existing PDFs instead of creating numbered copies.", + ) + args = parser.parse_args(argv) + + direction = args.direction + if args.rtl: + direction = "rtl" + if args.ltr: + direction = "ltr" + + options = PdfOptions( + output_dir=args.output_dir, + direction=direction, + font_family=args.font_family, + font_path=args.font_path, + font_size=args.font_size, + page_size=args.page_size, + margin_mm=args.margin_mm, + recursive=args.recursive, + overwrite=args.overwrite, + ) + + try: + outputs = convert_inputs(args.inputs, options) + except PdfConversionError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + for output in outputs: + print(f"Created {output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/chatgpt_share_exporter.py b/chatgpt_share_exporter.py index 97a9c22..20668cf 100644 --- a/chatgpt_share_exporter.py +++ b/chatgpt_share_exporter.py @@ -323,6 +323,12 @@ def format_timestamp(value: Any, tz) -> str: def main(argv: Optional[Sequence[str]] = None) -> int: + argv = list(argv) if argv is not None else sys.argv[1:] + if argv and argv[0] == "pdf": + from chatgpt_pdf_converter import main as pdf_main + + return pdf_main(argv[1:]) + parser = argparse.ArgumentParser( description="Export a public ChatGPT shared conversation to Markdown." ) diff --git a/setup.cfg b/setup.cfg index 4024275..e92a1b3 100644 --- a/setup.cfg +++ b/setup.cfg @@ -22,10 +22,16 @@ classifiers = Topic :: Text Processing :: Markup :: Markdown [options] -py_modules = chatgpt_share_exporter +py_modules = + chatgpt_share_exporter + chatgpt_pdf_converter python_requires = >=3.9 install_requires = + arabic-reshaper>=3.0.0 + python-bidi>=0.6.0 + reportlab>=4.0.0 [options.entry_points] console_scripts = chatgpt-share-exporter = chatgpt_share_exporter:main + chatgpt-export-to-pdf = chatgpt_pdf_converter:main diff --git a/tests/test_pdf_converter.py b/tests/test_pdf_converter.py new file mode 100644 index 0000000..6dc50f7 --- /dev/null +++ b/tests/test_pdf_converter.py @@ -0,0 +1,117 @@ +import tempfile +import unittest +from pathlib import Path + +from chatgpt_pdf_converter import ( + PdfOptions, + content_aware_column_widths, + convert_markdown_file, + detect_direction, + inline_markup, + parse_markdown, + reshape_plain_text, +) + + +class PdfConverterTests(unittest.TestCase): + def test_detects_rtl_text(self): + self.assertEqual(detect_direction("سلام این یک متن فارسی است"), "rtl") + self.assertEqual(detect_direction("This is an English export."), "ltr") + + def test_parses_markdown_blocks(self): + blocks = parse_markdown( + """--- +title: "Demo" +--- + +# Demo + +| Field | Value | +|---|---| +| Author | User | + +- first +- second + +```python +print("hello") +``` +""" + ) + + self.assertEqual(blocks[0]["type"], "heading") + self.assertEqual(blocks[1]["type"], "table") + self.assertEqual(blocks[2]["type"], "list") + self.assertEqual(blocks[3]["type"], "code") + + def test_inline_code_uses_reportlab_font_tag(self): + markup = inline_markup("Use `python3 main.py` now.", "ltr") + + self.assertIn('python3 main.py', markup) + + def test_rtl_shaping_preserves_iso_timestamps(self): + shaped = reshape_plain_text("1. کاربر - 2026-06-30T13:18:44+03:30") + + self.assertIn("2026-06-30T13:18:44+03:30", shaped) + self.assertIn(" - 2026-06-30T13:18:44+03:30", shaped) + + def test_rtl_inline_markup_preserves_mixed_ltr_order(self): + markup = inline_markup("با **L=2**، شما به طور کلی:", "rtl") + + self.assertIn("L=2", markup) + self.assertNotIn("", markup) + self.assertLess(markup.index("L=2"), markup.index("ﺎﺑ")) + + def test_content_aware_table_widths_prioritize_long_source_column(self): + rows = [ + ["نام", "نوع", "اندازه", "ابعاد", "منبع"], + [ + "1000404866.jpg", + "image/jpeg", + "164.8 KB", + "1884x4080", + "sediment://file_00000000741c71f6bd139887dd91b7c3?shared_conversation_id=6a43a1b9", + ], + ] + + widths = content_aware_column_widths(rows, 480) + + self.assertGreater(widths[-1], widths[0]) + self.assertGreater(widths[0], 95) + self.assertGreater(widths[1], 75) + self.assertGreater(widths[2], 45) + self.assertAlmostEqual(sum(widths), 480, delta=0.1) + + def test_generates_pdf(self): + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + markdown = tmp / "demo.md" + markdown.write_text( + """# Demo Export + +## 1. User + +| Field | Value | +|---|---| +| Author | User | + +Hello from the Markdown export. +""", + encoding="utf-8", + ) + output = convert_markdown_file( + markdown, + PdfOptions( + output_dir=tmp / "pdf", + direction="ltr", + font_family="Helvetica", + overwrite=True, + ), + ) + + self.assertTrue(output.exists()) + self.assertEqual(output.read_bytes()[:5], b"%PDF-") + + +if __name__ == "__main__": + unittest.main()