File size: 14,175 Bytes
19dcc9f
1e68797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19dcc9f
1e68797
 
19dcc9f
 
1e68797
 
 
 
19dcc9f
1e68797
 
c15c04b
19dcc9f
1e68797
19dcc9f
 
1e68797
 
19dcc9f
1e68797
c15c04b
19dcc9f
874332e
19dcc9f
 
 
1e68797
 
 
 
 
 
19dcc9f
1e68797
 
19dcc9f
 
1e68797
 
19dcc9f
 
 
1e68797
19dcc9f
1e68797
19dcc9f
 
1e68797
19dcc9f
1e68797
 
 
 
 
 
19dcc9f
 
 
1e68797
19dcc9f
 
 
 
 
1e68797
19dcc9f
 
 
 
 
 
 
 
1e68797
 
 
 
 
19dcc9f
1e68797
 
 
 
 
19dcc9f
 
1e68797
19dcc9f
 
 
 
1e68797
19dcc9f
 
 
 
 
1e68797
19dcc9f
 
1e68797
19dcc9f
 
 
 
1e68797
 
 
 
 
 
19dcc9f
1e68797
 
 
19dcc9f
 
 
1e68797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19dcc9f
c15c04b
 
1e68797
c15c04b
19dcc9f
c15c04b
 
 
 
 
 
 
19dcc9f
c15c04b
 
1e68797
 
c15c04b
 
1e68797
 
 
 
 
 
 
 
 
 
 
 
19dcc9f
1e68797
19dcc9f
 
1e68797
19dcc9f
 
9c21e71
19dcc9f
 
 
 
 
874332e
 
19dcc9f
 
 
874332e
19dcc9f
 
 
 
 
 
 
1e68797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19dcc9f
 
1e68797
19dcc9f
1e68797
 
 
 
 
 
 
 
 
 
 
 
c15c04b
1e68797
 
 
 
19dcc9f
1e68797
 
 
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# -*- coding: utf-8 -*-
"""
نصّ البرنامج: مساعد نورا + نظام مهام موزعة + خيار لتشغيل كل ملفات بايثون (.py) الموجودة في نفس المجلد.


الميزات المضافة/المعدّلة
========================
1. **تشغيل كل ملفات بايثون في نفس المجلد** يدويًا من واجهة Gradio أو تلقائيًا عند بدء التشغيل (يمكن التحكّم عبر متغيّر بيئة).
2. جمع المخرجات (stdout / stderr) لكل ملف بشكل منفصل وإرجاعها/عرضها للمستخدم.
3. استثناء الملف الحالي (الذي يحتوي الكود) تلقائيًا حتى لا يدخل في حلقة تشغيل ذاتي.
4. استثناء مجلدات مثل `__pycache__` وأي ملف يبدأ بشرطة سفلية اختياريا.
5. واجهة Gradio محدثة: تبويب جديد باسم "تشغيل جميع ملفات بايثون" يعرض قائمة الملفات + زر تشغيل + صندوق نتائج.
6. دوال مساعدة نظيفة + تسجيل (logging) اختياري.


طريقة التحكم بالتشغيل التلقائي عند بدء البرنامج
----------------------------------------------
- اضبط متغيّر البيئة: `RUN_ALL_PY_ON_START=1` لتشغيلها عند الإقلاع.
- أو اتركه فارغًا/0 لتعطيل التشغيل التلقائي.


ملاحظات مهمة
------------
- التنفيذ يتم باستخدام `runpy.run_path()` بحيث يعمل كل ملف في مساحة أسماء مستقلة (قاموس).
- لا يتم عمل `import` مباشر؛ هذا يقلل تداخل الرموز ولكن *إذا كانت لديك ملفات تعتمد على الاستيراد النسبي* فربما تفضّل التحميل عبر `importlib`. (أنظر التعليق داخل الكود لاختيار وضع الاستيراد.)
- لو احتجت تمرير متغيرات/وسائط إلى هذه السكربتات الخارجية فسيتطلب ذلك بروتوكول إضافي (argparse مخفي، أو بيئة، أو ملف إعدادات مشترَك).


"""

import os
import io
import re
import json
import time
import glob
import runpy
import types
import logging
import threading
from contextlib import redirect_stdout, redirect_stderr

from flask import Flask, request, jsonify
import gradio as gr

from transformers import AutoTokenizer, AutoModelForCausalLM
from accelerate import init_empty_weights, load_checkpoint_and_dispatch

# استيراد نظام التوزيع والمهام المعرّفة من ملفات أخرى
from distributed_executor import DistributedExecutor
from your_tasks import *  # يفترض أن يحتوي على matrix_multiply, prime_calculation, ... إلخ

# ================= إعدادات الموديل =================
local_model_path = "./Mistral-7B-Instruct-v0.1"
offload_dir = "offload_dir"
history_path = "history.json"

