File size: 13,666 Bytes
613e758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import requests
import pandas as pd
import time
from datetime import datetime
from dotenv import load_dotenv
import os
import gradio as gr

load_dotenv()

XAI_API_KEY = os.getenv("XAI_API_KEY")

# Global variable to store the most recent analysis results
GLOBAL_ANALYSIS_STORAGE = {
    'subreddit': None,
    'data': None
}

def call_LLM(query):
    return call_groq(query)
    
def call_groq(query):
    from groq import Groq
    client = Groq()
    chat_completion = client.chat.completions.create(
        messages=[
            {"role": "system", "content": query}
        ],
        model="llama3-8b-8192",
        temperature=0.5,
        max_tokens=1024,
        top_p=1,
        stop=None,
        stream=False,
    )

    return chat_completion.choices[0].message.content

def process(row):
    """
    Format this so that the model sees full post for now
    """
    # title
    # comment_body
    prompt = f"The below is a reddit post. Take a look and tell me if there is a business problem to be solved here ||| title: {row['post_title']} ||| comment: {row['comment_body']}"
    return call_LLM(prompt)

# ... [Keep previous helper functions like extract_comment_data, fetch_top_comments, fetch_subreddits, fetch_top_posts] ...

def extract_comment_data(comment, post_info):
    """Extract relevant data from a comment"""
    return {
        'subreddit': post_info['subreddit'],
        'post_title': post_info['title'],
        'post_score': post_info['score'],
        'post_created_utc': post_info['created_utc'],
        'comment_id': comment['data'].get('id'),
        'comment_author': comment['data'].get('author'),
        'comment_body': comment['data'].get('body'),
        'comment_score': comment['data'].get('score', 0),
        'comment_created_utc': datetime.fromtimestamp(comment['data'].get('created_utc', 0)),
        'post_url': post_info['url'],
        'comment_url': f"https://www.reddit.com{post_info['permalink']}{comment['data'].get('id')}",
    }

def fetch_top_comments(post_df, num_comments=2):
    """
    Fetch top comments for each post in the dataframe, sorted by upvotes
    """
    all_comments = []
    total_posts = len(post_df)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    print(f"\nFetching top {num_comments} most upvoted comments for {total_posts} posts...")
    
    for idx, post in post_df.iterrows():
        print(f"\nProcessing post {idx + 1}/{total_posts}")
        print(f"Title: {post['title'][:100]}...")
        print(f"Post Score: {post['score']}, Number of Comments: {post['num_comments']}")
        
        try:
            json_url = post['permalink'].replace('https://www.reddit.com', '') + '.json'
            url = f'https://www.reddit.com{json_url}'
            
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
            
            if len(data) > 1:
                comments_data = data[1]['data']['children']
                
                # Filter out non-comment entries and extract scores
                valid_comments = [
                    comment for comment in comments_data 
                    if comment['kind'] == 't1' and comment['data'].get('score') is not None
                ]
                
                # Sort comments by score (upvotes) in descending order
                sorted_comments = sorted(
                    valid_comments,
                    key=lambda x: x['data'].get('score', 0),
                    reverse=True
                )
                
                # Take only the top N comments
                top_comments = sorted_comments[:num_comments]
                
                # Print comment scores for verification
                print("\nTop comment scores for this post:")
                for i, comment in enumerate(top_comments, 1):
                    score = comment['data'].get('score', 0)
                    print(f"Comment {i}: {score} upvotes")
                
                # Add to main list
                for comment in top_comments:
                    all_comments.append(extract_comment_data(comment, post))
            
            time.sleep(2)
            
        except requests.exceptions.RequestException as e:
            print(f"Error fetching comments for post {idx + 1}: {e}")
            continue
            
    # Create DataFrame and sort
    comments_df = pd.DataFrame(all_comments)
    
    if not comments_df.empty:
        # Verify sorting by showing top comments for each post
        print("\nVerification of comment sorting:")
        for post_title in comments_df['post_title'].unique():
            post_comments = comments_df[comments_df['post_title'] == post_title]
            print(f"\nPost: {post_title[:100]}...")
            print("Comment scores:", post_comments['comment_score'].tolist())
    
    return comments_df


