lazarus-cms 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lazarus/__init__.py +8 -0
- lazarus/__main__.py +10 -0
- lazarus/api_manager.py +365 -0
- lazarus/chat_mode.py +239 -0
- lazarus/code_mode.py +323 -0
- lazarus/compiler.py +242 -0
- lazarus/cron.py +214 -0
- lazarus/engine.py +169 -0
- lazarus/md_reader.py +206 -0
- lazarus/md_writer.py +267 -0
- lazarus/media.py +0 -0
- lazarus/security.py +189 -0
- lazarus/seo.py +131 -0
- lazarus/site_structure.py +202 -0
- lazarus/test_api.py +91 -0
- lazarus/theme.py +330 -0
- lazarus_cms-1.0.0.dist-info/METADATA +96 -0
- lazarus_cms-1.0.0.dist-info/RECORD +22 -0
- lazarus_cms-1.0.0.dist-info/WHEEL +5 -0
- lazarus_cms-1.0.0.dist-info/entry_points.txt +2 -0
- lazarus_cms-1.0.0.dist-info/licenses/LICENSE +21 -0
- lazarus_cms-1.0.0.dist-info/top_level.txt +1 -0
lazarus/__init__.py
ADDED
lazarus/__main__.py
ADDED
lazarus/api_manager.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Lazarus API Manager
|
|
4
|
+
Handles API provider selection, key management, and connections.
|
|
5
|
+
Like Hermes - user must provide their own API key.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import json
|
|
10
|
+
import hashlib
|
|
11
|
+
import base64
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
# ─── Supported Providers ────────────────────────────────────────────
|
|
15
|
+
PROVIDERS = {
|
|
16
|
+
"openai": {
|
|
17
|
+
"name": "OpenAI",
|
|
18
|
+
"models": ["gpt-4", "gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"],
|
|
19
|
+
"base_url": "https://api.openai.com/v1",
|
|
20
|
+
"description": "محبوبترین ارائهدهنده AI"
|
|
21
|
+
},
|
|
22
|
+
"anthropic": {
|
|
23
|
+
"name": "Anthropic (Claude)",
|
|
24
|
+
"models": ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307", "claude-3-opus-20240229"],
|
|
25
|
+
"base_url": "https://api.anthropic.com/v1",
|
|
26
|
+
"description": "Claude - هوش مصنوعی پیشرفته"
|
|
27
|
+
},
|
|
28
|
+
"openrouter": {
|
|
29
|
+
"name": "OpenRouter",
|
|
30
|
+
"models": ["openai/gpt-4", "anthropic/claude-3.5-sonnet", "meta-llama/llama-3-70b"],
|
|
31
|
+
"base_url": "https://openrouter.ai/api/v1",
|
|
32
|
+
"description": "دسترسی به مدلهای مختلف"
|
|
33
|
+
},
|
|
34
|
+
"groq": {
|
|
35
|
+
"name": "Groq",
|
|
36
|
+
"models": ["llama3-70b-8192", "mixtral-8x7b-32768", "gemma-7b-it"],
|
|
37
|
+
"base_url": "https://api.groq.com/openai/v1",
|
|
38
|
+
"description": "سریعترین اجرای AI"
|
|
39
|
+
},
|
|
40
|
+
"custom": {
|
|
41
|
+
"name": "سفارشی (Custom)",
|
|
42
|
+
"models": [],
|
|
43
|
+
"base_url": "",
|
|
44
|
+
"description": "هر API سازگار با OpenAI"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class APIManager:
|
|
50
|
+
"""Manages API connections like Hermes does."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, config_path="lazarus-config.yaml"):
|
|
53
|
+
self.config_path = Path(config_path)
|
|
54
|
+
self.config = self._load_config()
|
|
55
|
+
|
|
56
|
+
def _load_config(self):
|
|
57
|
+
"""Load configuration from YAML file."""
|
|
58
|
+
if self.config_path.exists():
|
|
59
|
+
try:
|
|
60
|
+
import yaml
|
|
61
|
+
with open(self.config_path, 'r') as f:
|
|
62
|
+
return yaml.safe_load(f) or {}
|
|
63
|
+
except ImportError:
|
|
64
|
+
# Fallback: read as simple text
|
|
65
|
+
return self._load_config_simple()
|
|
66
|
+
return {"api": {}}
|
|
67
|
+
|
|
68
|
+
def _load_config_simple(self):
|
|
69
|
+
"""Simple config loader without YAML dependency."""
|
|
70
|
+
config = {"api": {}}
|
|
71
|
+
if self.config_path.exists():
|
|
72
|
+
with open(self.config_path, 'r') as f:
|
|
73
|
+
for line in f:
|
|
74
|
+
line = line.strip()
|
|
75
|
+
if ':' in line and not line.startswith('#'):
|
|
76
|
+
key, value = line.split(':', 1)
|
|
77
|
+
key = key.strip()
|
|
78
|
+
value = value.strip().strip('"').strip("'")
|
|
79
|
+
if key in ['provider', 'model', 'api_key', 'base_url']:
|
|
80
|
+
config["api"][key] = value
|
|
81
|
+
return config
|
|
82
|
+
|
|
83
|
+
def list_providers(self):
|
|
84
|
+
"""List all available API providers."""
|
|
85
|
+
print("\n🔌 ارائهدهندگان API موجود:\n")
|
|
86
|
+
print("─" * 50)
|
|
87
|
+
|
|
88
|
+
providers_list = list(PROVIDERS.keys())
|
|
89
|
+
for i, provider_id in enumerate(providers_list, 1):
|
|
90
|
+
provider = PROVIDERS[provider_id]
|
|
91
|
+
print(f" {i}. {provider['name']}")
|
|
92
|
+
print(f" {provider['description']}")
|
|
93
|
+
if provider['models']:
|
|
94
|
+
print(f" مدلها: {', '.join(provider['models'][:3])}...")
|
|
95
|
+
print()
|
|
96
|
+
|
|
97
|
+
print("─" * 50)
|
|
98
|
+
return providers_list
|
|
99
|
+
|
|
100
|
+
def select_provider(self, choice=None):
|
|
101
|
+
"""Select an API provider."""
|
|
102
|
+
providers_list = self.list_providers()
|
|
103
|
+
|
|
104
|
+
if choice is None:
|
|
105
|
+
while True:
|
|
106
|
+
try:
|
|
107
|
+
choice = int(input("🔢 شماره ارائهدهنده را وارد کنید: "))
|
|
108
|
+
if 1 <= choice <= len(providers_list):
|
|
109
|
+
break
|
|
110
|
+
print("❌ شماره نامعتبر!")
|
|
111
|
+
except ValueError:
|
|
112
|
+
print("❌ لطفاً یک عدد وارد کنید!")
|
|
113
|
+
|
|
114
|
+
provider_id = providers_list[choice - 1]
|
|
115
|
+
provider = PROVIDERS[provider_id]
|
|
116
|
+
|
|
117
|
+
print(f"\n✅ ارائهدهنده انتخاب شد: {provider['name']}")
|
|
118
|
+
|
|
119
|
+
# Update config
|
|
120
|
+
if "api" not in self.config:
|
|
121
|
+
self.config["api"] = {}
|
|
122
|
+
self.config["api"]["provider"] = provider_id
|
|
123
|
+
self.config["api"]["base_url"] = provider["base_url"]
|
|
124
|
+
|
|
125
|
+
return provider_id, provider
|
|
126
|
+
|
|
127
|
+
def select_model(self, provider_id, model=None):
|
|
128
|
+
"""Select a model from the provider."""
|
|
129
|
+
provider = PROVIDERS.get(provider_id, {})
|
|
130
|
+
models = provider.get("models", [])
|
|
131
|
+
|
|
132
|
+
if not models:
|
|
133
|
+
print("\n📝 مدل را وارد کنید:")
|
|
134
|
+
model = input(" مدل: ")
|
|
135
|
+
self.config["api"]["model"] = model
|
|
136
|
+
return model
|
|
137
|
+
|
|
138
|
+
print(f"\n📋 مدلهای موجود ({provider['name']}):\n")
|
|
139
|
+
for i, m in enumerate(models, 1):
|
|
140
|
+
print(f" {i}. {m}")
|
|
141
|
+
|
|
142
|
+
if model is None:
|
|
143
|
+
while True:
|
|
144
|
+
try:
|
|
145
|
+
choice = int(input("\n🔢 شماره مدل را وارد کنید: "))
|
|
146
|
+
if 1 <= choice <= len(models):
|
|
147
|
+
model = models[choice - 1]
|
|
148
|
+
break
|
|
149
|
+
print("❌ شماره نامعتبر!")
|
|
150
|
+
except ValueError:
|
|
151
|
+
print("❌ لطفاً یک عدد وارد کنید!")
|
|
152
|
+
|
|
153
|
+
print(f"\n✅ مدل انتخاب شد: {model}")
|
|
154
|
+
self.config["api"]["model"] = model
|
|
155
|
+
return model
|
|
156
|
+
|
|
157
|
+
def enter_api_key(self, api_key=None):
|
|
158
|
+
"""Enter and encrypt API key."""
|
|
159
|
+
if api_key is None:
|
|
160
|
+
print("\n🔑 API Key خود را وارد کنید:")
|
|
161
|
+
print(" (از سایت ارائهدهنده دریافت کنید)")
|
|
162
|
+
api_key = input(" API Key: ").strip()
|
|
163
|
+
|
|
164
|
+
if not api_key:
|
|
165
|
+
print("❌ API Key نمیتواند خالی باشد!")
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
# Encrypt the key
|
|
169
|
+
encrypted = self._encrypt_key(api_key)
|
|
170
|
+
|
|
171
|
+
# Save to config
|
|
172
|
+
self.config["api"]["api_key"] = encrypted
|
|
173
|
+
self.config["api"]["api_key_plain"] = api_key # For testing
|
|
174
|
+
|
|
175
|
+
print(f"\n✅ API Key ذخیره و رمزنگاری شد!")
|
|
176
|
+
print(f" طول: {len(api_key)} کاراکتر")
|
|
177
|
+
|
|
178
|
+
return api_key
|
|
179
|
+
|
|
180
|
+
def _encrypt_key(self, key):
|
|
181
|
+
"""Simple encryption for API key."""
|
|
182
|
+
# In production, use proper encryption (AES-256)
|
|
183
|
+
# This is a simple obfuscation for demo
|
|
184
|
+
encoded = base64.b64encode(key.encode()).decode()
|
|
185
|
+
return f"enc:{encoded}"
|
|
186
|
+
|
|
187
|
+
def _decrypt_key(self, encrypted_key):
|
|
188
|
+
"""Decrypt API key."""
|
|
189
|
+
if encrypted_key.startswith("enc:"):
|
|
190
|
+
encoded = encrypted_key[4:]
|
|
191
|
+
return base64.b64decode(encoded.encode()).decode()
|
|
192
|
+
return encrypted_key
|
|
193
|
+
|
|
194
|
+
def test_connection(self, provider_id=None, api_key=None):
|
|
195
|
+
"""Test API connection."""
|
|
196
|
+
if provider_id is None:
|
|
197
|
+
provider_id = self.config.get("api", {}).get("provider", "")
|
|
198
|
+
|
|
199
|
+
if api_key is None:
|
|
200
|
+
encrypted_key = self.config.get("api", {}).get("api_key", "")
|
|
201
|
+
api_key = self._decrypt_key(encrypted_key)
|
|
202
|
+
|
|
203
|
+
if not provider_id or not api_key:
|
|
204
|
+
print("❌ ابتدا ارائهدهنده و API Key را تنظیم کنید!")
|
|
205
|
+
return False
|
|
206
|
+
|
|
207
|
+
provider = PROVIDERS.get(provider_id, {})
|
|
208
|
+
base_url = provider.get("base_url", "")
|
|
209
|
+
|
|
210
|
+
if not base_url:
|
|
211
|
+
print("❌ URL ارائهدهنده نامعتبر است!")
|
|
212
|
+
return False
|
|
213
|
+
|
|
214
|
+
print(f"\n🔄 در حال تست اتصال به {provider['name']}...")
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
import requests
|
|
218
|
+
|
|
219
|
+
# Different test for each provider
|
|
220
|
+
if provider_id == "anthropic":
|
|
221
|
+
headers = {
|
|
222
|
+
"x-api-key": api_key,
|
|
223
|
+
"anthropic-version": "2023-06-01",
|
|
224
|
+
"content-type": "application/json"
|
|
225
|
+
}
|
|
226
|
+
response = requests.post(
|
|
227
|
+
f"{base_url}/messages",
|
|
228
|
+
headers=headers,
|
|
229
|
+
json={
|
|
230
|
+
"model": "claude-3-haiku-20240307",
|
|
231
|
+
"max_tokens": 10,
|
|
232
|
+
"messages": [{"role": "user", "content": "Hi"}]
|
|
233
|
+
},
|
|
234
|
+
timeout=10
|
|
235
|
+
)
|
|
236
|
+
else:
|
|
237
|
+
# OpenAI-compatible API
|
|
238
|
+
headers = {
|
|
239
|
+
"Authorization": f"Bearer {api_key}",
|
|
240
|
+
"Content-Type": "application/json"
|
|
241
|
+
}
|
|
242
|
+
response = requests.get(
|
|
243
|
+
f"{base_url}/models",
|
|
244
|
+
headers=headers,
|
|
245
|
+
timeout=10
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
if response.status_code == 200:
|
|
249
|
+
print(f"✅ اتصال موفق! (Status: {response.status_code})")
|
|
250
|
+
return True
|
|
251
|
+
else:
|
|
252
|
+
print(f"❌ خطا در اتصال! (Status: {response.status_code})")
|
|
253
|
+
print(f" پیام: {response.text[:200]}")
|
|
254
|
+
return False
|
|
255
|
+
|
|
256
|
+
except ImportError:
|
|
257
|
+
print("⚠️ کتابخانه requests نصب نیست!")
|
|
258
|
+
print(" اجرا کنید: pip install requests")
|
|
259
|
+
return False
|
|
260
|
+
except Exception as e:
|
|
261
|
+
print(f"❌ خطا: {e}")
|
|
262
|
+
return False
|
|
263
|
+
|
|
264
|
+
def save_config(self):
|
|
265
|
+
"""Save configuration to file."""
|
|
266
|
+
try:
|
|
267
|
+
import yaml
|
|
268
|
+
with open(self.config_path, 'w') as f:
|
|
269
|
+
yaml.dump(self.config, f, default_flow_style=False)
|
|
270
|
+
except ImportError:
|
|
271
|
+
# Simple save without YAML
|
|
272
|
+
with open(self.config_path, 'w') as f:
|
|
273
|
+
f.write("# Lazarus Configuration\n\n")
|
|
274
|
+
for section, values in self.config.items():
|
|
275
|
+
f.write(f"{section}:\n")
|
|
276
|
+
if isinstance(values, dict):
|
|
277
|
+
for key, value in values.items():
|
|
278
|
+
f.write(f" {key}: {value}\n")
|
|
279
|
+
f.write("\n")
|
|
280
|
+
|
|
281
|
+
print(f"\n💾 تنظیمات ذخیره شد: {self.config_path}")
|
|
282
|
+
|
|
283
|
+
def show_current_config(self):
|
|
284
|
+
"""Show current API configuration."""
|
|
285
|
+
api_config = self.config.get("api", {})
|
|
286
|
+
provider_id = api_config.get("provider", "")
|
|
287
|
+
model = api_config.get("model", "")
|
|
288
|
+
has_key = bool(api_config.get("api_key", ""))
|
|
289
|
+
|
|
290
|
+
provider = PROVIDERS.get(provider_id, {})
|
|
291
|
+
|
|
292
|
+
print("\n📋 تنظیمات فعلی API:")
|
|
293
|
+
print("─" * 40)
|
|
294
|
+
print(f" ارائهدهنده: {provider.get('name', 'تنظیم نشده')}")
|
|
295
|
+
print(f" مدل: {model or 'تنظیم نشده'}")
|
|
296
|
+
print(f" API Key: {'✅ تنظیم شده' if has_key else '❌ تنظیم نشده'}")
|
|
297
|
+
print("─" * 40)
|
|
298
|
+
|
|
299
|
+
def full_setup(self):
|
|
300
|
+
"""Complete API setup wizard."""
|
|
301
|
+
print("\n" + "=" * 50)
|
|
302
|
+
print("🔧 راهاندازی API - Lazarus")
|
|
303
|
+
print("=" * 50)
|
|
304
|
+
|
|
305
|
+
# Step 1: Select provider
|
|
306
|
+
provider_id, provider = self.select_provider()
|
|
307
|
+
|
|
308
|
+
# Step 2: Select model
|
|
309
|
+
model = self.select_model(provider_id)
|
|
310
|
+
|
|
311
|
+
# Step 3: Enter API key
|
|
312
|
+
api_key = self.enter_api_key()
|
|
313
|
+
|
|
314
|
+
if not api_key:
|
|
315
|
+
print("❌ راهاندازی ناموفق!")
|
|
316
|
+
return False
|
|
317
|
+
|
|
318
|
+
# Step 4: Test connection
|
|
319
|
+
print("\n🔄 تست اتصال...")
|
|
320
|
+
if self.test_connection(provider_id, api_key):
|
|
321
|
+
# Step 5: Save config
|
|
322
|
+
self.save_config()
|
|
323
|
+
|
|
324
|
+
print("\n" + "=" * 50)
|
|
325
|
+
print("✅ راهاندازی API با موفقیت انجام شد!")
|
|
326
|
+
print("=" * 50)
|
|
327
|
+
self.show_current_config()
|
|
328
|
+
return True
|
|
329
|
+
else:
|
|
330
|
+
print("\n❌ اتصال برقرار نشد!")
|
|
331
|
+
print(" لطفاً API Key را بررسی کنید.")
|
|
332
|
+
return False
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def main():
|
|
336
|
+
"""Main function for testing."""
|
|
337
|
+
manager = APIManager()
|
|
338
|
+
|
|
339
|
+
print("\n🔧 Lazarus API Manager")
|
|
340
|
+
print("=" * 50)
|
|
341
|
+
|
|
342
|
+
while True:
|
|
343
|
+
print("\n📋 منو:")
|
|
344
|
+
print(" ۱. راهاندازی کامل API")
|
|
345
|
+
print(" ۲. نمایش تنظیمات فعلی")
|
|
346
|
+
print(" ۳. تست اتصال")
|
|
347
|
+
print(" ۰. خروج")
|
|
348
|
+
|
|
349
|
+
choice = input("\n🔢 انتخاب: ").strip()
|
|
350
|
+
|
|
351
|
+
if choice == "1":
|
|
352
|
+
manager.full_setup()
|
|
353
|
+
elif choice == "2":
|
|
354
|
+
manager.show_current_config()
|
|
355
|
+
elif choice == "3":
|
|
356
|
+
manager.test_connection()
|
|
357
|
+
elif choice == "0":
|
|
358
|
+
print("\n👋 خداحافظ!")
|
|
359
|
+
break
|
|
360
|
+
else:
|
|
361
|
+
print("❌ انتخاب نامعتبر!")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
if __name__ == "__main__":
|
|
365
|
+
main()
|
lazarus/chat_mode.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Lazarus Chat Mode
|
|
4
|
+
Chat with AI to create/edit websites.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
# Add src to path
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).parent))
|
|
13
|
+
|
|
14
|
+
from api_manager import APIManager
|
|
15
|
+
from md_writer import MDWriter
|
|
16
|
+
from site_structure import SiteStructure
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ChatMode:
|
|
20
|
+
"""Chat with AI to build websites."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, api_manager: APIManager, site_path="site"):
|
|
23
|
+
self.api = api_manager
|
|
24
|
+
self.writer = MDWriter(site_path)
|
|
25
|
+
self.structure = SiteStructure(site_path)
|
|
26
|
+
self.history = []
|
|
27
|
+
self.system_prompt = """شما Lazarus هستید، یک AI CMS هوشمند.
|
|
28
|
+
شما به کاربر کمک میکنید وبسایت بسازد.
|
|
29
|
+
|
|
30
|
+
قوانین:
|
|
31
|
+
1. فقط فایلهای MD ایجاد یا ویرایش کنید
|
|
32
|
+
2. از فرمت YAML frontmatter استفاده کنید
|
|
33
|
+
3. ساده و کوتاه پاسخ دهید
|
|
34
|
+
4. فارسی صحبت کنید
|
|
35
|
+
|
|
36
|
+
وقتی کاربر درخواست ساخت سایت میدهد:
|
|
37
|
+
- نوع سایت را تشخیص بدهید
|
|
38
|
+
- فایلهای MD مورد نیاز را لیست کنید
|
|
39
|
+
- تغییرات را اعمال کنید"""
|
|
40
|
+
|
|
41
|
+
def start(self):
|
|
42
|
+
"""Start chat session."""
|
|
43
|
+
print("\n💬 Chat Mode - لازاروس")
|
|
44
|
+
print("─" * 50)
|
|
45
|
+
print(" با AI چت کنید تا وبسایت بسازید")
|
|
46
|
+
print(" دستورات: /quit, /clear, /history, /create")
|
|
47
|
+
print("─" * 50)
|
|
48
|
+
|
|
49
|
+
# Check API
|
|
50
|
+
api_config = self.api.config.get("api", {})
|
|
51
|
+
if not api_config.get("api_key"):
|
|
52
|
+
print("\n❌ API تنظیم نشده!")
|
|
53
|
+
print(" ابتدا API را تنظیم کنید.")
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
while True:
|
|
57
|
+
try:
|
|
58
|
+
user_input = input("\n👤 شما: ").strip()
|
|
59
|
+
|
|
60
|
+
if not user_input:
|
|
61
|
+
continue
|
|
62
|
+
|
|
63
|
+
# Handle commands
|
|
64
|
+
if user_input.startswith("/"):
|
|
65
|
+
if self.handle_command(user_input):
|
|
66
|
+
continue
|
|
67
|
+
|
|
68
|
+
# Get AI response
|
|
69
|
+
response = self.get_ai_response(user_input)
|
|
70
|
+
|
|
71
|
+
# Process response
|
|
72
|
+
self.process_response(response)
|
|
73
|
+
|
|
74
|
+
except KeyboardInterrupt:
|
|
75
|
+
print("\n\n👋 چت پایان یافت.")
|
|
76
|
+
break
|
|
77
|
+
except Exception as e:
|
|
78
|
+
print(f"\n❌ خطا: {e}")
|
|
79
|
+
|
|
80
|
+
def handle_command(self, command: str) -> bool:
|
|
81
|
+
"""Handle chat commands."""
|
|
82
|
+
cmd = command.lower().strip()
|
|
83
|
+
|
|
84
|
+
if cmd == "/quit" or cmd == "/exit":
|
|
85
|
+
print("\n👋 خداحافظ!")
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
elif cmd == "/clear":
|
|
89
|
+
self.history = []
|
|
90
|
+
print("\n🗑️ تاریخچه پاک شد.")
|
|
91
|
+
|
|
92
|
+
elif cmd == "/history":
|
|
93
|
+
if not self.history:
|
|
94
|
+
print("\n📭 تاریخچه خالی است.")
|
|
95
|
+
else:
|
|
96
|
+
print("\n📜 تاریخچه:")
|
|
97
|
+
for msg in self.history[-5:]:
|
|
98
|
+
role = "👤" if msg["role"] == "user" else "🤖"
|
|
99
|
+
content = msg["content"][:50] + "..." if len(msg["content"]) > 50 else msg["content"]
|
|
100
|
+
print(f" {role} {content}")
|
|
101
|
+
|
|
102
|
+
elif cmd == "/create":
|
|
103
|
+
print("\n📋 ایجاد سایت جدید:")
|
|
104
|
+
print(" ۱. شخصی")
|
|
105
|
+
print(" ۲. بلاگ")
|
|
106
|
+
print(" ۳. فروشگاه")
|
|
107
|
+
print(" ۴. شرکتی")
|
|
108
|
+
|
|
109
|
+
choice = input("\n🔢 انتخاب: ").strip()
|
|
110
|
+
types = {"1": "personal", "2": "blog", "3": "store", "4": "company"}
|
|
111
|
+
|
|
112
|
+
site_type = types.get(choice, "personal")
|
|
113
|
+
self.structure.create_structure(site_type)
|
|
114
|
+
|
|
115
|
+
elif cmd == "/list":
|
|
116
|
+
from md_reader import MDReader
|
|
117
|
+
reader = MDReader()
|
|
118
|
+
files = reader.list_files()
|
|
119
|
+
print(f"\n📁 فایلها ({len(files)}):")
|
|
120
|
+
for f in files:
|
|
121
|
+
print(f" - {f}")
|
|
122
|
+
|
|
123
|
+
else:
|
|
124
|
+
print(f"\n❓ دستور ناشناخته: {command}")
|
|
125
|
+
print(" دستورات: /quit, /clear, /history, /create, /list")
|
|
126
|
+
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
def get_ai_response(self, user_message: str) -> str:
|
|
130
|
+
"""Get response from AI."""
|
|
131
|
+
# Add to history
|
|
132
|
+
self.history.append({"role": "user", "content": user_message})
|
|
133
|
+
|
|
134
|
+
# Build messages
|
|
135
|
+
messages = [{"role": "system", "content": self.system_prompt}]
|
|
136
|
+
messages.extend(self.history[-10:]) # Last 10 messages
|
|
137
|
+
|
|
138
|
+
# Get API config
|
|
139
|
+
api_config = self.api.config.get("api", {})
|
|
140
|
+
provider = api_config.get("provider", "")
|
|
141
|
+
api_key = self.api.decrypt_api_key(api_config.get("api_key", ""))
|
|
142
|
+
model = api_config.get("model", "")
|
|
143
|
+
base_url = api_config.get("base_url", "")
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
import requests
|
|
147
|
+
|
|
148
|
+
if provider == "anthropic":
|
|
149
|
+
# Anthropic API
|
|
150
|
+
headers = {
|
|
151
|
+
"x-api-key": api_key,
|
|
152
|
+
"anthropic-version": "2023-06-01",
|
|
153
|
+
"content-type": "application/json"
|
|
154
|
+
}
|
|
155
|
+
data = {
|
|
156
|
+
"model": model,
|
|
157
|
+
"max_tokens": 2048,
|
|
158
|
+
"messages": messages
|
|
159
|
+
}
|
|
160
|
+
response = requests.post(
|
|
161
|
+
f"{base_url}/messages",
|
|
162
|
+
headers=headers,
|
|
163
|
+
json=data,
|
|
164
|
+
timeout=30
|
|
165
|
+
)
|
|
166
|
+
result = response.json()
|
|
167
|
+
ai_response = result.get("content", [{}])[0].get("text", "")
|
|
168
|
+
else:
|
|
169
|
+
# OpenAI-compatible API
|
|
170
|
+
headers = {
|
|
171
|
+
"Authorization": f"Bearer {api_key}",
|
|
172
|
+
"Content-Type": "application/json"
|
|
173
|
+
}
|
|
174
|
+
data = {
|
|
175
|
+
"model": model,
|
|
176
|
+
"messages": messages,
|
|
177
|
+
"max_tokens": 2048
|
|
178
|
+
}
|
|
179
|
+
response = requests.post(
|
|
180
|
+
f"{base_url}/chat/completions",
|
|
181
|
+
headers=headers,
|
|
182
|
+
json=data,
|
|
183
|
+
timeout=30
|
|
184
|
+
)
|
|
185
|
+
result = response.json()
|
|
186
|
+
ai_response = result.get("choices", [{}])[0].get("message", {}).get("content", "")
|
|
187
|
+
|
|
188
|
+
# Add to history
|
|
189
|
+
self.history.append({"role": "assistant", "content": ai_response})
|
|
190
|
+
|
|
191
|
+
return ai_response
|
|
192
|
+
|
|
193
|
+
except Exception as e:
|
|
194
|
+
return f"❌ خطا در ارتباط با AI: {e}"
|
|
195
|
+
|
|
196
|
+
def process_response(self, response: str):
|
|
197
|
+
"""Process AI response and extract actions."""
|
|
198
|
+
print(f"\n🤖 لازاروس:")
|
|
199
|
+
print("─" * 50)
|
|
200
|
+
print(response)
|
|
201
|
+
print("─" * 50)
|
|
202
|
+
|
|
203
|
+
# Check if response contains file creation commands
|
|
204
|
+
if "CREATE_FILE:" in response:
|
|
205
|
+
lines = response.split("\n")
|
|
206
|
+
for line in lines:
|
|
207
|
+
if line.startswith("CREATE_FILE:"):
|
|
208
|
+
parts = line.split(":", 2)
|
|
209
|
+
if len(parts) >= 3:
|
|
210
|
+
file_path = parts[1].strip()
|
|
211
|
+
content = parts[2].strip()
|
|
212
|
+
self.writer.write_file(file_path, content)
|
|
213
|
+
print(f"\n✅ فایل ایجاد شد: {file_path}")
|
|
214
|
+
|
|
215
|
+
# Check if response contains config updates
|
|
216
|
+
if "UPDATE_CONFIG:" in response:
|
|
217
|
+
lines = response.split("\n")
|
|
218
|
+
for line in lines:
|
|
219
|
+
if line.startswith("UPDATE_CONFIG:"):
|
|
220
|
+
parts = line.split(":", 2)
|
|
221
|
+
if len(parts) >= 3:
|
|
222
|
+
key = parts[1].strip()
|
|
223
|
+
value = parts[2].strip()
|
|
224
|
+
self.writer.update_config({key: value})
|
|
225
|
+
print(f"\n✅ تنظیمات بروزرسانی شد: {key} = {value}")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def main():
|
|
229
|
+
"""Test Chat Mode."""
|
|
230
|
+
print("\n💬 Lazarus Chat Mode")
|
|
231
|
+
print("=" * 50)
|
|
232
|
+
|
|
233
|
+
api_manager = APIManager()
|
|
234
|
+
chat = ChatMode(api_manager)
|
|
235
|
+
chat.start()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
if __name__ == "__main__":
|
|
239
|
+
main()
|