CoolFace
Apppublic

MightyOctopus/python-to-cpp-code-optimizer

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
app.py221 linesDownload Raw Back to root
1import os, io, sys, subprocess, shutil2from dotenv import load_dotenv3from openai import OpenAI4from google import genai5from google.genai import types6import gradio as gr7from datetime import datetime8from placeholder_python_code import pi_1, pi_29from css_elements import css_elements10 11### Environment12load_dotenv(".env")13OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")14ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")15GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")16 17### Initialize18openai_client = OpenAI(api_key=OPENAI_API_KEY)19gemini_client = genai.Client(api_key=GEMINI_API_KEY)20OPENAI_MODEL = "gpt-5-mini-2025-08-07"21GEMINI_MODEL = "gemini-1.5-flash"22 23 24def system_message_for_python() -> str:25    system_message = """26        You are an assistant that reimplements Python code in high performance C++27        for an M1 Mac.28    """.strip()29 30    system_message += """31        Respond only with C++; use comments sparingly and do not provide any32        explanation other than occasion comments.33    """.strip()34 35    system_message += """36        The C++ response needs to produce an identical output in the 37        fastest possible time. 38    """.strip()39 40    return system_message41 42current_time = datetime.now().strftime("%Y%m%d_%H:%M:%S")43 44def user_prompt_for_python(python_code):45    user_prompt = """46        Rewrite this Python code in C++ with the fastest possible implementation47        that produces identical output in the least time.48    """.strip()49    user_prompt += """50        Respond only with C++ code; do not explain your work other than the real code. 51        And also do not include ```cpp and as such. But just working code only!52    """.strip()53    user_prompt += """54        Pay attention to number types to ensure no int overflows. Remember to #include 55        all necessary C++ packages such as iomanip.\n\n56    """.strip()57    user_prompt += python_code58 59    return user_prompt60 61def messages_for_python(python):62    return [63        {"role": "system", "content": system_message_for_python()},64        {"role": "user", "content": user_prompt_for_python(python)}65    ]66 67### remove ```cpp and ```68### cpp is a file extension of C++ code69def write_output(cpp: str):70    code = cpp.replace("```cpp", "").replace("```", "")71    with open(f"/tmp/optimized-{current_time}.cpp", "w") as f:72        f.write(code)73 74def convert_and_optimize_code_with_openai(python: str):75    stream = openai_client.chat.completions.create(76        model=OPENAI_MODEL,77        messages=messages_for_python(python),78        stream=True79    )80    stream_response = ""81    for chunk in stream:82        fragment = chunk.choices[0].delta.content or ""83        stream_response += fragment84        # print(fragment, end="", flush=True)85 86        yield fragment87 88def convert_and_optimize_code_with_gemini(python: str):89    user_prompt = user_prompt_for_python(python)90 91    stream = gemini_client.models.generate_content_stream(92        model=GEMINI_MODEL,93        contents=user_prompt,94        config=types.GenerateContentConfig(95            system_instruction=system_message_for_python()96        ),97    )98 99    for chunk in stream:100        stream_response = getattr(chunk, "text", "")101        if stream_response:102            yield stream_response103 104    ### OR THIS -- Gemini model returns an object other than string. So it needs to retrieve the text105    # for chunk in stream:106    #     if chunk.text:107    #         yield chunk.text108 109 110# convert_and_optimize_code_with_openai(pi_1)111 112 113###============================= GRADIO UI ================================###114 115def stream_text_on_ui(model, pi):116    """117    :param model: The selected LLM model used for converting Python code to C++118    :param pi: Input Python code string119    :yield response: Each chunk of stream data(generated text) received from LLM call120    """121    response = ""122    if model == "GPT-5":123        stream_res = convert_and_optimize_code_with_openai(pi)124    elif model == "Gemini":125        stream_res = convert_and_optimize_code_with_gemini(pi)126    else:127        raise ValueError("Unknown model...")128    ### another loop to take in the streaming chunk129    for chunk in stream_res:130        response += chunk131        response = response.replace("```cpp", "").replace("```", "").replace("cpp", "")132        yield response133 134def run_python_code(code: str):135    output = io.StringIO()136    old_stdout = sys.stdout137    try:138        sys.stdout = output139        ### For proper ISOLATION: use a fresh globals __main__ dict140        exec(code, {"__name__": "__main__"})141        return output.getvalue()142    except Exception as e:143        return output.getvalue() + f"-- {e}"144    finally:145        sys.stdout = old_stdout146 147### subprocess used to connect to the external programs (g++ for c++ build and compile)148def run_cpp_code(code: str):149    write_output(code)150    try:151        compiler = shutil.which("clang++") or shutil.which("g++")152        if not compiler:153            return "Error: No C++ compiler found in container."154            155        ### 1. Compile the code156        compile_cmd = [157            compiler, "-O3", "-ffast-math", "-std=c++17",158             "-o", "/tmp/optimized",159            f"/tmp/optimized-{current_time}.cpp"160        ]161        subprocess.run(162            compile_cmd, check=True, text=True, capture_output=True163        )164 165        ### 2. Run the code166        run_cmd = [f"/tmp/optimized"]167        run_result = subprocess.run(168            run_cmd, check=True, text=True, capture_output=True169        )170        return run_result.stdout171    except subprocess.CalledProcessError as e:172        return f"An error occurred:\n{e.stderr}"173 174 175with gr.Blocks(176    css=css_elements,177    title="Python To C++ Code Convertor"178) as ui:179    with gr.Row():180        pi_textbox = gr.Textbox(label="Place Python Code Here:", lines=20, value=pi_1)181        cpp_output = gr.Textbox(label="C++ Code Converted:", lines=20)182 183    with gr.Row():184        model_selection = gr.Dropdown(185            choices=["GPT-5", "Gemini"],186            label="Select Model",187            value="GPT-5",188            interactive=True189        )190 191    with gr.Row():192        convert_btn = gr.Button(value="Convert", size="lg")193 194    with gr.Row():195        run_py_btn = gr.Button(value="Run Python")196        run_cpp_btn = gr.Button(value="Run C++")197 198    with gr.Row():199        python_out = gr.TextArea(label="Python Result:", elem_classes=["python"])200        cpp_out = gr.TextArea(label="C++ Result:", elem_classes=["cpp"])201 202    convert_btn.click(203        fn=stream_text_on_ui,204        inputs=[model_selection, pi_textbox],205        outputs=cpp_output206    )207 208    run_py_btn.click(209        fn=run_python_code,210        inputs=pi_textbox,211        outputs=python_out212    )213    run_cpp_btn.click(214        fn=run_cpp_code,215        inputs=cpp_output,216        outputs=cpp_out217    )218 219 220port = int(os.getenv("PORT", 7860))221ui.launch(server_name="0.0.0.0", server_port=port)