|
| 1 | +import json |
| 2 | +import os |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from pathlib import Path |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from unstructured.ingest.interfaces import ( |
| 8 | + BaseConnector, |
| 9 | + BaseConnectorConfig, |
| 10 | + BaseIngestDoc, |
| 11 | +) |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from praw.models import Submission |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class SimpleRedditConfig(BaseConnectorConfig): |
| 19 | + subreddit_name: str |
| 20 | + client_id: str |
| 21 | + client_secret: str |
| 22 | + user_agent: str |
| 23 | + search_query: str |
| 24 | + num_posts: int |
| 25 | + |
| 26 | + # Standard Connector options |
| 27 | + download_dir: str |
| 28 | + # where to write structured data |
| 29 | + output_dir: str |
| 30 | + preserve_downloads: bool = False |
| 31 | + re_download: bool = False |
| 32 | + verbose: bool = False |
| 33 | + |
| 34 | + def __post_init__(self): |
| 35 | + if self.num_posts <= 0: |
| 36 | + raise ValueError("The number of Reddit posts to fetch must be positive.") |
| 37 | + |
| 38 | + |
| 39 | +@dataclass |
| 40 | +class RedditIngestDoc(BaseIngestDoc): |
| 41 | + config: SimpleRedditConfig = field(repr=False) |
| 42 | + post: "Submission" |
| 43 | + |
| 44 | + @property |
| 45 | + def filename(self) -> Path: |
| 46 | + return (Path(self.config.download_dir) / f"{self.post.id}.md").resolve() |
| 47 | + |
| 48 | + def _output_filename(self): |
| 49 | + return Path(self.config.output_dir) / f"{self.post.id}.json" |
| 50 | + |
| 51 | + def _create_full_tmp_dir_path(self): |
| 52 | + self.filename.parent.mkdir(parents=True, exist_ok=True) |
| 53 | + |
| 54 | + def cleanup_file(self): |
| 55 | + """Removes the local copy the file (or anything else) after successful processing.""" |
| 56 | + if not self.config.preserve_downloads: |
| 57 | + if self.config.verbose: |
| 58 | + print(f"cleaning up {self}") |
| 59 | + os.unlink(self.filename) |
| 60 | + |
| 61 | + def get_file(self): |
| 62 | + """Fetches the "remote" doc and stores it locally on the filesystem.""" |
| 63 | + self._create_full_tmp_dir_path() |
| 64 | + if not self.config.re_download and self.filename.is_file() and self.filename.stat(): |
| 65 | + if self.config.verbose: |
| 66 | + print(f"File exists: {self.filename}, skipping download") |
| 67 | + return |
| 68 | + |
| 69 | + if self.config.verbose: |
| 70 | + print(f"fetching {self} - PID: {os.getpid()}") |
| 71 | + # Write the title plus the body, if any |
| 72 | + text_to_write = f"# {self.post.title}\n{self.post.selftext}" |
| 73 | + with open(self.filename, "w", encoding="utf8") as f: |
| 74 | + f.write(text_to_write) |
| 75 | + |
| 76 | + def has_output(self): |
| 77 | + """Determine if structured output for this doc already exists.""" |
| 78 | + output_filename = self._output_filename() |
| 79 | + return output_filename.is_file() and output_filename.stat() |
| 80 | + |
| 81 | + def write_result(self): |
| 82 | + """Write the structured json result for this doc. result must be json serializable.""" |
| 83 | + output_filename = self._output_filename() |
| 84 | + output_filename.parent.mkdir(parents=True, exist_ok=True) |
| 85 | + with open(output_filename, "w", encoding="utf8") as output_f: |
| 86 | + json.dump(self.isd_elems_no_filename, output_f, ensure_ascii=False, indent=2) |
| 87 | + print(f"Wrote {output_filename}") |
| 88 | + |
| 89 | + |
| 90 | +class RedditConnector(BaseConnector): |
| 91 | + def __init__(self, config: SimpleRedditConfig): |
| 92 | + from praw import Reddit |
| 93 | + |
| 94 | + self.config = config |
| 95 | + self.reddit = Reddit( |
| 96 | + client_id=config.client_id, |
| 97 | + client_secret=config.client_secret, |
| 98 | + user_agent=config.user_agent, |
| 99 | + ) |
| 100 | + self.cleanup_files = not config.preserve_downloads |
| 101 | + |
| 102 | + def cleanup(self, cur_dir=None): |
| 103 | + if not self.cleanup_files: |
| 104 | + return |
| 105 | + |
| 106 | + if cur_dir is None: |
| 107 | + cur_dir = self.config.download_dir |
| 108 | + sub_dirs = os.listdir(cur_dir) |
| 109 | + os.chdir(cur_dir) |
| 110 | + for sub_dir in sub_dirs: |
| 111 | + # don't traverse symlinks, not that there every should be any |
| 112 | + if os.path.isdir(sub_dir) and not os.path.islink(sub_dir): |
| 113 | + self.cleanup(sub_dir) |
| 114 | + os.chdir("..") |
| 115 | + if len(os.listdir(cur_dir)) == 0: |
| 116 | + os.rmdir(cur_dir) |
| 117 | + |
| 118 | + def initialize(self): |
| 119 | + pass |
| 120 | + |
| 121 | + def get_ingest_docs(self): |
| 122 | + subreddit = self.reddit.subreddit(self.config.subreddit_name) |
| 123 | + if self.config.search_query: |
| 124 | + posts = subreddit.search(self.config.search_query, limit=self.config.num_posts) |
| 125 | + else: |
| 126 | + posts = subreddit.hot(limit=self.config.num_posts) |
| 127 | + return [RedditIngestDoc(self.config, post) for post in posts] |
0 commit comments