diff --git a/week4/community-contributions/tochi/code_converter.ipynb b/week4/community-contributions/tochi/code_converter.ipynb new file mode 100644 index 0000000..5101d61 --- /dev/null +++ b/week4/community-contributions/tochi/code_converter.ipynb @@ -0,0 +1,569 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "c1fcc6e9", + "metadata": {}, + "source": [ + "# Code Converter - Python to TypeScript Code\n", + "\n", + "This implementation, converts python code to optimized TypeScript Code, and runs the function" + ] + }, + { + "cell_type": "markdown", + "id": "16b6b063", + "metadata": {}, + "source": [ + "## Set up and imports\n" + ] + }, + { + "cell_type": "code", + "execution_count": 115, + "id": "b3dc394c", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "import os\n", + "import io\n", + "import sys\n", + "from dotenv import load_dotenv\n", + "from openai import OpenAI\n", + "import subprocess\n", + "from IPython.display import Markdown, display, display_markdown\n", + "from system_info import retrieve_system_info\n", + "import gradio as gr" + ] + }, + { + "cell_type": "markdown", + "id": "1c9a0936", + "metadata": {}, + "source": [ + "# Initializing the access keys" + ] + }, + { + "cell_type": "code", + "execution_count": 116, + "id": "fac104ec", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "OpenAI API Key exists and begins sk-proj-\n" + ] + } + ], + "source": [ + "load_dotenv(override=True)\n", + "openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n", + "\n", + "if openai_api_key:\n", + " print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n", + "else:\n", + " print(\"OpenAI API Key not set. Check your engironment variables and try again\")" + ] + }, + { + "cell_type": "markdown", + "id": "5932182f", + "metadata": {}, + "source": [ + "# Connecting to client libraries" + ] + }, + { + "cell_type": "code", + "execution_count": 117, + "id": "4000f231", + "metadata": {}, + "outputs": [], + "source": [ + "openai = OpenAI()" + ] + }, + { + "cell_type": "code", + "execution_count": 118, + "id": "51c67ac0", + "metadata": {}, + "outputs": [], + "source": [ + "# contants\n", + "OPENAI_MODEL= \"gpt-5-nano\"" + ] + }, + { + "cell_type": "code", + "execution_count": 119, + "id": "ab4342bf", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'os': {'system': 'Darwin',\n", + " 'arch': 'arm64',\n", + " 'release': '24.5.0',\n", + " 'version': 'Darwin Kernel Version 24.5.0: Tue Apr 22 19:48:46 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T8103',\n", + " 'kernel': '24.5.0',\n", + " 'distro': None,\n", + " 'wsl': False,\n", + " 'rosetta2_translated': False,\n", + " 'target_triple': 'arm64-apple-darwin24.5.0'},\n", + " 'package_managers': ['xcode-select (CLT)', 'brew'],\n", + " 'cpu': {'brand': 'Apple M1',\n", + " 'cores_logical': 8,\n", + " 'cores_physical': 8,\n", + " 'simd': []},\n", + " 'toolchain': {'compilers': {'gcc': 'Apple clang version 17.0.0 (clang-1700.0.13.3)',\n", + " 'g++': 'Apple clang version 17.0.0 (clang-1700.0.13.3)',\n", + " 'clang': 'Apple clang version 17.0.0 (clang-1700.0.13.3)',\n", + " 'msvc_cl': ''},\n", + " 'build_tools': {'cmake': '', 'ninja': '', 'make': 'GNU Make 3.81'},\n", + " 'linkers': {'ld_lld': ''}}}" + ] + }, + "execution_count": 119, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "system_info = retrieve_system_info()\n", + "system_info" + ] + }, + { + "cell_type": "code", + "execution_count": 120, + "id": "1a1c1324", + "metadata": {}, + "outputs": [], + "source": [ + "message = f\"\"\"\n", + "Here is a report of the system information for my computer.\n", + "I want to run a TypeScript compiler to compile a single TypeScript file called main.cpp and then execute it in the simplest way possible.\n", + "Please reply with whether I need to install any TypeScript compiler to do this. If so, please provide the simplest step by step instructions to do so.\n", + "\n", + "If I'm already set up to compile TypeScript code, then I'd like to run something like this in Python to compile and execute the code:\n", + "```python\n", + "compile_command = # something here - to achieve the fastest possible runtime performance\n", + "compile_result = subprocess.run(compile_command, check=True, text=True, capture_output=True)\n", + "run_command = # something here\n", + "run_result = subprocess.run(run_command, check=True, text=True, capture_output=True)\n", + "return run_result.stdout\n", + "```\n", + "Please tell me exactly what I should use for the compile_command and run_command.\n", + "\n", + "System information:\n", + "{system_info}\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 121, + "id": "439015c1", + "metadata": {}, + "outputs": [ + { + "data": { + "text/markdown": [ + "Short answer:\n", + "- Yes, to compile TypeScript you need a TypeScript compiler (tsc). On macOS you’ll typically install Node.js first, then install TypeScript.\n", + "- Important: main.cpp sounds like a C++ file. The TypeScript compiler (tsc) cannot compile .cpp. If you want to use TypeScript, rename the file to main.ts (and ensure its contents are TypeScript). If you actually meant C++, use a C++ compiler instead (clang/g++).\n", + "\n", + "Step-by-step to set up TypeScript (simplest path on your system):\n", + "1) Install Node.js (which also installs npm)\n", + "- brew update\n", + "- brew install node\n", + "\n", + "2) Install the TypeScript compiler globally\n", + "- npm install -g typescript\n", + "\n", + "3) Verify installations\n", + "- node -v\n", + "- npm -v\n", + "- tsc -v\n", + "\n", + "4) Compile and run a TypeScript file (assuming your file is main.ts)\n", + "- tsc main.ts\n", + "- node main.js\n", + "\n", + "Notes:\n", + "- If your file is indeed C++ (main.cpp), you cannot compile it with tsc. To compile C++, use clang++ (on macOS) or g++:\n", + " - clang++ -std=c++17 main.cpp -o main\n", + " - ./main\n", + "\n", + "Python integration (fill-in for your example)\n", + "- If you have a TypeScript file named main.ts and you want to compile it to JavaScript and then run it with Node, use:\n", + " compile_command = [\"tsc\", \"main.ts\"]\n", + " run_command = [\"node\", \"main.js\"]\n", + "\n", + "- If you want to show a single command in Python that compiles and runs in one go (still two steps because TS compiles to JS first):\n", + " compile_command = [\"tsc\", \"main.ts\"]\n", + " run_command = [\"node\", \"main.js\"]\n", + "\n", + "- If you truly want to bypass TypeScript and run C++ instead (not TypeScript):\n", + " compile_command = [\"clang++\", \"-std=c++17\", \"main.cpp\", \"-o\", \"main\"]\n", + " run_command = [\"./main\"]\n", + "\n", + "If you’d like, tell me whether main.cpp is meant to be C++ or you actually have a TypeScript file named main.ts, and I can tailor the exact commands." + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "response = openai.chat.completions.create(model=OPENAI_MODEL, messages=[{\"role\":\"user\", \"content\":message}])\n", + "display(Markdown(response.choices[0].message.content))" + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "id": "576cb5fa", + "metadata": {}, + "outputs": [], + "source": [ + "compile_command = [\"tsc\", \"main.ts\", \"--target\", \"ES2020\", \"--module\", \"commonjs\"]\n", + "run_command = [\"ts-node\", \"main.ts\"]" + ] + }, + { + "cell_type": "markdown", + "id": "01b03700", + "metadata": {}, + "source": [ + "## System and user prompts for the code converter" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "id": "255e318b", + "metadata": {}, + "outputs": [], + "source": [ + "system_prompt = \"\"\"\n", + "Your task is to convert Python code into high performance TypeScript code.\n", + "Respond only with TypeScript code. Do not provide any explanation other than occasional comments.\n", + "The TypeScript response needs to produce an identical output in the fastest possible time.\n", + "\"\"\"\n", + "\n", + "\n", + "def user_prompt_for(python):\n", + " return f\"\"\" \n", + " port this Python code to TypeScript with the fastest possible implementation that produces identical output in the least time.\n", + "\n", + " The system information is \n", + "\n", + " {system_info}\n", + "\n", + " Your response will be written to a file called main.ts and then compile and ecexted; the compilation command is:\n", + "\n", + " {compile_command}\n", + "\n", + " Respond only with C++ code.\n", + " Python code to port:\n", + "\n", + " ```python\n", + " {python}\n", + " ```\n", + "\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "id": "09da7cb1", + "metadata": {}, + "outputs": [], + "source": [ + "def messages_for(python):\n", + " return [\n", + " {\"role\": \"system\", \"content\": system_prompt},\n", + " {\"role\": \"user\", \"content\": user_prompt_for(python)},\n", + " ]" + ] + }, + { + "cell_type": "code", + "execution_count": 125, + "id": "abcdb617", + "metadata": {}, + "outputs": [], + "source": [ + "def write_output(code):\n", + " with open(\"main.ts\", \"w\", encoding=\"utf-8\") as f:\n", + " f.write(code)" + ] + }, + { + "cell_type": "code", + "execution_count": 126, + "id": "c7a32d5f", + "metadata": {}, + "outputs": [], + "source": [ + "def convert(python):\n", + " reasoning_effort = \"high\"\n", + " response = openai.chat.completions.create(\n", + " model=OPENAI_MODEL,\n", + " messages=messages_for(python),\n", + " reasoning_effort=reasoning_effort,\n", + " )\n", + " reply = response.choices[0].message.content\n", + " reply = reply.replace(\"```ts\", \"\").replace(\"```\", \"\")\n", + " return reply" + ] + }, + { + "cell_type": "code", + "execution_count": 127, + "id": "59a7ec1f", + "metadata": {}, + "outputs": [], + "source": [ + "pi = \"\"\"\n", + "import time\n", + "\n", + "def calculate(iterations, param1, param2):\n", + " result = 1.0\n", + " for i in range(1, iterations+1):\n", + " j = i * param1 - param2\n", + " result -= (1/j)\n", + " j = i * param1 + param2\n", + " result += (1/j)\n", + " return result\n", + "\n", + "start_time = time.time()\n", + "result = calculate(200_000_000, 4, 1) * 4\n", + "end_time = time.time()\n", + "\n", + "print(f\"Result: {result:.12f}\")\n", + "print(f\"Execution Time: {(end_time - start_time):.6f} seconds\")\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 128, + "id": "6856393b", + "metadata": {}, + "outputs": [], + "source": [ + "def run_python(code):\n", + " globals_dict = {\"__builtins__\": __builtins__}\n", + "\n", + " buffer = io.StringIO()\n", + " old_stdout = sys.stdout\n", + " sys.stdout = buffer\n", + "\n", + " try:\n", + " exec(code, globals_dict)\n", + " output = buffer.getvalue()\n", + " except Exception as e:\n", + " output = f\"Error: {e}\"\n", + " finally:\n", + " sys.stdout = old_stdout\n", + "\n", + " return output" + ] + }, + { + "cell_type": "code", + "execution_count": 129, + "id": "c51fa5ea", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Result: 3.141592656089\\nExecution Time: 19.478347 seconds\\n'" + ] + }, + "execution_count": 129, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "run_python(pi)" + ] + }, + { + "cell_type": "code", + "execution_count": 130, + "id": "69eb2304", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "\"import { performance } from 'perf_hooks';\\n\\nfunction digamma(z: number): number {\\n let acc = 0;\\n while (z < 7) {\\n acc -= 1 / z;\\n z += 1;\\n }\\n const z2 = z * z;\\n const z4 = z2 * z2;\\n const z6 = z4 * z2;\\n const z8 = z4 * z4;\\n const z10 = z8 * z2;\\n const z12 = z10 * z2;\\n const series =\\n Math.log(z)\\n - 1 / (2 * z)\\n - 1 / (12 * z2)\\n + 1 / (120 * z4)\\n - 1 / (252 * z6)\\n + 1 / (240 * z8)\\n - 5 / (660 * z10)\\n + 691 / (32760 * z12);\\n return acc + series;\\n}\\n\\nconst N = 200_000_000;\\n\\nconst t0 = performance.now();\\nconst result =\\n 4 - digamma(N + 0.75) + digamma(0.75) + digamma(N + 1.25) - digamma(1.25);\\nconst t1 = performance.now();\\n\\nconsole.log(`Result: ${result.toFixed(12)}`);\\nconsole.log(`Execution Time: ${((t1 - t0) / 1000).toFixed(6)} seconds`);\"" + ] + }, + "execution_count": 130, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "convert(pi)" + ] + }, + { + "cell_type": "code", + "execution_count": 131, + "id": "2ea56d95", + "metadata": {}, + "outputs": [], + "source": [ + " \n", + "def run_typescript(code):\n", + " write_output(code)\n", + " try:\n", + " subprocess.run(compile_command, check=True, text=True, capture_output=True)\n", + " run_result = subprocess.run(run_command, check=True, text=True, capture_output=True)\n", + " return run_result.stdout\n", + " except subprocess.CalledProcessError as e:\n", + " return f\"An error occurred:\\n{e.stderr}\"" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "id": "79d6bd87", + "metadata": {}, + "outputs": [], + "source": [ + "# run_typescript()" + ] + }, + { + "cell_type": "markdown", + "id": "b4799b88", + "metadata": {}, + "source": [ + "## User Interface" + ] + }, + { + "cell_type": "code", + "execution_count": 133, + "id": "8486ce70", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* Running on local URL: http://127.0.0.1:7864\n", + "* To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 133, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "with gr.Blocks(\n", + " theme=gr.themes.Monochrome(), title=\"Port from Python to TypeScript\"\n", + ") as ui:\n", + " with gr.Row(equal_height=True):\n", + " with gr.Column(scale=6):\n", + " python = gr.Code(\n", + " label=\"Python Original Code\",\n", + " value=pi,\n", + " language=\"python\",\n", + " lines=30,\n", + " )\n", + " with gr.Column(scale=6):\n", + " ts = gr.Code(\n", + " label=\"TypeScript (generated)\", value=\"\", language=\"cpp\", lines=26\n", + " )\n", + " with gr.Row(elem_classes=[\"controls\"]):\n", + " python_run = gr.Button(\"Run Python\", elem_classes=[\"run-btn\", \"py\"])\n", + " port = gr.Button(\"Convert to TS\", elem_classes=[\"convert-btn\"])\n", + " ts_run = gr.Button(\"Run TS\", elem_classes=[\"run-btn\", \"ts\"])\n", + "\n", + " with gr.Row(equal_height=True):\n", + " with gr.Column(scale=6):\n", + " python_out = gr.TextArea(label=\"Python Result\", lines=10)\n", + " with gr.Column(scale=6):\n", + " ts_out = gr.TextArea(label=\"TS output\", lines=10)\n", + "\n", + " port.click(fn=convert, inputs=[python], outputs=[ts])\n", + " python_run.click(fn=run_python, inputs=[python], outputs=[python_out])\n", + " ts_run.click(fn=run_typescript, inputs=[ts], outputs=[ts_out])\n", + " \n", + " \n", + "ui.launch(inbrowser=True)" + ] + }, + { + "cell_type": "markdown", + "id": "4663a174", + "metadata": {}, + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9033e421", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}