Shell
#!/usr/bin/env python3
"""
Reddit Thread Analyzer
Fetches Reddit thread and analyzes with Claude for market research insights.
Usage:
python analyze_thread.py <reddit_url>
python analyze_thread.py https://www.reddit.com/r/SaaS/comments/xyz/title/
Outputs structured market research analysis.
"""
import json
import subprocess
import sys
from datetime import datetime
# Import from our extractor
from reddit_extractor import structure_for_analysis, format_for_llm, ANALYSIS_PROMPT
def analyze_with_claude(thread_markdown: str) -> str:
"""Send thread to Claude for analysis via claude CLI."""
full_prompt = ANALYSIS_PROMPT + "\n\n" + thread_markdown
# Use claude CLI in non-interactive mode
result = subprocess.run(
['claude', '-p', full_prompt, '--no-input'],
capture_output=True,
text=True,
timeout=120
)
if result.returncode != 0:
raise Exception(f"Claude analysis failed: {result.stderr}")
return result.stdout
def main():
if len(sys.argv) < 2:
print("Usage: python analyze_thread.py <reddit_url>")
sys.exit(1)
url = sys.argv[1]
save_json = '--json' in sys.argv
print(f"π Fetching thread: {url}")
print("-" * 60)
try:
# Extract thread data
data = structure_for_analysis(url)
thread_md = format_for_llm(data)
print(f"β
Extracted {data['metrics']['total_comments']} comments from {data['metrics']['unique_authors']} authors")
print(f"π Post score: {data['post']['score']} | Upvote ratio: {data['post']['upvote_ratio']}")
print("-" * 60)
# Save raw data if requested
if save_json:
json_file = f"thread_{data['post']['id'] if 'id' in data['post'] else 'export'}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(json_file, 'w') as f:
json.dump(data, f, indent=2, default=str)
print(f"πΎ Saved raw data to: {json_file}")
print("\nπ€ Analyzing with Claude...")
print("=" * 60)
analysis = analyze_with_claude(thread_md)
print(analysis)
# Save analysis
analysis_file = f"analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
with open(analysis_file, 'w') as f:
f.write(f"# Market Research Analysis\n\n")
f.write(f"**Source:** {url}\n")
f.write(f"**Analyzed:** {datetime.now().isoformat()}\n\n")
f.write(analysis)
print(f"\nπΎ Analysis saved to: {analysis_file}")
except Exception as e:
print(f"β Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()