Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 51 additions & 36 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
This provides a comprehensive web UI for the QPyth quantum computing library on Hugging Face Spaces.
"""

import json

import gradio as gr
import numpy as np
from qiskit import QuantumCircuit

from quantumpytho.engine import QuantumEngine
from quantumpytho.modules.bloch_ascii import one_qubit_from_angles
from quantumpytho.modules.circuit_explorer import bell_pair
Expand All @@ -25,8 +28,8 @@ def bloch_sphere_demo(theta, phi):
def create_bell_pair():
"""Create a Bell pair and return circuit diagram."""
try:
circuit = bell_pair()
return circuit.draw(output='text')
result = bell_pair(engine)
return result.circuit.draw(output="text")
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result.circuit.draw(output="text") returns a Qiskit drawing object (e.g., TextDrawing), not a plain string. Gradio Textbox outputs are simplest/most reliable when they receive a string; consider converting the drawing to str(...) (or calling .__str__()) before returning so the UI consistently renders the diagram.

Suggested change
return result.circuit.draw(output="text")
return str(result.circuit.draw(output="text"))

Copilot uses AI. Check for mistakes.
except Exception as e:
return f"Error: {str(e)}"

Expand All @@ -38,7 +41,9 @@ def run_quantum_teleport():

circuit = build_teleport_circuit()
result = engine.run(circuit)
return f"Teleportation circuit executed successfully!\n\nCounts: {result.counts}"
return (
f"Teleportation circuit executed successfully!\n\nCounts: {result.counts}"
)
except Exception as e:
return f"Error: {str(e)}"

Expand All @@ -56,6 +61,7 @@ def run_qec_demo(code_type="Shor"):
return run_steane_qec_demo()
else: # Surface
from quantumpytho.modules.qec_surface import run_surface_code_demo

return run_surface_code_demo()
except Exception as e:
return f"Error: {str(e)}"
Expand All @@ -78,60 +84,63 @@ def generate_qrng(count, phi_scale=False):
except Exception as e:
return f"Error: {str(e)}"


def run_vqe_h2(bond_length=0.74, shots=1024):
"""Run VQE for H2 molecule."""
try:
from quantumpytho.modules.vqe_h2_exact import compute_exact_energy
from quantumpytho.modules.vqe_core import VQEEngine

from quantumpytho.modules.vqe_h2_exact import compute_exact_energy

# Compute exact energy
exact_energy = compute_exact_energy(bond_length)

# Run VQE
vqe_engine = VQEEngine()
result = vqe_engine.run_h2(bond_length=bond_length, shots=shots)

output = f"""VQE Results for H₂ Molecule:
Bond Length: {bond_length} Å
Shots: {shots}

Exact Energy: {exact_energy:.6f} Hartree
VQE Energy: {result.get('energy', 'N/A')} Hartree
Error: {result.get('error', 'N/A')} Hartree
VQE Energy: {result.get("energy", "N/A")} Hartree
Error: {result.get("error", "N/A")} Hartree

Circuit Depth: {result.get('depth', 'N/A')}
Iterations: {result.get('iterations', 'N/A')}
Circuit Depth: {result.get("depth", "N/A")}
Iterations: {result.get("iterations", "N/A")}
"""
return output
except Exception as e:
return f"Error: {str(e)}"


def run_noisy_simulation(backend_profile="IBM", noise_level=0.01):
"""Run noisy simulation with backend profiles."""
try:
from quantumpytho.modules.noise_builder import NoiseModelBuilder
from quantumpytho.modules.backend_profiles import get_backend_profile

from quantumpytho.modules.noise_builder import NoiseModelBuilder

# Get backend profile
profile = get_backend_profile(backend_profile)

# Create circuit
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0, 1], [0, 1])

# Build noise model
noise_builder = NoiseModelBuilder()
noise_model = noise_builder.build_from_profile(profile, noise_level)

# Run with noise
from qiskit_aer import AerSimulator

backend = AerSimulator(noise_model=noise_model)
job = backend.run(circuit, shots=1024)
result = job.result()
counts = result.get_counts()

output = f"""Noisy Simulation Results:
Backend Profile: {backend_profile}
Noise Level: {noise_level}
Expand All @@ -146,28 +155,29 @@ def run_noisy_simulation(backend_profile="IBM", noise_level=0.01):
except Exception as e:
return f"Error: {str(e)}"


