ahmadgenus commited on
Commit
68ec988
·
1 Parent(s): 1c6e970

Initial working version

Browse files
Files changed (3) hide show
  1. app.py +153 -0
  2. chatbot.py +262 -0
  3. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import streamlit as st
4
+ from chatbot import setup_db, fetch_reddit_data, get_chatbot_response, get_db_conn
5
+ import json
6
+ import re
7
+ from urllib.parse import urlparse
8
+
9
+ # Helper function to remove image URLs from text.
10
+ def remove_image_urls(text):
11
+ # Regex pattern to remove URLs that end with typical image extensions.
12
+ image_url_pattern = r'https?://\S+\.(?:png|jpg|jpeg|webp)\S*'
13
+ return re.sub(image_url_pattern, '', text)
14
+
15
+ # Initialize DB and configure Streamlit
16
+ setup_db()
17
+ st.set_page_config(layout="wide")
18
+ st.title("🚀 Reddit Intelligent Chatbot")
19
+
20
+ # Use session state to store selected post ID for chat context
21
+ if 'selected_post_id' not in st.session_state:
22
+ st.session_state['selected_post_id'] = None
23
+
24
+ # Sidebar: Enter keyword and fetch data
25
+ with st.sidebar:
26
+ st.header("🔍 Fetch Reddit Data")
27
+ keyword = st.text_input("Enter keyword/topic:")
28
+ days = st.slider("Days range:", 1, 90, 7)
29
+ if st.button("Fetch Data"):
30
+ fetch_reddit_data(keyword, days=days)
31
+ st.success("Data fetched!")
32
+ st.session_state['selected_post_id'] = None # Reset selected post on new fetch
33
+
34
+ # Create two columns: Chat area (left) and Posts display (right)
35
+ chat_col, posts_col = st.columns([3, 2])
36
+
37
+ # RIGHT SIDE: Display fetched posts with resource-gather style card layout.
38
+ with posts_col:
39
+ st.subheader("📋 Reddit Posts")
40
+ if keyword.strip():
41
+ conn = get_db_conn()
42
+ cur = conn.cursor()
43
+ cur.execute("""
44
+ SELECT reddit_id, title, post_text, comments, metadata, created_at
45
+ FROM reddit_posts
46
+ WHERE keyword = %s
47
+ ORDER BY created_at DESC;
48
+ """, (keyword,))
49
+ posts = cur.fetchall()
50
+ cur.close()
51
+ conn.close()
52
+
53
+ if posts:
54
+ # Set up custom CSS for the card layout.
55
+ st.markdown(
56
+ """
57
+ <style>
58
+ .post-card {
59
+ border: 1px solid #ddd;
60
+ padding: 10px;
61
+ margin-bottom: 20px;
62
+ border-radius: 8px;
63
+ background-color: #f9f9f9;
64
+ }
65
+ .post-title {
66
+ font-size: 14px;
67
+ font-weight: bold;
68
+ margin-bottom: 5px;
69
+ }
70
+ .post-snippet {
71
+ font-size: 12px;
72
+ color: #444;
73
+ margin-bottom: 8px;
74
+ }
75
+ .post-meta {
76
+ font-size: 11px;
77
+ color: #777;
78
+ margin-bottom: 5px;
79
+ }
80
+ .reddit-logo {
81
+ width: 24px;
82
+ vertical-align: middle;
83
+ margin-right: 8px;
84
+ }
85
+ </style>
86
+ """, unsafe_allow_html=True)
87
+
88
+ for post in posts:
89
+ reddit_id, title, post_text, comments, metadata, created_at = post
90
+ try:
91
+ comments_list = json.loads(comments) if isinstance(comments, str) else comments
92
+ except Exception:
93
+ comments_list = comments
94
+
95
+ post_url = metadata.get('url', "#")
96
+ subreddit = metadata.get('subreddit', 'N/A')
97
+ created_str = created_at.strftime('%Y-%m-%d %H:%M:%S')
98
+
99
+ # Remove image URLs from post_text so that they don't show up in the snippet.
100
+ cleaned_text = remove_image_urls(post_text)
101
+ snippet = cleaned_text[:200] + ("..." if len(cleaned_text) > 200 else "")
102
+
103
+ # Build the card using HTML. The title itself is a clickable link.
104
+ card_html = f"""
105
+ <div class="post-card">
106
+ <div style="display: flex; align-items: center;">
107
+ <a href="{post_url}" target="_blank" style="font-size: 14px; font-weight: bold; color: blue;">{title}</a>
108
+ </div>
109
+ <div class="post-meta">
110
+ Subreddit: {metadata.get('subreddit','N/A')} <br> Created: {created_str}
111
+ </div>
112
+ <div class="post-snippet">
113
+ {snippet}
114
+ </div>
115
+ </div>
116
+ """
117
+ st.markdown(card_html, unsafe_allow_html=True)
118
+
119
+ # Expander for comments preview (first 3 comments)
120
+ with st.expander("Show Comments Preview"):
121
+ if comments_list:
122
+ for idx, comment in enumerate(comments_list[:3], start=1):
123
+ st.write(f"{idx}. {comment[:100]}{'...' if len(comment) > 100 else ''}")
124
+ else:
125
+ st.info("No comments available.")
126
+
127
+ # Button to select this post for chat context
128
+ if st.button("Chat with this Post", key=reddit_id):
129
+ st.session_state['selected_post_id'] = reddit_id
130
+ st.success("Post selected for chat!")
131
+ st.markdown("---")
132
+ else:
133
+ st.info("No posts found. Please fetch data using the sidebar.")
134
+ else:
135
+ st.info("Please enter a keyword and fetch data from the sidebar.")
136
+
137
+ # LEFT SIDE: Chatbot Interaction Area
138
+ with chat_col:
139
+ st.subheader("💬 Chat with AI")
140
+ question = st.text_area("Enter your question:", height=150)
141
+ context_choice = st.radio("Chat Context:", ["All Posts", "Selected Post"])
142
+ reddit_id = st.session_state['selected_post_id'] if context_choice == "Selected Post" else None
143
+
144
+ if st.button("Get Response"):
145
+ if not keyword.strip():
146
+ st.warning("Please enter a keyword/topic and fetch data first.")
147
+ elif not question.strip():
148
+ st.warning("Please enter your question.")
149
+ else:
150
+ with st.spinner("Generating response..."):
151
+ response, _ = get_chatbot_response(question, keyword, reddit_id)
152
+ st.markdown("**Chatbot Response:**")
153
+ st.write(response)
chatbot.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from langchain.chains import LLMChain
4
+ # chat_chain = LLMChain(
5
+ # llm=llm,
6
+ # prompt=chat_prompt,
7
+ # memory=memory,
8
+ # verbose=True # Enable verbose logging for debugging
9
+ # )
10
+
11
+
12
+ import os
13
+ import psycopg2
14
+ import praw
15
+ import json
16
+ from datetime import datetime, timedelta
17
+ from sentence_transformers import SentenceTransformer
18
+ from dotenv import load_dotenv
19
+ from langchain_groq import ChatGroq
20
+ from langchain.prompts import ChatPromptTemplate
21
+ from langchain.chains import ConversationChain, LLMChain
22
+ from langchain.memory import ConversationBufferMemory
23
+
24
+ load_dotenv()
25
+
26
+ # Initialize the LLM via LangChain (using Groq)
27
+ llm = ChatGroq(
28
+ groq_api_key=os.getenv("GROQ_API_KEY"),
29
+ # model_name=os.getenv("MODEL_NAME"),
30
+ model_name= "meta-llama/llama-4-maverick-17b-128e-instruct",
31
+ temperature=0.2
32
+ )
33
+
34
+ # Embedding Model
35
+ embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
36
+
37
+ # Reddit API Setup
38
+ reddit = praw.Reddit(
39
+ client_id=os.getenv("REDDIT_CLIENT_ID"),
40
+ client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
41
+ user_agent=os.getenv("REDDIT_USER_AGENT")
42
+ )
43
+
44
+ # Database connection function
45
+ import psycopg2
46
+ import os
47
+
48
+ def get_db_conn():
49
+ return psycopg2.connect(os.getenv("DATABASE_URL"))
50
+
51
+ # Set up the database schema: store raw post text, comments, computed embedding, and metadata.
52
+
53
+ def setup_db():
54
+ conn = get_db_conn()
55
+ cur = conn.cursor()
56
+ try:
57
+ cur.execute(""" -- remove EXTENSION line
58
+ CREATE TABLE IF NOT EXISTS reddit_posts (
59
+ id SERIAL PRIMARY KEY,
60
+ reddit_id VARCHAR(50) UNIQUE,
61
+ keyword TEXT,
62
+ title TEXT,
63
+ post_text TEXT,
64
+ comments JSONB,
65
+ created_at TIMESTAMP,
66
+ embedding VECTOR(384),
67
+ metadata JSONB
68
+ );
69
+ CREATE INDEX IF NOT EXISTS idx_keyword_created_at ON reddit_posts(keyword, created_at DESC);
70
+ """)
71
+ conn.commit()
72
+ except Exception as e:
73
+ print("DB Setup Error:", e)
74
+ finally:
75
+ cur.close()
76
+ conn.close()
77
+ # def setup_db():
78
+ # conn = get_db_conn()
79
+ # cur = conn.cursor()
80
+ # cur.execute("""
81
+ # CREATE EXTENSION IF NOT EXISTS vector;
82
+ # CREATE TABLE IF NOT EXISTS reddit_posts (
83
+ # id SERIAL PRIMARY KEY,
84
+ # reddit_id VARCHAR(50) UNIQUE,
85
+ # keyword TEXT,
86
+ # title TEXT,
87
+ # post_text TEXT,
88
+ # comments JSONB,
89
+ # created_at TIMESTAMP,
90
+ # embedding VECTOR(384),
91
+ # metadata JSONB
92
+ # );
93
+ # CREATE INDEX IF NOT EXISTS idx_keyword_created_at ON reddit_posts(keyword, created_at DESC);
94
+ # """)
95
+ # conn.commit()
96
+ # cur.close()
97
+ # conn.close()
98
+
99
+ # Utility: Check if the keyword appears in the post title, selftext, or any comment.
100
+ def keyword_in_post_or_comments(post, keyword):
101
+ keyword_lower = keyword.lower()
102
+ combined_text = (post.title + " " + post.selftext).lower()
103
+ if keyword_lower in combined_text:
104
+ return True
105
+ post.comments.replace_more(limit=None)
106
+ for comment in post.comments.list():
107
+ if keyword_lower in comment.body.lower():
108
+ return True
109
+ return False
110
+
111
+ # Fetch Reddit posts if the keyword is in the post or any comment.
112
+ # This version iterates over posts until reaching posts older than the specified day range.
113
+ def fetch_reddit_data(keyword, days=7, limit=None):
114
+ end_time = datetime.utcnow()
115
+ start_time = end_time - timedelta(days=days)
116
+ subreddit = reddit.subreddit("all")
117
+ posts_generator = subreddit.search(keyword, sort="new", time_filter="all", limit=limit)
118
+
119
+ data = []
120
+ for post in posts_generator:
121
+ created = datetime.utcfromtimestamp(post.created_utc)
122
+ if created < start_time:
123
+ break # Since sorted by new, we break once older posts are encountered.
124
+ if not keyword_in_post_or_comments(post, keyword):
125
+ continue
126
+
127
+ post.comments.replace_more(limit=None)
128
+ comments = [comment.body for comment in post.comments.list()]
129
+ combined_text = f"{post.title}\n{post.selftext}\n{' '.join(comments)}"
130
+ embedding = embedder.encode(combined_text).tolist()
131
+ metadata = {
132
+ "url": post.url,
133
+ "subreddit": post.subreddit.display_name,
134
+ "comments_count": len(comments)
135
+ }
136
+ data.append({
137
+ "reddit_id": post.id,
138
+ "keyword": keyword,
139
+ "title": post.title,
140
+ "post_text": post.selftext,
141
+ "comments": comments,
142
+ "created_at": created,
143
+ "embedding": embedding,
144
+ "metadata": metadata
145
+ })
146
+ save_to_db(data)
147
+
148
+ # Save posts data into PostgreSQL.
149
+ def save_to_db(posts):
150
+ conn = get_db_conn()
151
+ cur = conn.cursor()
152
+ for post in posts:
153
+ cur.execute("""
154
+ INSERT INTO reddit_posts
155
+ (reddit_id, keyword, title, post_text, comments, created_at, embedding, metadata)
156
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
157
+ ON CONFLICT DO NOTHING;
158
+ """, (
159
+ post["reddit_id"],
160
+ post["keyword"],
161
+ post["title"],
162
+ post["post_text"],
163
+ json.dumps(post["comments"]),
164
+ post["created_at"],
165
+ post["embedding"],
166
+ json.dumps(post["metadata"])
167
+ ))
168
+ conn.commit()
169
+ cur.close()
170
+ conn.close()
171
+
172
+ # Retrieve context from the DB.
173
+ # Updated retrieval: if summarization intent is detected, retrieve more posts.
174
+ def retrieve_context(question, keyword, reddit_id=None, top_k=10):
175
+ lower_q = question.lower()
176
+ # Check for summarization intent.
177
+ if any(word in lower_q for word in ["summarize", "overview", "all posts"]):
178
+ requested_top_k = 50
179
+ else:
180
+ requested_top_k = top_k
181
+
182
+ # Retrieve posts based on query embedding.
183
+ query_embedding = embedder.encode(question).tolist()
184
+ query_embedding_str = "[" + ",".join(map(str, query_embedding)) + "]"
185
+
186
+ conn = get_db_conn()
187
+ cur = conn.cursor()
188
+ if reddit_id:
189
+ cur.execute("""
190
+ SELECT title, post_text, comments FROM reddit_posts
191
+ WHERE reddit_id = %s;
192
+ """, (reddit_id,))
193
+ else:
194
+ cur.execute("""
195
+ SELECT title, post_text, comments FROM reddit_posts
196
+ WHERE keyword = %s
197
+ ORDER BY embedding <-> %s::vector LIMIT %s;
198
+ """, (keyword, query_embedding_str, requested_top_k))
199
+ results = cur.fetchall()
200
+ conn.close()
201
+
202
+ # If there are fewer posts than requested and none were retrieved by vector search,
203
+ # fall back to retrieving all posts for that keyword.
204
+ if not results:
205
+ conn = get_db_conn()
206
+ cur = conn.cursor()
207
+ cur.execute("""
208
+ SELECT title, post_text, comments FROM reddit_posts
209
+ WHERE keyword = %s ORDER BY created_at DESC;
210
+ """, (keyword,))
211
+ results = cur.fetchall()
212
+ conn.close()
213
+ return results
214
+
215
+ # --- New Summarization Step for Handling Long Context ---
216
+ # Create a summarization chain to compress the context if it exceeds a token/character threshold.
217
+ summarize_prompt = ChatPromptTemplate.from_template("""
218
+ You are a summarizer. Summarize the following context from Reddit posts into a concise summary that preserves the key insights. Do not add extra commentary.
219
+
220
+ Context:
221
+ {context}
222
+
223
+ Summary:
224
+ """)
225
+ summarize_chain = LLMChain(llm=llm, prompt=summarize_prompt)
226
+
227
+
228
+ # Set up conversation memory and chain.
229
+ memory = ConversationBufferMemory(memory_key="chat_history")
230
+ # Updated prompt: we now expect a single input field "input"
231
+ chat_prompt = ChatPromptTemplate.from_template("""
232
+ Chat History:
233
+ {chat_history}
234
+
235
+ Context from Reddit and User Question:
236
+ {input}
237
+
238
+ Act as an Professional Assistant as incremental chat agent and also give reasioning and Answer clearly based on context and chat history, your response should be valid and concise, and relavant .
239
+
240
+ """)
241
+
242
+ chat_chain = LLMChain(
243
+ llm=llm,
244
+ prompt=chat_prompt,
245
+ memory=memory,
246
+ verbose=True # Enable verbose logging for debugging
247
+ )
248
+
249
+ # Get chatbot response by merging context and question into a single input.
250
+ # Updated get_chatbot_response to handle summarization if context is too long.
251
+
252
+ def get_chatbot_response(question, keyword, reddit_id=None):
253
+ context_posts = retrieve_context(question, keyword, reddit_id)
254
+ context = "\n\n".join([f"{p[0]}:\n{p[1]}" for p in context_posts])
255
+
256
+ # Set a threshold (e.g., 3000 characters); if context length exceeds it, compress the context.
257
+ if len(context) > 3000:
258
+ context = summarize_chain.run({"context": context})
259
+
260
+ combined_input = f"Context:\n{context}\n\nUser Question: {question}"
261
+ response = chat_chain.run({"input": combined_input})
262
+ return response, context_posts
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ langchain
3
+ langchain-groq
4
+ langchain-core
5
+ sentence-transformers
6
+ psycopg2-binary
7
+ python-dotenv
8
+ praw
9
+ sqlalchemy
10
+ transformers