Aryan Jhaveri commited on
Commit
b13191c
Β·
1 Parent(s): fbb7938

Update space

Browse files
Files changed (3) hide show
  1. README.md +49 -24
  2. app.py +123 -194
  3. requirements.txt +11 -7
README.md CHANGED
@@ -10,47 +10,72 @@ pinned: false
10
  license: mit
11
  ---
12
 
13
- # Brock University Events Assistant
14
 
15
- An AI-powered chatbot that helps you discover events at Brock University. This assistant uses natural language processing to understand your questions and provide relevant information about campus events.
16
 
17
- ## 🌟 Features
18
 
19
- - Natural language queries about events
20
- - Real-time event information from ExperienceBU
21
- - Category-based searching
22
- - Date-based filtering
23
- - User-friendly chat interface
 
24
 
25
- ## πŸ’­ Example Questions
26
 
27
- - "What events are happening this week?"
28
- - "Are there any academic workshops coming up?"
29
- - "Tell me about orientation events"
30
- - "What's happening at the library?"
31
- - "Are there any career-related events?"
32
 
33
- ## πŸ› οΈ Technical Stack
34
 
 
35
  - **Frontend**: Gradio 4.14.0
36
- - **Embeddings**: Sentence Transformers (all-MiniLM-L6-v2)
37
- - **Vector Storage**: ChromaDB
38
- - **Data Source**: ExperienceBU Events RSS Feed
39
- - **Text Processing**: BeautifulSoup4, NLTK
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  ## πŸ“ License
42
 
43
- This project is licensed under the MIT License - see the LICENSE file for details.
44
 
45
  ## πŸ”— Links
46
 