def explore_dna_circuits(sequence_name="ATCG"):
"""Explore DNA-inspired circuits."""
try:
from quantumpytho.modules.dna_circuits import (
get_available_dna_sequences,
get_dna_sequence,
summarize_dna_circuit
summarize_dna_circuit,
)

# Get available sequences
available = get_available_dna_sequences()

# Get specific sequence
sequence_data = get_dna_sequence(sequence_name)

# Summarize
summary = summarize_dna_circuit(sequence_name)

output = f"""DNA Circuit Exploration:
Sequence: {sequence_name}

Available Sequences: {', '.join(available[:10])}...
Available Sequences: {", ".join(available[:10])}...

Sequence Data:
{json.dumps(sequence_data, indent=2)}
Expand All @@ -179,14 +189,15 @@ def explore_dna_circuits(sequence_name="ATCG"):
except Exception as e:
return f"Error: {str(e)}"


def run_tmt_sierpinski():
"""Run TMT Sierpinski 21-qubit sacred geometry circuit."""
try:
from quantumpytho.modules.tmt_sierpinski import build_tmt_circuit

circuit = build_tmt_circuit()
result = engine.run(circuit)

output = f"""TMT Sierpinski Circuit (Sacred Geometry):
Qubits: 21
Circuit Type: Sierpinski Triangle Pattern
Expand All @@ -202,26 +213,28 @@ def run_tmt_sierpinski():
except Exception as e:
return f"Error: {str(e)}"


def run_benchmark():
"""Run benchmark dashboard."""
try:
from quantumpytho.modules.benchmark_dashboard import run_benchmark_suite

results = run_benchmark_suite()

output = f"""QPyth Benchmark Results:

{json.dumps(results, indent=2)}

Summary:
- Total Tests: {len(results)}
- Passed: {sum(1 for r in results.values() if r.get('status') == 'pass')}
- Failed: {sum(1 for r in results.values() if r.get('status') == 'fail')}
- Passed: {sum(1 for r in results.values() if r.get("status") == "pass")}
- Failed: {sum(1 for r in results.values() if r.get("status") == "fail")}
"""
return output
except Exception as e:
return f"Error: {str(e)}"


# Create Gradio interface
def create_interface():
with gr.Blocks(title="QPyth - Quantum Computing", theme=gr.themes.Soft()) as demo:
Expand All @@ -231,35 +244,37 @@ def create_interface():
A professionally engineered quantum computing library built on Qiskit.
Featuring VQE, IBM Quantum integration, QEC, noisy simulation, and more.
""")

with gr.Tab("Bloch Sphere"):
gr.Markdown("Visualize quantum states on the Bloch sphere")
with gr.Row():
theta = gr.Slider(0, 180, value=45, label="Theta (degrees)")
phi = gr.Slider(0, 360, value=45, label="Phi (degrees)")
bloch_output = gr.Textbox(label="Bloch Sphere Visualization", lines=20)
bloch_btn = gr.Button("Generate")
bloch_btn.click(bloch_sphere_demo, inputs=[theta, phi], outputs=bloch_output)

bloch_btn.click(
bloch_sphere_demo, inputs=[theta, phi], outputs=bloch_output
)

with gr.Tab("Bell Pair"):
gr.Markdown("Create an entangled Bell pair")
bell_output = gr.Textbox(label="Bell Pair Results", lines=15)
bell_btn = gr.Button("Create Bell Pair")
bell_btn.click(create_bell_pair, outputs=bell_output)

with gr.Tab("Quantum Teleportation"):
gr.Markdown("Run the quantum teleportation protocol")
teleport_output = gr.Textbox(label="Teleportation Results", lines=15)
teleport_btn = gr.Button("Run Teleportation")
teleport_btn.click(run_quantum_teleport, outputs=teleport_output)

with gr.Tab("Quantum Error Correction"):
gr.Markdown("Demonstrate quantum error correction codes")
code_type = gr.Radio(["Shor", "Steane"], label="Code Type", value="Shor")
qec_output = gr.Textbox(label="Result", lines=15)
qec_btn = gr.Button("Run QEC Demo")
qec_btn.click(run_qec_demo, inputs=code_type, outputs=qec_output)

with gr.Tab("Quantum RNG"):
gr.Markdown("Generate quantum random numbers")
with gr.Row():
Expand Down
Loading
Loading