khirodsahoo93 commited on
Commit
62a6332
Β·
verified Β·
1 Parent(s): d5cc32a

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -270
app.py CHANGED
@@ -1,6 +1,5 @@
1
  """
2
  Python to C++ Code Optimizer - AI-Powered Code Conversion
3
- Modern Gradio app with password protection for secure deployments
4
 
5
  Supported Models:
6
  - GPT-4o (OpenAI) - Premium, fastest, most accurate
@@ -19,8 +18,6 @@ import socket
19
  import httpx
20
  from openai import OpenAI
21
  import anthropic
22
- # Workaround for Python 3.13 where stdlib audioop is removed; instruct pydub to use pure-python fallback
23
- os.environ.setdefault("PYDUB_SIMPLE_AUDIOOP", "1")
24
  import gradio as gr
25
 
26
  # Try to load from .env file if available
@@ -132,6 +129,7 @@ def stream_claude(python):
132
  except Exception as e:
133
  yield f"❌ Error: {str(e)}"
134
 
 
135
  def optimize(python, model):
136
  """Convert Python to C++ using selected AI model"""
137
  if model in ["GPT-4o", "GPT"]:
@@ -205,11 +203,6 @@ print(f"Execution Time: {(end_time - start_time):.6f} seconds")
205
 
206
  # Modern CSS
207
  modern_css = """