# ================= إعداد التسجيل (اختياري) =================
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

# ================= تحميل التوكنيزر والموديل =================
logger.info("Loading tokenizer: %s", local_model_path)
tokenizer = AutoTokenizer.from_pretrained(local_model_path)

logger.info("Initializing empty weights model shell…")
with init_empty_weights():
    model = AutoModelForCausalLM.from_pretrained(local_model_path)

logger.info("Dispatching model w/ CPU offload (accelerate)…")
model = load_checkpoint_and_dispatch(
    model,
    local_model_path,
    device_map={"": "cpu"},  # كلّه على CPU (يمكن التعديل لاحقًا)
    offload_folder=offload_dir,
    offload_state_dict=True,
)

# ================= تحميل سجل المحادثة =================
if os.path.exists(history_path):
    try:
        with open(history_path, "r", encoding="utf-8") as f:
            chat_history = json.load(f)
    except Exception as e:
        logger.warning("تعذّر تحميل سجل المحادثة (%s)، سيتم البدء بسجل فارغ.", e)
        chat_history = []
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 chat_with_nora(user_input):
    global chat_history
    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=200, do_sample=True, temperature=0.7)
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    # محاولة استخراج آخر رد بعد قالب الدردشة
    if "[/INST]" in response:
        answer = response.split("[/INST]")[-1].strip()
    else:
        answer = response.strip()
    chat_history.append({"role": "assistant", "content": answer})
    try:
        with open(history_path, "w", encoding="utf-8") as f:
            json.dump(chat_history, f, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error("Failed saving chat history: %s", e)
    return answer


# ================= نظام توزيع المهام =================
executor = DistributedExecutor("my_shared_secret_123")
executor.peer_registry.register_service("node1", 7520, load=0.2)

# المهام المعرفة يدويًا
tasks = {
    "ضرب المصفوفات": (matrix_multiply, 500),
    "حساب الأعداد الأولية": (prime_calculation, 100000),
    "معالجة البيانات": (data_processing, 10000),
    "محاكاة معالجة الصور": (image_processing_emulation, 100),
    "مهمة موزعة معقدة": (lambda x: x * x, 42),
}


def run_task(task_name):
    if task_name in tasks:
        func, arg = tasks[task_name]
        start = time.time()
        try:
            result = func(arg)
            status = "success"
        except Exception as e:
            result = f"ERROR: {e}"
            status = "error"
        duration = time.time() - start
        return f"✅ الحالة: {status}
النتيجة: {str(result)[:200]}...
⏱ الوقت: {duration:.2f} ثانية"
    else:
        return "❌ مهمة غير موجودة!"


# =====================================================
#     دعم تشغيل جميع ملفات بايثون في نفس المجلد
# =====================================================

def discover_py_files(directory=None, *, exclude_self=True, exclude_private=True):
    """اكتشف جميع ملفات .py في المجلد (غير متداخلة) مع خيارات استثناء."""
    directory = directory or os.path.dirname(os.path.abspath(__file__))
    self_path = os.path.abspath(__file__)
    files = []
    for path in glob.glob(os.path.join(directory, "*.py")):
        abs_path = os.path.abspath(path)
        name = os.path.basename(abs_path)
        if exclude_self and os.path.samefile(abs_path, self_path):
            continue
        if exclude_private and name.startswith("_"):
            continue
        files.append(abs_path)
    return sorted(files)


def execute_single_py(path):
    """شغّل ملف بايثون وأعد قاموسًا يحتوي stdout/stderr وزمن التنفيذ ونتيجة عودة محتملة."""
    start = time.time()
    stdout_buf = io.StringIO()
    stderr_buf = io.StringIO()
    result_namespace = None
    error = None
    try:
        with redirect_stdout(stdout_buf), redirect_stderr(stderr_buf):
            # run_path يعيد قاموس المتغيرات العالمية بعد التنفيذ
            result_namespace = runpy.run_path(path_name=path, run_name="__main__")
    except Exception as e:  # noqa: BLE001 (نريد التقاط كل شيء هنا)
        error = str(e)
    duration = time.time() - start
    return {
        "file": path,
        "stdout": stdout_buf.getvalue(),
        "stderr": stderr_buf.getvalue(),
        "error": error,
        "globals": result_namespace if isinstance(result_namespace, dict) else {},
        "time": duration,
    }


def execute_all_py_files(directory=None, *, exclude_self=True, exclude_private=True):
    files = discover_py_files(directory, exclude_self=exclude_self, exclude_private=exclude_private)
    results = []
    for fpath in files:
        logger.info("Running: %s", fpath)
        res = execute_single_py(fpath)
        results.append(res)
    return results


def summarize_execution_results(results):
    """حوّل نتائج التنفيذ إلى نص قابل للعرض في Gradio."""
    lines = []
    for r in results:
        lines.append("====================================")
        lines.append(f"📄 الملف: {os.path.basename(r['file'])}")
        lines.append(f"⏱ الوقت: {r['time']:.2f} ثانية")
        if r["error"]:
            lines.append(f"❌ خطأ: {r['error']}")
        if r["stderr"].strip():
            lines.append("--- STDERR ---")
            lines.append(r["stderr"].strip())
        if r["stdout"].strip():
            lines.append("--- STDOUT ---")
            # لا نعرض أكثر من 500 حرف لتجنب التضخم
            out_preview = r["stdout"].strip()
            if len(out_preview) > 500:
                out_preview = out_preview[:500] + "... [تم الاقتصاص]"
            lines.append(out_preview)
    if not lines:
        return "لا توجد ملفات للتشغيل."\

    return "
".join(lines)


# ================= خادم Flask API =================
app = Flask(__name__)


@app.route('/api/chat', methods=['POST'])
def api_chat():
    try:
        data = request.get_json(force=True)
        user_message = data.get('message', '').strip()

        if not user_message:
            return jsonify({'response': 'يرجى إدخال رسالة صالحة'}), 400

        response_text = chat_with_nora(user_message)
        return jsonify({'response': response_text})

    except Exception as e:  # noqa: BLE001
        logger.exception("/api/chat error")
        return jsonify({'response': 'حدث خطأ داخلي', 'error': str(e)}), 500


# ================ Flask: تشغيل كل الملفات عبر API (اختياري) ================
@app.route('/api/run_all', methods=['POST'])
def api_run_all():
    try:
        results = execute_all_py_files()
        return jsonify({'results': results})
    except Exception as e:  # noqa: BLE001
        logger.exception("/api/run_all error")
        return jsonify({'error': str(e)}), 500


# ================= واجهة Gradio =================

def launch_gradio():
    with gr.Blocks() as demo:
        gr.Markdown("# 🤖 مساعد نورا + نظام المهام الموزعة + تشغيل سكربتات المجلد")

        with gr.Tab("المحادثة مع نورا"):
            chatbot = gr.Chatbot(type="messages")
            msg = gr.Textbox()
            send = gr.Button("إرسال")

            def respond(message, chat_history_display):
                answer = chat_with_nora(message)
                chat_history_display.append({"role": "user", "content": message})
                chat_history_display.append({"role": "assistant", "content": answer})
                return "", chat_history_display

            send.click(respond, [msg, chatbot], [msg, chatbot])

        with gr.Tab("تشغيل المهام"):
            task_dropdown = gr.Dropdown(list(tasks.keys()), label="اختر مهمة")
            run_button = gr.Button("تشغيل")
            result_box = gr.Textbox(label="النتيجة", lines=6)

            run_button.click(run_task, inputs=task_dropdown, outputs=result_box)

        with gr.Tab("تشغيل جميع ملفات بايثون"):
            gr.Markdown("### اكتشاف وتشغيل جميع ملفات .py في نفس مجلد هذا البرنامج")
            refresh_btn = gr.Button("🔄 تحديث قائمة الملفات")
            run_all_btn = gr.Button("🚀 تشغيل الكل")
            files_box = gr.Textbox(label="الملفات المكتشفة", interactive=False)
            run_all_result = gr.Textbox(label="نتائج التشغيل", lines=15)

            def refresh_files():
                files = discover_py_files()
                if not files:
                    return "لا توجد ملفات .py (باستثناء هذا الملف)."
                return "
".join(os.path.basename(f) for f in files)

            def run_all_files_and_summarize():
                results = execute_all_py_files()
                return summarize_execution_results(results)

            refresh_btn.click(refresh_files, outputs=files_box)
            run_all_btn.click(run_all_files_and_summarize, outputs=run_all_result)

    demo.launch(server_name="0.0.0.0", server_port=7860)


# ================= تشغيل الاثنين معًا =================
def startup_run_all_if_enabled():
    run_flag = os.environ.get("RUN_ALL_PY_ON_START", "0").strip()
    if run_flag in {"1", "true", "True", "yes", "YES"}:
        logger.info("RUN_ALL_PY_ON_START=1 -> Running all py files at startup…")
        results = execute_all_py_files()
        summary = summarize_execution_results(results)
        logger.info("Startup batch complete:
%s", summary)
    else:
        logger.info("Startup batch NOT enabled (set RUN_ALL_PY_ON_START=1 to enable).")


if __name__ == '__main__':
    # (اختياري) شغّل كل ملفات .py عند الإقلاع إن كان المستخدِم فعّل ذلك.
    startup_run_all_if_enabled()

    # شغّل Gradio في خيط مستقل
    threading.Thread(target=launch_gradio, daemon=True).start()

    # شغّل Flask (المخدّم الأساسي)
    app.run(host='0.0.0.0', port=5321, debug=True)