debate-bots/json_to_markdown.py
2025-11-11 19:49:58 -07:00

164 lines
4.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Convert debate JSON files to Markdown format.
Usage:
python json_to_markdown.py <input_json_file> [output_markdown_file]
python json_to_markdown.py --all # Convert all JSON files in debates/ directory
"""
import json
import sys
from pathlib import Path
from datetime import datetime
def format_debate_to_markdown(debate_data):
"""Convert debate JSON data to markdown format."""
# Extract basic information
topic = debate_data.get("topic", "Unknown Topic")
timestamp = debate_data.get("timestamp", "")
agents = debate_data.get("agents", {})
exchanges = debate_data.get("exchanges", [])
total_exchanges = debate_data.get("total_exchanges", len(exchanges))
# Format timestamp
try:
dt = datetime.fromisoformat(timestamp)
formatted_time = dt.strftime("%B %d, %Y at %I:%M:%S %p")
except:
formatted_time = timestamp
# Build markdown content
markdown = []
# Title and metadata
markdown.append(f"# Debate: {topic.title()}")
markdown.append("")
markdown.append(f"**Date:** {formatted_time}")
markdown.append(f"**Total Exchanges:** {total_exchanges}")
markdown.append("")
# Agents information
markdown.append("## Participants")
markdown.append("")
for agent_id, agent_info in agents.items():
name = agent_info.get("name", "Unknown")
position = agent_info.get("position", "unknown")
markdown.append(f"- **{name}**: Arguing *{position}* the proposition")
markdown.append("")
markdown.append("---")
markdown.append("")
# Exchanges
for exchange in exchanges:
exchange_num = exchange.get("exchange", "?")
agent = exchange.get("agent", "Unknown")
position = exchange.get("position", "unknown")
content = exchange.get("content", "")
# Exchange header
markdown.append(f"## Exchange {exchange_num}")
markdown.append(f"**{agent}** (*{position}* the proposition)")
markdown.append("")
# Exchange content
markdown.append(content)
markdown.append("")
markdown.append("---")
markdown.append("")
return "\n".join(markdown)
def convert_file(input_path, output_path=None):
"""Convert a single JSON file to markdown."""
input_path = Path(input_path)
if not input_path.exists():
print(f"Error: File not found: {input_path}")
return False
# Read JSON file
try:
with open(input_path, 'r', encoding='utf-8') as f:
debate_data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in {input_path}: {e}")
return False
except Exception as e:
print(f"Error reading {input_path}: {e}")
return False
# Convert to markdown
markdown_content = format_debate_to_markdown(debate_data)
# Determine output path
if output_path is None:
output_path = input_path.with_suffix('.md')
else:
output_path = Path(output_path)
# Write markdown file
try:
with open(output_path, 'w', encoding='utf-8') as f:
f.write(markdown_content)
print(f"✓ Converted: {input_path.name}{output_path.name}")
return True
except Exception as e:
print(f"Error writing {output_path}: {e}")
return False
def convert_all_debates():
"""Convert all JSON files in the debates directory."""
debates_dir = Path("debates")
if not debates_dir.exists():
print(f"Error: debates directory not found")
return
json_files = list(debates_dir.glob("*.json"))
if not json_files:
print("No JSON files found in debates directory")
return
print(f"Found {len(json_files)} debate file(s)")
print()
success_count = 0
for json_file in json_files:
if convert_file(json_file):
success_count += 1
print()
print(f"Successfully converted {success_count}/{len(json_files)} files")
def main():
"""Main entry point."""
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
if sys.argv[1] == "--all":
convert_all_debates()
else:
input_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else None
if convert_file(input_file, output_file):
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()