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( """
مساعد برمجي أسطوري — Streaming • Preview • Download
""" ) 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 )