Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 234 additions & 0 deletions week4/community-contributions/victor_barny/code-converter.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3732a3e3",
"metadata": {},
"source": [
"# Code Converter - Python to Go\n",
"\n",
"Convert Python code to optimized Go code and run it.\n",
"Reference: `week4/community-contributions/tochi/code_converter.ipynb`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25c8addd",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"import os\n",
"import io\n",
"import sys\n",
"import json\n",
"import subprocess\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"from IPython.display import Markdown, display\n",
"import gradio as gr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "84e7192e",
"metadata": {},
"outputs": [],
"source": [
"# load env + client\n",
"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 environment variables and try again\")\n",
"\n",
"openai = OpenAI()\n",
"OPENAI_MODEL = \"gpt-5-nano\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "83b88d76",
"metadata": {},
"outputs": [],
"source": [
"# compile + run commands for Go\n",
"compile_command = [\"go\", \"build\", \"-o\", \"main\", \"main.go\"]\n",
"run_command = [\"./main\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a78d8317",
"metadata": {},
"outputs": [],
"source": [
"# prompts for conversion\n",
"system_prompt = \"\"\"\n",
"Your task is to convert Python code into high performance Go code.\n",
"Respond only with Go code. Do not provide any explanation other than occasional comments.\n",
"The Go response needs to produce an identical output in the fastest possible time.\n",
"\"\"\"\n",
"\n",
"def user_prompt_for(python):\n",
" return f\"\"\"\n",
"Port this Python code to Go with the fastest possible implementation that produces identical output in the least time.\n",
"\n",
"Your response will be written to a file called main.go and then compiled and executed; the compilation command is:\n",
"\n",
"{compile_command}\n",
"\n",
"Respond only with Go code.\n",
"Python code to port:\n",
"\n",
"```python\n",
"{python}\n",
"```\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c44604f3",
"metadata": {},
"outputs": [],
"source": [
"def messages_for(python):\n",
" return [\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": user_prompt_for(python)},\n",
" ]\n",
"\n",
"def write_output(code):\n",
" with open(\"main.go\", \"w\", encoding=\"utf-8\") as f:\n",
" f.write(code)\n",
"\n",
"def convert(python):\n",
" response = openai.chat.completions.create(\n",
" model=OPENAI_MODEL,\n",
" messages=messages_for(python),\n",
" reasoning_effort=\"high\",\n",
" )\n",
" reply = response.choices[0].message.content\n",
" reply = reply.replace(\"```go\", \"\").replace(\"```\", \"\")\n",
" return reply"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "31808299",
"metadata": {},
"outputs": [],
"source": [
"# sample python for testing\n",
"py_sample = \"\"\"\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": null,
"id": "e53a923d",
"metadata": {},
"outputs": [],
"source": [
"def run_python(code):\n",
" globals_dict = {\"__builtins__\": __builtins__}\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\n",
"\n",
"\n",
"def run_go(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": null,
"id": "2b95de77",
"metadata": {},
"outputs": [],
"source": [
"# Gradio UI\n",
"with gr.Blocks(theme=gr.themes.Monochrome(), title=\"Port from Python to Go\") 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=py_sample,\n",
" language=\"python\",\n",
" lines=30,\n",
" )\n",
" with gr.Column(scale=6):\n",
" go = gr.Code(\n",
" label=\"Go (generated)\", value=\"\", language=\"go\", 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 Go\", elem_classes=[\"convert-btn\"])\n",
" go_run = gr.Button(\"Run Go\", elem_classes=[\"run-btn\", \"go\"])\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",
" go_out = gr.TextArea(label=\"Go output\", lines=10)\n",
"\n",
" port.click(fn=convert, inputs=[python], outputs=[go])\n",
" python_run.click(fn=run_python, inputs=[python], outputs=[python_out])\n",
" go_run.click(fn=run_go, inputs=[go], outputs=[go_out])\n",
"\n",
"ui.launch(inbrowser=True)"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Common Cold
The common cold is a viral infection of your nose and throat (upper respiratory tract). It's usually harmless, although it might not feel that way. Many types of viruses can cause a common cold.
Symptoms: Runny or stuffy nose, sore throat, cough, congestion, slight body aches or a mild headache, sneezing, low-grade fever.
Prevention: Wash your hands, disinfect your stuff, use tissues, don't share, take care of yourself.

# Influenza (Flu)
Influenza is a viral infection that attacks your respiratory system — your nose, throat and lungs. Influenza is commonly called the flu, but it's not the same as stomach "flu" viruses that cause diarrhea and vomiting.
Symptoms: Fever, aching muscles, chills and sweats, headache, dry, persistent cough, shortness of breath, tiredness and weakness, runny or stuffy nose, sore throat, eye pain.
Prevention: Annual flu vaccine, hand-washing, avoiding crowds.

# Hypertension (High Blood Pressure)
Hypertension is a condition in which the force of the blood against your artery walls is too high. Usually hypertension is defined as blood pressure above 140/90, and is considered severe if the pressure is above 180/120.
Symptoms: Often has no symptoms. Over time, if untreated, it can cause health conditions, such as heart disease and stroke.
Treatment: Eating a healthier diet with less salt, exercising regularly, and taking medications can help lower blood pressure.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Paracetamol (Acetaminophen)
Usage: Common medication used to treat pain and fever. It is typically used for mild to moderate pain relief.
Side Effects: Nausea, stomach pain, loss of appetite, itching, rash, headache, dark urine, clay-colored stools, jaundice.
Warning: Avoid taking more than the recommended dose as it can cause serious liver damage.

# Ibuprofen
Usage: Nonsteroidal anti-inflammatory drug (NSAID) used for treating pain, fever, and inflammation.
Side Effects: Stomach pain, heartburn, nausea, vomiting, gas, constipation, diarrhea, dizziness, headache, nervousness, skin itching or rash, ringing in your ears.
Warning: Should be taken with food or milk to prevent stomach upset.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Cuts and Scrapes
1. Wash your hands.
2. Stop the bleeding with gentle pressure.
3. Clean the wound with water.
4. Apply an antibiotic or petroleum jelly.
5. Cover the wound with a bandage.

# Burns (Minor)
1. Cool the burn. Hold the burned area under cool (not cold) running water.
2. Remove rings or other tight items from the burned area.
3. Don't break blisters.
4. Apply lotion (aloe vera).
5. Bandage the burn.
Loading