Spaces:
Build error
Build error
Update app.py
Browse files2 unmodified lines3456783 unmodified lines12131415161718196 unmodified lines26272829303132333435366 unmodified lines43444546474849505152535455569 unmodified lines666768697071727374757677787980812 unmodified linesimport sysimport ioimport traceback# Initialize the AI modelmodel_name = "Qwen/Qwen2.5-72B-Instruct"3 unmodified lineseos_token = "<|endoftext|>"output = client.chat.completions.create(messages=[{"role": "system", "content": "You are a Python language guide. Write code on the user topic. If the input is code, correct it for mistakes."},{"role": "user", "content": f"Write only python code without any explanation: {user_sample}"},],stream=False,temperature=0.7,6 unmodified linesresponse += choice['message']['content']return responsedef chat(user_input, history):response = llm_inference(user_input)history.append((user_input, response))return history, historydef execute_code(code):old_stdout = sys.stdoutredirected_output = sys.stdout = io.StringIO()6 unmodified linessys.stdout = old_stdoutreturn outputdef solve_math_task(math_task):# Generate Python code for the math taskgenerated_code = llm_inference(f"Create a Python program to solve the following math problem:\n{math_task}")# Execute the generated codeexecution_result = execute_code(generated_code)return generated_code, execution_resultwith gr.Blocks() as demo:gr.Markdown("# π Python Helper Chatbot")9 unmodified linescode_output = gr.Textbox(label="Output")run_button.click(execute_code, inputs=code_input, outputs=code_output)with gr.Tab("Math Solver"):gr.Markdown("### π Math Task Solver")math_input = gr.Textbox(placeholder="Enter your mathematical task here...", lines=2)solve_button = gr.Button("Solve Task")with gr.Row():generated_code_output = gr.Code(label="Generated Python Code", language="python")with gr.Row():execution_output = gr.Textbox(label="Execution Result", lines=10)solve_button.click(solve_math_task, inputs=math_input, outputs=[generated_code_output, execution_output])with gr.Tab("Logs"):gr.Markdown("### π Logs")log_output = gr.Textbox(label="Logs", lines=10, interactive=False)2 unmodified lines34567893 unmodified lines13141516171819202122232425266 unmodified lines3334353637386 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586879 unmodified lines9798991001011022 unmodified linesimport sysimport ioimport tracebackimport re # Import the regular expressions module# Initialize the AI modelmodel_name = "Qwen/Qwen2.5-72B-Instruct"3 unmodified lineseos_token = "<|endoftext|>"output = client.chat.completions.create(messages=[{"role": "system","content": "You are a Python language guide. Write code on the user topic. If the input is code, correct it for mistakes."},{"role": "user","content": f"Write only python code without any explanation: {user_sample}"},],stream=False,temperature=0.7,6 unmodified linesresponse += choice['message']['content']return responsedef execute_code(code):old_stdout = sys.stdoutredirected_output = sys.stdout = io.StringIO()6 unmodified linessys.stdout = old_stdoutreturn outputdef is_math_task(user_input):"""Simple heuristic to determine if the user input is a math task.This can be enhanced with more sophisticated methods or NLP techniques."""math_keywords = ['calculate', 'compute', 'solve', 'integrate', 'differentiate', 'derivative', 'integral', 'factorial', 'sum', 'product']operators = ['+', '-', '*', '/', '^', '**', 'sqrt', 'sin', 'cos', 'tan', 'log', 'exp']user_input_lower = user_input.lower()return any(keyword in user_input_lower for keyword in math_keywords) or any(op in user_input for op in operators)def chat(user_input, history):"""Handles the chat interaction. If the user input is detected as a math task,it generates Python code to solve it, strips any code tags, executes the code,and returns the result."""if is_math_task(user_input):# Generate Python code for the math taskgenerated_code = llm_inference(f"Create a Python program to solve the following math problem:\n{user_input}")# Strip code tags using regex# This regex removes ```python and ``` or any other markdown code fencescleaned_code = re.sub(r"```(?:python)?\n?", "", generated_code).strip()cleaned_code = re.sub(r"```", "", cleaned_code).strip()# Execute the cleaned codeexecution_result = execute_code(cleaned_code)# Prepare the responsesassistant_response = f"**Generated Python Code:**\n```python\n{cleaned_code}\n```\n\n**Execution Result:**\n```\n{execution_result}\n```"else:# For regular chat messages, use the AI's responseassistant_response = llm_inference(user_input)# Append to chat historyhistory.append((user_input, assistant_response))return history, historywith gr.Blocks() as demo:gr.Markdown("# π Python Helper Chatbot")9 unmodified linescode_output = gr.Textbox(label="Output")run_button.click(execute_code, inputs=code_input, outputs=code_output)with gr.Tab("Logs"):gr.Markdown("### π Logs")log_output = gr.Textbox(label="Logs", lines=10, interactive=False)
app.py+45-24