poseidon666 commited on
Commit
cb7dfdc
·
verified ·
1 Parent(s): 0fc908f

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. server/app.py +55 -58
server/app.py CHANGED
@@ -7,8 +7,7 @@
7
  """
8
  FastAPI application with Gradio UI for the Quantum Circuit Optimization Environment.
9
 
10
- This module creates an HTTP server that exposes the QuantumCircuitEnvironment
11
- with both OpenEnv API endpoints and a custom Gradio UI.
12
 
13
  Usage:
14
  # Development (with auto-reload):
@@ -22,20 +21,10 @@ Usage:
22
  """
23
 
24
  import logging
25
- import os
26
- from pathlib import Path
27
 
28
  import gradio as gr
29
  from fastapi import FastAPI
30
  from fastapi.middleware.cors import CORSMiddleware
31
- from fastapi.responses import HTMLResponse, RedirectResponse
32
-
33
- try:
34
- from openenv.core.env_server.http_server import create_app
35
- except Exception as e:
36
- raise ImportError(
37
- "openenv is required for the web interface. Install dependencies with 'uv sync'"
38
- ) from e
39
 
40
  try:
41
  from ..models import ActionType, GateType, QuantumAction, QuantumObservation
@@ -48,29 +37,12 @@ logging.basicConfig(level=logging.INFO)
48
  logger = logging.getLogger(__name__)
49
 
50
  # ---------------------------------------------------------------------------
51
- # Environment factory
52
- # ---------------------------------------------------------------------------
53
-
54
- def make_env():
55
- """Factory function to create a new environment instance."""
56
- env = QuantumCircuitEnvironment(seed=42)
57
- env.reset(task_id="easy")
58
- return env
59
-
60
-
61
- # ---------------------------------------------------------------------------
62
- # Create OpenEnv FastAPI app
63
  # ---------------------------------------------------------------------------
64
 
65
- app = create_app(
66
- make_env,
67
- QuantumAction,
68
- QuantumObservation,
69
- env_name="quantum_circuit_env",
70
- max_concurrent_envs=10,
71
- )
72
 