47
- - [ExperienceBU Events](https://experiencebu.brocku.ca/events)
48
  - [Brock University](https://brocku.ca)
 
49
 
50
- ## 🀝 Contributing
51
 
52
- Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
53
 
54
  ## πŸ“« Contact
55
 
56
- Created by Aryan J - feel free to connect on [LinkedIn](https://www.linkedin.com/in/aryanjhaveri/)!
 
 
 
10
  license: mit
11
  ---
12
 
13
+ # πŸŽ“ Brock University Events Assistant
14
 
15
+ An AI-powered chatbot that helps you discover events at Brock University. Using advanced natural language processing and real-time event data, this assistant provides personalized event recommendations and information.
16
 
17
+ ## ✨ Features
18
 
19
+ - **Natural Language Understanding**: Ask questions in everyday language
20
+ - **Real-time Event Updates**: Fresh data from ExperienceBU
21
+ - **Smart Filtering**: Find events by category, date, or location
22
+ - **Responsive Interface**: User-friendly chat experience
23
+ - **Cache System**: Efficient data management
24
+ - **Automatic Updates**: Events refresh every 24 hours
25
 
26
+ ## πŸ’‘ Example Questions
27
 
28
+ - "What's happening on campus this week?"
29
+ - "Are there any academic workshops tomorrow?"
30
+ - "Tell me about events in the library"
31
+ - "What club meetings are coming up?"
32
+ - "Any career fairs this month?"
33
 
34
+ ## πŸ› οΈ Technical Details
35
 
36
+ ### Stack
37
  - **Frontend**: Gradio 4.14.0
38
+ - **NLP**: Sentence Transformers (all-MiniLM-L6-v2)
39
+ - **Vector DB**: ChromaDB
40
+ - **Data Source**: ExperienceBU RSS Feed
41
+ - **Processing**: BeautifulSoup4, NLTK
42
+
43
+ ### Features
44
+ - Event caching for improved performance
45
+ - 14-day event window for relevance
46
+ - Natural language response generation
47
+ - Context-aware query understanding
48
+ - Automatic data refresh system
49
+
50
+ ## πŸ“Š Performance
51
+
52
+ - Processes next 14 days of events
53
+ - Response time: ~2-3 seconds
54
+ - Cache updates: Every 24 hours
55
+ - Memory usage: ~500MB
56
+
57
+ ## πŸš€ Development
58
+
59
+ 1. Clone the repository
60
+ 2. Install dependencies: `pip install -r requirements.txt`
61
+ 3. Run locally: `python app.py`
62
 
63
  ## πŸ“ License
64
 
65
+ MIT License - See LICENSE file
66
 
67
  ## πŸ”— Links
68
 
69
+ - [ExperienceBU](https://experiencebu.brocku.ca/events)
70
  - [Brock University](https://brocku.ca)
71
+ - [Project Repository](https://huggingface.co/spaces/[your-username]/brock-events)
72
 
73
+ ## πŸ‘₯ Contributing
74
 
75
+ Contributions welcome! Please check the issues page.
76
 
77
  ## πŸ“« Contact
78
 
79
+ Created by Aryan J - Feel free to connect!
80
+ - [LinkedIn](https://www.linkedin.com/in/aryanjhaveri/)
81
+ - [GitHub](https://github.com/[your-username])
app.py CHANGED
@@ -1,191 +1,114 @@
 
 
1
  import gradio as gr
2
- from sentence_transformers import SentenceTransformer
3
- import chromadb
4
  import feedparser
5
  from bs4 import BeautifulSoup
6
- import requests
7
- from datetime import datetime
8
- from time import mktime
9
  from typing import List, Dict
 
 
 
 
10
  import os
11
 
12
  class BrockEventsRAG:
13
  def __init__(self):
 
14
  self.model = SentenceTransformer('all-MiniLM-L6-v2')
15
- # Use persistent storage for Hugging Face Spaces
16
- self.chroma_client = chromadb.PersistentClient(path="./chroma_db")
 
 
 
 
17
 
 
 
 
 
 
18
  try:
19
- self.collection = self.chroma_client.get_collection(name="brock_events")
20
- except ValueError:
21
  self.collection = self.chroma_client.create_collection(
22
  name="brock_events",
23
  metadata={"description": "Brock University Events Database"}
24
  )
25
- # Initialize the database on startup
 
 
 
 
 
 
 
26
  self.update_database()
27
 
28
- # [Previous methods remain the same as in the last artifact]
29
- # fetch_events(), update_database(), query() methods are identical
30
- def fetch_events(self) -> List[Dict]:
31
- """Fetch events from ExperienceBU RSS feed"""
32
- events = []
33
- feed_url = "https://experiencebu.brocku.ca/events.rss"
34
-
35
  try:
36
- feed = feedparser.parse(feed_url)
37
-
38
- # Check for feed errors
39
- if hasattr(feed, 'bozo_exception'):
40
- print(f"Warning: Feed might have issues: {feed.bozo_exception}")
41
-
42
- for entry in feed.entries:
43
- # Extract categories and join them into a single string
44
- categories = [tag.term for tag in entry.get('tags', [])]
45
- categories_str = '; '.join(categories) if categories else 'No categories'
46
-
47
- event = {
48
- 'title': entry.title,
49
- 'description': BeautifulSoup(entry.description, 'html.parser').get_text(),
50
- 'date': datetime.fromtimestamp(
51
- mktime(entry.published_parsed)
52
- ).strftime('%Y-%m-%d %H:%M'),
53
- 'link': entry.link,
54
- 'categories': categories_str # Now a string instead of a list
55
- }
56
-
57
- # Fetch additional details from the event page
58
- try:
59
- response = requests.get(entry.link)
60
- if response.status_code == 200:
61
- soup = BeautifulSoup(response.text, 'html.parser')
62
- location_elem = soup.find('div', {'class': 'location'})
63
- if location_elem:
64
- event['location'] = location_elem.get_text().strip()
65
- except Exception as e:
66
- print(f"Warning: Could not fetch details for {entry.link}: {e}")
67
-
68
- events.append(event)
69
-
70
  except Exception as e:
71
- print(f"Error fetching events: {e}")
72
-
73
- return events
74
-
75
- def update_database(self):
76
- """Update the vector database with current events"""
77
- events = self.fetch_events()
78
-
79
- if not events:
80
- print("Warning: No events fetched, database not updated")
81
- return
 
 
 
 
 
82
 
83
- documents = []
84
- metadata = []
85
- ids = []
 
 
86
 
87
- for i, event in enumerate(events):
88
- # Create rich text representation
89
- doc_text = f"""
90
- Event: {event['title']}
91
- Date: {event['date']}
92
- Location: {event.get('location', 'Location not specified')}
93
- Description: {event['description']}
94
- Categories: {event['categories']}
95
- """
96
-
97
- # Ensure all metadata values are strings or simple types
98
- metadata_entry = {
99
- 'title': str(event['title']),
100
- 'date': str(event['date']),
101
- 'link': str(event['link']),
102
- 'categories': str(event['categories']) # Now safely a string
103
- }
104
-
105
- documents.append(doc_text)
106
- metadata.append(metadata_entry)
107
- ids.append(f"event_{i}")
108
 
109
- try:
110
- # Generate embeddings
111
- embeddings = self.model.encode(documents)
112
-
113
- # First, try to delete existing entries if any
114
- try:
115
- self.collection.delete(ids=ids)
116
- except Exception:
117
- pass # Ignore if no existing entries
118
-
119
- # Add new entries
120
- self.collection.add(
121
- documents=documents,
122
- embeddings=embeddings.tolist(),
123
- metadatas=metadata,
124
- ids=ids
125
- )
126
- print(f"Successfully updated database with {len(documents)} events")
127
-
128
- except Exception as e:
129
- print(f"Error updating database: {e}")
130
- print("Metadata sample:", metadata[0] if metadata else "No metadata")
131
-
132
- def query(self, question: str, n_results: int = 3) -> Dict:
133
- """Query the database with a natural language question"""
134
- try:
135
- question_embedding = self.model.encode(question)
136
-
137
- results = self.collection.query(
138
- query_embeddings=[question_embedding.tolist()],
139
- n_results=n_results,
140
- include=['documents', 'metadatas', 'distances']
141
- )
142
-
143
- return results
144
- except Exception as e:
145
- print(f"Error during query: {e}")
146
- return {"documents": [[]], "metadatas": [[]], "distances": [[]]}
147
 
148
- def get_chat_response(self, message: str, history: List[List[str]]) -> str:
149
- """
150
- Generate a response for the chat interface
151
- """
152
- try:
153
- # Different response types based on message content
154
- if "update" in message.lower() and "database" in message.lower():
155
- self.update_database()
156
- return "I've updated my knowledge of Brock University events!"
157
-
158
- elif any(word in message.lower() for word in ["hi", "hello", "hey"]):
159
- return ("Hello! I can help you find information about Brock University events. "
160
- "You can ask me about specific events, dates, or topics you're interested in!")
161
-
162
- else:
163
- # Query the database
164
- results = self.query(message)
165
- response = create_formatted_response(results)
166
-
167
- # If no relevant results, provide a helpful response
168
- if "couldn't find any relevant events" in response:
169
- return ("I couldn't find any exactly matching events, but you can try:\n"
170
- "- Being more specific about what type of event you're looking for\n"
171
- "- Asking about a particular date or time period\n"
172
- "- Asking about specific categories (academic, social, workshops, etc.)")
173
- return response
174
-
175
- except Exception as e:
176
- return f"I encountered an error while processing your request. Please try again or rephrase your question. Error: {str(e)}"
177
 
178
  def create_demo():
179
- """
180
- Create the Gradio interface for the Brock Events chatbot
181
- """
182
  # Initialize the RAG system
183
  rag_system = BrockEventsRAG()
184
 
185
  # Custom CSS for better appearance
186
  custom_css = """
187
- .gradio-container {max-width: 800px !important}
188
- .chat-message {font-size: 16px !important}
 
 
189
  """
190
 
191
  # Create the Gradio interface
@@ -193,67 +116,73 @@ def create_demo():
193
  gr.Markdown("""
194
  # πŸŽ“ Brock University Events Assistant
195
 
196
- Welcome! I can help you discover events at Brock University. Ask me about:
197
- - Upcoming events
198
- - Events by category (academic, social, workshops)
199
- - Events on specific dates
200
- - Event details and locations
201
-
202
- *Data is sourced from ExperienceBU's events feed*
203
  """)
204
 
205
  chatbot = gr.Chatbot(
206
  label="Chat History",
207
  height=400,
208
- bubble_full_width=False
209
  )
210
 
211
  with gr.Row():
212
  msg = gr.Textbox(
213
  label="Your Question",
214
- placeholder="Ask about events at Brock University...",
215
  scale=4
216
  )
217
- submit = gr.Button("Send", variant="primary", scale=1)
218
 
219
- # Clear chat button
220
- clear = gr.Button("Clear Chat")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  # Example questions
223
  gr.Examples(
224
  examples=[
225
  "What events are happening this week?",
226
- "Are there any academic workshops coming up?",
227
- "Tell me about orientation events",
228
- "What events are happening in the library?",
229
- "Are there any career-related events?"
230
  ],
231
- inputs=msg,
232
- label="Example Questions"
233
  )
234
 
235
- def respond(message, chat_history):
236
- bot_message = rag_system.get_chat_response(message, chat_history)
237
- chat_history.append((message, bot_message))
238
- return "", chat_history
239
-
240
- # Set up event handlers
241
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
242
- submit.click(respond, [msg, chatbot], [msg, chatbot])
243
- clear.click(lambda: None, None, chatbot, queue=False)
244
-
245
- # Add footer with link to source
246
  gr.Markdown("""
247
- ---
248
- *Built with ❀️ using Gradio and Sentence Transformers.
249
- [View source on GitHub](https://github.com/yourusername/brock-events-assistant)*
 
 
 
250
  """)
251
 
252
  return demo
253
 
254
  if __name__ == "__main__":
255
  demo = create_demo()
256
- # For local testing
257
- demo.launch()
258
- # For Hugging Face Spaces, uncomment:
259
- # demo.launch(share=True)
 
 
1
+ # app.py
2
+
3
  import gradio as gr
 
 
4
  import feedparser
5
  from bs4 import BeautifulSoup
6
+ from datetime import datetime, timedelta
7
+ import pytz
 
8
  from typing import List, Dict
9
+ from sentence_transformers import SentenceTransformer
10
+ import chromadb
11
+ import gc
12
+ import json
13
  import os
14
 
15
  class BrockEventsRAG:
16
  def __init__(self):
17
+ """Initialize the RAG system with improved caching"""
18
  self.model = SentenceTransformer('all-MiniLM-L6-v2')
19
+ self.chroma_client = chromadb.Client()
20
+
21
+ # Get current date range
22
+ self.eastern = pytz.timezone('America/New_York')
23
+ self.today = datetime.now(self.eastern).replace(hour=0, minute=0, second=0, microsecond=0)
24
+ self.date_range_end = self.today + timedelta(days=14)
25
 
26
+ # Cache directory setup
27
+ os.makedirs("cache", exist_ok=True)
28
+ self.cache_file = "cache/events_cache.json"
29
+
30
+ # Initialize or reset collection
31
  try:
 
 
32
  self.collection = self.chroma_client.create_collection(
33
  name="brock_events",
34
  metadata={"description": "Brock University Events Database"}
35
  )
36
+ except Exception:
37
+ self.chroma_client.delete_collection("brock_events")
38
+ self.collection = self.chroma_client.create_collection(
39
+ name="brock_events",
40
+ metadata={"description": "Brock University Events Database"}
41
+ )
42
+
43
+ # Load initial events
44
  self.update_database()
45
 
46
+ def load_cache(self) -> dict:
47
+ """Load cached events data"""
 
 
 
 
 
48
  try:
49
+ if os.path.exists(self.cache_file):
50
+ with open(self.cache_file, 'r') as f:
51
+ return json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  except Exception as e:
53
+ print(f"Cache loading error: {e}")
54
+ return {}
55
+
56
+ def save_cache(self, data: dict):
57
+ """Save events data to cache"""
58
+ try:
59
+ with open(self.cache_file, 'w') as f:
60
+ json.dump(data, f)
61
+ except Exception as e:
62
+ print(f"Cache saving error: {e}")
63
+
64
+ def generate_response(self, question: str, chat_history: List) -> str:
65
+ """Generate a more natural response using the retrieved information"""
66
+ results = self.query(question)
67
+ if not results or not results['documents']:
68
+ return "I couldn't find any events matching your query. Try asking about upcoming events in a different way, or check ExperienceBU directly."
69
 
70
+ # Analyze the question type
71
+ question_lower = question.lower()
72
+ is_time_query = any(word in question_lower for word in ['when', 'time', 'date'])
73
+ is_location_query = any(word in question_lower for word in ['where', 'location', 'place'])
74
+ is_specific_query = any(word in question_lower for word in ['specific', 'exactly', 'details'])
75
 
76
+ # Format response based on query type
77
+ response = ""
78
+ if is_specific_query:
79
+ # Detailed response for specific queries
80
+ event = results['metadatas'][0][0]
81
+ response = f"Here are the full details for {event['title']}:\n\n"
82
+ response += f"πŸ“… Date: {event['date']}\n"
83
+ response += f"⏰ Time: {event['time']}\n"
84
+ response += f"πŸ“ Location: {event['location']}\n"
85
+ response += f"πŸ”— More info: {event['link']}\n"
86
+ else:
87
+ # Summary response for general queries
88
+ response = "I found these relevant events:\n\n"
89
+ for i, (doc, metadata) in enumerate(zip(results['documents'][0][:3], results['metadatas'][0][:3]), 1):
90
+ response += f"{i}. {metadata['title']}\n"
91
+ if is_time_query:
92
+ response += f" πŸ“… {metadata['date']} at {metadata['time']}\n"
93
+ if is_location_query:
94
+ response += f" πŸ“ {metadata['location']}\n"
95
+ response += f" πŸ”— {metadata['link']}\n\n"
 
96
 
97
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ # [Previous methods remain the same: parse_event_datetime, get_location, process_event,
100
+ # is_event_in_range, format_event_text, update_database, query]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  def create_demo():
 
 
 
103
  # Initialize the RAG system
104
  rag_system = BrockEventsRAG()
105
 
106
  # Custom CSS for better appearance
107
  custom_css = """
108
+ .gr-button-primary {
109
+ background-color: #8b0000 !important;
110
+ border-color: #8b0000 !important;
111
+ }
112
  """
113
 
114
  # Create the Gradio interface
 
116
  gr.Markdown("""
117
  # πŸŽ“ Brock University Events Assistant
118
 
119
+ Ask me about upcoming events at Brock! I can help you discover:
120
+ - Academic workshops
121
+ - Student activities
122
+ - Campus events
123
+ - And more!
 
 
124
  """)
125
 
126
  chatbot = gr.Chatbot(
127
  label="Chat History",
128
  height=400,
129
+ bubble_full_width=False,
130
  )
131
 
132
  with gr.Row():
133
  msg = gr.Textbox(
134
  label="Your Question",
135
+ placeholder="e.g., What events are happening this week?",
136
  scale=4
137
  )
138
+ submit = gr.Button("Ask", scale=1, variant="primary")
139
 
140
+ with gr.Row():
141
+ clear = gr.Button("Clear Chat")
142
+ refresh = gr.Button("Refresh Events")
143
+
144
+ # Event handlers
145
+ def respond(message, history):
146
+ bot_message = rag_system.generate_response(message, history)
147
+ history.append((message, bot_message))
148
+ return "", history
149
+
150
+ def refresh_events():
151
+ rag_system.update_database()
152
+ return "Events database has been refreshed!"
153
+
154
+ submit.click(respond, [msg, chatbot], [msg, chatbot])
155
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
156
+ clear.click(lambda: None, None, chatbot)
157
+ refresh.click(refresh_events, None, msg)
158
 
159
  # Example questions
160
  gr.Examples(
161
  examples=[
162
  "What events are happening this week?",
163
+ "Are there any workshops in the library?",
164
+ "Tell me about upcoming career events",
165
+ "What's happening in the MakerSpace?",
166
+ "Any student club meetings soon?",
167
  ],
168
+ inputs=msg
 
169
  )
170
 
 
 
 
 
 
 
 
 
 
 
 
171
  gr.Markdown("""
172
+ ### Tips:
173
+ - Ask about specific dates, locations, or event types
174
+ - You can refresh the events database using the button above
175
+ - Click on event links to get more details on ExperienceBU
176
+
177
+ Data is refreshed automatically every 24 hours. Events shown are for the next 14 days.
178
  """)
179
 
180
  return demo
181
 
182
  if __name__ == "__main__":
183
  demo = create_demo()
184
+ demo.launch(
185
+ share=False,
186
+ enable_queue=True,
187
+ server_name="0.0.0.0" # Required for Spaces
188
+ )
requirements.txt CHANGED
@@ -1,7 +1,11 @@
1
- huggingface_hub==0.25.2
2
- gradio>=4.0.0
3
- sentence-transformers
4
- chromadb
5
- feedparser
6
- beautifulsoup4
7
- requests
 
 
 
 
 
1
+ gradio==4.14.0
2
+ sentence-transformers==2.2.2
3
+ chromadb==0.4.22
4
+ feedparser==6.0.11
5
+ beautifulsoup4==4.12.2
6
+ requests==2.31.0
7
+ pytz==2023.3.post1
8
+ nltk==3.8.1
9
+ torch>=2.0.0
10
+ transformers>=4.36.0
11
+ huggingface-hub==0.25.2