Spaces:
Build error
Build error
Ilya commited on
Update app.py
Browse files2 unmodified lines3456782 unmodified lines111213141516177 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061621 unmodified line646566676869707172737475762 unmodified linesimport sysimport ioimport tracebackmodel_name = "Qwen/Qwen2.5-72B-Instruct"client = InferenceClient(model_name)2 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. Make sure that the code is runnable and doesn't close the shell window, so end with input() if the user request is simple. If the input is code, correct it for mistakes."},{"role": "user", "content": f"Write only python code without any explanation: {user_sample}"},],stream=False,7 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, user_inputs):# Split user inputs by newlineinputs = user_inputs.strip().split('\n')input_iter = iter(inputs)# Custom input function to replace built-in input()def custom_input(prompt=''):try:return next(input_iter)except StopIteration:raise Exception("Not enough inputs provided.")# Redirect stdoutold_stdout = sys.stdoutredirected_output = sys.stdout = io.StringIO()old_input = __builtins__.input__builtins__.input = custom_inputtry:exec(code, {})output = redirected_output.getvalue()except Exception as e:output = f"Error: {e}\n{traceback.format_exc()}"finally:sys.stdout = old_stdout__builtins__.input = old_inputreturn outputwith gr.Blocks() as demo:gr.Markdown("# 🐍 Python Helper Chatbot")with gr.Tab("Chat"):1 unmodified linemsg = gr.Textbox(placeholder="Type your message here...")msg.submit(chat, inputs=[msg, chatbot], outputs=[chatbot, chatbot])with gr.Tab("Interpreter"):gr.Markdown("### 🖥️ Test Your Code")code_input = gr.Code(language="python", lines=20)gr.Markdown("#### 📝 Provide Inputs (Each input on a new line):")user_inputs = gr.Textbox(lines=5, placeholder="Enter inputs for your code here...")run_button = gr.Button("Run Code")code_output = gr.Textbox(label="Output", lines=15)run_button.click(execute_code, inputs=[code_input, user_inputs], outputs=code_output)with gr.Tab("Logs"):gr.Markdown("### 📜 Logs")log_output = gr.Textbox(label="Logs", lines=10, interactive=False)2 unmodified lines34567892 unmodified lines121314151617187 unmodified lines26272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461472 unmodified linesimport sysimport ioimport tracebackimport threadingmodel_name = "Qwen/Qwen2.5-72B-Instruct"client = InferenceClient(model_name)2 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. Make sure that the code is runnable and doesn't close the shell window. If the input is code, correct it for mistakes."},{"role": "user", "content": f"Write only python code without any explanation: {user_sample}"},],stream=False,7 unmodified linesresponse += choice['message']['content']return response# A class to handle the execution environment per user sessionclass CodeExecutor:def __init__(self):self.local_vars = {}self.output = ""self.input_buffer = []self.waiting_for_input = Falseself.execution_thread = Noneself.execution_complete = Falsedef custom_input(self, prompt=''):self.waiting_for_input = Truewhile self.waiting_for_input:pass # Wait until input is providedreturn self.input_buffer.pop(0)def execute_code(self, code):def run_code():# Redirect stdoutold_stdout = sys.stdoutsys.stdout = io.StringIO()# Replace input functionold_input = __builtins__.input__builtins__.input = self.custom_inputtry:exec(code, {}, self.local_vars)except Exception as e:self.output += f"\nError: {e}\n{traceback.format_exc()}"finally:self.output += sys.stdout.getvalue()sys.stdout = old_stdout__builtins__.input = old_inputself.execution_complete = Trueself.execution_thread = threading.Thread(target=run_code)self.execution_thread.start()def provide_input(self, user_input):self.input_buffer.append(user_input)self.waiting_for_input = Falsedef get_output(self):return self.outputdef is_execution_complete(self):return self.execution_completeexecutors = {}def start_execution(code, session_id):executor = CodeExecutor()executors[session_id] = executorexecutor.execute_code(code)return "Execution started. Waiting for output..."def provide_input(user_input, session_id):executor = executors.get(session_id)if executor and not executor.is_execution_complete():executor.provide_input(user_input)return "Input received."else:return "No execution in progress or execution has completed."def get_output(session_id):executor = executors.get(session_id)if executor:output = executor.get_output()if executor.is_execution_complete():del executors[session_id]return outputelse:return "No execution in progress."def chat(user_input, history):response = llm_inference(user_input)history.append((user_input, response))return history, historywith gr.Blocks() as demo:gr.Markdown("# 🐍 Python Helper Chatbot")with gr.Tab("Chat"):1 unmodified linemsg = gr.Textbox(placeholder="Type your message here...")msg.submit(chat, inputs=[msg, chatbot], outputs=[chatbot, chatbot])with gr.Tab("Interpreter"):gr.Markdown("### 🖥️ Interactive Code Interpreter")code_input = gr.Code(language="python", lines=20)run_button = gr.Button("Run Code")output_box = gr.Textbox(label="Output", lines=15)input_box = gr.Textbox(label="Program Input", placeholder="Enter input for your program here...")send_input_button = gr.Button("Send Input")session_id = gr.State()def run_code(code):from uuid import uuid4session = str(uuid4())session_id.set(session)start_execution(code, session)return "Code is running...", gr.update(visible=True), gr.update(visible=True)def send_input(user_input):session = session_id.get()provide_input(user_input, session)return ""def update_output():session = session_id.get()if session:output = get_output(session)return outputelse:return "No execution in progress."run_button.click(run_code, inputs=code_input, outputs=[output_box, input_box, send_input_button])send_input_button.click(send_input, inputs=input_box, outputs=input_box)output_box.change(update_output, outputs=output_box).every(1)with gr.Tab("Logs"):gr.Markdown("### 📜 Logs")log_output = gr.Textbox(label="Logs", lines=10, interactive=False)
app.py+104-33