khirodsahoo93 commited on
Commit
af21194
Β·
verified Β·
1 Parent(s): 9e7eb94

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +149 -7
  2. app.py +499 -0
  3. requirements.txt +5 -0
README.md CHANGED
@@ -1,14 +1,156 @@
1
  ---
2
- title: Python Cpp Optimizer
3
- emoji: πŸ‘€
4
- colorFrom: blue
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: Converts python to cpp, execute the code
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Python to C++ Code Optimizer
3
+ emoji: πŸš€
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
11
  ---
12
 
13
+ # πŸš€ Python to C++ Code Optimizer
14
+
15
+ An AI-powered tool that converts Python code to high-performance C++ using GPT-4o and Claude-3.5-Sonnet.
16
+
17
+ ## 🎯 What It Does
18
+
19
+ This application takes Python code as input and uses frontier AI models to automatically convert it to optimized C++ code. It then allows you to:
20
+
21
+ - Compare the generated C++ code side-by-side with the original Python
22
+ - Execute both versions and compare performance
23
+ - See real-world speedups (typically 10-100x faster)
24
+
25
+ ## πŸ” Password Protection
26
+
27
+ This Space is password-protected. To access:
28
+
29
+ 1. **Username:** `user`
30
+ 2. **Password:** Contact the Space owner for the password
31
+
32
+ The password helps limit access while keeping the Space publicly discoverable.
33
+
34
+ ## ⚠️ Security Warning
35
+
36
+ **IMPORTANT**: This application executes arbitrary code (both Python and C++).
37
+
38
+ - Only run code from trusted sources
39
+ - Malicious code can harm the system
40
+ - Use at your own risk
41
+ - Not recommended for production use without proper sandboxing
42
+
43
+ ## πŸ”§ Setup Instructions
44
+
45
+ ### For Hugging Face Spaces
46
+
47
+ 1. Fork or duplicate this Space
48
+ 2. Go to **Settings** β†’ **Repository secrets**
49
+ 3. Add the following secrets:
50
+ - `OPENAI_API_KEY` - Your OpenAI API key from https://platform.openai.com/api-keys
51
+ - `ANTHROPIC_API_KEY` - Your Anthropic API key from https://console.anthropic.com/
52
+ - `APP_PASSWORD` - Your chosen password for accessing the app (e.g., `mySecurePass123`)
53
+
54
+ ### For Local Development
55
+
56
+ 1. Clone the repository
57
+ 2. Install dependencies:
58
+ ```bash
59
+ pip install -r requirements.txt
60
+ ```
61
+ 3. Set environment variables:
62
+ ```bash
63
+ export OPENAI_API_KEY="your-openai-key"
64
+ export ANTHROPIC_API_KEY="your-anthropic-key"
65
+ ```
66
+ 4. Run the app:
67
+ ```bash
68
+ python app.py
69
+ ```
70
+
71
+ ### For C++ Compilation
72
+
73
+ The app requires a C++ compiler:
74
+ - **Linux**: `g++` (usually pre-installed)
75
+ - **macOS**: Install Xcode Command Line Tools
76
+ - **Windows**: Install MinGW or use WSL
77
+
78
+ The default compilation command uses `g++`. You may need to adjust the compiler flags in `app.py` for your platform.
79
+
80
+ ## πŸŽ“ Educational Use
81
+
82
+ This project is designed for educational purposes to demonstrate:
83
+ - AI-powered code generation and optimization
84
+ - Performance differences between Python and C++
85
+ - Real-time streaming from AI models
86
+ - Interactive code execution environments
87
+
88
+ ## πŸ“Š Example Performance
89
+
90
+ **Pi Calculation (100M iterations):**
91
+ - Python: ~6.3 seconds
92
+ - C++ (optimized): ~0.6 seconds
93
+ - **Speedup: ~10x**
94
+
95
+ **Maximum Subarray (10K elements, 20 runs):**
96
+ - Python: ~45 seconds
97
+ - C++ (optimized): ~0.4 seconds
98
+ - **Speedup: ~110x**
99
+
100
+ ## πŸ›‘οΈ Safety Features
101
+
102
+ - Execution timeouts (30 seconds)
103
+ - Error handling for compilation failures
104
+ - Clear security warnings in UI
105
+ - Sandboxed execution recommended for production
106
+
107
+ ## πŸ“ Model Options
108
+
109
+ Choose between two frontier models:
110
+
111
+ 1. **GPT-4o** (OpenAI)
112
+ - Excellent at code generation
113
+ - Good optimization strategies
114
+ - Fast streaming responses
115
+
116
+ 2. **Claude-3.5-Sonnet** (Anthropic)
117
+ - Strong code understanding
118
+ - Detailed optimization
119
+ - High-quality output
120
+
121
+ ## πŸ’° Cost Considerations
122
+
123
+ Both models are paid APIs:
124
+ - GPT-4o: ~$5 per million input tokens
125
+ - Claude-3.5-Sonnet: ~$3 per million input tokens
126
+
127
+ For ultra-low cost, modify the code to use:
128
+ - `gpt-4o-mini` (20x cheaper)
129
+ - `claude-3-haiku` (15x cheaper)
130
+
131
+ ## 🀝 Contributing
132
+
133
+ Contributions are welcome! Please:
134
+ 1. Fork the repository
135
+ 2. Create a feature branch
136
+ 3. Submit a pull request
137
+
138
+ ## πŸ“„ License
139
+
140
+ MIT License - feel free to use and modify as needed.
141
+
142
+ ## ⚑ Credits
143
+
144
+ Created as part of an LLM Engineering course demonstrating practical applications of frontier AI models.
145
+
146
+ ## πŸ”— Resources
147
+
148
+ - [OpenAI Platform](https://platform.openai.com/)
149
+ - [Anthropic Console](https://console.anthropic.com/)
150
+ - [Gradio Documentation](https://www.gradio.app/docs/)
151
+ - [C++ Performance Optimization](https://en.cppreference.com/)
152
+
153
+ ---
154
+
155
+ **Disclaimer**: This tool is for educational and research purposes. Always review generated code before using in production. The developers assume no liability for damages caused by code execution.
156
+
app.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python to C++ Code Optimizer - Modern UI with Password Protection
3
+ AI-powered code conversion using GPT-4o and Claude-3.5-Sonnet
4
+
5
+ ⚠️ SECURITY WARNING:
6
+ This app executes arbitrary code. Only run code from trusted sources.
7
+ Malicious code can harm the system. Use at your own risk.
8
+ """
9
+
10
+ import os
11
+ import io
12
+ import sys
13
+ import subprocess
14
+ import socket
15
+ from openai import OpenAI
16
+ import anthropic
17
+ import gradio as gr
18
+
19
+ # Try to load from .env file if available
20
+ try:
21
+ from dotenv import load_dotenv
22
+ load_dotenv()
23
+ except ImportError:
24
+ pass
25
+
26
+ # PASSWORD PROTECTION
27
+ # Set this as a Hugging Face Secret: APP_PASSWORD
28
+ APP_PASSWORD = os.environ.get("APP_PASSWORD", "demo123") # Change default!
29
+
30
+ # Lazy initialization of AI clients
31
+ def get_openai_client():
32
+ api_key = os.environ.get("OPENAI_API_KEY")
33
+ if not api_key:
34
+ raise ValueError("OPENAI_API_KEY not found. Please set it in your environment or .env file.")
35
+ return OpenAI(api_key=api_key)
36
+
37
+ def get_claude_client():
38
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
39
+ if not api_key:
40
+ raise ValueError("ANTHROPIC_API_KEY not found. Please set it in your environment or .env file.")
41
+ return anthropic.Anthropic(api_key=api_key)
42
+
43
+ # Model configurations
44
+ OPENAI_MODEL = "gpt-4o"
45
+ CLAUDE_MODEL = "claude-3-5-sonnet-20240620"
46
+
47
+ # System and user prompts
48
+ system_message = (
49
+ "You are an assistant that reimplements Python code in high performance C++. "
50
+ "Respond only with C++ code; use comments sparingly and do not provide any explanation other than occasional comments. "
51
+ "The C++ response needs to produce an identical output in the fastest possible time."
52
+ )
53
+
54
+ def user_prompt_for(python):
55
+ user_prompt = (
56
+ "Rewrite this Python code in C++ with the fastest possible implementation that produces identical output in the least time. "
57
+ "Respond only with C++ code; do not explain your work other than a few comments. "
58
+ "Pay attention to number types to ensure no int overflows. Remember to #include all necessary C++ packages such as iomanip.\n\n"
59
+ )
60
+ user_prompt += python
61
+ return user_prompt
62
+
63
+ def messages_for(python):
64
+ return [
65
+ {"role": "system", "content": system_message},
66
+ {"role": "user", "content": user_prompt_for(python)}
67
+ ]
68
+
69
+ def write_output(cpp):
70
+ """Write C++ code to file for compilation"""
71
+ code = cpp.replace("```cpp","").replace("```","")
72
+ with open("optimized.cpp", "w") as f:
73
+ f.write(code)
74
+
75
+ def stream_gpt(python):
76
+ """Stream GPT-4o response"""
77
+ try:
78
+ client = get_openai_client()
79
+ stream = client.chat.completions.create(
80
+ model=OPENAI_MODEL,
81
+ messages=messages_for(python),
82
+ stream=True
83
+ )
84
+ reply = ""
85
+ for chunk in stream:
86
+ fragment = chunk.choices[0].delta.content or ""
87
+ reply += fragment
88
+ yield reply.replace('```cpp\n','').replace('```','')
89
+ except ValueError as e:
90
+ yield f"❌ Error: {str(e)}"
91
+ except Exception as e:
92
+ yield f"❌ Error: {str(e)}"
93
+
94
+ def stream_claude(python):
95
+ """Stream Claude response"""
96
+ try:
97
+ client = get_claude_client()
98
+ result = client.messages.stream(
99
+ model=CLAUDE_MODEL,
100
+ max_tokens=2000,
101
+ system=system_message,
102
+ messages=[{"role": "user", "content": user_prompt_for(python)}],
103
+ )
104
+ reply = ""
105
+ with result as stream:
106
+ for text in stream.text_stream:
107
+ reply += text
108
+ yield reply.replace('```cpp\n','').replace('```','')
109
+ except ValueError as e:
110
+ yield f"❌ Error: {str(e)}"
111
+ except Exception as e:
112
+ yield f"❌ Error: {str(e)}"
113
+
114
+ def optimize(python, model):
115
+ """Convert Python to C++ using selected AI model"""
116
+ if model in ["GPT-4o", "GPT"]:
117
+ result = stream_gpt(python)
118
+ elif model in ["Claude-3.5-Sonnet", "Claude"]:
119
+ result = stream_claude(python)
120
+ else:
121
+ raise ValueError(f"Unknown model: {model}")
122
+
123
+ for stream_so_far in result:
124
+ yield stream_so_far
125
+
126
+ def execute_python(code):
127
+ """⚠️ WARNING: Executes arbitrary Python code"""
128
+ try:
129
+ output = io.StringIO()
130
+ sys.stdout = output
131
+ exec(code)
132
+ finally:
133
+ sys.stdout = sys.__stdout__
134
+ return output.getvalue()
135
+
136
+ def execute_cpp(code):
137
+ """⚠️ WARNING: Compiles and executes arbitrary C++ code"""
138
+ write_output(code)
139
+ try:
140
+ compile_cmd = ["g++", "-O3", "-std=c++17", "-o", "optimized", "optimized.cpp"]
141
+ compile_result = subprocess.run(
142
+ compile_cmd,
143
+ check=True,
144
+ text=True,
145
+ capture_output=True,
146
+ timeout=30
147
+ )
148
+
149
+ run_cmd = ["./optimized"]
150
+ run_result = subprocess.run(
151
+ run_cmd,
152
+ check=True,
153
+ text=True,
154
+ capture_output=True,
155
+ timeout=30
156
+ )
157
+ return run_result.stdout
158
+ except subprocess.TimeoutExpired:
159
+ return "⚠️ Execution timed out (30 seconds limit)"
160
+ except subprocess.CalledProcessError as e:
161
+ return f"❌ An error occurred:\n{e.stderr}"
162
+ except Exception as e:
163
+ return f"❌ Unexpected error: {str(e)}"
164
+
165
+ # Example Python code
166
+ default_python = """import time
167
+
168
+ def calculate(iterations, param1, param2):
169
+ result = 1.0
170
+ for i in range(1, iterations+1):
171
+ j = i * param1 - param2
172
+ result -= (1/j)
173
+ j = i * param1 + param2
174
+ result += (1/j)
175
+ return result
176
+
177
+ start_time = time.time()
178
+ result = calculate(100_000_000, 4, 1) * 4
179
+ end_time = time.time()
180
+
181
+ print(f"Result: {result:.12f}")
182
+ print(f"Execution Time: {(end_time - start_time):.6f} seconds")
183
+ """
184
+
185
+ # Modern CSS
186
+ modern_css = """
187
+ .gradio-container {
188
+ max-width: 1400px !important;
189
+ margin: 0 auto !important;
190
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
191
+ }
192
+
193
+ .modern-header {
194
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
195
+ color: white;
196
+ padding: 24px;
197
+ border-radius: 16px;
198
+ margin-bottom: 24px;
199
+ text-align: center;
200
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
201
+ }
202
+
203
+ .modern-header h1 {
204
+ margin: 0;
205
+ font-size: 32px;
206
+ font-weight: 700;
207
+ letter-spacing: -0.5px;
208
+ }
209
+
210
+ .modern-header p {
211
+ margin: 12px 0 0 0;
212
+ opacity: 0.9;
213
+ font-size: 18px;
214
+ font-weight: 400;
215
+ }
216
+
217
+ .security-warning {
218
+ background: #fee2e2 !important;
219
+ border: 2px solid #dc2626 !important;
220
+ border-radius: 12px !important;
221
+ padding: 16px !important;
222
+ margin: 16px 0 !important;
223
+ }
224
+
225
+ .python-input {
226
+ background: #f8fafc !important;
227
+ border: 2px solid #e2e8f0 !important;
228
+ border-radius: 12px !important;
229
+ padding: 16px !important;
230
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
231
+ font-size: 14px !important;
232
+ color: #1e293b !important;
233
+ line-height: 1.5 !important;
234
+ }
235
+
236
+ .python-input:focus {
237
+ border-color: #3b82f6 !important;
238
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
239
+ }
240
+
241
+ .cpp-output {
242
+ background: #f1f5f9 !important;
243
+ border: 2px solid #cbd5e1 !important;
244
+ border-radius: 12px !important;
245
+ padding: 16px !important;
246
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
247
+ font-size: 14px !important;
248
+ color: #0f172a !important;
249
+ line-height: 1.5 !important;
250
+ }
251
+
252
+ .model-selector {
253
+ background: white !important;
254
+ border: 2px solid #e2e8f0 !important;
255
+ border-radius: 12px !important;
256
+ padding: 12px 16px !important;
257
+ font-size: 16px !important;
258
+ color: #374151 !important;
259
+ }
260
+
261
+ .model-selector:focus {
262
+ border-color: #3b82f6 !important;
263
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
264
+ }
265
+
266
+ .modern-button {
267
+ background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important;
268
+ color: white !important;
269
+ border: none !important;
270
+ border-radius: 12px !important;
271
+ padding: 14px 28px !important;
272
+ font-weight: 600 !important;
273
+ font-size: 16px !important;
274
+ cursor: pointer !important;
275
+ transition: all 0.2s ease !important;
276
+ box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2) !important;
277
+ }
278
+
279
+ .modern-button:hover {
280
+ transform: translateY(-2px) !important;
281
+ box-shadow: 0 8px 12px rgba(59, 130, 246, 0.3) !important;
282
+ }
283
+
284
+ .run-button {
285
+ background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
286
+ color: white !important;
287
+ border: none !important;
288
+ border-radius: 10px !important;
289
+ padding: 12px 24px !important;
290
+ font-weight: 600 !important;
291
+ font-size: 14px !important;
292
+ cursor: pointer !important;
293
+ transition: all 0.2s ease !important;
294
+ box-shadow: 0 4px 6px rgba(16, 185, 129, 0.2) !important;
295
+ }
296
+
297
+ .run-button:hover {
298
+ transform: translateY(-1px) !important;
299
+ box-shadow: 0 6px 8px rgba(16, 185, 129, 0.3) !important;
300
+ }
301
+
302
+ .output-section {
303
+ background: #f8fafc;
304
+ border: 1px solid #e2e8f0;
305
+ border-radius: 12px;
306
+ padding: 16px;
307
+ margin: 12px 0;
308
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
309
+ font-size: 13px;
310
+ line-height: 1.4;
311
+ color: #374151;
312
+ min-height: 100px;
313
+ overflow-y: auto;
314
+ }
315
+
316
+ .python-output {
317
+ background: #fef3c7 !important;
318
+ border: 2px solid #f59e0b !important;
319
+ color: #92400e !important;
320
+ }
321
+
322
+ .cpp-output-result {
323
+ background: #dbeafe !important;
324
+ border: 2px solid #3b82f6 !important;
325
+ color: #1e40af !important;
326
+ }
327
+
328
+ .performance-card {
329
+ background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
330
+ border: 1px solid #0ea5e9;
331
+ border-radius: 12px;
332
+ padding: 20px;
333
+ margin: 16px 0;
334
+ text-align: center;
335
+ }
336
+
337
+ .performance-card h3 {
338
+ margin: 0 0 12px 0;
339
+ color: #0c4a6e;
340
+ font-size: 18px;
341
+ font-weight: 600;
342
+ }
343
+
344
+ .performance-metric {
345
+ display: inline-block;
346
+ background: white;
347
+ border-radius: 8px;
348
+ padding: 8px 16px;
349
+ margin: 4px;
350
+ font-weight: 600;
351
+ color: #0c4a6e;
352
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
353
+ }
354
+ """
355
+
356
+ # Create the interface with password protection
357
+ def create_interface():
358
+ with gr.Blocks(css=modern_css, title="Python to C++ Code Optimizer", theme=gr.themes.Soft()) as app:
359
+
360
+ # Header Section
361
+ gr.HTML("""
362
+ <div class="modern-header">
363
+ <h1>πŸš€ Python to C++ Code Optimizer</h1>
364
+ <p>AI-powered code conversion with real-time execution and performance analysis</p>
365
+ </div>
366
+ """)
367
+
368
+ # Security Warning
369
+ gr.HTML("""
370
+ <div class="security-warning">
371
+ <h3 style="color: #dc2626; margin: 0 0 8px 0;">⚠️ Security Warning</h3>
372
+ <p style="margin: 0; color: #991b1b; font-weight: 500;">
373
+ This interface executes arbitrary code. <strong>Only run code from trusted sources.</strong><br>
374
+ Malicious code can harm your system. Use at your own risk.
375
+ </p>
376
+ </div>
377
+ """)
378
+
379
+ # Main Content Area
380
+ with gr.Row():
381
+ with gr.Column(scale=1):
382
+ gr.Markdown("### πŸ“ Python Code Input")
383
+ python_input = gr.Textbox(
384
+ label="Python Code:",
385
+ value=default_python,
386
+ lines=15,
387
+ placeholder="Enter your Python code here...",
388
+ elem_classes=["python-input"],
389
+ show_copy_button=True
390
+ )
391
+
392
+ gr.Markdown("### πŸ€– AI Model Selection")
393
+ model_selector = gr.Dropdown(
394
+ ["GPT-4o", "Claude-3.5-Sonnet"],
395
+ label="Select AI Model",
396
+ value="GPT-4o",
397
+ elem_classes=["model-selector"]
398
+ )
399
+
400
+ convert_btn = gr.Button("πŸ”„ Convert to C++", elem_classes=["modern-button"])
401
+
402
+ with gr.Column(scale=1):
403
+ gr.Markdown("### ⚑ Generated C++ Code")
404
+ cpp_output = gr.Textbox(
405
+ label="C++ Code:",
406
+ lines=15,
407
+ placeholder="Generated C++ code will appear here...",
408
+ elem_classes=["cpp-output"],
409
+ show_copy_button=True
410
+ )
411
+
412
+ # Execution Section
413
+ with gr.Row():
414
+ with gr.Column(scale=1):
415
+ gr.Markdown("### 🐍 Python Execution")
416
+ python_run_btn = gr.Button("▢️ Run Python", elem_classes=["run-button"])
417
+ python_result = gr.TextArea(
418
+ label="Python Output:",
419
+ lines=8,
420
+ elem_classes=["output-section", "python-output"],
421
+ placeholder="Python execution results will appear here..."
422
+ )
423
+
424
+ with gr.Column(scale=1):
425
+ gr.Markdown("### πŸš€ C++ Execution")
426
+ cpp_run_btn = gr.Button("▢️ Run C++", elem_classes=["run-button"])
427
+ cpp_result = gr.TextArea(
428
+ label="C++ Output:",
429
+ lines=8,
430
+ elem_classes=["output-section", "cpp-output-result"],
431
+ placeholder="C++ execution results will appear here..."
432
+ )
433
+
434
+ # Performance Metrics Section
435
+ gr.HTML("""
436
+ <div class="performance-card">
437
+ <h3>πŸ“Š Performance Comparison</h3>
438
+ <div>
439
+ <span class="performance-metric">Python: ~6.3s</span>
440
+ <span class="performance-metric">C++: ~0.6s</span>
441
+ <span class="performance-metric">Speedup: 10x</span>
442
+ </div>
443
+ <p style="margin: 12px 0 0 0; color: #64748b; font-size: 14px;">
444
+ Compare execution times and performance metrics between Python and C++ implementations.<br>
445
+ Typical speedup: 10-100x depending on the algorithm.
446
+ </p>
447
+ </div>
448
+ """)
449
+
450
+ # Event Handlers
451
+ convert_btn.click(
452
+ optimize,
453
+ inputs=[python_input, model_selector],
454
+ outputs=[cpp_output],
455
+ show_progress=True
456
+ )
457
+
458
+ python_run_btn.click(
459
+ execute_python,
460
+ inputs=[python_input],
461
+ outputs=[python_result],
462
+ show_progress=True
463
+ )
464
+
465
+ cpp_run_btn.click(
466
+ execute_cpp,
467
+ inputs=[cpp_output],
468
+ outputs=[cpp_result],
469
+ show_progress=True
470
+ )
471
+
472
+ return app
473
+
474
+ # Launch with password protection
475
+ if __name__ == "__main__":
476
+ app = create_interface()
477
+
478
+ def find_free_port():
479
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
480
+ s.bind(('', 0))
481
+ s.listen(1)
482
+ port = s.getsockname()[1]
483
+ return port
484
+
485
+ free_port = find_free_port()
486
+ print(f"πŸš€ Launching Python to C++ Code Optimizer on port: {free_port}")
487
+ print(f"πŸ” Password protection enabled. Password: {APP_PASSWORD}")
488
+
489
+ # Launch with authentication
490
+ app.launch(
491
+ inbrowser=True,
492
+ share=False,
493
+ server_name="127.0.0.1",
494
+ server_port=free_port,
495
+ show_error=True,
496
+ auth=("user", APP_PASSWORD), # Simple username/password
497
+ auth_message="πŸ” Enter credentials to access the Python to C++ Code Optimizer"
498
+ )
499
+
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ openai==1.54.3
3
+ anthropic==0.39.0
4
+ python-dotenv==1.0.0
5
+