File size: 4,841 Bytes
769c7b6
 
 
 
dd0cfc8
769c7b6
 
 
 
 
 
 
 
 
10721fb
769c7b6
 
 
 
 
 
 
 
 
 
0d9e1eb
769c7b6
 
 
3bea862
769c7b6
 
0d9e1eb
769c7b6
 
0d9e1eb
 
769c7b6
0d9e1eb
769c7b6
 
2bbb834
769c7b6
 
 
 
10721fb
769c7b6
 
 
3bea862
769c7b6
0d9e1eb
 
 
 
10721fb
0d9e1eb
 
 
 
 
 
 
 
 
769c7b6
0d9e1eb
3bea862
 
 
 
 
 
 
0d9e1eb
 
10721fb
3bea862
 
 
 
 
 
 
769c7b6
0d9e1eb
 
769c7b6
3bea862
 
 
 
 
 
769c7b6
 
2bbb834
769c7b6
 
 
0d9e1eb
 
 
 
 
 
769c7b6
0d9e1eb
769c7b6
 
0d9e1eb
769c7b6
0d9e1eb
 
 
 
 
 
 
 
3bea862
 
0d9e1eb
 
 
 
3bea862
0d9e1eb
 
 
 
 
 
 
 
 
3bea862
 
0d9e1eb
e2a9cf7
 
0d9e1eb
 
 
 
d55b72e
769c7b6
0d9e1eb
 
 
 
 
 
769c7b6
 
e2a9cf7
 
0d9e1eb
769c7b6
0d9e1eb
769c7b6
 
0d9e1eb
769c7b6
e2a9cf7
10721fb
 
 
 
 
0d9e1eb
769c7b6
0d9e1eb
 
769c7b6
 
e2a9cf7
dd0cfc8
769c7b6
2bbb834
769c7b6
 
e2a9cf7
10721fb
 
 
 
 
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
import os
import re
import gradio as gr
from huggingface_hub import InferenceClient

# ==============================
# Environment Setup
# ==============================

HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
    raise EnvironmentError("HF_TOKEN is not set in environment variables.")

client = InferenceClient(
    model="Qwen/Qwen2.5-Coder-7B-Instruct",
    token=HF_TOKEN
)

SYSTEM_MESSAGE = (
    "أنت مساعد برمجي خبير تدعى CODEK. "
    "تحدث باللغة العربية بأسلوب تقني واحترافي. "
    "قدم حلولاً برمجية كاملة ومنظمة داخل صناديق أكواد Markdown دائماً."
)

# ==============================
# Code Extraction
# ==============================

def extract_code(text: str) -> str:
    blocks = re.findall(r"```(?:\w+)?\n(.*?)```", text, re.DOTALL)
    if not blocks:
        return ""
    return "\n\n# --- New Block ---\n\n".join(b.strip() for b in blocks)

def save_code_to_file(code: str) -> str:
    path = "codek_output.txt"
    with open(path, "w", encoding="utf-8") as f:
        f.write(code)
    return path

# ==============================
# Streaming Chat Logic
# ==============================

def chat_stream(user_message, history):
    messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
    messages.extend(history)
    messages.append({"role": "user", "content": user_message})

    assistant_text = ""
    new_history = history + [{"role": "user", "content": user_message}]

    try:
        stream = client.chat_completion(
            messages=messages,
            stream=True,
            max_tokens=2048
        )

        for chunk in stream:
            if not chunk or not chunk.choices:
                continue

            delta = chunk.choices[0].delta
            if not delta or not delta.content:
                continue

            assistant_text += delta.content

            yield (
                new_history + [{"role": "assistant", "content": assistant_text}],
                "",
                None,
                ""
            )

    except Exception as e:
        error_msg = f"❌ حصل خطأ:\n{str(e)}"
        yield (
            new_history + [{"role": "assistant", "content": error_msg}],
            "",
            None,
            ""
        )
        return

    extracted = extract_code(assistant_text)
    file_path = save_code_to_file(extracted) if extracted else None

    yield (
        new_history + [{"role": "assistant", "content": assistant_text}],
        extracted,
        file_path,
        ""
    )

# ==============================
# Animated Legendary UI (CSS)
# ==============================

CUSTOM_CSS = """
@keyframes gradientMove {
    0% {background-position: 0% 50%;}
    50% {background-position: 100% 50%;}
    100% {background-position: 0% 50%;}
}

body {
    background: #0f0f11;
    color: #e3e3e3;
}

header {
    background: linear-gradient(270deg, #7f00ff, #e100ff, #00c6ff);
    background-size: 600% 600%;
    animation: gradientMove 10s ease infinite;
}

button {
    background: linear-gradient(135deg, #7f00ff, #00c6ff) !important;
    color: white !important;
    border-radius: 14px !important;
    transition: all 0.2s ease;
}

button:hover {
    transform: scale(1.05);
    box-shadow: 0 0 25px rgba(0,198,255,0.6);
}

textarea, .gr-code {
    background: #16161a !important;
    color: #e3e3e3 !important;
    border-radius: 12px;
}

.gr-chatbot {
    border-radius: 18px;
    box-shadow: 0 0 30px rgba(127,0,255,0.2);
}
"""

# ==============================
# App Layout
# ==============================

with gr.Blocks() as demo:
    gr.Markdown(
        """
        <h1 style="text-align:center;">⚡ CODEK AI</h1>
        <p style="text-align:center; opacity:0.8;">
        مساعد برمجي أسطوري — Streaming • Preview • Download
        </p>
        """
    )

    with gr.Row():
        with gr.Column(scale=2):
            chatbot = gr.Chatbot(height=520)
            user_input = gr.Textbox(
                placeholder="اكتب سؤالك البرمجي هنا...",
                lines=3
            )
            submit = gr.Button("🚀 Generate")

        with gr.Column(scale=1):
            code_preview = gr.Code(
                label="⚙ Code Preview",
                language="python",
                lines=28
            )
            file_download = gr.File(label="⬇ Download Code")

    submit.click(
        chat_stream,
        inputs=[user_input, chatbot],
        outputs=[chatbot, code_preview, file_download, user_input]
    )

# ==============================
# Run App (HF Spaces Ready)
# ==============================

if __name__ == "__main__":
    demo.launch(
        css=CUSTOM_CSS,
        server_name="0.0.0.0",
        server_port=7860
    )