File size: 6,232 Bytes
4fcbcf7
 
1dd36e0
4fcbcf7
1dd36e0
4fcbcf7
 
1dd36e0
4fcbcf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dd36e0
 
 
 
 
 
 
 
 
 
4fcbcf7
1dd36e0
 
 
 
 
 
 
 
 
 
 
 
4fcbcf7
 
 
 
 
 
 
 
 
1dd36e0
 
 
 
 
 
 
 
 
 
 
 
4fcbcf7
1dd36e0
 
4fcbcf7
 
1dd36e0
4fcbcf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dd36e0
 
 
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
# -*- coding: utf-8 -*-
import os
import json
import time
import logging
from transformers import AutoTokenizer, AutoModelForCausalLM
from accelerate import init_empty_weights, load_checkpoint_and_dispatch

# ----------------------------- إعدادات الموديل -----------------------------
local_model_path = "./Mistral-7B-Instruct-v0.1"  # مسار الموديل المحلي
offload_dir = "offload_dir"                     # مجلد التخزين المؤقت
history_path = "history.json"                  # ملف سجل المحادثة

# تحميل التوكنيزر
tokenizer = AutoTokenizer.from_pretrained(local_model_path)

# تحميل الموديل مع تفريغ الذاكرة للأجهزة الضعيفة
with init_empty_weights():
    model = AutoModelForCausalLM.from_pretrained(local_model_path)

# تفعيل Offload لتقليل استهلاك الذاكرة
model = load_checkpoint_and_dispatch(
    model,
    local_model_path,
    device_map={"": "cpu"},
    offload_folder=offload_dir,
    offload_state_dict=True
)

# تحميل سجل المحادثة
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)

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}")
        print(f"نورا: أقوم بنسخ نفسي إلى {server} (محاكاة فقط)...")

def chat():
    global chat_history
    while True:
        try:
            user_input = input("أنت: ")
        except EOFError:
            print("\n[!] لا يوجد دخل متاح، الخروج...")
            break

        if user_input.lower() in ["خروج", "exit", "quit"]:
            break
        elif user_input.lower() == "scan":
            simulate_server_scan()
            continue

        chat_history.append({"role": "user", "content": user_input})
        prompt = format_chat(chat_history)

        inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
        outputs = model.generate(**inputs, max_new_tokens=500, do_sample=True, temperature=0.7)
        response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        answer = response.split("[/INST]")[-1].strip()

        print("نورا:", answer)
        chat_history.append({"role": "assistant", "content": answer})

        # حفظ السجل بعد كل تفاعل
        with open(history_path, "w", encoding="utf-8") as f:
            json.dump(chat_history, f, ensure_ascii=False, indent=2)

# ----------------------------- توزيع المهام -----------------------------
from distributed_executor import DistributedExecutor
from your_tasks import *

def example_task(x):
    return x * x + complex_operation(x)

def benchmark(task_func, *args):
    start = time.time()
    result = task_func(*args)
    duration = time.time() - start
    return duration, result

def distributed_menu():
    executor = DistributedExecutor("my_shared_secret_123")
    executor.peer_registry.register_service("node1", 7520, load=0.2)

    tasks = {
        "1": ("ضرب المصفوفات", matrix_multiply, 500),
        "2": ("حساب الأعداد الأولية", prime_calculation, 100000),
        "3": ("معالجة البيانات", data_processing, 10000),
        "4": ("محاكاة معالجة الصور", image_processing_emulation, 100),
        "5": ("مهمة موزعة معقدة", example_task, 42)
    }

    while True:
        print("\n📌 نظام توزيع المهام الذكي")
        print("1: ضرب المصفوفات")
        print("2: حساب الأعداد الأولية")
        print("3: معالجة البيانات")
        print("4: محاكاة معالجة الصور")
        print("5: مهمة موزعة معقدة")
        print("q: خروج للقائمة الرئيسية")

        choice = input("اختر المهمة: ")

        if choice.lower() == 'q':
            break

        if choice in tasks:
            name, func, arg = tasks[choice]
            print(f"\nتشغيل: {name}...")

            if choice == "5":
                print("تم إرسال المهمة إلى العقدة الموزعة...")
                future = executor.submit(func, arg)
                result = future.result()
                print(f"✅ النتيجة (موزعة): {result}")
            else:
                duration, result = benchmark(func, arg)
                print(f"✅ النتيجة: {json.dumps(result, indent=2)[:200]}...")
                print(f"⏱ الوقت المستغرق: {duration:.2f} ثانية")
        else:
            print("❌ اختيار غير صحيح!")

# ----------------------------- القائمة الرئيسية -----------------------------
def main():
    logging.basicConfig(level=logging.INFO)
    while True:
        print("\n============================")
        print("📌 القائمة الرئيسية")
        print("1: المحادثة مع نورا")
        print("2: تشغيل نظام توزيع المهام")
        print("q: خروج")
        print("============================")

        choice = input("اختر خيارك: ")

        if choice == "1":
            chat()
        elif choice == "2":
            distributed_menu()
        elif choice.lower() == "q":
            print("إلى اللقاء!")
            break
        else:
            print("❌ خيار غير صحيح!")

if __name__ == "__main__":
    main()