73
- app.add_middleware(
74
  CORSMiddleware,
75
  allow_origins=["*"],
76
  allow_methods=["*"],
@@ -78,7 +50,7 @@ app.add_middleware(
78
  )
79
 
80
  # ---------------------------------------------------------------------------
81
- # Gradio UI State (for interactive UI)
82
  # ---------------------------------------------------------------------------
83
 
84
  ui_env = QuantumCircuitEnvironment(seed=42)
@@ -232,37 +204,68 @@ def do_step(action_type, gate_type, qubit_0, qubit_1, parameter):
232
  # ---------------------------------------------------------------------------
233
 
234
  def create_gradio_app() -> gr.Blocks:
235
- with gr.Blocks(title="Quantum Circuit Optimizer") as demo:
236
  gr.Markdown(
237
- """# Quantum Circuit Optimizer
238
- Build quantum circuits step-by-step to maximize fidelity with target states.
 
239
 
240
- **Available Tasks:**
241
- - Bell State (Easy): 2 qubits, no noise
242
- - GHZ State (Medium): 3 qubits, depolarizing noise
243
- - Unitary Approximation (Hard): 2 qubits, thermal noise
 
 
 
 
 
 
 
244
  """
245
  )
246
 
247
  with gr.Row():
248
- task_dd = gr.Dropdown(choices=list(TASK_MAP.keys()), value="Bell State (Easy)", label="Task")
249
- reset_btn = gr.Button("Reset Environment", variant="primary")
250
-
 
 
 
 
 
 
 
 
251
  with gr.Row():
252
- action_dd = gr.Dropdown(choices=["ADD", "REMOVE", "SWAP", "PARAM", "STOP"], value="ADD", label="Action Type")
253
- gate_dd = gr.Dropdown(choices=["H", "X", "CNOT", "RX", "RZ"], value="H", label="Gate (for ADD)")
 
 
 
 
 
 
 
 
254
 
255
  with gr.Row():
256
  qubit_0 = gr.Number(value=0, label="Qubit 0", precision=0)
257
  qubit_1 = gr.Number(value=1, label="Qubit 1 (CNOT/SWAP)", precision=0)
258
- parameter = gr.Number(value=None, label="Parameter (RX/RZ angle)", precision=4)
259
 
260
- step_btn = gr.Button("Execute Step", variant="secondary")
261
 
 
 
262
  status_out = gr.Textbox(label="Status", lines=3, interactive=False)
263
- circuit_out = gr.Textbox(label="Circuit", lines=10, interactive=False)
264
- scores_out = gr.Textbox(label="Scores", lines=6, interactive=False)
265
- history_out = gr.Textbox(label="Step History", lines=8, interactive=False)
 
 
 
 
 
266
 
267
  OUTS = [status_out, circuit_out, scores_out, history_out]
268
 
@@ -277,13 +280,7 @@ def create_gradio_app() -> gr.Blocks:
277
  # ---------------------------------------------------------------------------
278
 
279
  demo = create_gradio_app()
280
- app = gr.mount_gradio_app(app, demo, path="/ui")
281
-
282
-
283
- @app.get("/")
284
- async def root():
285
- """Root endpoint - redirect to Gradio UI."""
286
- return RedirectResponse(url="/ui")
287
 
288
 
289
  @app.get("/health")
@@ -292,7 +289,7 @@ async def health():
292
  return {"status": "ok", "environment": "quantum_circuit_optimizer"}
293
 
294
 
295
- @app.get("/tasks")
296
  async def list_tasks():
297
  """List available quantum circuit optimization tasks."""
298
  return {
 
7
  """
8
  FastAPI application with Gradio UI for the Quantum Circuit Optimization Environment.
9
 
10
+ This module creates a custom Gradio interface for quantum circuit optimization.
 
11
 
12
  Usage:
13
  # Development (with auto-reload):
 
21
  """
22
 
23
  import logging
 
 
24
 
25
  import gradio as gr
26
  from fastapi import FastAPI
27
  from fastapi.middleware.cors import CORSMiddleware
 
 
 
 
 
 
 
 
28
 
29
  try:
30
  from ..models import ActionType, GateType, QuantumAction, QuantumObservation
 
37
  logger = logging.getLogger(__name__)
38
 
39
  # ---------------------------------------------------------------------------
40
+ # FastAPI app
 
 
 
 
 
 
 
 
 
 
 
41
  # ---------------------------------------------------------------------------
42
 
43
+ fastapi_app = FastAPI(title="Quantum Circuit Optimizer")
 
 
 
 
 
 
44
 
45
+ fastapi_app.add_middleware(
46
  CORSMiddleware,
47
  allow_origins=["*"],
48
  allow_methods=["*"],
 
50
  )
51
 
52
  # ---------------------------------------------------------------------------
53
+ # Gradio UI State
54
  # ---------------------------------------------------------------------------
55
 
56
  ui_env = QuantumCircuitEnvironment(seed=42)
 
204
  # ---------------------------------------------------------------------------
205
 
206
  def create_gradio_app() -> gr.Blocks:
207
+ with gr.Blocks(title="Quantum Circuit Optimizer", theme=gr.themes.Soft()) as demo:
208
  gr.Markdown(
209
+ """# ⚛️ Quantum Circuit Optimizer
210
+
211
+ Build quantum circuits step-by-step to maximize fidelity with target quantum states.
212
 
213
+ ### 🎯 Available Tasks:
214
+ - **Bell State (Easy)**: Create entangled 2-qubit Bell state - No noise
215
+ - **GHZ State (Medium)**: Create 3-qubit GHZ state - Depolarizing noise, linear connectivity
216
+ - **Unitary Approximation (Hard)**: Approximate complex unitary - Thermal noise, restricted connectivity
217
+
218
+ ### 🎮 How to Use:
219
+ 1. Select a task and click **Reset Environment**
220
+ 2. Choose an action type (ADD gate, REMOVE last gate, SWAP qubits, tune PARAM, or STOP)
221
+ 3. Configure gate parameters (gate type, qubits, rotation angle)
222
+ 4. Click **Execute Step** to apply the action
223
+ 5. Monitor fidelity, scores, and circuit depth in real-time
224
  """
225
  )
226
 
227
  with gr.Row():
228
+ with gr.Column(scale=2):
229
+ task_dd = gr.Dropdown(
230
+ choices=list(TASK_MAP.keys()),
231
+ value="Bell State (Easy)",
232
+ label="🎯 Select Task"
233
+ )
234
+ with gr.Column(scale=1):
235
+ reset_btn = gr.Button("🔄 Reset Environment", variant="primary", size="lg")
236
+
237
+ gr.Markdown("### 🎛️ Action Configuration")
238
+
239
  with gr.Row():
240
+ action_dd = gr.Dropdown(
241
+ choices=["ADD", "REMOVE", "SWAP", "PARAM", "STOP"],
242
+ value="ADD",
243
+ label="Action Type"
244
+ )
245
+ gate_dd = gr.Dropdown(
246
+ choices=["H", "X", "CNOT", "RX", "RZ"],
247
+ value="H",
248
+ label="Gate (for ADD)"
249
+ )
250
 
251
  with gr.Row():
252
  qubit_0 = gr.Number(value=0, label="Qubit 0", precision=0)
253
  qubit_1 = gr.Number(value=1, label="Qubit 1 (CNOT/SWAP)", precision=0)
254
+ parameter = gr.Number(value=None, label="Parameter θ (RX/RZ angle in radians)", precision=4)
255
 
256
+ step_btn = gr.Button("▶️ Execute Step", variant="secondary", size="lg")
257
 
258
+ gr.Markdown("### 📊 Environment State")
259
+
260
  status_out = gr.Textbox(label="Status", lines=3, interactive=False)
261
+
262
+ with gr.Row():
263
+ with gr.Column():
264
+ circuit_out = gr.Textbox(label="🔗 Current Circuit", lines=12, interactive=False)
265
+ with gr.Column():
266
+ scores_out = gr.Textbox(label="📈 Scores", lines=12, interactive=False)
267
+
268
+ history_out = gr.Textbox(label="📜 Step History", lines=10, interactive=False)
269
 
270
  OUTS = [status_out, circuit_out, scores_out, history_out]
271
 
 
280
  # ---------------------------------------------------------------------------
281
 
282
  demo = create_gradio_app()
283
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/")
 
 
 
 
 
 
284
 
285
 
286
  @app.get("/health")
 
289
  return {"status": "ok", "environment": "quantum_circuit_optimizer"}
290
 
291
 
292
+ @app.get("/api/tasks")
293
  async def list_tasks():
294
  """List available quantum circuit optimization tasks."""
295
  return {