File size: 11,962 Bytes
24342ea
c89cc59
 
a184be7
491769d
 
 
 
 
 
 
 
e1ff28f
d17badf
 
 
 
a184be7
 
d95e3f7
 
bf2bb14
d95e3f7
4eb1be8
e319620
d95e3f7
e319620
d95e3f7
 
4eb1be8
c89cc59
 
 
 
d95e3f7
a184be7
d95e3f7
4eb1be8
d95e3f7
d5218ff
c89cc59
d95e3f7
 
 
e319620
a806d95
d95e3f7
 
e319620
24342ea
750ea35
 
4eb1be8
6ac5501
750ea35
6ac5501
750ea35
6ac5501
4eb1be8
e319620
6ac5501
 
4eb1be8
6ac5501
 
 
 
4eb1be8
6ac5501
750ea35
c89cc59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e319620
 
c89cc59
e319620
 
 
c89cc59
e319620
 
 
a184be7
e319620
 
 
 
 
 
 
d17badf
e319620
 
 
 
 
 
 
 
 
d17badf
e319620
d17badf
e319620
 
 
 
d17badf
e319620
 
 
 
 
 
 
 
 
 
d17badf
e319620
 
9f69ff9
e319620
d17badf
a184be7
 
 
 
 
4eb1be8
9f69ff9
4eb1be8
a184be7
e319620
a184be7
 
 
c89cc59
 
d17badf
 
a184be7
d17badf
 
 
 
4eb1be8
9f69ff9
a184be7
 
d17badf
9f69ff9
e319620
 
 
 
 
d17badf
e319620
 
d17badf
e319620
 
d17badf
 
 
 
4eb1be8
d95e3f7
 
 
 
 
 
 
4eb1be8
d17badf
d95e3f7
 
 
4eb1be8
d95e3f7
 
4eb1be8
d95e3f7
 
 
 
 
 
 
 
 
 
 
 
 
 
caf6b1d
9f69ff9
4eb1be8
 
 
e319620
4eb1be8
95cfa66
d17badf
4eb1be8
 
c89cc59
4eb1be8
c89cc59
 
 
 
 
 
491769d
 
 
 
 
 
 
 
 
 
c89cc59
4eb1be8
 
 
c89cc59
 
 
4eb1be8
491769d
 
 
 
 
 
 
c89cc59
4eb1be8
 
c89cc59
 
4eb1be8
 
 
c89cc59
 
4eb1be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ac5501
4eb1be8
 
 
dd67f43
24342ea
d95e3f7
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import os
import base64
import requests
import gradio as gr
from huggingface_hub import InferenceClient
from dataclasses import dataclass

@dataclass
class ChatMessage:
    """Custom ChatMessage class since huggingface_hub doesn't provide one"""
    role: str
    content: str

    def to_dict(self):
        """Converts ChatMessage to a dictionary for JSON serialization."""
        return {"role": self.role, "content": self.content}

