main.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import sys
  2. import os
  3. from datetime import datetime, timezone
  4. from bs4 import BeautifulSoup, NavigableString
  5. def sanitize_filename(title: str) -> str:
  6. return "".join(c if c.isalnum() or c in (' ', '-', '_') else '_' for c in title).strip()[:100]
  7. def get_text_with_formatting(element) -> str:
  8. def walk(node):
  9. if isinstance(node, NavigableString):
  10. return str(node)
  11. elif node.name in ("strong", "b"):
  12. return f"**{''.join(walk(c) for c in node.children)}**"
  13. elif node.name in ("em", "i"):
  14. return f"*{''.join(walk(c) for c in node.children)}*"
  15. elif node.name == "code":
  16. return f"`{''.join(walk(c) for c in node.children)}`"
  17. elif node.name == "a":
  18. href = node.get("href", "#")
  19. label = ''.join(walk(c) for c in node.children)
  20. return f"[{label}]({href})"
  21. elif node.name == "img":
  22. alt = node.get("alt", "")
  23. src = node.get("src", "")
  24. return f"![{alt}]({src})"
  25. else:
  26. return ''.join(walk(c) for c in node.children)
  27. return walk(element).strip()
  28. def extract_markdown_from_conversation(conversation: BeautifulSoup) -> str:
  29. md_lines = []
  30. for element in conversation.children:
  31. if isinstance(element, NavigableString):
  32. text = element.strip().replace("\n", " \n") # Preserve single spacing
  33. if text:
  34. md_lines.append(text)
  35. continue
  36. tag = element.name
  37. # Headings
  38. if tag.startswith("h") and tag[1:].isdigit():
  39. level = int(tag[1:])
  40. md_lines.append(f"{'#' * level} {get_text_with_formatting(element)}")
  41. # Paragraphs with possible links or inline formatting
  42. elif tag == "p":
  43. for link in element.find_all("a"):
  44. href = link.get("href", "#")
  45. link_text = link.get_text(strip=True)
  46. link.replace_with(f"[{link_text}]({href})")
  47. for code in element.find_all("code"):
  48. code_text = code.get_text()
  49. code.replace_with(f"`{code_text}`")
  50. md_lines.append(get_text_with_formatting(element))
  51. # Preformatted code blocks
  52. elif tag == "pre":
  53. code = element.find("code")
  54. if code:
  55. lang_class = code.get("class", [])
  56. language = ""
  57. for cls in lang_class:
  58. if cls.startswith("language-"):
  59. language = cls.replace("language-", "")
  60. break
  61. code_text = code.get_text()
  62. md_lines.append(f"```{language}\n{code_text.strip()}\n```")
  63. # Images
  64. elif tag == "img":
  65. src = element.get("src", "")
  66. alt = element.get("alt", "")
  67. if src:
  68. md_lines.append(f"![{alt}]({src})")
  69. # Inline code
  70. elif tag == "code":
  71. code_text = get_text_with_formatting(element)
  72. md_lines.append(f"`{code_text}`")
  73. # Fallback
  74. else:
  75. text = get_text_with_formatting(element)
  76. if text:
  77. md_lines.append(text)
  78. return "\n\n".join(md_lines)
  79. def convert_chat_html_to_markdown(html_path: str) -> str:
  80. with open(html_path, "r", encoding="utf-8") as f:
  81. soup = BeautifulSoup(f, "html.parser")
  82. title = soup.title.string.strip() if soup.title else "chatgpt_conversation"
  83. filename = sanitize_filename(title) + ".md"
  84. main = soup.find("main")
  85. if not main:
  86. raise ValueError("Could not find <main> in HTML. Is this a valid saved ChatGPT conversation?")
  87. messages = []
  88. conversation = main.find_all("div", attrs={'data-message-author-role': True})
  89. for conversation_turn in conversation:
  90. # ChatGPT response div class="prose"
  91. # User response div class="whitespace-pre-wrap"
  92. content = conversation_turn.find("div", class_=["prose", "whitespace-pre-wrap"])
  93. body = extract_markdown_from_conversation(content).strip()
  94. if not body:
  95. continue
  96. role = conversation_turn.get_attribute_list('data-message-author-role')
  97. if role[0] == "user":
  98. message = f"**You:**\n\n{body}"
  99. else:
  100. message = f"**ChatGPT**\n\n{body}"
  101. messages.append(message)
  102. dd_trace_time = int(int(soup.find("meta", {"name":"dd-trace-time"}).attrs["content"]) / 1000) # UTC time
  103. timestamp = datetime.fromtimestamp(dd_trace_time).strftime("%c")
  104. header = f"*ChatGPT conversation saved {timestamp} converted to Markdown*"
  105. markdown = f"# {title}\n\n{header}\n\n---\n\n" + "\n\n---\n\n".join(messages)
  106. return filename, markdown
  107. def main(args):
  108. if len(args) != 2:
  109. print("Usage: python html_to_markdown.py <path_to_saved_html>")
  110. sys.exit(1)
  111. input_html = args[1]
  112. if not os.path.isfile(input_html):
  113. input_html_ext = os.path.join("input", input_html)
  114. if not os.path.isfile(input_html_ext):
  115. print(f"File not found: {input_html}")
  116. sys.exit(1)
  117. else:
  118. input_html = input_html_ext
  119. output_name, markdown_text = convert_chat_html_to_markdown(input_html)
  120. os.makedirs("output", exist_ok=True)
  121. output_path = os.path.join("output", output_name)
  122. with open(output_path, "w", encoding="utf-8") as f:
  123. f.write(markdown_text)
  124. print(f"Markdown saved to: {output_path}")
  125. if __name__ == "__main__":
  126. main(sys.argv)