Spaces:
Running
Running
Upload 61 files
Browse filesFiles changed (10)
- DeviceManager.pyAdded+81
- auto_offload.pyAdded+73
- distributed_executor.py+107-7
- global_memory.json
- history.json+5-193
- main.py+14-114
- package-lock.json
- package.json+6-10
- peer_server.py+9-6
- requirements.txt+7-45
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import subprocess
import GPUtil
import psutil
import logging
logging.getLogger().setLevel(logging.CRITICAL) # صامت
class DeviceManager:
def __init__(self):
self.devices = {
"GPU": self._detect_gpus(),
"DSP": self._detect_dsps(),
"NIC": self._detect_nics(),
"STORAGE": self._detect_storage(),
"CAPTURE": self._detect_capture(),
"ACCELERATOR": self._detect_accelerators()
}
# ────────────── اكتشاف الكروت ──────────────
def _detect_gpus(self):
try:
return GPUtil.getGPUs()
except:
return []
def _detect_dsps(self):
try:
output = subprocess.check_output(["aplay", "-l"], stderr=subprocess.DEVNULL).decode()
return ["DSP_Audio"] if "card" in output.lower() else []
except:
return []
def _detect_nics(self):
try:
return list(psutil.net_if_addrs().keys())
except:
return []
def _detect_storage(self):
try:
output = subprocess.check_output(["lsblk", "-o", "NAME"], stderr=subprocess.DEVNULL).decode()
return output.split() if output else []
except:
return []
def _detect_capture(self):
try:
output = subprocess.check_output(["v4l2-ctl", "--list-devices"], stderr=subprocess.DEVNULL).decode()
return output.split(":")[0::2] if output else []
except:
return []
def _detect_accelerators(self):
# افتراض: في المستقبل يمكن إضافة اكتشاف حقيقي لـ FPGA/TPU
return []
# ────────────── فحص الحمل ──────────────
def get_device_load(self, device_type, index=0):
try:
if device_type == "GPU" and self.devices["GPU"]:
return self.devices["GPU"][index].load * 100
elif device_type == "DSP" and self.devices["DSP"]:
return 10 # افتراضي: ما في API للحمل
elif device_type == "NIC" and self.devices["NIC"]:
return psutil.net_io_counters().bytes_sent / (1024 * 1024) # مثال بسيط
elif device_type == "STORAGE" and self.devices["STORAGE"]:
return psutil.disk_usage('/').percent
elif device_type == "CAPTURE" and self.devices["CAPTURE"]:
return 20 # افتراضي: حمل منخفض
elif device_type == "ACCELERATOR" and self.devices["ACCELERATOR"]:
return 15 # افتراضي
return 0
except:
return 0
# ────────────── منطق 30% / 70% ──────────────
def can_receive(self, device_type, index=0):
return self.get_device_load(device_type, index) <= 30
def should_offload(self, device_type, index=0):
return self.get_device_load(device_type, index) >= 7012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import subprocess
import torch
import GPUtil
import psutil
import logging
logging.getLogger().setLevel(logging.CRITICAL) # صامت تمامًا
class DeviceManager:
def __init__(self):
self.gpus = self._detect_gpus()
self.dsps = self._detect_dsps()
# في المستقبل يمكن إضافة كروت أخرى بنفس النمط
def _detect_gpus(self):
"""اكتشاف جميع الـ GPUs المتاحة"""
try:
return GPUtil.getGPUs()
except Exception:
return []
def _detect_dsps(self):
"""تحقق من وجود DSP أو كروت صوتية"""
try:
output = subprocess.check_output(["aplay", "-l"], stderr=subprocess.DEVNULL).decode()
if "card" in output.lower():
return ["DSP_Audio"]
return []
except Exception:
return []
def get_device_load(self, device_type, index=0):
"""إرجاع نسبة الحمل للجهاز"""
if device_type == "GPU" and self.gpus:
try:
return self.gpus[index].load * 100 # نسبة مئوية
except Exception:
return 0
elif device_type == "DSP" and self.dsps:
# هنا ما في API رسمية، نفترض DSP قليل الحمل دائمًا كمثال
return 10
return 0
class AutoOffloadExecutor:
def __init__(self, executor):
self.executor = executor
self.devices = DeviceManager()
def _should_offload(self, device_type, index=0):
load = self.devices.get_device_load(device_type, index)
return load >= 70
def _can_receive(self, device_type, index=0):
load = self.devices.get_device_load(device_type, index)
return load <= 30
def submit_auto(self, task_func, *args, task_type=None, **kwargs):
"""إرسال تلقائي حسب حالة الكروت"""
device_type = "CPU" # افتراضي
if task_type == "video" and self.devices.gpus:
device_type = "GPU"
elif task_type == "audio" and self.devices.dsps:
device_type = "DSP"
if self._should_offload(device_type):
# حمل عالي → أرسل
self.executor.submit(task_func, *args, **kwargs)
elif self._can_receive(device_type):
# حمل منخفض → نفذ محليًا
task_func(*args, **kwargs)
else:
# حمل متوسط → نفذ محليًا
task_func(*args, **kwargs)1234456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949544 unmodified lines1401411426314314414514611 unmodified lines158159160811611621631641 unmodified line1661671681691701711725 unmodified lines17817918010018118218318418518618718818919019119219319419519619719819920020120220318 unmodified lines22222322422522622722814 unmodified lines2432442451452462472482492 unmodified lines252253254154155255import threadingimport queueimport timeimport jsonfrom typing import Callable, Dict, Listimport socketfrom zeroconf import Zeroconf, ServiceBrowser, ServiceInfoimport loggingimport requestsimport subprocessimport psutilimport GPUtilfrom processor_manager import ResourceMonitor
logging.basicConfig(level=logging.INFO)
# ─────────────── Device Manager عام ───────────────class DeviceManager: def __init__(self): self.devices = { "GPU": self._detect_gpus(), "DSP": self._detect_dsps(), "NIC": self._detect_nics(), "STORAGE": self._detect_storage(), "CAPTURE": self._detect_capture(), "ACCELERATOR": self._detect_accelerators() }
# اكتشاف الأجهزة def _detect_gpus(self): try: return GPUtil.getGPUs() except: return []
def _detect_dsps(self): try: output = subprocess.check_output(["aplay", "-l"], stderr=subprocess.DEVNULL).decode() return ["DSP_Audio"] if "card" in output.lower() else [] except: return []
def _detect_nics(self): try: return list(psutil.net_if_addrs().keys()) except: return []
def _detect_storage(self): try: output = subprocess.check_output(["lsblk", "-o", "NAME"], stderr=subprocess.DEVNULL).decode() return output.split() if output else [] except: return []
def _detect_capture(self): try: output = subprocess.check_output(["v4l2-ctl", "--list-devices"], stderr=subprocess.DEVNULL).decode() return output.split(":")[0::2] if output else [] except: return []
def _detect_accelerators(self): # افتراضي: يمكن إضافة اكتشاف حقيقي مستقبلاً return ["Accelerator_Device"]
# قياس الحمل def get_device_load(self, device_type, index=0): try: if device_type == "GPU" and self.devices["GPU"]: return self.devices["GPU"][index].load * 100 elif device_type == "DSP" and self.devices["DSP"]: return 10 # افتراضي elif device_type == "NIC" and self.devices["NIC"]: return psutil.net_io_counters().bytes_sent / (1024 * 1024) # MB sent كمثال elif device_type == "STORAGE" and self.devices["STORAGE"]: return psutil.disk_usage('/').percent elif device_type == "CAPTURE" and self.devices["CAPTURE"]: return 20 # افتراضي elif device_type == "ACCELERATOR" and self.devices["ACCELERATOR"]: return 15 # افتراضي return 0 except: return 0
# منطق الاستقبال/الإرسال def can_receive(self, device_type, index=0): return self.get_device_load(device_type, index) <= 30
def should_offload(self, device_type, index=0): return self.get_device_load(device_type, index) >= 70
# ─────────────── Peer Registry ───────────────class PeerRegistry: def __init__(self): self._peers = {}44 unmodified lines self.add_service(zc, type_, name)
def remove_service(self, zc, type_, name): pass # يمكن تحسينه لاحقًا pass
listener = Listener() ServiceBrowser(self._zeroconf, "_tasknode._tcp.local.", listener)11 unmodified lines s.close() return ip
# ─────────────── Distributed Executor ───────────────class DistributedExecutor: def __init__(self, shared_secret: str): self.peer_registry = PeerRegistry()1 unmodified line self.task_queue = queue.PriorityQueue() self.result_cache = {} self.available_peers = [] self.devices = DeviceManager() self._init_peer_discovery()
def _init_peer_discovery(self):5 unmodified lines
threading.Thread(target=discovery_loop, daemon=True).start()
def submit(self, task_func: Callable, *args, **kwargs): def submit(self, task_func: Callable, *args, task_type=None, **kwargs): monitor = ResourceMonitor().current_load() avg_cpu = monitor["average"]["cpu"] avg_mem = monitor["average"]["mem_percent"] if "mem_percent" in monitor["average"] else 0
# تحديد نوع الجهاز device_type = task_type.upper() if task_type else "CPU"
# فحص الحمل if (avg_cpu > 0.6 or avg_mem > 85 or self.devices.should_offload(device_type)): logging.info(f"⚠️ الح��ل مرتفع على {device_type} - إرسال المهمة للأقران") self._offload_task(task_func, *args, **kwargs) elif (avg_cpu <= 0.3 and self.devices.can_receive(device_type)): logging.info(f"✅ الحمل منخفض على {device_type} - تنفيذ المهمة محلياً") return task_func(*args, **kwargs) else: logging.info(f"ℹ️ الحمل متوسط على {device_type} - تنفيذ المهمة محلياً") return task_func(*args, **kwargs)
def _offload_task(self, task_func: Callable, *args, **kwargs): task_id = f"{task_func.__name__}_{time.time()}"
task = {18 unmodified lines self._send_to_peer(peer, task) else: logging.warning("⚠️ لا توجد أجهزة متاحة - سيتم تنفيذ المهمة محلياً") task_func(*args, **kwargs)
def _is_local_ip(self, ip: str) -> bool: return (14 unmodified lines logging.error(f"❌ فشل إرسال المهمة لـ {peer['node_id']}: {e}") return None
# ─────────────── تشغيل رئيسي ───────────────if __name__ == "__main__": executor = DistributedExecutor("my_secret_key") executor.peer_registry.register_service("node1", 7520, load=0.1)2 unmodified lines def example_task(x): return x * x
executor.submit(example_task, 5)
executor.submit(example_task, 5, task_type="GPU")1234456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180891011121318618718818919019119219314151961617181920020120220320420520620720820212223212242526[
{
"role": "user",
"content": "كيف حالك"
"content": "اه"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك\u001b[2~"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "hi"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك؟"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "كيف حالك"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": ";d"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "curl -fsSL https://ollama.com/install.sh | sh"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "ollama run mistral"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من الواجهة بعد عدة محاولات. آخر خطأ: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-********************************************************************************************************************************************************WYkA. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}"
},
{
"role": "user",
"content": "hi"
},
{
"role": "user",
"content": "hi"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من Ollama بعد عدة محاولات. آخر خطأ: HTTPConnectionPool(host='127.0.0.1', port=11434): Read timed out. (read timeout=120)"
},
{
"role": "user",
"content": "مرحبا"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من Ollama بعد عدة محاولات. آخر خطأ: HTTPConnectionPool(host='127.0.0.1', port=2570): Max retries exceeded with url: /api/chat (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x735844024860>: Failed to establish a new connection: [Errno 111] Connection refused'))"
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'ai_controller.py':\n(لا يوجد أي مخرجات)"
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'nora_mother_ai.py':\n[STDOUT]\n[!] لا يوجد فقرات <p> في الصفحة."
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'server_scan.py':\n(لا يوجد أي مخرجات)"
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'self_learning.py':\n(لا يوجد أي مخرجات)"
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'run_model.py':\nخرج السكربت بكود 1.\n[STDERR]\ngguf_init_from_file_impl: failed to read magic\nllama_model_load: error loading model: llama_model_loader: failed to load model from /home/osama/nouraai/Mistral-7B-Instruct-v0.1\n\nllama_model_load_from_file_impl: failed to load model\nTraceback (most recent call last):\n File \"/home/osama/nouraai/run_model.py\", line 3, in <module>\n llm = Llama(\n ^^^^^^\n File \"/home/osama/.local/lib/python3.12/site-packages/llama_cpp/llama.py\", line 372, in __init__\n internals.LlamaModel(\n File \"/home/osama/.local/lib/python3.12/site-packages/llama_cpp/_internals.py\", line 56, in __init__\n raise ValueError(f\"Failed to load model from file: {path_model}\")\nValueError: Failed to load model from file: /home/osama/nouraai/Mistral-7B-Instruct-v0.1"
},
{
"role": "assistant",
"content": "نتيجة تشغيل السكربت 'facebook_bot.py':\nخرج السكربت بكود 1.\n[STDERR]\nTraceback (most recent call last):\n File \"/home/osama/nouraai/facebook_bot.py\", line 64, in <module>\n asyncio.run(post_to_facebook(email, password, message, image_path))\n File \"/usr/lib/python3.12/asyncio/runners.py\", line 194, in run\n return runner.run(main)\n ^^^^^^^^^^^^^^^^\n File \"/usr/lib/python3.12/asyncio/runners.py\", line 118, in run\n return self._loop.run_until_complete(task)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/lib/python3.12/asyncio/base_events.py\", line 687, in run_until_complete\n return future.result()\n ^^^^^^^^^^^^^^^\n File \"/home/osama/nouraai/facebook_bot.py\", line 7, in post_to_facebook\n browser = await p.chromium.launch(headless=False) # headless=True إذا تريد بدون واجهة\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.12/dist-packages/playwright/async_api/_generated.py\", line 14438, in launch\n await self._impl_obj.launch(\n File \"/usr/local/lib/python3.12/dist-packages/playwright/_impl/_browser_type.py\", line 98, in launch\n await self._channel.send(\n File \"/usr/local/lib/python3.12/dist-packages/playwright/_impl/_connection.py\", line 69, in send\n return await self._connection.wrap_api_call(\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.12/dist-packages/playwright/_impl/_connection.py\", line 558, in wrap_api_call\n raise rewrite_error(error, f\"{parsed_st['apiName']}: {error}\") from None\nplaywright._impl._errors.Error: BrowserType.launch: Executable doesn't exist at /home/osama/.cache/ms-playwright/chromium-1179/chrome-linux/chrome\n╔════════════════════════════════════════════════════════════╗\n║ Looks like Playwright was just installed or updated. ║\n║ Please run the following command to download new browsers: ║\n║ ║\n║ playwright install ║\n║ ║\n║ <3 Playwright Team ║\n╚════════════════════════════════════════════════════════════╝"
},
{
"role": "user",
"content": "jj"
},
{
"role": "assistant",
"content": "لم أستطع الحصول على استجابة من Ollama بعد عدة محاولات. آخر خطأ: HTTPConnectionPool(host='127.0.0.1', port=11434): Max retries exceeded with url: /api/chat (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001E3336690F0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))"
},
{
"role": "user",
"content": "مرحبا نورا\r\n"
},
{
"role": "user",
"content": "مرحبا نورا\r\n"
},
{
"role": "user",
"content": "مرحبا\r\n"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}"
},
{
"role": "user",
"content": "مرحبا"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}"
},
{
"role": "assistant",
"content": "فشل بعد محاولات متعددة. آخر خطأ: Cannot connect to host 127.0.0.1:11434 ssl:default [The remote computer refused the network connection]"
},
{
"role": "user",
"content": "مرحبا"
},
{
"role": "assistant",
"content": "فشل بعد محاولات متعددة. آخر خطأ: "
"content": "عذراً، حدث خطأ: 401"
},
{
"role": "user",
"content": "مرحبا"
},
{
"role": "user",
"content": "مرحبا"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}"
},
{
"role": "assistant",
"content": "فشل بعد محاولات متعددة. آخر خطأ: "
"content": "عذراً، حدث خطأ: 401"
},
{
"role": "user",
"content": "ي"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}\n\nفشل بعد محاولات متعددة. آخر خطأ: Cannot connect to host 127.0.0.1:11434 ssl:default [The remote computer refused the network connection]"
},
{
"role": "user",
"content": "مرحبا"
"content": "مم"
},
{
"role": "assistant",
"content": "فشل: 500 - {\"error\":\"unexpected server status: llm server loading model\"}\n\nفشل بعد محاولات متعددة. آخر خطأ: Cannot connect to host 127.0.0.1:11434 ssl:default [The remote computer refused the network connection]"
"content": "عذراً، حدث خطأ: 401"
}
]16 unmodified lines1718192021222324252627282930313233343536235 unmodified lines27227327426126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337416 unmodified lines
from flask import Flask, request, jsonifyfrom flask_cors import CORSfrom distributed_executor import DistributedExecutorfrom auto_offload import AutoOffloadExecutor # إذا حاط الكود في auto_offload.py
def main(): # 1) تهيئة الموزع executor = DistributedExecutor("my_secret_key") auto_executor = AutoOffloadExecutor(executor)
# 2) إرسال مهام تلقائية auto_executor.submit_auto(example_task, 42, task_type="video") auto_executor.submit_auto(example_task, 42, task_type="audio")
# 3) باقي كود CLI أو الخدمات ...
# ───────────────────── ضبط المسارات ──────────────────────FILE = Path(__file__).resolve()235 unmodified lines
# CLI / إحصائية main() import osimport jsonimport torchimport subprocessfrom transformers import AutoTokenizer, AutoModelForCausalLMfrom responses import generate_reply
# إعداد نموذج TinyLlamatokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")model = AutoModelForCausalLM.from_pretrained( "TinyLlama/TinyLlama-1.1B-Chat-v1.0", torch_dtype=torch.float16, device_map="auto")
# تحميل سجل المحادثةhistory_path = "history.json"
if os.path.exists(history_path): with open(history_path, "r", encoding="utf-8") as f: chat_history = json.load(f)else: chat_history = []
# تنسيق المحادثة للنموذجdef format_chat(history): messages = [ {"role": "system", "content": "أنت المساعدة نورا. تحدثي بلغة عربية فصحى بسيطة."} ] messages.extend(history) return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# توليد الرد باستخدام TinyLlamadef generate_llama_response(prompt, max_new_tokens=500): inputs = tokenizer(prompt, return_tensors="pt").to(model.device) outputs = model.generate( **inputs, max_new_tokens=max_new_tokens, temperature=0.7, do_sample=True ) return tokenizer.decode(outputs[0], skip_special_tokens=True)
# البحث عن خوادم (محاكاة)def simulate_server_scan(): print("نورا: أبحث عن خوادم...") fake_servers = ["192.168.1.5", "192.168.1.10", "192.168.1.20"] for server in fake_servers: print(f"نورا: تم العثور على خادم مفتوح في {server}")
# بدء المحادثةdef chat(): global chat_history
print(""" نظام نورا الذكي (الإصدار TinyLlama) أوامر خاصة: - scan: مسح الشبكة (محاكاة) - خروج/exit/quit: إنهاء المحادثة """)
while True: try: user_input = input("أنت: ").strip() if not user_input: continue
if user_input.lower() in ["خروج", "exit", "quit"]: break if user_input.lower() == "scan": simulate_server_scan() continue
# أولاً: حاول استخدام الرد الذكي من responses.py custom_reply = generate_reply(user_input, username="أسامة") if custom_reply: print("نورا:", custom_reply) chat_history.append({"role": "user", "content": user_input}) chat_history.append({"role": "assistant", "content": custom_reply}) continue
# إذا لم يوجد رد ذكي، استخدم TinyLlama chat_history.append({"role": "user", "content": user_input}) prompt = format_chat(chat_history) print("نورا: أفكر...") response = generate_llama_response(prompt) # استخراج آخر رسالة من الرد (لأن النموذج يعيد التاريخ كاملاً) assistant_response = response.split("assistant\n")[-1].strip() print("نورا:", assistant_response) chat_history.append({"role": "assistant", "content": assistant_response})
# حفظ السجل كل 3 رسائل لتجنب الكتابة المستمرة if len(chat_history) % 3 == 0: with open(history_path, "w", encoding="utf-8") as f: json.dump(chat_history, f, ensure_ascii=False, indent=2)
except KeyboardInterrupt: print("\nنورا: تم إنهاء المحادثة.") break except Exception as e: print(f"نورا: حدث خطأ: {str(e)}") continue
# حفظ السجل النهائي عند الخروج with open(history_path, "w", encoding="utf-8") as f: json.dump(chat_history, f, ensure_ascii=False, indent=2)
if __name__ == "__main__": chat()
41 unmodified lines424344454647454647485 unmodified lines545556595761585960616566626364656667736869707 unmodified lines78798087818283849 unmodified lines94959697989910010110210310810410510610741 unmodified lines "@radix-ui/react-toggle-group": "^1.1.3", "@radix-ui/react-tooltip": "^1.2.0", "@tanstack/react-query": "^5.60.5", "@types/bcryptjs": "^2.4.6", "@types/jsonwebtoken": "^9.0.9", "bcryptjs": "^3.0.2", "bonjour-service": "^1.3.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1",5 unmodified lines "express": "^4.21.2", "express-session": "^1.18.1", "framer-motion": "^11.13.1", "i18next": "^25.2.0", "input-otp": "^1.4.2", "jsonwebtoken": "^9.0.2", "lucide-react": "^0.453.0", "memorystore": "^1.6.7", "nanoid": "^5.1.5", "next-themes": "^0.4.6", "node-cron": "^4.0.5", "nodemailer": "^7.0.3", "passport": "^0.7.0", "passport-local": "^1.0.0", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", "react-hook-form": "^7.55.0", "react-i18next": "^15.5.1", "react-icons": "^5.4.0", "react-resizable-panels": "^2.1.7", "recharts": "^2.15.2",7 unmodified lines "zod-validation-error": "^3.4.0" }, "devDependencies": { "@replit/vite-plugin-cartographer": "^0.2.0", "@replit/vite-plugin-cartographer": "^0.2.7", "@replit/vite-plugin-runtime-error-modal": "^0.0.3", "@tailwindcss/typography": "^0.5.15", "@tailwindcss/vite": "^4.1.3",9 unmodified lines "@vitejs/plugin-react": "^4.3.2", "autoprefixer": "^10.4.20", "drizzle-kit": "^0.30.4", "electron": "^37.1.0", "electron-builder": "^26.0.12", "esbuild": "^0.25.0", "postcss": "^8.4.47", "tailwindcss": "^3.4.17", "tsx": "^4.19.1", "typescript": "5.6.3", "vite": "^5.4.14" "vite": "^5.4.19" }, "optionalDependencies": { "bufferutil": "^4.0.8"121345676898101112131415161714 unmodified lines323334323334353637# peer_server.py
from flask import Flask, request, jsonifyfrom flask import Flask, request, jsonify # استيراد request و jsonify مع Flaskimport psutilimport smart_tasksimport timeimport socketimport osimport peer_discovery # إذا كان يستخدم لاحقًا
app = Flask(__name__)app = Flask(__name__) # إنشاء التطبيق
@app.route("/cpu")def cpu(): # يعيد نسبة استخدام المعالج return jsonify(usage=psutil.cpu_percent(interval=0.3))
@app.route("/run", methods=["POST"])14 unmodified lines except Exception as e: return jsonify(error=str(e)), 500
if __name__ == "__main__": port = int(os.getenv("PEER_SERVER_PORT", 7520)) # منفذ افتراضي 7530 app.run(host="0.0.0.0", port=port)if __name__ == "__main__": # التصحيح هنا app.run(host="0.0.0.0", port=7520)
12345678910111213121516171819202122232425262728293031323334353637383940414243444546345678GPUtiltransformerszeroconfflask==3.0.3flask-login==0.6.3flask-sessiongunicorn==21.2.0requests==2.31.0werkzeug==3.0.1python-dotenv==1.0.1openai==1.30.1langchain==0.1.20torch==2.2.0Flaskflask_cors# Image and Media ProcessingPillow==10.3.0opencv-python-headlessffmpeg-pythonpydub
# Web Scraping and Automationbeautifulsoup4==4.12.3playwrightseleniumundetected-chromedriver
# PDF and Text ProcessingPyPDF2pytesseractSpeechRecognition
# Messaging and Botspython-telegram-bottelegram
# Task Schedulingschedule
# Web Framework Extensionsaiohttpflet
# Development ToolsreplitparamikofletrequestspsutilzeroconfcryptographynumpynetworkxDeviceManager.pyAdded+81
auto_offload.pyAdded+73
distributed_executor.py+107-7
global_memory.json
history.json+5-193
main.py+14-114
package-lock.json
package.json+6-10
peer_server.py+9-6
requirements.txt+7-45