Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,11 @@
|
|
1 |
import os
|
|
|
|
|
2 |
import gradio as gr
|
3 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
4 |
|
5 |
class XylariaChat:
|
6 |
def __init__(self):
|
@@ -15,6 +20,11 @@ class XylariaChat:
|
|
15 |
api_key=self.hf_token
|
16 |
)
|
17 |
|
|
|
|
|
|
|
|
|
|
|
18 |
# Initialize conversation history and persistent memory
|
19 |
self.conversation_history = []
|
20 |
self.persistent_memory = {}
|
@@ -41,9 +51,153 @@ Capabilities:
|
|
41 |
- Provide explanations and insights
|
42 |
- Offer supportive and constructive guidance """
|
43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
def store_information(self, key, value):
|
45 |
"""Store important information in persistent memory"""
|
46 |
self.persistent_memory[key] = value
|
|
|
|
|
|
|
47 |
|
48 |
def retrieve_information(self, key):
|
49 |
"""Retrieve information from persistent memory"""
|
@@ -52,10 +206,13 @@ Capabilities:
|
|
52 |
def reset_conversation(self):
|
53 |
"""
|
54 |
Completely reset the conversation history and persistent memory
|
55 |
-
This helps prevent exposing previous users' conversations
|
56 |
"""
|
57 |
self.conversation_history = []
|
58 |
self.persistent_memory = {}
|
|
|
|
|
|
|
|
|
59 |
|
60 |
def get_response(self, user_input):
|
61 |
# Prepare messages with conversation context and persistent memory
|
@@ -88,7 +245,28 @@ Capabilities:
|
|
88 |
return f"Error generating response: {str(e)}"
|
89 |
|
90 |
def create_interface(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
def streaming_response(message, chat_history):
|
|
|
|
|
|
|
|
|
92 |
# Clear input textbox
|
93 |
response_stream = self.get_response(message)
|
94 |
|
@@ -121,6 +299,9 @@ Capabilities:
|
|
121 |
# Limit conversation history to prevent token overflow
|
122 |
if len(self.conversation_history) > 10:
|
123 |
self.conversation_history = self.conversation_history[-10:]
|
|
|
|
|
|
|
124 |
|
125 |
# Custom CSS for Inter font
|
126 |
custom_css = """
|
@@ -142,6 +323,41 @@ Capabilities:
|
|
142 |
"""
|
143 |
|
144 |
with gr.Blocks(theme='soft', css=custom_css) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
# Chat interface with improved styling
|
146 |
with gr.Column():
|
147 |
chatbot = gr.Chatbot(
|
|
|
1 |
import os
|
2 |
+
import uuid
|
3 |
+
import json
|
4 |
import gradio as gr
|
5 |
from huggingface_hub import InferenceClient
|
6 |
+
import firebase_admin
|
7 |
+
from firebase_admin import credentials, firestore
|
8 |
+
import hashlib
|
9 |
|
10 |
class XylariaChat:
|
11 |
def __init__(self):
|
|
|
20 |
api_key=self.hf_token
|
21 |
)
|
22 |
|
23 |
+
# Firebase initialization
|
24 |
+
self.firebase_cred = None
|
25 |
+
self.firebase_db = None
|
26 |
+
self.current_user_id = None
|
27 |
+
|
28 |
# Initialize conversation history and persistent memory
|
29 |
self.conversation_history = []
|
30 |
self.persistent_memory = {}
|
|
|
51 |
- Provide explanations and insights
|
52 |
- Offer supportive and constructive guidance """
|
53 |
|
54 |
+
def generate_user_key(self):
|
55 |
+
"""
|
56 |
+
Generate a unique user key that can be saved locally
|
57 |
+
"""
|
58 |
+
# Generate a UUID and hash it for additional security
|
59 |
+
unique_key = str(uuid.uuid4())
|
60 |
+
hashed_key = hashlib.sha256(unique_key.encode()).hexdigest()
|
61 |
+
return hashed_key
|
62 |
+
|
63 |
+
def init_firebase(self):
|
64 |
+
"""
|
65 |
+
Initialize Firebase using the service account from environment variable
|
66 |
+
"""
|
67 |
+
try:
|
68 |
+
# Get Firebase service account from environment variable
|
69 |
+
firebase_cred_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
70 |
+
if not firebase_cred_json:
|
71 |
+
raise ValueError("Firebase service account not found in environment variables")
|
72 |
+
|
73 |
+
# Parse the JSON credentials
|
74 |
+
cred_dict = json.loads(firebase_cred_json)
|
75 |
+
|
76 |
+
# Write credentials to a temporary file (Firebase requirement)
|
77 |
+
with open('firebase_credentials.json', 'w') as f:
|
78 |
+
json.dump(cred_dict, f)
|
79 |
+
|
80 |
+
# Initialize Firebase Admin SDK
|
81 |
+
cred = credentials.Certificate('firebase_credentials.json')
|
82 |
+
firebase_admin.initialize_app(cred)
|
83 |
+
|
84 |
+
# Initialize Firestore
|
85 |
+
self.firebase_db = firestore.client()
|
86 |
+
|
87 |
+
return True
|
88 |
+
except Exception as e:
|
89 |
+
print(f"Firebase initialization error: {e}")
|
90 |
+
return False
|
91 |
+
|
92 |
+
def save_user_chat_history(self):
|
93 |
+
"""
|
94 |
+
Save chat history to Firebase for the current user
|
95 |
+
"""
|
96 |
+
if not self.firebase_db or not self.current_user_id:
|
97 |
+
return False
|
98 |
+
|
99 |
+
try:
|
100 |
+
# Create a document reference for the user
|
101 |
+
user_doc_ref = self.firebase_db.collection('user_chats').document(self.current_user_id)
|
102 |
+
|
103 |
+
# Prepare chat history data
|
104 |
+
chat_data = {
|
105 |
+
'conversation_history': self.conversation_history,
|
106 |
+
'persistent_memory': self.persistent_memory,
|
107 |
+
'timestamp': firestore.SERVER_TIMESTAMP
|
108 |
+
}
|
109 |
+
|
110 |
+
# Save or update the document
|
111 |
+
user_doc_ref.set(chat_data, merge=True)
|
112 |
+
return True
|
113 |
+
except Exception as e:
|
114 |
+
print(f"Error saving chat history: {e}")
|
115 |
+
return False
|
116 |
+
|
117 |
+
def load_user_chat_history(self, user_id):
|
118 |
+
"""
|
119 |
+
Load chat history from Firebase for a specific user
|
120 |
+
"""
|
121 |
+
if not self.firebase_db:
|
122 |
+
return False
|
123 |
+
|
124 |
+
try:
|
125 |
+
# Retrieve user document
|
126 |
+
user_doc_ref = self.firebase_db.collection('user_chats').document(user_id)
|
127 |
+
user_doc = user_doc_ref.get()
|
128 |
+
|
129 |
+
if user_doc.exists:
|
130 |
+
user_data = user_doc.to_dict()
|
131 |
+
# Restore conversation history and persistent memory
|
132 |
+
self.conversation_history = user_data.get('conversation_history', [])
|
133 |
+
self.persistent_memory = user_data.get('persistent_memory', {})
|
134 |
+
self.current_user_id = user_id
|
135 |
+
return True
|
136 |
+
return False
|
137 |
+
except Exception as e:
|
138 |
+
print(f"Error loading chat history: {e}")
|
139 |
+
return False
|
140 |
+
|
141 |
+
def authenticate_user(self, user_key):
|
142 |
+
"""
|
143 |
+
Authenticate user based on their unique key
|
144 |
+
"""
|
145 |
+
if not self.firebase_db:
|
146 |
+
return False, "Firebase not initialized"
|
147 |
+
|
148 |
+
try:
|
149 |
+
# Check if user key exists in users collection
|
150 |
+
users_ref = self.firebase_db.collection('users')
|
151 |
+
query = users_ref.where('user_key', '==', user_key).limit(1)
|
152 |
+
docs = query.stream()
|
153 |
+
|
154 |
+
for doc in docs:
|
155 |
+
# User found, set current user ID and load history
|
156 |
+
self.current_user_id = doc.id
|
157 |
+
self.load_user_chat_history(self.current_user_id)
|
158 |
+
return True, "Authentication successful"
|
159 |
+
|
160 |
+
return False, "Invalid user key"
|
161 |
+
except Exception as e:
|
162 |
+
print(f"Authentication error: {e}")
|
163 |
+
return False, "Authentication error"
|
164 |
+
|
165 |
+
def register_user(self, user_key):
|
166 |
+
"""
|
167 |
+
Register a new user with a unique key
|
168 |
+
"""
|
169 |
+
if not self.firebase_db:
|
170 |
+
return False, "Firebase not initialized"
|
171 |
+
|
172 |
+
try:
|
173 |
+
# Check if user key already exists
|
174 |
+
users_ref = self.firebase_db.collection('users')
|
175 |
+
query = users_ref.where('user_key', '==', user_key).limit(1)
|
176 |
+
existing_users = list(query.stream())
|
177 |
+
|
178 |
+
if existing_users:
|
179 |
+
return False, "User key already exists"
|
180 |
+
|
181 |
+
# Create new user document
|
182 |
+
new_user_ref = users_ref.document()
|
183 |
+
new_user_ref.set({
|
184 |
+
'user_key': user_key,
|
185 |
+
'created_at': firestore.SERVER_TIMESTAMP
|
186 |
+
})
|
187 |
+
|
188 |
+
# Set current user ID
|
189 |
+
self.current_user_id = new_user_ref.id
|
190 |
+
return True, "User registered successfully"
|
191 |
+
except Exception as e:
|
192 |
+
print(f"Registration error: {e}")
|
193 |
+
return False, "Registration error"
|
194 |
+
|
195 |
def store_information(self, key, value):
|
196 |
"""Store important information in persistent memory"""
|
197 |
self.persistent_memory[key] = value
|
198 |
+
# Automatically save to Firebase if user is authenticated
|
199 |
+
if self.current_user_id:
|
200 |
+
self.save_user_chat_history()
|
201 |
|
202 |
def retrieve_information(self, key):
|
203 |
"""Retrieve information from persistent memory"""
|
|
|
206 |
def reset_conversation(self):
|
207 |
"""
|
208 |
Completely reset the conversation history and persistent memory
|
|
|
209 |
"""
|
210 |
self.conversation_history = []
|
211 |
self.persistent_memory = {}
|
212 |
+
|
213 |
+
# If user is authenticated, update Firebase
|
214 |
+
if self.current_user_id:
|
215 |
+
self.save_user_chat_history()
|
216 |
|
217 |
def get_response(self, user_input):
|
218 |
# Prepare messages with conversation context and persistent memory
|
|
|
245 |
return f"Error generating response: {str(e)}"
|
246 |
|
247 |
def create_interface(self):
|
248 |
+
# Initialize Firebase
|
249 |
+
firebase_initialized = self.init_firebase()
|
250 |
+
|
251 |
+
def generate_key():
|
252 |
+
"""Generate a new user key"""
|
253 |
+
return self.generate_user_key()
|
254 |
+
|
255 |
+
def authenticate(user_key):
|
256 |
+
"""Authenticate user and load chat history"""
|
257 |
+
success, message = self.authenticate_user(user_key)
|
258 |
+
return message
|
259 |
+
|
260 |
+
def register(user_key):
|
261 |
+
"""Register a new user"""
|
262 |
+
success, message = self.register_user(user_key)
|
263 |
+
return message
|
264 |
+
|
265 |
def streaming_response(message, chat_history):
|
266 |
+
# Check if user is authenticated
|
267 |
+
if not self.current_user_id:
|
268 |
+
return "", chat_history + [[message, "Please authenticate first."]]
|
269 |
+
|
270 |
# Clear input textbox
|
271 |
response_stream = self.get_response(message)
|
272 |
|
|
|
299 |
# Limit conversation history to prevent token overflow
|
300 |
if len(self.conversation_history) > 10:
|
301 |
self.conversation_history = self.conversation_history[-10:]
|
302 |
+
|
303 |
+
# Save chat history to Firebase
|
304 |
+
self.save_user_chat_history()
|
305 |
|
306 |
# Custom CSS for Inter font
|
307 |
custom_css = """
|
|
|
323 |
"""
|
324 |
|
325 |
with gr.Blocks(theme='soft', css=custom_css) as demo:
|
326 |
+
# User Authentication Section
|
327 |
+
with gr.Column():
|
328 |
+
# Generate Key Section
|
329 |
+
with gr.Row():
|
330 |
+
generate_key_btn = gr.Button("Generate User Key")
|
331 |
+
user_key_output = gr.Textbox(label="Your User Key", interactive=False)
|
332 |
+
generate_key_btn.click(
|
333 |
+
fn=generate_key,
|
334 |
+
inputs=None,
|
335 |
+
outputs=[user_key_output]
|
336 |
+
)
|
337 |
+
|
338 |
+
# Authentication Section
|
339 |
+
with gr.Row():
|
340 |
+
auth_key_input = gr.Textbox(label="Enter User Key")
|
341 |
+
auth_btn = gr.Button("Authenticate")
|
342 |
+
register_btn = gr.Button("Register")
|
343 |
+
|
344 |
+
# Authentication result
|
345 |
+
auth_result = gr.Textbox(label="Authentication Result", interactive=False)
|
346 |
+
|
347 |
+
# Authenticate button click
|
348 |
+
auth_btn.click(
|
349 |
+
fn=authenticate,
|
350 |
+
inputs=[auth_key_input],
|
351 |
+
outputs=[auth_result]
|
352 |
+
)
|
353 |
+
|
354 |
+
# Register button click
|
355 |
+
register_btn.click(
|
356 |
+
fn=register,
|
357 |
+
inputs=[auth_key_input],
|
358 |
+
outputs=[auth_result]
|
359 |
+
)
|
360 |
+
|
361 |
# Chat interface with improved styling
|
362 |
with gr.Column():
|
363 |
chatbot = gr.Chatbot(
|