|
| 1 | +import json |
| 2 | +import os |
| 3 | +from datetime import datetime |
| 4 | +from typing import Any, Dict, List |
| 5 | + |
| 6 | +from reddit_scraper.core.models import Comment, Post, SubredditConfig |
| 7 | +from reddit_scraper.utils.config import get_scraper_config |
| 8 | + |
| 9 | + |
| 10 | +class DateTimeEncoder(json.JSONEncoder): |
| 11 | + """Custom JSON encoder for datetime objects.""" |
| 12 | + |
| 13 | + def default(self, obj): |
| 14 | + if isinstance(obj, datetime): |
| 15 | + return obj.isoformat() |
| 16 | + return super().default(obj) |
| 17 | + |
| 18 | + |
| 19 | +class DataProcessor: |
| 20 | + """Handles data processing and storage operations.""" |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + """Initialize the data processor.""" |
| 24 | + self.config = get_scraper_config() |
| 25 | + |
| 26 | + def parse_post_data(self, json_data: Dict[str, Any]) -> Post: |
| 27 | + """Parse raw JSON data into a Post model.""" |
| 28 | + post = json_data[0]["data"]["children"][0]["data"] |
| 29 | + comments_data = json_data[1]["data"]["children"] |
| 30 | + |
| 31 | + return Post( |
| 32 | + post_body=post["title"], |
| 33 | + post_user=post["author"], |
| 34 | + post_time=datetime.fromtimestamp(post["created_utc"]), |
| 35 | + comments=self._parse_comments(comments_data), |
| 36 | + ) |
| 37 | + |
| 38 | + def _parse_comments(self, comment_data: List[Dict[str, Any]]) -> List[Comment]: |
| 39 | + """Parse comment data into Comment models.""" |
| 40 | + comments = [] |
| 41 | + for comment in comment_data: |
| 42 | + if comment["kind"] != "t1": |
| 43 | + continue |
| 44 | + |
| 45 | + comment_dict = comment["data"] |
| 46 | + comments.append( |
| 47 | + Comment( |
| 48 | + body=comment_dict["body"], |
| 49 | + user=comment_dict["author"], |
| 50 | + time=datetime.fromtimestamp(comment_dict["created_utc"]), |
| 51 | + replies=self._parse_comments( |
| 52 | + comment_dict["replies"]["data"]["children"] |
| 53 | + ) |
| 54 | + if comment_dict.get("replies") |
| 55 | + else [], |
| 56 | + ) |
| 57 | + ) |
| 58 | + return comments |
| 59 | + |
| 60 | + def save_to_json(self, data: List[Post], subreddit: str) -> str: |
| 61 | + """Save processed data to a JSON file.""" |
| 62 | + directory = self.config.data_dir |
| 63 | + os.makedirs(directory, exist_ok=True) |
| 64 | + filename = f"{directory}/{subreddit}.json" |
| 65 | + |
| 66 | + with open(filename, "w") as f: |
| 67 | + json.dump([post.dict() for post in data], f, cls=DateTimeEncoder) |
| 68 | + return filename |
| 69 | + |
| 70 | + def read_subreddits_from_json( |
| 71 | + self, filename: str, duration: str |
| 72 | + ) -> List[SubredditConfig]: |
| 73 | + """Read subreddit configurations from a JSON file.""" |
| 74 | + with open(filename) as f: |
| 75 | + subreddits_list = json.load(f) |
| 76 | + |
| 77 | + return [ |
| 78 | + SubredditConfig( |
| 79 | + name=subreddit, |
| 80 | + url=f"https://www.reddit.com/r/{subreddit}/top/?t={duration}", |
| 81 | + ) |
| 82 | + for subreddit in subreddits_list |
| 83 | + ] |
0 commit comments