Skip to content
Shell
6.8 KB
Raw Blame
#!/usr/bin/env python3
"""
Reddit Research Extractor
Extracts threads via JSON API and structures data for LLM analysis.

Usage:
    python reddit_extractor.py <reddit_url>
    python reddit_extractor.py https://www.reddit.com/r/SaaS/comments/xyz/title/
"""

import json
import subprocess
import sys
from datetime import datetime
from typing import Optional

USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"


def fetch_reddit_json(url: str) -> dict:
    """Fetch Reddit thread as JSON using curl (bypasses urllib fingerprinting)."""
    # Normalize URL to use www.reddit.com
    url = url.replace('reddit.com', 'www.reddit.com')
    if 'www.www.' in url:
        url = url.replace('www.www.', 'www.')

    # Normalize URL to JSON endpoint
    if not url.endswith('.json'):
        url = url.rstrip('/') + '.json'

    result = subprocess.run(
        ['curl', '-s', '-A', USER_AGENT, url],
        capture_output=True,
        text=True,
        timeout=30
    )
    if result.returncode != 0:
        raise Exception(f"curl failed: {result.stderr}")
    return json.loads(result.stdout)


def extract_comments(children: list, depth: int = 0) -> list:
    """Recursively extract all comments from thread."""
    results = []
    for c in children:
        if c['kind'] == 't1':  # t1 = comment
            d = c['data']
            comment = {
                'score': d.get('score', 0),
                'author': d.get('author', '[deleted]'),
                'body': d.get('body', ''),
                'created_utc': d.get('created_utc'),
                'depth': depth,
                'id': d.get('id'),
                'replies_count': 0
            }

            # Count and extract replies
            replies = []
            if d.get('replies') and isinstance(d['replies'], dict):
                reply_children = d['replies']['data']['children']
                replies = extract_comments(reply_children, depth + 1)
                comment['replies_count'] = len(replies)

            results.append(comment)
            results.extend(replies)

    return results


def structure_for_analysis(url: str) -> dict:
    """Extract and structure Reddit thread for LLM analysis."""
    data = fetch_reddit_json(url)

    # Extract post
    post_data = data[0]['data']['children'][0]['data']
    post = {
        'title': post_data.get('title', ''),
        'selftext': post_data.get('selftext', ''),
        'score': post_data.get('score', 0),
        'upvote_ratio': post_data.get('upvote_ratio', 0),
        'num_comments': post_data.get('num_comments', 0),
        'author': post_data.get('author', '[deleted]'),
        'created_utc': post_data.get('created_utc'),
        'subreddit': post_data.get('subreddit', ''),
        'url': f"https://reddit.com{post_data.get('permalink', '')}",
        'flair': post_data.get('link_flair_text'),
    }

    # Extract all comments
    comments = extract_comments(data[1]['data']['children'])

    # Sort by score for top comments
    top_comments = sorted(comments, key=lambda x: x['score'], reverse=True)

    # Calculate engagement metrics
    total_comment_score = sum(c['score'] for c in comments)
    avg_comment_score = total_comment_score / len(comments) if comments else 0

    return {
        'extracted_at': datetime.utcnow().isoformat(),
        'post': post,
        'metrics': {
            'total_comments': len(comments),
            'total_comment_score': total_comment_score,
            'avg_comment_score': round(avg_comment_score, 2),
            'max_depth': max((c['depth'] for c in comments), default=0),
            'unique_authors': len(set(c['author'] for c in comments)),
        },
        'top_comments': top_comments[:30],  # Top 30 by score
        'all_comments': comments,  # Full thread
    }


def format_for_llm(data: dict, include_all: bool = False) -> str:
    """Format extracted data as markdown for LLM analysis."""
    post = data['post']
    metrics = data['metrics']

    output = []
    output.append(f"# Reddit Thread Analysis\n")
    output.append(f"**Subreddit:** r/{post['subreddit']}")
    output.append(f"**Title:** {post['title']}")
    output.append(f"**Score:** {post['score']} | **Upvote Ratio:** {post['upvote_ratio']}")
    output.append(f"**Comments:** {post['num_comments']} | **Unique Authors:** {metrics['unique_authors']}")
    output.append(f"**URL:** {post['url']}\n")

    output.append("## Original Post\n")
    output.append(post['selftext'] or "*No text content*")
    output.append("\n")

    output.append("## Engagement Metrics\n")
    output.append(f"- Total comment score: {metrics['total_comment_score']}")
    output.append(f"- Avg comment score: {metrics['avg_comment_score']}")
    output.append(f"- Max thread depth: {metrics['max_depth']}")
    output.append("\n")

    comments = data['all_comments'] if include_all else data['top_comments']
    output.append(f"## {'All' if include_all else 'Top'} Comments ({len(comments)})\n")

    for i, c in enumerate(comments, 1):
        indent = "  " * c['depth']
        output.append(f"{indent}### [{c['score']} pts] u/{c['author']}")
        body = c['body'].replace('\n', '\n' + indent)
        output.append(f"{indent}{body}")
        output.append("")

    return '\n'.join(output)


# Analysis prompt template
ANALYSIS_PROMPT = """
Analyze this Reddit thread for market research insights. Extract:

## 1. Pain Points
- What problems are people experiencing?
- What frustrations are expressed?
- What's missing from current solutions?

## 2. Product/Competitor Mentions
- What products/services are mentioned (positively or negatively)?
- What alternatives do people suggest?

## 3. Buying Signals
- Who is actively looking for solutions?
- What would make them pay?
- Price sensitivity indicators

## 4. Feature Requests / Opportunities
- What features do people wish existed?
- What would make existing solutions better?

## 5. Marketing Insights
- What messaging resonates?
- Where do these users hang out?
- What objections would they have?

## 6. Key Quotes
- Extract 3-5 verbatim quotes that capture valuable insights

## 7. Actionable Recommendations
- Based on this thread, what product/feature should be built?
- How should it be marketed to this audience?

---

THREAD DATA:
"""


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python reddit_extractor.py <reddit_url> [--json] [--prompt]")
        sys.exit(1)

    url = sys.argv[1]
    output_json = '--json' in sys.argv
    include_prompt = '--prompt' in sys.argv

    try:
        data = structure_for_analysis(url)

        if output_json:
            print(json.dumps(data, indent=2, default=str))
        else:
            formatted = format_for_llm(data)
            if include_prompt:
                print(ANALYSIS_PROMPT)
            print(formatted)

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)