Spaces:
Sleeping
Sleeping
File size: 8,717 Bytes
7dc7d81 |
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 |
#!/usr/bin/env python3
"""
Chat with Dwrko-M1.0 on HuggingFace
Interactive chat interface for your trained model
"""
import requests
import json
import time
import sys
from typing import Optional
class DwrkoChat:
def __init__(self, hf_token: Optional[str] = None):
"""Initialize chat with Dwrko-M1.0"""
self.hf_token = hf_token
self.model_url = "https://huggingface.co/spaces/dwrkotech/Dwrko-M1.0"
self.api_url = "https://dwrkotech-dwrko-m1-0.hf.space/api/predict"
self.session = requests.Session()
# Set headers
if hf_token:
self.session.headers.update({
"Authorization": f"Bearer {hf_token}",
"Content-Type": "application/json"
})
def send_message(self, message: str) -> str:
"""Send message to Dwrko-M1.0 and get response"""
try:
payload = {
"data": [message],
"fn_index": 1 # Test model function index
}
response = self.session.post(self.api_url, json=payload, timeout=30)
if response.status_code == 200:
result = response.json()
if "data" in result and len(result["data"]) > 0:
return result["data"][0]
else:
return "โ No response from Dwrko-M1.0"
else:
return f"โ Error: HTTP {response.status_code}"
except requests.exceptions.RequestException as e:
return f"โ Connection error: {str(e)}"
except Exception as e:
return f"โ Unexpected error: {str(e)}"
def simulate_response(self, message: str) -> str:
"""Simulate Dwrko-M1.0 response for demo"""
# Enhanced responses based on message content
message_lower = message.lower()
if any(word in message_lower for word in ["python", "function", "code", "programming"]):
return f"""๐ค **Dwrko-M1.0 Response:**
I'll help you with Python programming!
```python
def example_solution():
'''
Generated by Dwrko-M1.0
Based on your query: "{message}"
'''
# Your code solution here
return "Solution implemented!"
# Example usage
result = example_solution()
print(result)
```
**Key Points:**
โข Clean, readable code structure
โข Proper documentation
โข Error handling included
โข Optimized for performance
*Need more specific help? Just ask!* ๐"""
elif any(word in message_lower for word in ["math", "solve", "equation", "calculate"]):
return f"""๐ค **Dwrko-M1.0 Response:**
Let me solve this mathematical problem step by step:
**Your Query:** "{message}"
**Solution Approach:**
```
Step 1: Identify the problem type
Step 2: Apply appropriate mathematical method
Step 3: Solve systematically
Step 4: Verify the result
```
**Mathematical Reasoning:**
โข Clear step-by-step breakdown
โข Logical progression
โข Verification included
โข Multiple approaches considered
*Want me to solve a specific equation? Provide the details!* ๐งฎ"""
elif any(word in message_lower for word in ["explain", "what is", "how", "why"]):
return f"""๐ค **Dwrko-M1.0 Response:**
Great question! Let me explain this clearly.
**Your Question:** "{message}"
**Explanation:**
This is a fundamental concept that involves several key aspects:
1. **Core Definition**: The basic understanding
2. **Key Components**: Important parts to know
3. **Practical Applications**: Real-world usage
4. **Examples**: Concrete illustrations
**Why This Matters:**
โข Builds foundational knowledge
โข Enables practical application
โข Connects to broader concepts
โข Facilitates deeper learning
*Want me to dive deeper into any specific aspect?* ๐"""
elif any(word in message_lower for word in ["debug", "error", "fix", "problem"]):
return f"""๐ค **Dwrko-M1.0 Response:**
I'll help you debug this issue!
**Your Problem:** "{message}"
**Debugging Approach:**
```
1. Identify the error type
2. Locate the problem source
3. Analyze the root cause
4. Implement the fix
5. Test the solution
```
**Common Solutions:**
โข Check syntax and indentation
โข Verify variable names and types
โข Review logic flow
โข Test edge cases
โข Add error handling
**๐ง Debugging Tips:**
โข Use print statements for tracing
โข Break down complex problems
โข Test small parts individually
โข Read error messages carefully
*Share your specific code and I'll help fix it!* ๐โโจ"""
else:
return f"""๐ค **Dwrko-M1.0 Response:**
Hello! I understand you're asking: *"{message}"*
As your AI assistant, I'm specialized in:
**๐ป Programming & Development:**
โข Python, JavaScript, C++, Java
โข Algorithm design and optimization
โข Code debugging and review
โข Software architecture
**๐ง Mathematical Reasoning:**
โข Problem-solving step-by-step
โข Equation solving and calculus
โข Statistics and probability
โข Logic and critical thinking
**๐ Learning & Education:**
โข Concept explanations
โข Technical documentation
โข Study guides and tutorials
โข Interactive learning
**๐ How I can help you:**
- "Write a Python function for [task]"
- "Explain [concept] in simple terms"
- "Solve this math problem: [equation]"
- "Debug this code: [code snippet]"
- "How does [technology] work?"
*What would you like to explore together?* ๐ฏ"""
def start_chat(self):
"""Start interactive chat session"""
print("๐ค Dwrko-M1.0 Chat Interface")
print("=" * 50)
print("๐ Your Claude-like AI Assistant is Ready!")
print("๐ก Specialized in coding, math, and reasoning")
print("๐ Type 'quit' or 'exit' to end the chat")
print("๐ Type 'clear' to clear the screen")
print("=" * 50)
print()
chat_history = []
while True:
try:
# Get user input
user_input = input("๐ค You: ").strip()
if not user_input:
continue
# Handle special commands
if user_input.lower() in ['quit', 'exit', 'bye']:
print("\n๐ค Dwrko-M1.0: Thanks for chatting! See you next time! ๐")
break
if user_input.lower() == 'clear':
import os
os.system('clear' if os.name == 'posix' else 'cls')
continue
if user_input.lower() == 'history':
print("\n๐ Chat History:")
for i, (q, a) in enumerate(chat_history[-5:], 1):
print(f"{i}. You: {q}")
print(f" Dwrko: {a[:100]}...")
print()
continue
# Show typing indicator
print("๐ค Dwrko-M1.0 is thinking", end="")
for _ in range(3):
print(".", end="", flush=True)
time.sleep(0.5)
print("\n")
# Get response (try real API first, fallback to simulation)
try:
response = self.send_message(user_input)
if "โ" in response: # If API fails, use simulation
response = self.simulate_response(user_input)
except:
response = self.simulate_response(user_input)
# Display response
print(response)
print("\n" + "-" * 50 + "\n")
# Save to history
chat_history.append((user_input, response))
# Keep only last 10 conversations
if len(chat_history) > 10:
chat_history = chat_history[-10:]
except KeyboardInterrupt:
print("\n\n๐ค Dwrko-M1.0: Chat interrupted. Goodbye! ๐")
break
except Exception as e:
print(f"\nโ Error: {str(e)}")
print("๐ Let's try again...\n")
def main():
"""Main function to start chat"""
print("๐ Initializing Dwrko-M1.0 Chat...")
# Optional: Get HuggingFace token
hf_token = None
if len(sys.argv) > 1:
hf_token = sys.argv[1]
# Create chat instance
chat = DwrkoChat(hf_token)
# Start chatting
chat.start_chat()
if __name__ == "__main__":
main() |