Reality123b commited on
Commit
bf2bb14
·
verified ·
1 Parent(s): dd67f43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -91
app.py CHANGED
@@ -13,37 +13,52 @@ class XylariaChat:
13
  self.hf_token = os.environ.get("HF_TOKEN")
14
  firebase_cred_json = os.environ.get("FIREBASE_SERVICE_ACCOUNT")
15
 
16
- if not self.hf_token or not firebase_cred_json:
17
- raise ValueError("Required secrets (HF_TOKEN or FIREBASE_SERVICE_ACCOUNT) not found")
 
18
 
19
- # Initialize Firebase
20
- try:
21
- # Convert the JSON string to a temporary credentials file
22
- with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_cred_file:
23
- json.dump(json.loads(firebase_cred_json), temp_cred_file)
24
- temp_cred_file.close()
25
-
26
- firebase_cred = credentials.Certificate(temp_cred_file.name)
27
- firebase_admin.initialize_app(firebase_cred)
28
- self.db = firestore.client()
29
-
30
- # Remove the temporary credentials file
31
- os.unlink(temp_cred_file.name)
32
- except Exception as e:
33
- print(f"Firebase initialization error: {e}")
34
- self.db = None
 
 
 
 
 
 
35
 
36
- # Initialize the inference client
37
- self.client = InferenceClient(
38
- model="Qwen/QwQ-32B-Preview",
39
- api_key=self.hf_token
40
- )
 
 
 
 
 
41
 
42
  # Initialize conversation history
43
  self.conversation_history = []
44
 
45
  def signup(self, username, email, password):
46
  """User signup method"""
 
 
 
47
  try:
48
  # Create user in Firebase Authentication
49
  user = auth.create_user(
@@ -53,13 +68,12 @@ class XylariaChat:
53
  )
54
 
55
  # Store additional user info in Firestore
56
- if self.db:
57
- user_ref = self.db.collection('users').document(user.uid)
58
- user_ref.set({
59
- 'username': username,
60
- 'email': email,
61
- 'created_at': firestore.SERVER_TIMESTAMP
62
- })
63
 
64
  return f"Successfully created account for {username}"
65
  except Exception as e:
@@ -67,6 +81,9 @@ class XylariaChat:
67
 
68
  def login(self, email, password):
69
  """User login method"""
 
 
 
70
  try:
71
  # Authenticate user with Firebase
72
  user = auth.get_user_by_email(email)
@@ -93,6 +110,10 @@ class XylariaChat:
93
  print(f"Error saving message: {e}")
94
 
95
  def get_response(self, user_input, chat_history):
 
 
 
 
96
  # Prepare messages with conversation context