208
- .gradio-container, body, html {
209
- background: #f9fafb !important; /* light background to avoid dark-mode conflicts */
210
- color: #111827 !important; /* ensure readable text */
211
- }
212
-
213
  .gradio-container {
214
  max-width: 1400px !important;
215
  margin: 0 auto !important;
@@ -377,259 +370,128 @@ modern_css = """
377
  color: #0c4a6e;
378
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
379
  }
380
-
381
- /* Login styling */
382
- body, .gradio-container {
383
- background: url('assets/3656064.jpg') center/cover no-repeat fixed !important;
384
- }
385
-
386
- .login-wrapper {
387
- display: flex;
388
- align-items: center;
389
- justify-content: center;
390
- min-height: 100vh;
391
- padding: 24px;
392
- background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url('assets/3656064.jpg') center/cover no-repeat fixed;
393
- }
394
-
395
- .login-card {
396
- max-width: 400px;
397
- width: 100%;
398
- background: rgba(255, 255, 255, 0.95);
399
- backdrop-filter: blur(10px);
400
- border: 1px solid rgba(255, 255, 255, 0.3);
401
- border-radius: 20px;
402
- padding: 48px 40px;
403
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
404
- }
405
-
406
- .login-icon {
407
- font-size: 56px;
408
- text-align: center;
409
- margin-bottom: 16px;
410
- filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
411
- }
412
-
413
- .login-title {
414
- text-align: center;
415
- margin: 0 0 8px 0;
416
- font-size: 28px;
417
- font-weight: 700;
418
- color: #1f2937;
419
- letter-spacing: -0.02em;
420
- }
421
-
422
- .login-subtitle {
423
- text-align: center;
424
- margin: 0 0 32px 0;
425
- font-size: 15px;
426
- color: #6b7280;
427
- font-weight: 400;
428
- }
429
-
430
- .login-input label {
431
- color: #374151 !important;
432
- font-weight: 600 !important;
433
- font-size: 14px !important;
434
- }
435
-
436
- .login-input input {
437
- background: white !important;
438
- border: 2px solid #e5e7eb !important;
439
- border-radius: 10px !important;
440
- padding: 12px 16px !important;
441
- font-size: 16px !important;
442
- color: #111827 !important;
443
- }
444
-
445
- .login-input input:focus {
446
- border-color: #667eea !important;
447
- background: white !important;
448
- outline: none !important;
449
- box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1) !important;
450
- }
451
-
452
- .login-error {
453
- color: #dc2626;
454
- background: #fee2e2;
455
- border: 1px solid #fca5a5;
456
- padding: 12px;
457
- border-radius: 10px;
458
- text-align: center;
459
- font-weight: 500;
460
- }
461
-
462
- .freepik-credit {
463
- margin-top: 24px;
464
- text-align: center;
465
- font-size: 12px;
466
- color: #9ca3af;
467
- }
468
-
469
- .freepik-credit a {
470
- color: #667eea;
471
- text-decoration: none;
472
- font-weight: 500;
473
- }
474
-
475
- .freepik-credit a:hover {
476
- text-decoration: underline;
477
- }
478
  """
479
 
480
  # Create the interface with password protection
481
  def create_interface():
482
  with gr.Blocks(css=modern_css, title="Python to C++ Code Optimizer", theme=gr.themes.Soft()) as app:
483
- authorized = gr.State(False)
484
- # Background image is handled via CSS: assets/3656064.jpg
485
- # For Hugging Face Space: use /file=assets/3656064.jpg in CSS
486
- # For local: use assets/3656064.jpg in CSS
487
-
488
- def check_password(pw):
489
- ok = pw == APP_PASSWORD
490
- return (
491
- gr.update(visible=not ok), # login hidden when ok
492
- gr.update(visible=ok), # main shown when ok
493
- gr.update(value="" if ok else "Invalid password", visible=not ok)
494
- )
495
-
496
- # Login gate
497
- with gr.Group(visible=True) as login_group:
498
- gr.HTML("""
499
- <div class="login-wrapper">
500
- <div class="login-card">
501
- <div class="login-icon">πŸ”</div>
502
- <div class="login-title">Private Access</div>
503
- <div class="login-subtitle">Enter password to continue</div>
504
- """)
505
- pw = gr.Textbox(
506
- label="Password",
507
- type="password",
508
- placeholder="Enter password",
509
- elem_classes=["login-input"],
510
- container=True
511
- )
512
- login_btn = gr.Button("Continue", elem_classes=["modern-button"], size="lg")
513
- login_error = gr.Markdown(visible=False, elem_classes=["login-error"])
514
- gr.HTML("""
515
- <div class="freepik-credit">Background image by <a href="https://www.freepik.com" target="_blank">Freepik</a></div>
516
- </div>
517
- </div>
518
- """)
519
-
520
- # Main UI wrapped for toggling visibility
521
- with gr.Group(visible=False) as main_group:
522
- main_group.elem_id = "main_group"
523
- # Header Section
524
- gr.HTML("""
525
- <div class="modern-header">
526
- <h1>πŸš€ Python to C++ Code Optimizer</h1>
527
- <p>AI-powered code conversion with real-time execution and performance analysis</p>
528
- </div>
529
- """)
530
-
531
- # Security Warning
532
- gr.HTML("""
533
- <div class="security-warning">
534
- <h3 style="color: #dc2626; margin: 0 0 8px 0;">⚠️ Security Warning</h3>
535
- <p style="margin: 0; color: #991b1b; font-weight: 500;">
536
- This interface executes arbitrary code. <strong>Only run code from trusted sources.</strong><br>
537
- Malicious code can harm your system. Use at your own risk.
538
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
539
  </div>
540
- """)
541
-
542
- # Main Content Area
543
- with gr.Row():
544
- with gr.Column(scale=1):
545
- gr.Markdown("### πŸ“ Python Code Input")
546
- python_input = gr.Textbox(
547
- label="Python Code:",
548
- value=default_python,
549
- lines=15,
550
- elem_classes=["python-input"],
551
- placeholder="Enter your Python code here..."
552
- )
553
-
554
- with gr.Row():
555
- model_selector = gr.Dropdown(
556
- ["GPT-4o", "Claude-3.5-Sonnet"],
557
- label="Select AI Model",
558
- value="GPT-4o",
559
- elem_classes=["model-selector"]
560
- )
561
-
562
- convert_button = gr.Button("✨ Convert to C++", elem_classes=["modern-button"])
563
-
564
- with gr.Column(scale=1):
565
- gr.Markdown("### ⚑ Optimized C++ Code")
566
- cpp_output = gr.Textbox(
567
- label="Generated C++ Code:",
568
- lines=15,
569
- elem_classes=["cpp-output"],
570
- interactive=False
571
- )
572
-
573
- # Execution Section
574
- gr.Markdown("---")
575
- gr.Markdown("## πŸƒ Code Execution & Performance Comparison")
576
-
577
- with gr.Row():
578
- with gr.Column():
579
- gr.Markdown("### 🐍 Python Output")
580
- run_python_button = gr.Button("▢️ Run Python", elem_classes=["run-button"])
581
- python_output = gr.Textbox(
582
- label="Python Execution Output:",
583
- lines=5,
584
- elem_classes=["python-output"],
585
- interactive=False
586
- )
587
-
588
- with gr.Column():
589
- gr.Markdown("### ⚑ C++ Output")
590
- run_cpp_button = gr.Button("▢️ Run C++", elem_classes=["run-button"])
591
- cpp_execution_output = gr.Textbox(
592
- label="C++ Execution Output:",
593
- lines=5,
594
- elem_classes=["cpp-output-result"],
595
- interactive=False
596
- )
597
-
598
- # Event handlers
599
- convert_button.click(
600
- fn=optimize,
601
- inputs=[python_input, model_selector],
602
- outputs=cpp_output
603
- )
604
-
605
- run_python_button.click(
606
- fn=execute_python,
607
- inputs=python_input,
608
- outputs=python_output
609
- )
610
-
611
- run_cpp_button.click(
612
- fn=execute_cpp,
613
- inputs=cpp_output,
614
- outputs=cpp_execution_output
615
- )
616
-
617
- # Bind login after main_group is defined
618
- login_btn.click(
619
- fn=check_password,
620
- inputs=[pw],
621
- outputs=[login_group, main_group, login_error]
622
  )
623
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
624
  return app
625
 
626
- # Launch the app
627
  if __name__ == "__main__":
628
- print("\n" + "="*50)
629
- print(f"===== Application Startup at {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")
630
- print("="*50)
631
-
632
- # Create the app
633
  app = create_interface()
634
 
635
  # Check if running on Hugging Face Spaces
@@ -637,32 +499,34 @@ if __name__ == "__main__":
637
 
638
  if is_huggingface:
639
  # Hugging Face Spaces configuration
640
- print("πŸš€ Launching Python to C++ Code Optimizer on Hugging Face Spaces")
641
- print("πŸ” Password protection enabled")
 
642
  app.launch(
643
- show_error=True
 
644
  )
645
  else:
646
  # Local development configuration
647
- def get_available_port(start_port=7860):
648
- """Find an available port starting from start_port"""
649
- port = start_port
650
- while port < start_port + 100:
651
- try:
652
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
653
- s.bind(('', port))
654
- return port
655
- except OSError:
656
- port += 1
657
- return start_port
658
 
659
- port = get_available_port()
660
- print(f"πŸš€ Launching Python to C++ Code Optimizer on port: {port}")
661
- print(f"πŸ” Password protection enabled. Password: {APP_PASSWORD}")
662
 
 
663
  app.launch(
 
 
664
  server_name="127.0.0.1",
665
- server_port=port,
666
- show_error=True
 
 
667
  )
668
 
 
1
  """
2
  Python to C++ Code Optimizer - AI-Powered Code Conversion
 
3
 
4
  Supported Models:
5
  - GPT-4o (OpenAI) - Premium, fastest, most accurate
 
18
  import httpx
19
  from openai import OpenAI
20
  import anthropic
 
 
21
  import gradio as gr
22
 
23
  # Try to load from .env file if available
 
129
  except Exception as e:
130
  yield f"❌ Error: {str(e)}"
131
 
132
+
133
  def optimize(python, model):
134
  """Convert Python to C++ using selected AI model"""
135
  if model in ["GPT-4o", "GPT"]:
 
203
 
204
  # Modern CSS
205
  modern_css = """
 
 
 
 
 
206
  .gradio-container {
207
  max-width: 1400px !important;
208
  margin: 0 auto !important;
 
370
  color: #0c4a6e;
371
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
372
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  """
374
 
375
  # Create the interface with password protection
376
  def create_interface():
377
  with gr.Blocks(css=modern_css, title="Python to C++ Code Optimizer", theme=gr.themes.Soft()) as app:
378
+
379
+ # Header Section
380
+ gr.HTML("""
381
+ <div class="modern-header">
382
+ <h1>πŸš€ Python to C++ Code Optimizer</h1>
383
+ <p>AI-powered code conversion with real-time execution and performance analysis</p>
384
+ </div>
385
+ """)
386
+
387
+ # Security Warning
388
+ gr.HTML("""
389
+ <div class="security-warning">
390
+ <h3 style="color: #dc2626; margin: 0 0 8px 0;">⚠️ Security Warning</h3>
391
+ <p style="margin: 0; color: #991b1b; font-weight: 500;">
392
+ This interface executes arbitrary code. <strong>Only run code from trusted sources.</strong><br>
393
+ Malicious code can harm your system. Use at your own risk.
394
+ </p>
395
+ </div>
396
+ """)
397
+
398
+ # Main Content Area
399
+ with gr.Row():
400
+ with gr.Column(scale=1):
401
+ gr.Markdown("### πŸ“ Python Code Input")
402
+ python_input = gr.Textbox(
403
+ label="Python Code:",
404
+ value=default_python,
405
+ lines=15,
406
+ placeholder="Enter your Python code here...",
407
+ elem_classes=["python-input"],
408
+ show_copy_button=True
409
+ )
410
+
411
+ gr.Markdown("### πŸ€– AI Model Selection")
412
+ model_selector = gr.Dropdown(
413
+ ["GPT-4o", "Claude-3.5-Sonnet"],
414
+ label="Select AI Model",
415
+ value="GPT-4o",
416
+ elem_classes=["model-selector"]
417
+ )
418
+
419
+ convert_btn = gr.Button("πŸ”„ Convert to C++", elem_classes=["modern-button"])
420
+
421
+ with gr.Column(scale=1):
422
+ gr.Markdown("### ⚑ Generated C++ Code")
423
+ cpp_output = gr.Textbox(
424
+ label="C++ Code:",
425
+ lines=15,
426
+ placeholder="Generated C++ code will appear here...",
427
+ elem_classes=["cpp-output"],
428
+ show_copy_button=True
429
+ )
430
+
431
+ # Execution Section
432
+ with gr.Row():
433
+ with gr.Column(scale=1):
434
+ gr.Markdown("### 🐍 Python Execution")
435
+ python_run_btn = gr.Button("▢️ Run Python", elem_classes=["run-button"])
436
+ python_result = gr.TextArea(
437
+ label="Python Output:",
438
+ lines=8,
439
+ elem_classes=["output-section", "python-output"],
440
+ placeholder="Python execution results will appear here..."
441
+ )
442
+
443
+ with gr.Column(scale=1):
444
+ gr.Markdown("### πŸš€ C++ Execution")
445
+ cpp_run_btn = gr.Button("▢️ Run C++", elem_classes=["run-button"])
446
+ cpp_result = gr.TextArea(
447
+ label="C++ Output:",
448
+ lines=8,
449
+ elem_classes=["output-section", "cpp-output-result"],
450
+ placeholder="C++ execution results will appear here..."
451
+ )
452
+
453
+ # Performance Metrics Section
454
+ gr.HTML("""
455
+ <div class="performance-card">
456
+ <h3>πŸ“Š Performance Comparison</h3>
457
+ <div>
458
+ <span class="performance-metric">Python: ~6.3s</span>
459
+ <span class="performance-metric">C++: ~0.6s</span>
460
+ <span class="performance-metric">Speedup: 10x</span>
461
  </div>
462
+ <p style="margin: 12px 0 0 0; color: #64748b; font-size: 14px;">
463
+ Compare execution times and performance metrics between Python and C++ implementations.<br>
464
+ Typical speedup: 10-100x depending on the algorithm.
465
+ </p>
466
+ </div>
467
+ """)
468
+
469
+ # Event Handlers
470
+ convert_btn.click(
471
+ optimize,
472
+ inputs=[python_input, model_selector],
473
+ outputs=[cpp_output],
474
+ show_progress=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  )
476
+
477
+ python_run_btn.click(
478
+ execute_python,
479
+ inputs=[python_input],
480
+ outputs=[python_result],
481
+ show_progress=True
482
+ )
483
+
484
+ cpp_run_btn.click(
485
+ execute_cpp,
486
+ inputs=[cpp_output],
487
+ outputs=[cpp_result],
488
+ show_progress=True
489
+ )
490
+
491
  return app
492
 
493
+ # Launch with password protection
494
  if __name__ == "__main__":
 
 
 
 
 
495
  app = create_interface()
496
 
497
  # Check if running on Hugging Face Spaces
 
499
 
500
  if is_huggingface:
501
  # Hugging Face Spaces configuration
502
+ print(f"πŸš€ Launching Python to C++ Code Optimizer on Hugging Face Spaces")
503
+ print(f"πŸ” Password protection enabled")
504
+
505
  app.launch(
506
+ auth=("user", APP_PASSWORD),
507
+ auth_message="πŸ” Enter credentials to access the Python to C++ Code Optimizer"
508
  )
509
  else:
510
  # Local development configuration
511
+ def find_free_port():
512
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
513
+ s.bind(('', 0))
514
+ s.listen(1)
515
+ port = s.getsockname()[1]
516
+ return port
 
 
 
 
 
517
 
518
+ free_port = find_free_port()
519
+ print(f"πŸš€ Launching Python to C++ Code Optimizer on port: {free_port}")
520
+ print(f"πŸ” Password protection enabled")
521
 
522
+ # Launch with authentication
523
  app.launch(
524
+ inbrowser=True,
525
+ share=True,
526
  server_name="127.0.0.1",
527
+ server_port=free_port,
528
+ show_error=True,
529
+ auth=("user", APP_PASSWORD),
530
+ auth_message="πŸ” Enter credentials to access the Python to C++ Code Optimizer"
531
  )
532