Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import osimport gradio as grfrom huggingface_hub import InferenceClientimport spaces # <--- Hugging Face's mandatory import for ZeroGPU# Initialize the Hugging Face serverless client using Qwen Coderclient = InferenceClient("Qwen/Qwen2.5-Coder-32B-Instruct")# This system prompt primes the AI to act as an elite, direct PHP and MariaDB coderSYSTEM_PROMPT = """You are a senior PHP and MariaDB software engineer specializing in backend game development.Your goal is to write highly optimized, clean, and modern procedural or object-oriented PHP algorithms.When writing code updates, prioritize writing functional backend logic and raw database interactions over building user interface designs.If database updates are required, prioritize writing raw console queries or standard PDO commands.Keep explanations concise, directly addressing logic, database structures, and performance optimization. Avoid generic conversational fluff."""# We decorate our main function so Hugging Face allocates the space resource@spaces.GPU # <--- This prevents the "No @spaces.GPU function detected" error!def respond(message, chat_history):# Prepare chat format with our specialized rulesmessages = [{"role": "system", "content": SYSTEM_PROMPT}]# Pack past messages so the chatbot remembers contextfor val in chat_history:if val[0]:messages.append({"role": "user", "content": val[0]})if val[1]:messages.append({"role": "assistant", "content": val[1]})messages.append({"role": "user", "content": message})response = ""# Stream the code back in real-timetry:for message_chunk in client.chat_completion(messages,max_tokens=2048,stream=True,temperature=0.2, # Low temperature forces more accurate, deterministic code logic):token = message_chunk.choices[0].delta.contentif token:response += tokenyield responseexcept Exception as e:yield f"Error calling Hugging Face API: {str(e)}\nIf this persists, make sure the Hugging Face Serverless API is healthy."# Build a simple, robust chat layoutwith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# ๐ PHP Algorithm Specialist")gr.Markdown("Your private, high-speed assistant for writing backend game logic, MariaDB queries, and clean PHP algorithms.")chatbot = gr.Chatbot(height=550)msg = gr.Textbox(placeholder="e.g., Write a PHP function to handle custom player updates directly in the database...",label="Your Coding Task")clear = gr.ClearButton([msg, chatbot])def user(user_message, history):return "", history + [[user_message, None]]def bot(history):user_message = history[-1][0]bot_message_generator = respond(user_message, history[:-1])history[-1][1] = ""for character in bot_message_generator:history[-1][1] = characteryield historymsg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot)demo.queue()demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import gradio as grfrom huggingface_hub import InferenceClientimport spaces # Mandatory import for Hugging Face ZeroGPU# Initialize the clientclient = InferenceClient("Qwen/Qwen2.5-Coder-32B-Instruct")SYSTEM_PROMPT = """You are a senior PHP and MariaDB software engineer specializing in backend game development.Your goal is to write highly optimized, clean, and modern procedural or object-oriented PHP algorithms.When writing code updates, prioritize writing functional backend logic and raw database interactions over building user interface designs.If database updates are required, prioritize writing raw console queries or standard PDO commands.Keep explanations concise, directly addressing logic, database structures, and performance optimization. Avoid generic conversational fluff."""# 1. The @spaces.GPU function MUST be simple and return the final string.# We set a low duration since API calls are fast, giving you higher queue priority.@spaces.GPU(duration=15)def call_inference_api(messages):response = ""# We call the completion directly without streaming to avoid ZeroGPU process/pickle bugscompletion = client.chat_completion(messages,max_tokens=2048,temperature=0.2,)return completion.choices[0].message.content# 2. This is the UI helper function (runs on CPU, no pickle/generator issues)def generate_php_code(message, history):messages = [{"role": "system", "content": SYSTEM_PROMPT}]# Reconstruct conversation historyfor user_msg, assistant_msg in history:if user_msg:messages.append({"role": "user", "content": user_msg})if assistant_msg:messages.append({"role": "assistant", "content": assistant_msg})messages.append({"role": "user", "content": message})try:# Call the GPU-allocated function safelyreply = call_inference_api(messages)return replyexcept Exception as e:return f"Error occurred: {str(e)}\n\nIf this persists, the Serverless API may be temporarily rate-limiting requests. Please try again in a moment."# 3. Clean Gradio interfacedemo = gr.ChatInterface(fn=generate_php_code,title="๐ PHP Algorithm Specialist",description="Your private, high-speed assistant for writing backend game logic, MariaDB queries, and clean PHP algorithms.",theme="soft")if __name__ == "__main__":demo.queue()demo.launch()
app.py+40-58