import gradio as gr import os import subprocess import tempfile import time from openai import OpenAI import google.generativeai as genai # Initialize APIs openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) if os.getenv("OPENAI_API_KEY") else None genai.configure(api_key=os.getenv("GEMINI_API_KEY")) gemini_model = genai.GenerativeModel("gemini-2.0-flash-exp") if os.getenv("GEMINI_API_KEY") else None # System prompt from notebook SYSTEM_PROMPT = """You are an assistant that reimplements Python code in high performance C++ for Windows. Respond only with C++ code; use comments sparingly and do not provide any explanation other than occasional comments. The C++ must produce identical output in the fastest possible time.""" # Example codes from notebook EXAMPLES = { "PI Calculation": """import time def calculate(iterations, param1, param2): result = 1.0 for i in range(1, iterations+1): j = i * param1 - param2 result -= (1/j) j = i * param1 + param2 result += (1/j) return result start_time = time.time() result = calculate(1_000_000, 4, 1) * 4 end_time = time.time() print(f"Result: {result:.12f}") print(f"Execution Time: {(end_time - start_time):.6f} seconds")""", "Subarray Sum": """def lcg(seed, a=1664525, c=1013904223, m=2**32): value = seed while True: value = (a * value + c) % m yield value def max_subarray_sum(n, seed, min_val, max_val): lcg_gen = lcg(seed) random_numbers = [next(lcg_gen) % (max_val - min_val + 1) + min_val for _ in range(n)] max_sum = float('-inf') for i in range(n): current_sum = 0 for j in range(i, n): current_sum += random_numbers[j] if current_sum > max_sum: max_sum = current_sum return max_sum def total_max_subarray_sum(n, initial_seed, min_val, max_val): total_sum = 0 lcg_gen = lcg(initial_seed) for _ in range(20): seed = next(lcg_gen) total_sum += max_subarray_sum(n, seed, min_val, max_val) return total_sum n = 10000 initial_seed = 42 min_val = -10 max_val = 10 import time start_time = time.time() result = total_max_subarray_sum(n, initial_seed, min_val, max_val) end_time = time.time() print("Total Maximum Subarray Sum (20 runs):", result) print("Execution Time: {:.6f} seconds".format(end_time - start_time))""" } # Core functionality from notebook def generate_stream(python_code, model): user_prompt = f"Rewrite this Python code in C++ with the fastest possible implementation that produces identical output in the least time. Respond only with C++ code; do not explain your work other than a few comments. Pay attention to number types to ensure no int overflows. Remember to #include all necessary C++ packages such as iomanip or cstdint.\n{python_code}\n" if model == "GPT": stream = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}], stream=True ) for chunk in stream: content = chunk.choices.delta.content or "" yield content.replace("```cpp", "").replace("```","").replace("cpp","") elif model == "Gemini": response = gemini_model.generate_content(user_prompt, stream=True) for chunk in response: text = chunk.text or "" # Specjalna naprawa dla artefaktów Gemini cleaned = text.replace("```cpp", "").replace("```","").replace("cpp","") if cleaned.startswith("p"): cleaned = cleaned[1:] yield cleaned.strip() def execute_code(code, lang): with tempfile.NamedTemporaryFile(suffix=f".{lang}", delete=False) as f: f.write(code.encode()) file_path = f.name start_time = time.time() try: if lang == "cpp": compile_result = subprocess.run( ["g++", file_path, "-o", f"{file_path}.exe", "-O3", "-std=c++17"], capture_output=True, text=True ) if compile_result.returncode != 0: return f"Compilation error:\n{compile_result.stderr}", 0.0 exec_result = subprocess.run( [f"{file_path}.exe"], capture_output=True, text=True, timeout=10 ) else: exec_result = subprocess.run( ["python", file_path], capture_output=True, text=True, timeout=10 ) execution_time = time.time() - start_time output = exec_result.stdout or exec_result.stderr return output, execution_time except subprocess.TimeoutExpired: return "Timeout after 10 seconds", 0.0 finally: for fpath in [file_path, f"{file_path}.exe"]: try: os.unlink(fpath) except: pass # Gradio UI matching notebook layout with gr.Blocks(title="Python→C++ Converter") as app: gr.Markdown("# Python to Optimized C++ Converter\nGenerate and compare implementations") with gr.Row(): with gr.Column(): example_selector = gr.Dropdown( list(EXAMPLES.keys()), label="Select Example", value="PI Calculation" ) python_editor = gr.Code( label="Python Code", language="python", value=EXAMPLES["PI Calculation"] ) model_selector = gr.Radio( ["GPT", "Gemini"], label="AI Model", value="Gemini" ) generate_btn = gr.Button("Generate C++", variant="primary") with gr.Column(): cpp_output = gr.Code( label="Generated C++", language="cpp", interactive=True ) exec_py = gr.Button("Run Python Code") exec_cpp = gr.Button("Run C++ Code") execution_output = gr.Textbox( label="Execution Results", interactive=False ) # Example loader def load_example(example_name): return EXAMPLES[example_name] example_selector.change( load_example, example_selector, python_editor ) # Code generation def generate_handler(python_code, model): full_code = "" for chunk in generate_stream(python_code, model): full_code += chunk # Usuwanie wszystkich wystąpień znaczników kodu cleaned = full_code.replace("```cpp", "").replace("```","").replace("cpp","") # Specjalna obsługa przypadku gdy Gemini dodaje 'p' na początku if model == "Gemini" and cleaned.startswith("p"): cleaned = cleaned[1:].strip() yield cleaned generate_btn.click( generate_handler, [python_editor, model_selector], cpp_output ) # Code execution def execute_handler(code, lang): output, exec_time = execute_code(code, lang) return f"{output}\n\nExecution time: {exec_time:.6f}s" exec_py.click( lambda code: execute_handler(code, "py"), python_editor, execution_output ) exec_cpp.click( lambda code: execute_handler(code, "cpp"), cpp_output, execution_output ) if __name__ == "__main__": app.launch()