def fetch_subreddits(limit=10, min_subscribers=1000):
    """
    Fetch subreddits from Reddit
    
    Args:
        limit (int): Number of subreddits to fetch
        min_subscribers (int): Minimum number of subscribers required
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    subreddits_data = []
    after = None
    
    while len(subreddits_data) < limit:
        try:
            url = f'https://www.reddit.com/subreddits/popular.json?limit=100'
            if after:
                url += f'&after={after}'
            
            print(f"Fetching subreddits... Current count: {len(subreddits_data)}")
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
            
            for subreddit in data['data']['children']:
                subreddit_data = subreddit['data']
                    
                if subreddit_data.get('subscribers', 0) >= min_subscribers:
                    sub_info = {
                        'display_name': subreddit_data.get('display_name'),
                        'display_name_prefixed': subreddit_data.get('display_name_prefixed'),
                        'title': subreddit_data.get('title'),
                        'subscribers': subreddit_data.get('subscribers', 0),
                        'active_users': subreddit_data.get('active_user_count', 0),
                        'created_utc': datetime.fromtimestamp(subreddit_data.get('created_utc', 0)),
                        'description': subreddit_data.get('description'),
                        'subreddit_type': subreddit_data.get('subreddit_type'),
                        'over18': subreddit_data.get('over18', False),
                        'url': f"https://www.reddit.com/r/{subreddit_data.get('display_name')}/"
                    }
                    subreddits_data.append(sub_info)
            
            after = data['data'].get('after')
            if not after:
                print("Reached end of listings")
                break
                
            time.sleep(2)
            
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            break
            
    return pd.DataFrame(subreddits_data)

def fetch_top_posts(subreddit, limit=5):
    """
    Fetch top posts from a subreddit using Reddit's JSON API
    
    Args:
        subreddit (str): Name of the subreddit without the 'r/'
        limit (int): Maximum number of posts to fetch
        
    Returns:
        list: List of post dictionaries
    """
    posts_data = []
    url = f'https://www.reddit.com/r/{subreddit}/top.json?t=all&limit={limit}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.json()
        
        for post in data['data']['children']:
            post_data = post['data']
            posts_data.append({
                'subreddit': subreddit,
                'title': post_data.get('title'),
                'score': post_data.get('score'),
                'num_comments': post_data.get('num_comments'),
                'created_utc': datetime.fromtimestamp(post_data.get('created_utc', 0)),
                'url': post_data.get('url'),
                'permalink': 'https://www.reddit.com' + post_data.get('permalink', '')
            })
        
        time.sleep(2)
        
    except requests.exceptions.RequestException as e:
        print(f"Error fetching posts from r/{subreddit}: {e}")
    
    return pd.DataFrame(posts_data)


def show_dataframe(subreddit):
    # Fetch top posts
    top_posts = fetch_top_posts(subreddit)
    
    # Fetch top comments for these posts
    data_to_analyze = fetch_top_comments(top_posts)
    
    # Process and analyze each comment
    responses = []
    for _, row in data_to_analyze.iterrows():
        print(f"{_} done")
        responses.append(process(row))
    
    # Add analysis to the dataframe
    data_to_analyze['analysis'] = responses
    
    # Store in global storage for quick access
    GLOBAL_ANALYSIS_STORAGE['subreddit'] = subreddit
    GLOBAL_ANALYSIS_STORAGE['data'] = data_to_analyze
    
    return data_to_analyze

def launch_interface():
    # Fetch list of subreddits for user to choose from
    sub_reddits = fetch_subreddits()
    subreddit_list = sub_reddits["display_name"].tolist()
    
    # Create Gradio Blocks for more flexible interface
    with gr.Blocks() as demo:
        # Title and description
        gr.Markdown("# Reddit Business Problem Analyzer")
        gr.Markdown("Discover potential business opportunities from Reddit discussions")
        
        # Subreddit selection
        subreddit_dropdown = gr.Dropdown(
            choices=subreddit_list, 
            label="Select Subreddit", 
            info="Choose a subreddit to analyze"
        )
        
        # Outputs
        with gr.Row():
            with gr.Column():
                # Overall Analysis Section
                gr.Markdown("## Overall Analysis")
                # overall_analysis = gr.Textbox(
                #     label="Aggregated Business Insights", 
                #     interactive=False,
                #     lines=5
                # )
                
                # Results Table
                results_table = gr.Dataframe(
                    label="Analysis Results",
                    headers=["Index", "Post Title", "Comment", "Analysis"],
                    interactive=False
                )
                
                # Row Selection
                row_index = gr.Number(
                    label="Select Row Index for Detailed View",
                    precision=0
                )
            
            with gr.Column():
                # Detailed Post Analysis
                gr.Markdown("## Detailed Post Analysis")
                detailed_analysis = gr.Markdown(
                    label="Detailed Insights"
                )
        
        # Function to update posts when subreddit is selected
        def update_posts(subreddit):
            # Fetch and analyze data
            data_to_analyze = show_dataframe(subreddit)
            
            # Prepare table data
            table_data = data_to_analyze[['post_title', 'comment_body', 'analysis']].reset_index()
            table_data.columns = ['Index', 'Post Title', 'Comment', 'Analysis']
            
            return table_data, None
        
        # Function to show detailed analysis for a specific row
        def show_row_details(row_index):
            # Ensure we have data loaded
            if GLOBAL_ANALYSIS_STORAGE['data'] is None:
                return "Please select a subreddit first."
            
            try:
                # Convert to integer and subtract 1 (since index is 0-based)
                row_index = int(row_index)
                
                # Retrieve the specific row
                row_data = GLOBAL_ANALYSIS_STORAGE['data'].loc[row_index]
                
                # Format detailed view
                detailed_view = f"""
                ### Post Details
                **Title:** {row_data.get('post_title', 'N/A')}
                
                **Comment:** {row_data.get('comment_body', 'N/A')}
                
                **Comment Score:** {row_data.get('comment_score', 'N/A')}
                
                **Analysis:** {row_data.get('analysis', 'No analysis available')}
                
                **Post URL:** {row_data.get('post_url', 'N/A')}
                
                **Comment URL:** {row_data.get('comment_url', 'N/A')}
                """
                
                return detailed_view
            
            except (KeyError, ValueError, TypeError) as e:
                return f"Error retrieving row details: {str(e)}"
        
        # Event Listeners
        subreddit_dropdown.change(
            fn=update_posts, 
            inputs=subreddit_dropdown, 
            outputs=[results_table, detailed_analysis]
        )
        
        row_index.change(
            fn=show_row_details, 
            inputs=row_index, 
            outputs=detailed_analysis
        )
    
    return demo

# Launch the interface
if __name__ == "__main__":
    interface = launch_interface()
    interface.launch(share=True)