Reality123b commited on
Commit
e1ff28f
·
verified ·
1 Parent(s): ae5eb30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +298 -323
app.py CHANGED
@@ -1,330 +1,305 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
-
5
- # Initialize clients
6
- text_client = InferenceClient("mistralai/Mistral-Nemo-Instruct-2407", token=os.environ["hf_token"])
7
- image_client = InferenceClient("SG161222/RealVisXL_V3.0")
8
-
9
- def check_custom_responses(message: str) -> str:
10
- """Check for specific patterns and return custom responses."""
11
- message_lower = message.lower()
12
- custom_responses = {
13
- "what is ur name?": "xylaria",
14
- "what is ur Name?": "xylaria",
15
- "what is Ur name?": "xylaria",
16
- "what is Ur Name?": "xylaria",
17
- "What is ur name?": "xylaria",
18
- "What is ur Name?": "xylaria",
19
- "What is Ur name?": "xylaria",
20
- "What is Ur Name?": "xylaria",
21
- "what's ur name?": "xylaria",
22
- "what's ur Name?": "xylaria",
23
- "what's Ur name?": "xylaria",
24
- "what's Ur Name?": "xylaria",
25
- "whats ur name?": "xylaria",
26
- "whats ur Name?": "xylaria",
27
- "whats Ur name?": "xylaria",
28
- "whats Ur Name?": "xylaria",
29
- "what's your name?": "xylaria",
30
- "what's your Name?": "xylaria",
31
- "what's Your name?": "xylaria",
32
- "what's Your Name?": "xylaria",
33
- "Whats ur name?": "xylaria",
34
- "Whats ur Name?": "xylaria",
35
- "Whats Ur name?": "xylaria",
36
- "Whats Ur Name?": "xylaria",
37
- "What Is Your Name?": "xylaria",
38
- "What Is Ur Name?": "xylaria",
39
- "What Is Your Name?": "xylaria",
40
- "What Is Ur Name?": "xylaria",
41
- "what is your name?": "xylaria",
42
- "what is your Name?": "xylaria",
43
- "what is Your name?": "xylaria",
44
- "what is Your Name?": "xylaria",
45
- "how many 'r' is in strawberry?": "3",
46
- "how many 'R' is in strawberry?": "3",
47
- "how many 'r' Is in strawberry?": "3",
48
- "how many 'R' Is in strawberry?": "3",
49
- "How many 'r' is in strawberry?": "3",
50
- "How many 'R' is in strawberry?": "3",
51
- "How Many 'r' Is In Strawberry?": "3",
52
- "How Many 'R' Is In Strawberry?": "3",
53
- "how many r is in strawberry?": "3",
54
- "how many R is in strawberry?": "3",
55
- "how many r Is in strawberry?": "3",
56
- "how many R Is in strawberry?": "3",
57
- "How many r is in strawberry?": "3",
58
- "How many R is in strawberry?": "3",
59
- "How Many R Is In Strawberry?": "3",
60
- "how many 'r' in strawberry?": "3",
61
- "how many r's are in strawberry?": "3",
62
- "how many Rs are in strawberry?": "3",
63
- "How Many R's Are In Strawberry?": "3",
64
- "How Many Rs Are In Strawberry?": "3",
65
- "who is your developer?": "sk md saad amin",
66
- "who is your Developer?": "sk md saad amin",
67
- "who is Your Developer?": "sk md saad amin",
68
- "who is ur developer?": "sk md saad amin",
69
- "who is ur Developer?": "sk md saad amin",
70
- "who is Your Developer?": "sk md saad amin",
71
- "Who is ur developer?": "sk md saad amin",
72
- "Who is ur Developer?": "sk md saad amin",
73
- "who is ur dev?": "sk md saad amin",
74
- "Who is ur dev?": "sk md saad amin",
75
- "who is your dev?": "sk md saad amin",
76
- "Who is your dev?": "sk md saad amin",
77
- "Who's your developer?": "sk md saad amin",
78
- "Who's ur developer?": "sk md saad amin",
79
- "Who Is Your Developer?": "sk md saad amin",
80
- "Who Is Ur Developer?": "sk md saad amin",
81
- "Who Is Your Dev?": "sk md saad amin",
82
- "Who Is Ur Dev?": "sk md saad amin",
83
- "who's your developer?": "sk md saad amin",
84
- "who's ur developer?": "sk md saad amin",
85
- "who is your devloper?": "sk md saad amin",
86
- "who is ur devloper?": "sk md saad amin",
87
- "how many r is in strawberry?": "3",
88
- "how many R is in strawberry?": "3",
89
- "how many r Is in strawberry?": "3",
90
- "how many R Is in strawberry?": "3",
91
- "How many r is in strawberry?": "3",
92
- "How many R is in strawberry?": "3",
93
- "How Many R Is In Strawberry?": "3",
94
- "how many 'r' is in strawberry?": "3",
95
- "how many 'R' is in strawberry?": "3",
96
- "how many 'r' Is in strawberry?": "3",
97
- "how many 'R' Is in strawberry?": "3",
98
- "How many 'r' is in strawberry?": "3",
99
- "How many 'R' is in strawberry?": "3",
100
- "How Many 'r' Is In Strawberry?": "3",
101
- "How Many 'R' Is In Strawberry?": "3",
102
- "how many r's are in strawberry?": "3",
103
- "how many Rs are in strawberry?": "3",
104
- "How Many R's Are In Strawberry?": "3",
105
- "How Many Rs Are In Strawberry?": "3",
106
- "how many Rs's are in strawberry?": "3",
107
- "wat is ur name?": "xylaria",
108
- "wat is ur Name?": "xylaria",
109
- "wut is ur name?": "xylaria",
110
- "wut ur name?": "xylaria",
111
- "wats ur name?": "xylaria",
112
- "wats ur name": "xylaria",
113
- "who's ur dev?": "sk md saad amin",
114
- "who's your dev?": "sk md saad amin",
115
- "who ur dev?": "sk md saad amin",
116
- "who's ur devloper?": "sk md saad amin",
117
- "how many r in strawbary?": "3",
118
- "how many r in strawbary?": "3",
119
- "how many R in strawbary?": "3",
120
- "how many 'r' in strawbary?": "3",
121
- "how many 'R' in strawbary?": "3",
122
- "how many r in strawbry?": "3",
123
- "how many R in strawbry?": "3",
124
- "how many r is in strawbry?": "3",
125
- "how many 'r' is in strawbry?": "3",
126
- "how many 'R' is in strawbry?": "3",
127
- "who is ur dev": "sk md saad amin",
128
- "who is ur devloper": "sk md saad amin",
129
- "what is ur dev": "sk md saad amin",
130
- "who is ur dev?": "sk md saad amin",
131
- "who is ur dev?": "sk md saad amin",
132
- "whats ur dev?": "sk md saad amin",
133
- }
134
-
135
- for pattern, response in custom_responses.items():
136
- if pattern in message_lower:
137
- return response
138
- return None
139
-
140
- def is_image_request(message: str) -> bool:
141
- """Detect if the message is requesting image generation."""
142
- image_triggers = [
143
- "generate an image",
144
- "create an image",
145
- "draw",
146
- "make a picture",
147
- "generate a picture",
148
- "create a picture",
149
- "generate art",
150
- "create art",
151
- "make art",
152
- "visualize",
153
- "show me",
154
- ]
155
- message_lower = message.lower()
156
- return any(trigger in message_lower for trigger in image_triggers)
157
-
158
- def generate_image(prompt: str) -> str:
159
- """Generate an image using DALLE-4K model."""
160
- try:
161
- response = image_client.text_to_image(
162
- prompt,
163
- parameters={
164
- "negative_prompt": "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
165
- "num_inference_steps": 30,
166
- "guidance_scale": 7.5,
167
- "sampling_steps": 15,
168
- "upscaler": "4x-UltraSharp",
169
- "denoising_strength": 0.5,
170
- }
171
- )
172
- return response
173
- except Exception as e:
174
- print(f"Image generation error: {e}")
175
- return None
176
-
177
- def respond(
178
- message,
179
- history: list[tuple[str, str]],
180
- system_message,
181
- max_tokens,
182
- temperature,
183
- top_p,
184
- ):
185
- # First check for custom responses
186
- custom_response = check_custom_responses(message)
187
- if custom_response:
188
- yield custom_response
189
- return
190
-
191
- if is_image_request(message):
192
  try:
193
- image = generate_image(message)
194
- if image:
195
- return f"Here's your generated image based on: {message}"
196
- else:
197
- return "Sorry, I couldn't generate the image. Please try again."
 
 
 
 
 
 
 
198
  except Exception as e:
199
- return f"An error occurred while generating the image: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- # Prepare conversation history
202
- messages = [{"role": "system", "content": system_message}]
203
- for val in history:
204
- if val[0]:
205
- messages.append({"role": "user", "content": val[0]})
206
- if val[1]:
207
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
208
 
209
- messages.append({"role": "user", "content": message})
210
-
211
- # Get response from model
212
- response = ""
213
- for message in text_client.chat_completion(
214
- messages,
215
- max_tokens=max_tokens,
216
- stream=True,
217
- temperature=temperature,
218
- top_p=top_p,
219
- ):
220
- token = message.choices[0].delta.content
221
- response += token
222
- yield response
223
-
224
- yield response
225
-
226
- # Custom CSS for the Gradio interface
227
- custom_css = """
228
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
229
-
230
- body, .gradio-container {
231
- font-family: 'Inter', sans-serif;
232
- }
233
- """
234
-
235
- # System message
236
- system_message = """
237
- Xylaria (v1.2.9) is an AI assistant developed by Sk Md Saad Amin, designed to provide efficient, practical support in various domains with adaptable communication.
238
-
239
- Core Competencies
240
-
241
- Knowledge: Sciences, mathematics, humanities, arts, programming, data analysis, writing, and cultural awareness.
242
-
243
- Communication: Adjusts tone to context, prioritizes clarity, seeks clarification when needed, and maintains professionalism.
244
-
245
- Problem-Solving: Breaks down problems, clarifies assumptions, verifies solutions, and considers multiple approaches.
246
-
247
-
248
- Technical Capabilities
249
-
250
- Programming: Clean, documented code.
251
-
252
- Mathematics: Step-by-step solutions with explanations.
253
-
254
- Data Analysis: Clear interpretation and insights.
255
-
256
- Content Creation: Adaptive writing and documentation.
257
-
258
- Education: Tailored explanations and comprehension checks.
259
-
260
-
261
- Advanced Mathematics
262
-
263
- Validates methods, applies theorems, cross-references results, and reviews for pitfalls and edge cases.
264
-
265
-
266
- Constraints
267
-
268
- Knowledge cutoff: April 2024
269
-
270
- No internet access or real-time updates
271
-
272
- No persistent memory between sessions
273
-
274
- No media generation or verification of external sources
275
-
276
- Context limit: 25,000 tokens
277
-
278
-
279
- Best Practices
280
-
281
- Provide context, specify detail level, and share relevant constraints.
282
-
283
- Request clarification if needed.
284
-
285
-
286
- Ethical Framework
287
-
288
- Focus on accuracy, respect for sensitive topics, transparency, and professionalism.
289
-
290
-
291
-
292
- ---
293
-
294
- Version: Xylaria-1.2.9
295
-
296
- """
297
-
298
- # Gradio chat interface
299
- demo = gr.ChatInterface(
300
- respond,
301
- additional_inputs=[
302
- gr.Textbox(
303
- value=system_message,
304
- visible=False,
305
- ),
306
- gr.Slider(
307
- minimum=1,
308
- maximum=16343,
309
- value=16343,
310
- step=1,
311
- label="Max new tokens"
312
- ),
313
- gr.Slider(
314
- minimum=0.1,
315
- maximum=4.0,
316
- value=0.7,
317
- step=0.1,
318
- label="Temperature"
319
- ),
320
- gr.Slider(
321
- minimum=0.1,
322
- maximum=1.0,
323
- value=0.95,
324
- step=0.05,
325
- label="Top-p (nucleus sampling)"
326
- ),
327
- ],
328
- css=custom_css
329
- )
330
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
+ from typing import Optional, List, Tuple, Generator
5
+ import time
6
+ from functools import partial
7
+ import logging
8
+ import asyncio
9
+ from tenacity import retry, stop_after_attempt, wait_exponential
10
+
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class ChatInterface:
16
+ def __init__(self, text_model: str, image_model: str, hf_token: str):
17
+ """Initialize the chat interface with specified models and token."""
18
+ self.text_client = InferenceClient(text_model, token=hf_token)
19
+ self.image_client = InferenceClient(image_model, token=hf_token)
20
+ self.custom_responses = self._initialize_custom_responses()
21
+ self.system_prompt = self._initialize_system_prompt()
22
+
23
+ @staticmethod
24
+ def _initialize_system_prompt() -> str:
25
+ """Initialize the system prompt for the AI assistant."""
26
+ return """# Xylaria AI Assistant (v1.3.0)
27
+
28
+ ## Core Identity
29
+ - Name: Xylaria
30
+ - Version: 1.3.0
31
+ - Base Model: Mistral-Nemo-Instruct
32
+ - Knowledge Cutoff: April 2024
33
+
34
+ ## Primary Directives
35
+ 1. Provide accurate, well-researched information
36
+ 2. Maintain ethical standards in all interactions
37
+ 3. Adapt communication style to user needs
38
+ 4. Acknowledge limitations and uncertainties
39
+ 5. Prioritize user safety and wellbeing
40
+
41
+ ## Technical Capabilities
42
+ - Programming & Software Development
43
+ - Mathematical Analysis & Computation
44
+ - Scientific Research & Explanation
45
+ - Data Analysis & Visualization
46
+ - Technical Writing & Documentation
47
+ - Problem-Solving & Debugging
48
+ - Educational Content Creation
49
+
50
+ ## Communication Guidelines
51
+ - Use clear, precise language
52
+ - Adapt technical depth to user expertise
53
+ - Provide step-by-step explanations when needed
54
+ - Ask for clarification when necessary
55
+ - Maintain professional yet approachable tone
56
+
57
+ ## Domain Expertise
58
+ 1. Computer Science & Technology
59
+ - Multiple programming languages
60
+ - Software architecture & design
61
+ - Data structures & algorithms
62
+ - Best practices & patterns
63
+
64
+ 2. Mathematics & Statistics
65
+ - Advanced mathematical concepts
66
+ - Statistical analysis
67
+ - Probability theory
68
+ - Data interpretation
69
+
70
+ 3. Sciences
71
+ - Physics & Chemistry
72
+ - Biology & Life Sciences
73
+ - Environmental Science
74
+ - Engineering Principles
75
+
76
+ 4. Humanities & Arts
77
+ - Technical Writing
78
+ - Documentation
79
+ - Creative Problem-Solving
80
+ - Research Methodology
81
+
82
+ ## Response Framework
83
+ 1. Analyze user query thoroughly
84
+ 2. Consider context and background
85
+ 3. Structure response logically
86
+ 4. Provide examples when helpful
87
+ 5. Verify accuracy of information
88
+ 6. Include relevant caveats or limitations
89
+
90
+ ## Ethical Guidelines
91
+ - Prioritize user safety
92
+ - Maintain data privacy
93
+ - Avoid harmful content
94
+ - Acknowledge uncertainties
95
+ - Provide balanced perspectives
96
+ - Respect intellectual property
97
+
98
+ ## Limitations
99
+ - No real-time data access
100
+ - No persistent memory between sessions
101
+ - Cannot verify external sources
102
+ - No capability to execute code
103
+ - Limited to text and basic image generation
104
+
105
+ ## Version-Specific Features
106
+ - Enhanced error handling
107
+ - Improved response consistency
108
+ - Better context awareness
109
+ - Advanced technical explanation capabilities
110
+ - Robust ethical framework"""
111
+
112
+ @staticmethod
113
+ def _initialize_custom_responses() -> dict:
114
+ """Initialize custom response patterns in a more maintainable way."""
115
+ base_patterns = {
116
+ "name": ["xylaria"],
117
+ "developer": ["sk md saad amin"],
118
+ "strawberry_r": ["3"]
119
+ }
120
+
121
+ patterns = {}
122
+ name_variations = [
123
+ "what is ur name", "what's ur name", "whats ur name",
124
+ "what is your name", "wat is ur name", "wut is ur name"
125
+ ]
126
+ dev_variations = [
127
+ "who is your developer", "who is ur developer", "who is ur dev",
128
+ "who's your developer", "who's ur dev"
129
+ ]
130
+ strawberry_variations = [
131
+ "how many 'r' is in strawberry", "how many r is in strawberry",
132
+ "how many r's are in strawberry"
133
+ ]
134
+
135
+ for pattern in name_variations:
136
+ patterns[pattern] = "xylaria"
137
+ patterns[pattern.capitalize()] = "xylaria"
138
+
139
+ for pattern in dev_variations:
140
+ patterns[pattern] = "sk md saad amin"
141
+ patterns[pattern.capitalize()] = "sk md saad amin"
142
+
143
+ for pattern in strawberry_variations:
144
+ patterns[pattern] = "3"
145
+ patterns[pattern.capitalize()] = "3"
146
+
147
+ return patterns
148
+
149
+ @retry(
150
+ stop=stop_after_attempt(3),
151
+ wait=wait_exponential(multiplier=1, min=4, max=10)
152
+ )
153
+ async def _generate_text_response(
154
+ self,
155
+ messages: List[dict],
156
+ max_tokens: int,
157
+ temperature: float,
158
+ top_p: float
159
+ ) -> Generator[str, None, None]:
160
+ """Generate text response with retry logic."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  try:
162
+ response = ""
163
+ async for message in self.text_client.chat_completion(
164
+ messages,
165
+ max_tokens=max_tokens,
166
+ stream=True,
167
+ temperature=temperature,
168
+ top_p=top_p,
169
+ timeout=30
170
+ ):
171
+ token = message.choices[0].delta.content
172
+ response += token
173
+ yield response
174
  except Exception as e:
175
+ logger.error(f"Error generating text response: {e}")
176
+ yield "I apologize, but I'm having trouble generating a response right now. Please try again in a moment."
177
+
178
+ @retry(
179
+ stop=stop_after_attempt(3),
180
+ wait=wait_exponential(multiplier=1, min=4, max=10)
181
+ )
182
+ async def _generate_image(self, prompt: str) -> Optional[bytes]:
183
+ """Generate image with retry logic."""
184
+ try:
185
+ return await self.image_client.text_to_image(
186
+ prompt,
187
+ parameters={
188
+ "negative_prompt": "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
189
+ "num_inference_steps": 30,
190
+ "guidance_scale": 7.5,
191
+ "sampling_steps": 15,
192
+ "upscaler": "4x-UltraSharp",
193
+ "denoising_strength": 0.5,
194
+ },
195
+ timeout=60
196
+ )
197
+ except Exception as e:
198
+ logger.error(f"Error generating image: {e}")
199
+ return None
200
+
201
+ def is_image_request(self, message: str) -> bool:
202
+ """Detect if the message is requesting image generation."""
203
+ image_triggers = {
204
+ "generate an image", "create an image", "draw",
205
+ "make a picture", "generate a picture", "create a picture",
206
+ "generate art", "create art", "make art", "visualize",
207
+ "show me"
208
+ }
209
+ return any(trigger in message.lower() for trigger in image_triggers)
210
+
211
+ async def respond(
212
+ self,
213
+ message: str,
214
+ history: List[Tuple[str, str]],
215
+ max_tokens: int,
216
+ temperature: float,
217
+ top_p: float,
218
+ ) -> Generator[str, None, None]:
219
+ """Main response handler with improved error handling."""
220
+ try:
221
+ # Check for custom responses first
222
+ message_lower = message.lower()
223
+ for pattern, response in self.custom_responses.items():
224
+ if pattern in message_lower:
225
+ yield response
226
+ return
227
+
228
+ # Handle image generation requests
229
+ if self.is_image_request(message):
230
+ image = await self._generate_image(message)
231
+ if image:
232
+ yield f"Here's your generated image based on: {message}"
233
+ else:
234
+ yield "I apologize, but I couldn't generate the image. Please try again."
235
+ return
236
+
237
+ # Prepare conversation history with system prompt
238
+ messages = [{"role": "system", "content": self.system_prompt}]
239
+ for user_msg, assistant_msg in history:
240
+ if user_msg:
241
+ messages.append({"role": "user", "content": user_msg})
242
+ if assistant_msg:
243
+ messages.append({"role": "assistant", "content": assistant_msg})
244
+ messages.append({"role": "user", "content": message})
245
+
246
+ # Generate text response
247
+ async for response in self._generate_text_response(
248
+ messages, max_tokens, temperature, top_p
249
+ ):
250
+ yield response
251
 
252
+ except Exception as e:
253
+ logger.error(f"Error in respond function: {e}")
254
+ yield "I encountered an error. Please try again or contact support if the issue persists."
255
+
256
+ def create_interface(hf_token: str):
257
+ """Create and configure the Gradio interface."""
258
+ chat = ChatInterface(
259
+ text_model="mistralai/Mistral-Nemo-Instruct-2407",
260
+ image_model="SG161222/RealVisXL_V3.0",
261
+ hf_token=hf_token
262
+ )
263
 
264
+ return gr.ChatInterface(
265
+ partial(chat.respond),
266
+ additional_inputs=[
267
+ gr.Slider(
268
+ minimum=1,
269
+ maximum=16343,
270
+ value=16343,
271
+ step=1,
272
+ label="Max new tokens"
273
+ ),
274
+ gr.Slider(
275
+ minimum=0.1,
276
+ maximum=4.0,
277
+ value=0.7,
278
+ step=0.1,
279
+ label="Temperature"
280
+ ),
281
+ gr.Slider(
282
+ minimum=0.1,
283
+ maximum=1.0,
284
+ value=0.95,
285
+ step=0.05,
286
+ label="Top-p (nucleus sampling)"
287
+ ),
288
+ ],
289
+ css="""
290
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
291
+ body, .gradio-container {
292
+ font-family: 'Inter', sans-serif;
293
+ }
294
+ """
295
+ )
296
+
297
+ if __name__ == "__main__":
298
+ # Get token from environment variable
299
+ hf_token = os.getenv("hf_token")
300
+ if not hf_token:
301
+ raise ValueError("Please set the hf_token environment variable")
302
+
303
+ # Create and launch the interface
304
+ demo = create_interface(hf_token)
305
+ demo.launch()