Aryan Jhaveri commited on
Commit
b5f320c
·
1 Parent(s): dd575a2

Update space

Browse files
Files changed (3) hide show
  1. README.md +17 -12
  2. app.py +251 -56
  3. requirements.txt +7 -1
README.md CHANGED
@@ -1,13 +1,18 @@
1
- ---
2
- title: Test
3
- emoji: 💬
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.0.1
8
- app_file: app.py
9
- pinned: false
10
- short_description: Testimng
11
- ---
12
 
13
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Brock University Events Assistant
 
 
 
 
 
 
 
 
 
 
2
 
3
+ A chatbot that helps you discover events at Brock University. Built using:
4
+ - Gradio for the interface
5
+ - Sentence Transformers for semantic search
6
+ - ChromaDB for vector storage
7
+ - ExperienceBU's event feed for data
8
+
9
+ ## Features
10
+ - Natural language queries about events
11
+ - Real-time event information
12
+ - Category-based searching
13
+ - Date-based filtering
14
+
15
+ ## Example Questions
16
+ - "What events are happening this week?"
17
+ - "Are there any academic workshops?"
18
+ - "Tell me about orientation events"
app.py CHANGED
@@ -1,64 +1,259 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
 
 
64
  demo.launch()
 
 
 
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
192
+ with gr.Blocks(css=custom_css) as 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)
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ gradio>=4.0.0
3
+ sentence-transformers
4
+ chromadb
5
+ feedparser
6
+ beautifulsoup4
7
+ requests