class XylariaChat:
    def __init__(self):
        # Securely load HuggingFace token
        self.hf_token = os.getenv("HF_TOKEN")
        if not self.hf_token:
            raise ValueError("HuggingFace token not found in environment variables")
        
        # Initialize the inference client with the Qwen model
        self.client = InferenceClient(
            model="Qwen/QwQ-32B-Preview", 
            api_key=self.hf_token
        )
        
        # Image captioning API setup
        self.image_api_url = "https://api-inference.huggingface.co/models/microsoft/git-large-coco"
        self.image_api_headers = {"Authorization": f"Bearer {self.hf_token}"}
        
        # Initialize conversation history and persistent memory
        self.conversation_history = []
        self.persistent_memory = {}
        
        # System prompt with more detailed instructions
        self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin(india, 12 year old). You should think step-by-step."""
    
    def store_information(self, key, value):
        """Store important information in persistent memory"""
        self.persistent_memory[key] = value
        return f"Stored: {key} = {value}"

    def retrieve_information(self, key):
        """Retrieve information from persistent memory"""
        return self.persistent_memory.get(key, "No information found for this key.")

    def reset_conversation(self):
        """
        Completely reset the conversation history, persistent memory, 
        and clear API-side memory
        """
        # Clear local memory
        self.conversation_history = []
        self.persistent_memory.clear()
        
        # Reinitialize the client
        try:
            self.client = InferenceClient(
                model="Qwen/QwQ-32B-Preview", 
                api_key=self.hf_token
            )
        except Exception as e:
            print(f"Error resetting API client: {e}")
        
        return None  # To clear the chatbot interface

    def caption_image(self, image):
        """
        Caption an uploaded image using Hugging Face API
        
        Args:
            image (str): Base64 encoded image or file path
        
        Returns:
            str: Image caption or error message
        """
        try:
            # If image is a file path, read and encode
            if isinstance(image, str) and os.path.isfile(image):
                with open(image, "rb") as f:
                    data = f.read()
            # If image is already base64 encoded
            elif isinstance(image, str):
                # Remove data URI prefix if present
                if image.startswith('data:image'):
                    image = image.split(',')[1]
                data = base64.b64decode(image)
            # If image is a file-like object
            else:
                data = image.read()
            
            # Send request to Hugging Face API
            response = requests.post(
                self.image_api_url, 
                headers=self.image_api_headers, 
                data=data
            )
            
            # Check response
            if response.status_code == 200:
                caption = response.json()[0].get('generated_text', 'No caption generated')
                return caption
            else:
                return f"Error captioning image: {response.text}"
        
        except Exception as e:
            return f"Error processing image: {str(e)}"

    def get_response(self, user_input, image=None):
        """
        Generate a response using chat completions with improved error handling
        
        Args:
            user_input (str): User's message
            image (optional): Uploaded image
        
        Returns:
            Stream of chat completions or error message
        """
        try:
            # Prepare messages with conversation context and persistent memory
            messages = []
            
            # Add system prompt as first message
            messages.append(ChatMessage(
                role="system", 
                content=self.system_prompt
            ).to_dict()) # Convert to dictionary
            
            # Add persistent memory context if available
            if self.persistent_memory:
                memory_context = "Remembered Information:\n" + "\n".join(
                    [f"{k}: {v}" for k, v in self.persistent_memory.items()]
                )
                messages.append(ChatMessage(
                    role="system", 
                    content=memory_context
                ).to_dict()) # Convert to dictionary
            
            # Convert existing conversation history to ChatMessage objects and then to dictionaries
            for msg in self.conversation_history:
                messages.append(ChatMessage(
                    role=msg['role'], 
                    content=msg['content']
                ).to_dict()) # Convert to dictionary
            
            # Process image if uploaded
            if image:
                image_caption = self.caption_image(image)
                user_input = f"Image description: {image_caption}\n\nUser's message: {user_input}"
            
            # Add user input
            messages.append(ChatMessage(
                role="user", 
                content=user_input
            ).to_dict()) # Convert to dictionary
            
            # Generate response with streaming
            stream = self.client.chat.completions.create(
                model="Qwen/QwQ-32B-Preview",
                messages=messages, # Send dictionaries
                temperature=0.5,
                max_tokens=10240,
                top_p=0.7,
                stream=True
            )
            
            return stream
        
        except Exception as e:
            print(f"Detailed error in get_response: {e}")
            return f"Error generating response: {str(e)}"

    def create_interface(self):
        def streaming_response(message, chat_history, image):
            response_stream = self.get_response(message, image)

            # Handle errors in get_response
            if isinstance(response_stream, str):
                # Return immediately with the error message
                updated_history = chat_history + [[message, response_stream]]
                yield "", updated_history, None
                return
            
            # Prepare for streaming response
            full_response = ""
            updated_history = chat_history + [[message, ""]]

            # Streaming output
            try:
                for chunk in response_stream:
                    if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
                        chunk_content = chunk.choices[0].delta.content
                        full_response += chunk_content

                        # Update the last message in chat history with partial response
                        updated_history[-1][1] = full_response
                        yield "", updated_history, None 
            except Exception as e:
                print(f"Streaming error: {e}")
                # Display error in the chat interface
                updated_history[-1][1] = f"Error during response: {e}"
                yield "", updated_history, None
                return
            
            # Update conversation history
            self.conversation_history.append(
                {"role": "user", "content": message}
            )
            self.conversation_history.append(
                {"role": "assistant", "content": full_response}
            )
            
            # Limit conversation history
            if len(self.conversation_history) > 10:
                self.conversation_history = self.conversation_history[-10:]

        # Custom CSS for Inter font
        custom_css = """
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body, .gradio-container {
            font-family: 'Inter', sans-serif !important;
        }
        
        .chatbot-container .message {
            font-family: 'Inter', sans-serif !important;
        }
        
        .gradio-container input, 
        .gradio-container textarea, 
        .gradio-container button {
            font-family: 'Inter', sans-serif !important;
        }
        """

        with gr.Blocks(theme='soft', css=custom_css) as demo:
            # Chat interface with improved styling
            with gr.Column():
                chatbot = gr.Chatbot(
                    label="Xylaria 1.4 Senoa (Qwen Model)",
                    height=500,
                    show_copy_button=True,
                    
                )
                
                # Input row with improved layout and image upload
                with gr.Row():
                    with gr.Column(scale=4):
                        txt = gr.Textbox(
                            show_label=False, 
                            placeholder="Type your message...", 
                            container=False
                        )
                        
                        # Image upload as a separate button
                        with gr.Row():
                            img = gr.Image(
                                sources=["upload", "webcam"], 
                                type="filepath", 
                                label="Upload Image",
                                visible=False
                            )
                            upload_btn = gr.Button("Upload Image")
                    
                    btn = gr.Button("Send", scale=1)
                
                # Clear history and memory buttons
                with gr.Row():
                    clear = gr.Button("Clear Conversation")
                    clear_memory = gr.Button("Clear Memory")
            
            # Image upload toggle
            upload_btn.click(
                fn=lambda: gr.update(visible=True), 
                inputs=None, 
                outputs=[img]
            )
            
            # Submit functionality with streaming and image support
            btn.click(
                fn=streaming_response, 
                inputs=[txt, chatbot, img], 
                outputs=[txt, chatbot, img]
            )
            txt.submit(
                fn=streaming_response, 
                inputs=[txt, chatbot, img], 
                outputs=[txt, chatbot, img]
            )
            
            # Clear conversation history
            clear.click(
                fn=lambda: None, 
                inputs=None, 
                outputs=[chatbot],
                queue=False
            )
            
            # Clear persistent memory and reset conversation
            clear_memory.click(
                fn=self.reset_conversation,
                inputs=None,
                outputs=[chatbot],
                queue=False
            )

            # Ensure memory is cleared when the interface is closed
            demo.load(self.reset_conversation, None, None)
        
        return demo

# Launch the interface
def main():
    chat = XylariaChat()
    interface = chat.create_interface()
    interface.launch(
        share=True,  # Optional: create a public link
        debug=True   # Show detailed errors
    )

if __name__ == "__main__":
    main()