anuragbb commited on
Commit
cac74e8
·
verified ·
1 Parent(s): fe98ed2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +422 -425
app.py CHANGED
@@ -1,425 +1,422 @@
1
- #!/usr/bin/env python
2
- # coding: utf-8
3
-
4
- # # Code Generator
5
- #
6
- # The requirement: use a Frontier model to generate high performance C++ code from Python code
7
- #
8
-
9
- # <table style="margin: 0; text-align: left;">
10
- # <tr>
11
- # <td style="width: 150px; height: 150px; vertical-align: middle;">
12
- # <img src="../resources.jpg" width="150" height="150" style="display: block;" />
13
- # </td>
14
- # <td>
15
- # <h2 style="color:#f71;">Reminder: fetch latest code</h2>
16
- # <span style="color:#f71;">I'm continually improving these labs, adding more examples and exercises.
17
- # At the start of each week, it's worth checking you have the latest code.<br/>
18
- # First do a <a href="https://chatgpt.com/share/6734e705-3270-8012-a074-421661af6ba9">git pull and merge your changes as needed</a>. Any problems? Try asking ChatGPT to clarify how to merge - or contact me!<br/><br/>
19
- # After you've pulled the code, from the llm_engineering directory, in an Anaconda prompt (PC) or Terminal (Mac), run:<br/>
20
- # <code>conda env update --f environment.yml --prune</code><br/>
21
- # Or if you used virtualenv rather than Anaconda, then run this from your activated environment in a Powershell (PC) or Terminal (Mac):<br/>
22
- # <code>pip install -r requirements.txt</code>
23
- # <br/>Then restart the kernel (Kernel menu >> Restart Kernel and Clear Outputs Of All Cells) to pick up the changes.
24
- # </span>
25
- # </td>
26
- # </tr>
27
- # </table>
28
-
29
- # <table style="margin: 0; text-align: left;">
30
- # <tr>
31
- # <td style="width: 150px; height: 150px; vertical-align: middle;">
32
- # <img src="../important.jpg" width="150" height="150" style="display: block;" />
33
- # </td>
34
- # <td>
35
- # <h1 style="color:#900;">Important Note</h1>
36
- # <span style="color:#900;">
37
- # In this lab, I use GPT-4o and Claude-3.5-Sonnet, which are the slightly higher priced models. The costs are still low, but if you'd prefer to keep costs ultra low, please make the suggested switches to the models (3 cells down from here).
38
- # </span>
39
- # </td>
40
- # </tr>
41
- # </table>
42
-
43
- # In[1]:
44
-
45
-
46
- # imports
47
-
48
- import os
49
- import io
50
- import sys
51
- from dotenv import load_dotenv
52
- from openai import OpenAI
53
-
54
- import anthropic
55
- from IPython.display import Markdown, display, update_display
56
- import gradio as gr
57
- import subprocess
58
- import google.generativeai as genai
59
-
60
-
61
- # In[2]:
62
-
63
-
64
- # environment
65
-
66
- load_dotenv()
67
-
68
- google_api_key = os.getenv('GOOGLE_API_KEY')
69
-
70
-
71
- # In[3]:
72
-
73
-
74
- GeminiModel=genai.configure(api_key=google_api_key)
75
-
76
-
77
- # In[4]:
78
-
79
-
80
- system_message = "You are an assistant that reimplements Python code in high performance C++ for an windows 11 OS. "
81
- system_message += "Respond only with C++ code; use comments sparingly and do not provide any explanation other than occasional comments. "
82
- system_message += "The C++ response needs to produce an identical output in the fastest possible time."
83
-
84
-
85
- # In[5]:
86
-
87
-
88
- def user_prompt_for(python):
89
- user_prompt = "Rewrite this Python code in C++ with the fastest possible implementation that produces identical output in the least time. "
90
- user_prompt += "Respond only with C++ code; do not explain your work other than a few comments. "
91
- user_prompt += "Pay attention to number types to ensure no int overflows. Remember to #include all necessary C++ packages such as iomanip.\n\n"
92
- user_prompt += python
93
- return user_prompt
94
-
95
-
96
- # In[6]:
97
-
98
-
99
- def messages_for(python):
100
- return [
101
- {"role": "system", "content": system_message},
102
- {"role": "user", "content": user_prompt_for(python)}
103
- ]
104
-
105
-
106
- # In[7]:
107
-
108
-
109
- def write_output(cpp):
110
- code = cpp.replace("```cpp","").replace("```","")
111
- with open("optimized.cpp", "w") as f:
112
- f.write(code)
113
-
114
-
115
- # In[8]:
116
-
117
-
118
- def optimize_gemini(python):
119
- stream=genai.GenerativeModel("gemini-1.5-flash")
120
- prompt=f"{system_message}\n\n{messages_for(python)}"
121
- response=stream.generate_content(prompt,stream=True)
122
- result=""
123
- for chunks in response:
124
- if chunks.text:
125
- result+=chunks.text
126
- print(chunks.text,end='',flush=True)
127
- write_output(result)
128
-
129
-
130
-
131
- # In[11]:
132
-
133
-
134
- pi = """
135
- import time
136
-
137
- def calculate(iterations, param1, param2):
138
- result = 1.0
139
- for i in range(1, iterations+1):
140
- j = i * param1 - param2
141
- result -= (1/j)
142
- j = i * param1 + param2
143
- result += (1/j)
144
- return result
145
-
146
- start_time = time.time()
147
- result = calculate(100_000_000, 4, 1) * 4
148
- end_time = time.time()
149
-
150
- print(f"Result: {result:.12f}")
151
- print(f"Execution Time: {(end_time - start_time):.6f} seconds")
152
- """
153
-
154
-
155
- # In[12]:
156
-
157
-
158
- exec(pi)
159
-
160
-
161
- # In[13]:
162
-
163
-
164
- optimize_gemini(pi)
165
-
166
-
167
- # In[14]:
168
-
169
-
170
- exec(pi)
171
-
172
-
173
- # # Compiling C++ and executing
174
- #
175
- # This next cell contains the command to compile a C++ file on my M1 Mac.
176
- # It compiles the file `optimized.cpp` into an executable called `optimized`
177
- # Then it runs the program called `optimized`
178
- #
179
- # You can google (or ask ChatGPT!) for how to do this on your platform, then replace the lines below.
180
- # If you're not comfortable with this step, you can skip it for sure - I'll show you exactly how it performs on my Mac.
181
-
182
- # In[15]:
183
-
184
-
185
- get_ipython().system('g++ -O3 -std=c++17 -o optimized.exe optimized.cpp')
186
- get_ipython().system('optimized.exe')
187
-
188
-
189
- # In[16]:
190
-
191
-
192
- optimize_gemini(pi)
193
-
194
-
195
- # In[20]:
196
-
197
-
198
- python_hard = """
199
- def lcg(seed, a=1664525, c=1013904223, m=2**32):
200
- value = seed
201
- while True:
202
- value = (a * value + c) % m
203
- yield value
204
-
205
- def max_subarray_sum(n, seed, min_val, max_val):
206
- lcg_gen = lcg(seed)
207
- random_numbers = [next(lcg_gen) % (max_val - min_val + 1) + min_val for _ in range(n)]
208
- max_sum = float('-inf')
209
- for i in range(n):
210
- current_sum = 0
211
- for j in range(i, n):
212
- current_sum += random_numbers[j]
213
- if current_sum > max_sum:
214
- max_sum = current_sum
215
- return max_sum
216
-
217
- def total_max_subarray_sum(n, initial_seed, min_val, max_val):
218
- total_sum = 0
219
- lcg_gen = lcg(initial_seed)
220
- for _ in range(20):
221
- seed = next(lcg_gen)
222
- total_sum += max_subarray_sum(n, seed, min_val, max_val)
223
- return total_sum
224
-
225
- # Parameters
226
- n = 10000 # Number of random numbers
227
- initial_seed = 42 # Initial seed for the LCG
228
- min_val = -10 # Minimum value of random numbers
229
- max_val = 10 # Maximum value of random numbers
230
-
231
- # Timing the function
232
- import time
233
- start_time = time.time()
234
- result = total_max_subarray_sum(n, initial_seed, min_val, max_val)
235
- end_time = time.time()
236
-
237
- print("Total Maximum Subarray Sum (20 runs):", result)
238
- print("Execution Time: {:.6f} seconds".format(end_time - start_time))
239
- """
240
-
241
-
242
- # In[21]:
243
-
244
-
245
- exec(python_hard)
246
-
247
-
248
- # In[22]:
249
-
250
-
251
- optimize_gemini(python_hard)
252
-
253
-
254
- # In[23]:
255
-
256
-
257
- get_ipython().system('g++ -O3 -std=c++17 -o optimized.exe optimized.cpp')
258
- get_ipython().system('optimized.exe')
259
-
260
-
261
- # In[28]:
262
-
263
-
264
- def write_output(cpp):
265
- code = cpp.replace("```cpp","").replace("```","")
266
- with open("optimized.cpp", "w") as f:
267
- f.write(code)
268
-
269
-
270
- # In[29]:
271
-
272
-
273
- def stream_gemini(python):
274
- stream=genai.GenerativeModel("gemini-1.5-flash")
275
- prompt=f"{system_message}\n\n{messages_for(python)}"
276
- response=stream.generate_content(prompt,stream=True)
277
- result=""
278
- for chunks in response:
279
- if chunks.text:
280
- result+=chunks.text
281
- print(chunks.text,end='',flush=True)
282
- write_output(result)
283
- return result
284
-
285
-
286
-
287
- # In[32]:
288
-
289
-
290
- def optimize(python, model):
291
- if model=="GEMINI":
292
- result = stream_gemini(python)
293
- return result
294
- else:
295
- raise ValueError("Unknown model")
296
- # for stream_so_far in result:
297
- # yield stream_so_far
298
-
299
-
300
- # In[34]:
301
-
302
-
303
- def execute_python(code):
304
- try:
305
- output = io.StringIO()
306
- sys.stdout = output
307
- exec(code)
308
- finally:
309
- sys.stdout = sys.__stdout__
310
- return output.getvalue()
311
-
312
-
313
- # In[35]:
314
-
315
-
316
- def execute_cpp(code):
317
- write_output(code)
318
- try:
319
- # Windows compilation and execution commands
320
- compile_cmd = ["g++", "-O3", "-std=c++17", "-o", "optimized.exe", "optimized.cpp"]
321
- compile_result = subprocess.run(compile_cmd, check=True, text=True, capture_output=True)
322
- run_cmd = ["optimized.exe"]
323
- run_result = subprocess.run(run_cmd, check=True, text=True, capture_output=True)
324
- return run_result.stdout
325
- except subprocess.CalledProcessError as e:
326
- return f"An error occurred:\n{e.stderr}"
327
-
328
-
329
- # In[51]:
330
-
331
-
332
- css = """
333
- .container { margin: 15px; padding: 15px; }
334
- .title { text-align: center; margin-bottom: 20px; }
335
- .code-container {
336
- background: #f5f5f5;
337
- border-radius: 10px;
338
- padding: 15px;
339
- height: 500px !important; /* Fixed height */
340
- overflow-y: auto !important; /* Enable vertical scrolling */
341
- }
342
- .button-row { gap: 10px; }
343
- .convert-button { background: #4CAF50 !important; }
344
- .run-button { background: #2196F3 !important; }
345
- .output-container {
346
- border-radius: 8px;
347
- padding: 10px;
348
- margin-top: 10px;
349
- }
350
- .python { background-color: #306998 !important; color: white !important; }
351
- .cpp { background-color: #00599C !important; color: white !important; }
352
-
353
- # /* Make sure the code editors take full height */
354
- # .code-container > div {
355
- # height: 100% !important;
356
- # }
357
- # .code-container textarea {
358
- # height: 100% !important;
359
- # }
360
- """
361
-
362
-
363
- # In[52]:
364
-
365
-
366
- with gr.Blocks(css=css) as ui:
367
- with gr.Column(elem_classes=["container"]):
368
- gr.Markdown("# 🔄 Python to C++ Converter", elem_classes=["title"])
369
-
370
- # Code input section
371
- with gr.Row(equal_height=True):
372
- with gr.Column():
373
- gr.Markdown("### Source Code")
374
- python = gr.Code(
375
- label="Python Code",
376
- value=python_hard,
377
- language="python",
378
- elem_classes=["code-container"]
379
- )
380
- with gr.Column():
381
- gr.Markdown("### Generated Code")
382
- cpp = gr.Code(
383
- label="C++ Code",
384
- language="cpp",
385
- elem_classes=["code-container"]
386
- )
387
-
388
- # Controls section
389
- with gr.Row(elem_classes=["button-row"]):
390
- model = gr.Dropdown(
391
- ["GEMINI"],
392
- label="Select Model",
393
- value="GEMINI",
394
- container=False
395
- )
396
- convert = gr.Button("🔄 Convert", elem_classes=["convert-button"])
397
-
398
- gr.Markdown("### Execution Results")
399
- with gr.Row(equal_height=True):
400
- with gr.Column():
401
- python_run = gr.Button("▶️ Run Python", elem_classes=["run-button"])
402
- python_out = gr.TextArea(
403
- label="Python Output",
404
- elem_classes=["output-container", "python"]
405
- )
406
- with gr.Column():
407
- cpp_run = gr.Button("▶️ Run C++", elem_classes=["run-button"])
408
- cpp_out = gr.TextArea(
409
- label="C++ Output",
410
- elem_classes=["output-container", "cpp"]
411
- )
412
-
413
- # Event handlers
414
- convert.click(fn=optimize, inputs=[python, model], outputs=cpp)
415
- python_run.click(fn=execute_python, inputs=[python], outputs=[python_out])
416
- cpp_run.click(fn=execute_cpp, inputs=[cpp], outputs=[cpp_out])
417
-
418
- ui.launch(inbrowser=True)
419
-
420
-
421
- # In[ ]:
422
-
423
-
424
-
425
-
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # # Code Generator
5
+ #
6
+ # The requirement: use a Frontier model to generate high performance C++ code from Python code
7
+ #
8
+
9
+ # <table style="margin: 0; text-align: left;">
10
+ # <tr>
11
+ # <td style="width: 150px; height: 150px; vertical-align: middle;">
12
+ # <img src="../resources.jpg" width="150" height="150" style="display: block;" />
13
+ # </td>
14
+ # <td>
15
+ # <h2 style="color:#f71;">Reminder: fetch latest code</h2>
16
+ # <span style="color:#f71;">I'm continually improving these labs, adding more examples and exercises.
17
+ # At the start of each week, it's worth checking you have the latest code.<br/>
18
+ # First do a <a href="https://chatgpt.com/share/6734e705-3270-8012-a074-421661af6ba9">git pull and merge your changes as needed</a>. Any problems? Try asking ChatGPT to clarify how to merge - or contact me!<br/><br/>
19
+ # After you've pulled the code, from the llm_engineering directory, in an Anaconda prompt (PC) or Terminal (Mac), run:<br/>
20
+ # <code>conda env update --f environment.yml --prune</code><br/>
21
+ # Or if you used virtualenv rather than Anaconda, then run this from your activated environment in a Powershell (PC) or Terminal (Mac):<br/>
22
+ # <code>pip install -r requirements.txt</code>
23
+ # <br/>Then restart the kernel (Kernel menu >> Restart Kernel and Clear Outputs Of All Cells) to pick up the changes.
24
+ # </span>
25
+ # </td>
26
+ # </tr>
27
+ # </table>
28
+
29
+ # <table style="margin: 0; text-align: left;">
30
+ # <tr>
31
+ # <td style="width: 150px; height: 150px; vertical-align: middle;">
32
+ # <img src="../important.jpg" width="150" height="150" style="display: block;" />
33
+ # </td>
34
+ # <td>
35
+ # <h1 style="color:#900;">Important Note</h1>
36
+ # <span style="color:#900;">
37
+ # In this lab, I use GPT-4o and Claude-3.5-Sonnet, which are the slightly higher priced models. The costs are still low, but if you'd prefer to keep costs ultra low, please make the suggested switches to the models (3 cells down from here).
38
+ # </span>
39
+ # </td>
40
+ # </tr>
41
+ # </table>
42
+
43
+ # In[1]:
44
+
45
+
46
+ # imports
47
+
48
+ import os
49
+ import io
50
+ import sys
51
+ from dotenv import load_dotenv
52
+ from IPython.display import Markdown, display, update_display
53
+ import gradio as gr
54
+ import subprocess
55
+ import google.generativeai as genai
56
+
57
+
58
+ # In[2]:
59
+
60
+
61
+ # environment
62
+
63
+ load_dotenv()
64
+
65
+ google_api_key = os.getenv('GOOGLE_API_KEY')
66
+
67
+
68
+ # In[3]:
69
+
70
+
71
+ GeminiModel=genai.configure(api_key=google_api_key)
72
+
73
+
74
+ # In[4]:
75
+
76
+
77
+ system_message = "You are an assistant that reimplements Python code in high performance C++ for an windows 11 OS. "
78
+ system_message += "Respond only with C++ code; use comments sparingly and do not provide any explanation other than occasional comments. "
79
+ system_message += "The C++ response needs to produce an identical output in the fastest possible time."
80
+
81
+
82
+ # In[5]:
83
+
84
+
85
+ def user_prompt_for(python):
86
+ user_prompt = "Rewrite this Python code in C++ with the fastest possible implementation that produces identical output in the least time. "
87
+ user_prompt += "Respond only with C++ code; do not explain your work other than a few comments. "
88
+ user_prompt += "Pay attention to number types to ensure no int overflows. Remember to #include all necessary C++ packages such as iomanip.\n\n"
89
+ user_prompt += python
90
+ return user_prompt
91
+
92
+
93
+ # In[6]:
94
+
95
+
96
+ def messages_for(python):
97
+ return [
98
+ {"role": "system", "content": system_message},
99
+ {"role": "user", "content": user_prompt_for(python)}
100
+ ]
101
+
102
+
103
+ # In[7]:
104
+
105
+
106
+ def write_output(cpp):
107
+ code = cpp.replace("```cpp","").replace("```","")
108
+ with open("optimized.cpp", "w") as f:
109
+ f.write(code)
110
+
111
+
112
+ # In[8]:
113
+
114
+
115
+ def optimize_gemini(python):
116
+ stream=genai.GenerativeModel("gemini-1.5-flash")
117
+ prompt=f"{system_message}\n\n{messages_for(python)}"
118
+ response=stream.generate_content(prompt,stream=True)
119
+ result=""
120
+ for chunks in response:
121
+ if chunks.text:
122
+ result+=chunks.text
123
+ print(chunks.text,end='',flush=True)
124
+ write_output(result)
125
+
126
+
127
+
128
+ # In[11]:
129
+
130
+
131
+ pi = """
132
+ import time
133
+
134
+ def calculate(iterations, param1, param2):
135
+ result = 1.0
136
+ for i in range(1, iterations+1):
137
+ j = i * param1 - param2
138
+ result -= (1/j)
139
+ j = i * param1 + param2
140
+ result += (1/j)
141
+ return result
142
+
143
+ start_time = time.time()
144
+ result = calculate(100_000_000, 4, 1) * 4
145
+ end_time = time.time()
146
+
147
+ print(f"Result: {result:.12f}")
148
+ print(f"Execution Time: {(end_time - start_time):.6f} seconds")
149
+ """
150
+
151
+
152
+ # In[12]:
153
+
154
+
155
+ exec(pi)
156
+
157
+
158
+ # In[13]:
159
+
160
+
161
+ optimize_gemini(pi)
162
+
163
+
164
+ # In[14]:
165
+
166
+
167
+ exec(pi)
168
+
169
+
170
+ # # Compiling C++ and executing
171
+ #
172
+ # This next cell contains the command to compile a C++ file on my M1 Mac.
173
+ # It compiles the file `optimized.cpp` into an executable called `optimized`
174
+ # Then it runs the program called `optimized`
175
+ #
176
+ # You can google (or ask ChatGPT!) for how to do this on your platform, then replace the lines below.
177
+ # If you're not comfortable with this step, you can skip it for sure - I'll show you exactly how it performs on my Mac.
178
+
179
+ # In[15]:
180
+
181
+
182
+ get_ipython().system('g++ -O3 -std=c++17 -o optimized.exe optimized.cpp')
183
+ get_ipython().system('optimized.exe')
184
+
185
+
186
+ # In[16]:
187
+
188
+
189
+ optimize_gemini(pi)
190
+
191
+
192
+ # In[20]:
193
+
194
+
195
+ python_hard = """
196
+ def lcg(seed, a=1664525, c=1013904223, m=2**32):
197
+ value = seed
198
+ while True:
199
+ value = (a * value + c) % m
200
+ yield value
201
+
202
+ def max_subarray_sum(n, seed, min_val, max_val):
203
+ lcg_gen = lcg(seed)
204
+ random_numbers = [next(lcg_gen) % (max_val - min_val + 1) + min_val for _ in range(n)]
205
+ max_sum = float('-inf')
206
+ for i in range(n):
207
+ current_sum = 0
208
+ for j in range(i, n):
209
+ current_sum += random_numbers[j]
210
+ if current_sum > max_sum:
211
+ max_sum = current_sum
212
+ return max_sum
213
+
214
+ def total_max_subarray_sum(n, initial_seed, min_val, max_val):
215
+ total_sum = 0
216
+ lcg_gen = lcg(initial_seed)
217
+ for _ in range(20):
218
+ seed = next(lcg_gen)
219
+ total_sum += max_subarray_sum(n, seed, min_val, max_val)
220
+ return total_sum
221
+
222
+ # Parameters
223
+ n = 10000 # Number of random numbers
224
+ initial_seed = 42 # Initial seed for the LCG
225
+ min_val = -10 # Minimum value of random numbers
226
+ max_val = 10 # Maximum value of random numbers
227
+
228
+ # Timing the function
229
+ import time
230
+ start_time = time.time()
231
+ result = total_max_subarray_sum(n, initial_seed, min_val, max_val)
232
+ end_time = time.time()
233
+
234
+ print("Total Maximum Subarray Sum (20 runs):", result)
235
+ print("Execution Time: {:.6f} seconds".format(end_time - start_time))
236
+ """
237
+
238
+
239
+ # In[21]:
240
+
241
+
242
+ exec(python_hard)
243
+
244
+
245
+ # In[22]:
246
+
247
+
248
+ optimize_gemini(python_hard)
249
+
250
+
251
+ # In[23]:
252
+
253
+
254
+ get_ipython().system('g++ -O3 -std=c++17 -o optimized.exe optimized.cpp')
255
+ get_ipython().system('optimized.exe')
256
+
257
+
258
+ # In[28]:
259
+
260
+
261
+ def write_output(cpp):
262
+ code = cpp.replace("```cpp","").replace("```","")
263
+ with open("optimized.cpp", "w") as f:
264
+ f.write(code)
265
+
266
+
267
+ # In[29]:
268
+
269
+
270
+ def stream_gemini(python):
271
+ stream=genai.GenerativeModel("gemini-1.5-flash")
272
+ prompt=f"{system_message}\n\n{messages_for(python)}"
273
+ response=stream.generate_content(prompt,stream=True)
274
+ result=""
275
+ for chunks in response:
276
+ if chunks.text:
277
+ result+=chunks.text
278
+ print(chunks.text,end='',flush=True)
279
+ write_output(result)
280
+ return result
281
+
282
+
283
+
284
+ # In[32]:
285
+
286
+
287
+ def optimize(python, model):
288
+ if model=="GEMINI":
289
+ result = stream_gemini(python)
290
+ return result
291
+ else:
292
+ raise ValueError("Unknown model")
293
+ # for stream_so_far in result:
294
+ # yield stream_so_far
295
+
296
+
297
+ # In[34]:
298
+
299
+
300
+ def execute_python(code):
301
+ try:
302
+ output = io.StringIO()
303
+ sys.stdout = output
304
+ exec(code)
305
+ finally:
306
+ sys.stdout = sys.__stdout__
307
+ return output.getvalue()
308
+
309
+
310
+ # In[35]:
311
+
312
+
313
+ def execute_cpp(code):
314
+ write_output(code)
315
+ try:
316
+ # Windows compilation and execution commands
317
+ compile_cmd = ["g++", "-O3", "-std=c++17", "-o", "optimized.exe", "optimized.cpp"]
318
+ compile_result = subprocess.run(compile_cmd, check=True, text=True, capture_output=True)
319
+ run_cmd = ["optimized.exe"]
320
+ run_result = subprocess.run(run_cmd, check=True, text=True, capture_output=True)
321
+ return run_result.stdout
322
+ except subprocess.CalledProcessError as e:
323
+ return f"An error occurred:\n{e.stderr}"
324
+
325
+
326
+ # In[51]:
327
+
328
+
329
+ css = """
330
+ .container { margin: 15px; padding: 15px; }
331
+ .title { text-align: center; margin-bottom: 20px; }
332
+ .code-container {
333
+ background: #f5f5f5;
334
+ border-radius: 10px;
335
+ padding: 15px;
336
+ height: 500px !important; /* Fixed height */
337
+ overflow-y: auto !important; /* Enable vertical scrolling */
338
+ }
339
+ .button-row { gap: 10px; }
340
+ .convert-button { background: #4CAF50 !important; }
341
+ .run-button { background: #2196F3 !important; }
342
+ .output-container {
343
+ border-radius: 8px;
344
+ padding: 10px;
345
+ margin-top: 10px;
346
+ }
347
+ .python { background-color: #306998 !important; color: white !important; }
348
+ .cpp { background-color: #00599C !important; color: white !important; }
349
+
350
+ # /* Make sure the code editors take full height */
351
+ # .code-container > div {
352
+ # height: 100% !important;
353
+ # }
354
+ # .code-container textarea {
355
+ # height: 100% !important;
356
+ # }
357
+ """
358
+
359
+
360
+ # In[52]:
361
+
362
+
363
+ with gr.Blocks(css=css) as ui:
364
+ with gr.Column(elem_classes=["container"]):
365
+ gr.Markdown("# 🔄 Python to C++ Converter", elem_classes=["title"])
366
+
367
+ # Code input section
368
+ with gr.Row(equal_height=True):
369
+ with gr.Column():
370
+ gr.Markdown("### Source Code")
371
+ python = gr.Code(
372
+ label="Python Code",
373
+ value=python_hard,
374
+ language="python",
375
+ elem_classes=["code-container"]
376
+ )
377
+ with gr.Column():
378
+ gr.Markdown("### Generated Code")
379
+ cpp = gr.Code(
380
+ label="C++ Code",
381
+ language="cpp",
382
+ elem_classes=["code-container"]
383
+ )
384
+
385
+ # Controls section
386
+ with gr.Row(elem_classes=["button-row"]):
387
+ model = gr.Dropdown(
388
+ ["GEMINI"],
389
+ label="Select Model",
390
+ value="GEMINI",
391
+ container=False
392
+ )
393
+ convert = gr.Button("🔄 Convert", elem_classes=["convert-button"])
394
+
395
+ gr.Markdown("### Execution Results")
396
+ with gr.Row(equal_height=True):
397
+ with gr.Column():
398
+ python_run = gr.Button("▶️ Run Python", elem_classes=["run-button"])
399
+ python_out = gr.TextArea(
400
+ label="Python Output",
401
+ elem_classes=["output-container", "python"]
402
+ )
403
+ with gr.Column():
404
+ cpp_run = gr.Button("▶️ Run C++", elem_classes=["run-button"])
405
+ cpp_out = gr.TextArea(
406
+ label="C++ Output",
407
+ elem_classes=["output-container", "cpp"]
408
+ )
409
+
410
+ # Event handlers
411
+ convert.click(fn=optimize, inputs=[python, model], outputs=cpp)
412
+ python_run.click(fn=execute_python, inputs=[python], outputs=[python_out])
413
+ cpp_run.click(fn=execute_cpp, inputs=[cpp], outputs=[cpp_out])
414
+
415
+ ui.launch(inbrowser=True)
416
+
417
+
418
+ # In[ ]:
419
+
420
+
421
+
422
+