97
  messages = [
98
  {"role": "system", "content": """You are Xylaria 1.4 Senoa, an AI assistant developed by SK MD Saad Amin.
@@ -128,23 +149,6 @@ class XylariaChat:
128
  background-color: #121212;
129
  color: #ffffff;
130
  }
131
- .chatbot .user-message {
132
- background-color: #2563eb;
133
- color: white;
134
- }
135
- .chatbot .bot-message {
136
- background-color: #1f2937;
137
- color: #f3f4f6;
138
- box-shadow: 0 1px 3px 0 rgba(255, 255, 255, 0.1);
139
- }
140
- .chatbot-input-row {
141
- background-color: #1f2937;
142
- color: #f3f4f6;
143
- }
144
- .send-button {
145
- background-color: #2563eb;
146
- color: white;
147
- }
148
  }
149
 
150
  @media (prefers-color-scheme: light) {
@@ -153,34 +157,6 @@ class XylariaChat:
153
  background-color: #f3f4f6;
154
  color: #1f2937;
155
  }
156
- .chatbot .message {
157
- max-width: 80%;
158
- border-radius: 1rem;
159
- padding: 0.75rem;
160
- margin-bottom: 0.5rem;
161
- }
162
- .chatbot .user-message {
163
- background-color: #3b82f6;
164
- color: white;
165
- align-self: flex-end;
166
- }
167
- .chatbot .bot-message {
168
- background-color: white;
169
- color: #1f2937;
170
- align-self: flex-start;
171
- box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
172
- }
173
- .chatbot-input-row {
174
- background-color: white;
175
- border-radius: 9999px;
176
- padding: 0.5rem 1rem;
177
- }
178
- .send-button {
179
- background-color: #3b82f6;
180
- color: white;
181
- border-radius: 9999px;
182
- padding: 0.5rem;
183
- }
184
  }
185
  """
186
 
@@ -194,7 +170,7 @@ class XylariaChat:
194
  # Get AI response stream
195
  response_stream = self.get_response(message, chat_history)
196
 
197
- # If it's an error, return immediately
198
  if isinstance(response_stream, str):
199
  return "", chat_history + [[message, response_stream]]
200
 
@@ -203,14 +179,17 @@ class XylariaChat:
203
  updated_history = chat_history + [[message, ""]]
204
 
205
  # Streaming output
206
- for chunk in response_stream:
207
- if chunk.choices[0].delta.content:
208
- chunk_content = chunk.choices[0].delta.content
209
- full_response += chunk_content
210
-
211
- # Update the last message in chat history with partial response
212
- updated_history[-1][1] = full_response
213
- yield "", updated_history
 
 
 
214
 
215
  # Save bot message to Firestore
216
  self.save_message(user_id, full_response, 'bot')
@@ -240,7 +219,8 @@ class XylariaChat:
240
  chatbot = gr.Chatbot(
241
  label="Xylaria 1.4 Senoa",
242
  height=500,
243
- show_copy_button=True
 
244
  )
245
 
246
  # Input row with minimalist design
@@ -248,11 +228,9 @@ class XylariaChat:
248
  txt = gr.Textbox(
249
  show_label=False,
250
  placeholder="Type your message...",
251
- container=False,
252
- scale=4,
253
- container_css_class="chatbot-input-row"
254
  )
255
- btn = gr.Button("Send", css_class="send-button", scale=1)
256
 
257
  # Clear conversation button
258
  clear = gr.Button("Clear Conversation")
@@ -285,6 +263,6 @@ class XylariaChat:
285
 
286
  return demo
287
 
288
- # Initialize the chat system and launch interface
289
  xylaria_chat = XylariaChat()
290
- xylaria_chat.create_interface().launch(share=True)
 
13
  self.hf_token = os.environ.get("HF_TOKEN")
14
  firebase_cred_json = os.environ.get("FIREBASE_SERVICE_ACCOUNT")
15
 
16
+ # Optional: Add more robust error handling for missing environment variables
17
+ if not self.hf_token:
18
+ print("Warning: HuggingFace token not found. Some functionality may be limited.")
19
 
20
+ # Firebase initialization
21
+ self.db = None
22
+ if firebase_cred_json:
23
+ try:
24
+ # Convert the JSON string to a temporary credentials file
25
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_cred_file:
26
+ # Add error handling for JSON parsing
27
+ try:
28
+ firebase_creds = json.loads(firebase_cred_json)
29
+ json.dump(firebase_creds, temp_cred_file)
30
+ temp_cred_file.close()
31
+
32
+ firebase_cred = credentials.Certificate(temp_cred_file.name)
33
+ firebase_admin.initialize_app(firebase_cred)
34
+ self.db = firestore.client()
35
+ except json.JSONDecodeError:
36
+ print("Error: Invalid Firebase credentials JSON")
37
+
38
+ # Remove the temporary credentials file
39
+ os.unlink(temp_cred_file.name)
40
+ except Exception as e:
41
+ print(f"Firebase initialization error: {e}")
42
 
43
+ # Initialize the inference client (only if token is available)
44
+ self.client = None
45
+ if self.hf_token:
46
+ try:
47
+ self.client = InferenceClient(
48
+ model="Qwen/QwQ-32B-Preview",
49
+ api_key=self.hf_token
50
+ )
51
+ except Exception as e:
52
+ print(f"Inference client initialization error: {e}")
53
 
54
  # Initialize conversation history
55
  self.conversation_history = []
56
 
57
  def signup(self, username, email, password):
58
  """User signup method"""
59
+ if not self.db:
60
+ return "Firebase is not initialized. Signup unavailable."
61
+
62
  try:
63
  # Create user in Firebase Authentication
64
  user = auth.create_user(
 
68
  )
69
 
70
  # Store additional user info in Firestore
71
+ user_ref = self.db.collection('users').document(user.uid)
72
+ user_ref.set({
73
+ 'username': username,
74
+ 'email': email,
75
+ 'created_at': firestore.SERVER_TIMESTAMP
76
+ })
 
77
 
78
  return f"Successfully created account for {username}"
79
  except Exception as e:
 
81
 
82
  def login(self, email, password):
83
  """User login method"""
84
+ if not self.db:
85
+ return "Firebase is not initialized. Login unavailable."
86
+
87
  try:
88
  # Authenticate user with Firebase
89
  user = auth.get_user_by_email(email)
 
110
  print(f"Error saving message: {e}")
111
 
112
  def get_response(self, user_input, chat_history):
113
+ # Check if client is initialized
114
+ if not self.client:
115
+ return "AI response is currently unavailable."
116
+
117
  # Prepare messages with conversation context
118
  messages = [
119
  {"role": "system", "content": """You are Xylaria 1.4 Senoa, an AI assistant developed by SK MD Saad Amin.
 
149
  background-color: #121212;
150
  color: #ffffff;
151
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  }
153
 
154
  @media (prefers-color-scheme: light) {
 
157
  background-color: #f3f4f6;
158
  color: #1f2937;
159
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  }
161
  """
162
 
 
170
  # Get AI response stream
171
  response_stream = self.get_response(message, chat_history)
172
 
173
+ # If it's an error or string, return immediately
174
  if isinstance(response_stream, str):
175
  return "", chat_history + [[message, response_stream]]
176
 
 
179
  updated_history = chat_history + [[message, ""]]
180
 
181
  # Streaming output
182
+ try:
183
+ for chunk in response_stream:
184
+ if chunk.choices[0].delta.content:
185
+ chunk_content = chunk.choices[0].delta.content
186
+ full_response += chunk_content
187
+
188
+ # Update the last message in chat history with partial response
189
+ updated_history[-1][1] = full_response
190
+ yield "", updated_history
191
+ except Exception as e:
192
+ return "", updated_history + [["", f"Error in response: {str(e)}"]]
193
 
194
  # Save bot message to Firestore
195
  self.save_message(user_id, full_response, 'bot')
 
219
  chatbot = gr.Chatbot(
220
  label="Xylaria 1.4 Senoa",
221
  height=500,
222
+ show_copy_button=True,
223
+ type="messages" # Added to resolve deprecation warning
224
  )
225
 
226
  # Input row with minimalist design
 
228
  txt = gr.Textbox(
229
  show_label=False,
230
  placeholder="Type your message...",
231
+ scale=4
 
 
232
  )
233
+ btn = gr.Button("Send", scale=1)
234
 
235
  # Clear conversation button
236
  clear = gr.Button("Clear Conversation")
 
263
 
264
  return demo
265
 
266
+ # Note: Actual launch should be done with proper environment variable setup
267
  xylaria_chat = XylariaChat()
268
+ xylaria_chat.create_interface().launch(share=True)