File size: 4,316 Bytes
97f7b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
import os

# فحص نوع العتاد المتوفر (هل يوجد GPU أم لا؟)
IS_GPU_AVAILABLE = torch.cuda.is_available()

# تحميل النموذج فقط إذا كان هناك GPU (لتجنب انهيار المساحة المجانية)
if IS_GPU_AVAILABLE:
    from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
    from peft import PeftModel
    from huggingface_hub import login
    
    # جلب مفتاح الأمان من إعدادات المساحة (Secrets)
    hf_token = os.environ.get("HF_TOKEN")
    if hf_token:
        login(token=hf_token)
        
    base_model_id = "NousResearch/Hermes-3-Llama-3.1-8B"
    adapter_repo_id = "maherghanem86/BlueprintFix"

    bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_use_double_quant=True
    )

    tokenizer = AutoTokenizer.from_pretrained(base_model_id, token=hf_token)
    base_model = AutoModelForCausalLM.from_pretrained(
        base_model_id,
        quantization_config=bnb_config,
        device_map="auto",
        torch_dtype=torch.float16,
        token=hf_token
    )

    model = PeftModel.from_pretrained(base_model, adapter_repo_id, token=hf_token)
    model.eval()

# دالة الاستدلال
def predict_bug_fix(instruction, arch_context, buggy_code):
    # إذا كانت المساحة مجانية، نعيد رداً وهمياً برمجياً لتوضيح الفكرة للجنة
    if not IS_GPU_AVAILABLE:
        mock_response = """
        **[System Notice]:** ⚠️ Running on Free CPU Tier. Real-time inference requires a GPU.
       
       
        ```
        """
        return mock_response.strip()
    
    # إذا كان الـ GPU متوفراً، نقوم بالاستدلال الحقيقي
    prompt = f"### Instruction:\n{instruction}\n\n### Architectural Context:\n{arch_context}\n\n### Buggy Code:\n{buggy_code}\n\n### Response:\n**Root Cause Analysis:**\n"
    inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=512,
            temperature=0.1,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id
        )
    
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    final_output = response.split("### Response:\n")[-1].strip()
    
    if not final_output.startswith("**Root Cause"):
        final_output = "**Root Cause Analysis:**\n" + final_output
        
    return final_output

# بناء واجهة المستخدم (Gradio UI)
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # 🛡️ BlueprintFix

    )
    
    # عرض رسالة تحذيرية أنيقة إذا كانت المساحة مجانية
    if not IS_GPU_AVAILABLE:
        gr.Warning("⏳ You are viewing the 'Simulation Mode' on a free CPU space. The UI is fully functional, but outputs are simulated. GPU upgrade is required for real inference.")
        
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### 📥 Input Parameters (المدخلات)")
            inst_input = gr.Textbox(
                label="Instruction (التعليمة)", 
                value="Analyze the bug based on the architectural context and provide the fixed code."
            )
            context_input = gr.Textbox(
                label="Architectural Context (الوثيقة المعمارية)", 
                lines=4, 
                placeholder="Paste the design rule or architectural constraint here..."
            )
            code_input = gr.Code(
                label="Buggy Code (الكود المعيب)", 
                lines=10
            )
            submit_btn = gr.Button("🚀 Analyze & Repair", variant="primary")
            
        with gr.Column(scale=1):
            gr.Markdown("### 📤 Model Response (التشخيص والإصلاح)")
            output_display = gr.Markdown(label="Root Cause & Fixed Code")

    submit_btn.click(
        fn=predict_bug_fix, 
        inputs=[inst_input, context_input, code_input], 
        outputs=output_display
    )

# إطلاق التطبيق
demo.launch()