Yuchen Yuan commited on
Commit
90bf6ec
·
1 Parent(s): 95967ab

Feature: Export pipeline as runnable Python script

Browse files

New "Export .py" button in the canvas toolbar (Code2 icon). Generates
a flat, readable Python script that reproduces the current pipeline:

- Topologically sorts the canvas nodes using the edge list
- For each block, emits the corresponding Python code with the
actual parameter values from the canvas (iterations, lambda, rho,
noise_snapshot, alpha, backend_name, etc.)
- Includes import statements, parameter binding for parameterized
circuits, and print statements for each step's output
- Downloads as pipeline.py with a browser file-save dialog

Supports all 9 block types: input_circuit, fake_backend, ibm_backend,
qucad, qubound, compvqc, qshot, fidelity, output. IBM live backend
generates commented-out code with instructions + a fake backend
fallback.

Also added to the mobile MoreMenu so the feature works on phones.

frontend/src/components/FlowCanvas.tsx CHANGED
@@ -20,6 +20,7 @@ import {
20
  AlertTriangle,
21
  Box,
22
  Check,
 
23
  Link2,
24
  Loader2,
25
  Play,
@@ -28,6 +29,7 @@ import {
28
  X,
29
  } from "lucide-react";
30
  import { copyToClipboard } from "../lib/clipboard";
 
31
  import { NODE_BY_KIND, type NodeKind } from "../lib/nodeCatalog";
32
  import {
33
  DEFAULT_PRESET_KEY,
@@ -309,6 +311,23 @@ export function FlowCanvas() {
309
  setNotice({ text: "Share link copied to clipboard.", tone: "ok" });
310
  };
311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  const runAutoConnect = () => {
313
  const result = autoConnect(nodes, edges);
314
  if (!result.connected) {
@@ -417,6 +436,16 @@ export function FlowCanvas() {
417
  className="hidden md:inline-flex"
418
  labelBreakpoint="lg"
419
  />
 
 
 
 
 
 
 
 
 
 
420
  <button
421
  onClick={clearGraph}
422
  className="btn hidden md:inline-flex"
@@ -434,8 +463,10 @@ export function FlowCanvas() {
434
  canAutoConnect={nodes.length >= 2}
435
  hasEdgesToReplace={edges.length > 0}
436
  canClear={nodes.length > 0 || edges.length > 0}
 
437
  onAutoConnect={runAutoConnect}
438
  onShare={handleShareFromMenu}
 
439
  onClear={clearGraph}
440
  />
441
 
 
20
  AlertTriangle,
21
  Box,
22
  Check,
23
+ Code2,
24
  Link2,
25
  Loader2,
26
  Play,
 
29
  X,
30
  } from "lucide-react";
31
  import { copyToClipboard } from "../lib/clipboard";
32
+ import { generatePythonScript } from "../lib/exportPython";
33
  import { NODE_BY_KIND, type NodeKind } from "../lib/nodeCatalog";
34
  import {
35
  DEFAULT_PRESET_KEY,
 
311
  setNotice({ text: "Share link copied to clipboard.", tone: "ok" });
312
  };
313
 
314
+ const exportPython = () => {
315
+ if (nodes.length === 0) {
316
+ setNotice({ text: "Nothing to export — add some blocks first.", tone: "warn" });
317
+ return;
318
+ }
319
+ const script = generatePythonScript(nodes, edges, sampleKey);
320
+ // Download as .py file
321
+ const blob = new Blob([script], { type: "text/x-python" });
322
+ const url = URL.createObjectURL(blob);
323
+ const a = document.createElement("a");
324
+ a.href = url;
325
+ a.download = "pipeline.py";
326
+ a.click();
327
+ URL.revokeObjectURL(url);
328
+ setNotice({ text: "Python script downloaded as pipeline.py", tone: "ok" });
329
+ };
330
+
331
  const runAutoConnect = () => {
332
  const result = autoConnect(nodes, edges);
333
  if (!result.connected) {
 
436
  className="hidden md:inline-flex"
437
  labelBreakpoint="lg"
438
  />
439
+ <button
440
+ onClick={exportPython}
441
+ disabled={nodes.length === 0}
442
+ className="btn hidden md:inline-flex disabled:opacity-40 disabled:cursor-not-allowed"
443
+ title="Export this pipeline as a runnable Python script"
444
+ aria-label="Export Python script"
445
+ >
446
+ <Code2 className="w-3.5 h-3.5" />
447
+ <span className="hidden lg:inline">Export .py</span>
448
+ </button>
449
  <button
450
  onClick={clearGraph}
451
  className="btn hidden md:inline-flex"
 
463
  canAutoConnect={nodes.length >= 2}
464
  hasEdgesToReplace={edges.length > 0}
465
  canClear={nodes.length > 0 || edges.length > 0}
466
+ canExport={nodes.length > 0}
467
  onAutoConnect={runAutoConnect}
468
  onShare={handleShareFromMenu}
469
+ onExport={exportPython}
470
  onClear={clearGraph}
471
  />
472
 
frontend/src/components/MoreMenu.tsx CHANGED
@@ -1,5 +1,6 @@
1
  import { useEffect, useRef, useState } from "react";
2
  import {
 
3
  Link as LinkIcon,
4
  MoreHorizontal,
5
  Trash2,
@@ -28,16 +29,20 @@ export function MoreMenu({
28
  canAutoConnect,
29
  hasEdgesToReplace,
30
  canClear,
 
31
  onAutoConnect,
32
  onShare,
 
33
  onClear,
34
  }: {
35
  className?: string;
36
  canAutoConnect: boolean;
37
  hasEdgesToReplace: boolean;
38
  canClear: boolean;
 
39
  onAutoConnect: () => void;
40
  onShare: () => void;
 
41
  onClear: () => void;
42
  }) {
43
  const [open, setOpen] = useState(false);
@@ -102,6 +107,14 @@ export function MoreMenu({
102
  sub: "Copies a URL that restores this pipeline",
103
  onClick: onShare,
104
  },
 
 
 
 
 
 
 
 
105
  {
106
  key: "clear",
107
  icon: <Trash2 className="w-4 h-4" />,
 
1
  import { useEffect, useRef, useState } from "react";
2
  import {
3
+ Code2,
4
  Link as LinkIcon,
5
  MoreHorizontal,
6
  Trash2,
 
29
  canAutoConnect,
30
  hasEdgesToReplace,
31
  canClear,
32
+ canExport,
33
  onAutoConnect,
34
  onShare,
35
+ onExport,
36
  onClear,
37
  }: {
38
  className?: string;
39
  canAutoConnect: boolean;
40
  hasEdgesToReplace: boolean;
41
  canClear: boolean;
42
+ canExport: boolean;
43
  onAutoConnect: () => void;
44
  onShare: () => void;
45
+ onExport: () => void;
46
  onClear: () => void;
47
  }) {
48
  const [open, setOpen] = useState(false);
 
107
  sub: "Copies a URL that restores this pipeline",
108
  onClick: onShare,
109
  },
110
+ {
111
+ key: "export",
112
+ icon: <Code2 className="w-4 h-4" />,
113
+ label: "Export .py",
114
+ sub: "Download pipeline as a Python script",
115
+ disabled: !canExport,
116
+ onClick: onExport,
117
+ },
118
  {
119
  key: "clear",
120
  icon: <Trash2 className="w-4 h-4" />,
frontend/src/lib/exportPython.ts ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Generate a runnable Python script from the current canvas pipeline.
3
+ *
4
+ * The script imports Qiskit + qlib modules and reproduces the same
5
+ * operations the backend would run, so a researcher can copy the file
6
+ * into their own project, tweak it, and run batch experiments without
7
+ * the web UI.
8
+ *
9
+ * We deliberately keep the generated code flat and readable (no
10
+ * classes, no abstractions) so someone unfamiliar with the codebase
11
+ * can follow it line by line.
12
+ */
13
+
14
+ import type { Node, Edge } from "@xyflow/react";
15
+ import type { QNodeData } from "../components/QNode";
16
+ import { NODE_BY_KIND, type NodeKind } from "./nodeCatalog";
17
+
18
+ interface PipelineNode {
19
+ kind: NodeKind;
20
+ params: Record<string, unknown>;
21
+ }
22
+
23
+ /**
24
+ * Topological sort of canvas nodes using the edge list.
25
+ * Falls back to catalog family order if the graph is disconnected.
26
+ */
27
+ function topoSort(nodes: Node[], edges: Edge[]): Node[] {
28
+ const adj = new Map<string, string[]>();
29
+ const indeg = new Map<string, number>();
30
+ for (const n of nodes) {
31
+ adj.set(n.id, []);
32
+ indeg.set(n.id, 0);
33
+ }
34
+ for (const e of edges) {
35
+ adj.get(e.source)?.push(e.target);
36
+ indeg.set(e.target, (indeg.get(e.target) ?? 0) + 1);
37
+ }
38
+ const queue = nodes.filter((n) => (indeg.get(n.id) ?? 0) === 0).map((n) => n.id);
39
+ const order: string[] = [];
40
+ while (queue.length > 0) {
41
+ const id = queue.shift()!;
42
+ order.push(id);
43
+ for (const next of adj.get(id) ?? []) {
44
+ const d = (indeg.get(next) ?? 1) - 1;
45
+ indeg.set(next, d);
46
+ if (d === 0) queue.push(next);
47
+ }
48
+ }
49
+ const byId = new Map(nodes.map((n) => [n.id, n]));
50
+ // Append any disconnected nodes at the end.
51
+ for (const n of nodes) {
52
+ if (!order.includes(n.id)) order.push(n.id);
53
+ }
54
+ return order.map((id) => byId.get(id)!).filter(Boolean);
55
+ }
56
+
57
+ export function generatePythonScript(
58
+ nodes: Node[],
59
+ edges: Edge[],
60
+ sampleKey: string | null,
61
+ ): string {
62
+ const sorted = topoSort(nodes, edges);
63
+ const blocks: PipelineNode[] = sorted.map((n) => ({
64
+ kind: (n.data as QNodeData).kind,
65
+ params: ((n.data as QNodeData).params as Record<string, unknown>) ?? {},
66
+ }));
67
+
68
+ const lines: string[] = [];
69
+ const imports = new Set<string>();
70
+
71
+ // Header
72
+ lines.push(`"""`);
73
+ lines.push(`Pipeline exported from QuDA Studio`);
74
+ lines.push(`https://qudastudio-app.hf.space/`);
75
+ lines.push(`"""`);
76
+ lines.push(``);
77
+
78
+ // Always need QuantumCircuit
79
+ imports.add("from qiskit import QuantumCircuit");
80
+
81
+ let hasBackend = false;
82
+ let hasQucad = false;
83
+ let hasQubound = false;
84
+ let hasCompvqc = false;
85
+ let hasQshot = false;
86
+ let hasFidelity = false;
87
+
88
+ // Scan what we need
89
+ for (const b of blocks) {
90
+ switch (b.kind) {
91
+ case "fake_backend":
92
+ case "ibm_backend":
93
+ hasBackend = true;
94
+ break;
95
+ case "qucad":
96
+ hasQucad = true;
97
+ break;
98
+ case "qubound":
99
+ hasQubound = true;
100
+ break;
101
+ case "compvqc":
102
+ hasCompvqc = true;
103
+ break;
104
+ case "qshot":
105
+ hasQshot = true;
106
+ break;
107
+ case "fidelity":
108
+ hasFidelity = true;
109
+ break;
110
+ }
111
+ }
112
+
113
+ // Imports section
114
+ if (hasBackend) {
115
+ imports.add("from qiskit_aer import AerSimulator");
116
+ imports.add("from qiskit_aer.noise import NoiseModel");
117
+ }
118
+
119
+ lines.push([...imports].sort().join("\n"));
120
+ lines.push(``);
121
+
122
+ // Generate code for each block
123
+ let stepNum = 0;
124
+ for (const b of blocks) {
125
+ stepNum++;
126
+ const sep = `# ${"─".repeat(60)}`;
127
+ lines.push(sep);
128
+
129
+ switch (b.kind) {
130
+ case "input_circuit": {
131
+ lines.push(`# Step ${stepNum}: Load circuit`);
132
+ if (sampleKey) {
133
+ lines.push(`# Sample: ${sampleKey}`);
134
+ lines.push(`# Option A: Load from a .qpy file`);
135
+ lines.push(`# from qiskit import qpy`);
136
+ lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);
137
+ lines.push(`# qc = qpy.load(f)[0]`);
138
+ lines.push(``);
139
+ lines.push(`# Option B: Build programmatically (replace with your circuit)`);
140
+ } else {
141
+ lines.push(`# Replace with your circuit`);
142
+ }
143
+ lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);
144
+ lines.push(`# qc.ry(0.5, 0)`);
145
+ lines.push(`# qc.cx(0, 1)`);
146
+ lines.push(`# ... add your gates here`);
147
+ lines.push(``);
148
+ break;
149
+ }
150
+
151
+ case "fake_backend": {
152
+ const name = String(b.params.backend_name ?? "FakeFez");
153
+ lines.push(`# Step ${stepNum}: Noisy simulator (${name})`);
154
+ lines.push(`from qiskit.providers.fake_provider import ${name}V2`);
155
+ lines.push(`backend = ${name}V2()`);
156
+ lines.push(`noise_model = NoiseModel.from_backend(backend)`);
157
+ lines.push(``);
158
+ break;
159
+ }
160
+
161
+ case "ibm_backend": {
162
+ const name = String(b.params.backend_name ?? "ibm_fez");
163
+ lines.push(`# Step ${stepNum}: IBM live backend (${name})`);
164
+ lines.push(`# Requires: pip install qiskit-ibm-runtime`);
165
+ lines.push(`# from qiskit_ibm_runtime import QiskitRuntimeService`);
166
+ lines.push(`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`);
167
+ lines.push(`# backend = service.backend("${name}")`);
168
+ lines.push(`# noise_model = NoiseModel.from_backend(backend)`);
169
+ lines.push(`#`);
170
+ lines.push(`# For now, falling back to fake backend:`);
171
+ lines.push(`from qiskit.providers.fake_provider import FakeFezV2`);
172
+ lines.push(`backend = FakeFezV2()`);
173
+ lines.push(`noise_model = NoiseModel.from_backend(backend)`);
174
+ lines.push(``);
175
+ break;
176
+ }
177
+
178
+ case "qucad": {
179
+ const iters = Number(b.params.iterations ?? 3);
180
+ const lam = Number(b.params.lam ?? 0.005);
181
+ const rho = Number(b.params.rho ?? 500.0);
182
+ lines.push(`# Step ${stepNum}: QuCAD — noise-aware VQC sparsification`);
183
+ lines.push(`from qlib.qucad import run_qucad_training_noisy`);
184
+ lines.push(``);
185
+ lines.push(`# Bind free parameters to zero if circuit is parameterized`);
186
+ lines.push(`if qc.num_parameters > 0:`);
187
+ lines.push(` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`);
188
+ lines.push(`else:`);
189
+ lines.push(` qc_bound = qc`);
190
+ lines.push(``);
191
+ lines.push(`theta, mask, history = run_qucad_training_noisy(`);
192
+ lines.push(` qc, noise_model, backend,`);
193
+ lines.push(` iterations=${iters}, lam=${lam}, rho=${rho},`);
194
+ lines.push(`)`);
195
+ lines.push(`qc = qc.assign_parameters(theta * (mask != 0))`);
196
+ lines.push(`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`);
197
+ lines.push(``);
198
+ break;
199
+ }
200
+
201
+ case "qubound": {
202
+ const cacheBackend = String(b.params.cache_backend ?? "ibm_fez");
203
+ lines.push(`# Step ${stepNum}: QuBound — LSTM error-bound prediction`);
204
+ lines.push(`from qlib.qbound import call_QuBound_from_cache`);
205
+ lines.push(`from pathlib import Path`);
206
+ lines.push(``);
207
+ lines.push(`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`);
208
+ lines.push(`if qc.num_parameters > 0:`);
209
+ lines.push(` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`);
210
+ lines.push(`else:`);
211
+ lines.push(` qc_eval = qc`);
212
+ lines.push(``);
213
+ lines.push(`bound, model, meta = call_QuBound_from_cache(`);
214
+ lines.push(` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`);
215
+ lines.push(`)`);
216
+ lines.push(`print(f"QuBound predicted error bound: {bound:.6f}")`);
217
+ lines.push(``);
218
+ break;
219
+ }
220
+
221
+ case "compvqc": {
222
+ lines.push(`# Step ${stepNum}: CompressVQC — fold redundant gates`);
223
+ lines.push(`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`);
224
+ lines.push(``);
225
+ lines.push(`if qc.num_parameters > 0:`);
226
+ lines.push(` comp_backend = backend if 'backend' in dir() else None`);
227
+ lines.push(` if comp_backend is None:`);
228
+ lines.push(` from qiskit.providers.fake_provider import FakeFezV2`);
229
+ lines.push(` comp_backend = FakeFezV2()`);
230
+ lines.push(` lut = get_LUT(qc, comp_backend)`);
231
+ lines.push(` if lut:`);
232
+ lines.push(` qp = quadraticProgram_luttoqp(lut)`);
233
+ lines.push(` result = admmOptimizedCompVQC(qp, lut)`);
234
+ lines.push(` qc = resultsCompressVQC(qc, result, lut)`);
235
+ lines.push(` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`);
236
+ lines.push(` else:`);
237
+ lines.push(` print("CompressVQC: no compressible pairs found")`);
238
+ lines.push(`else:`);
239
+ lines.push(` print("CompressVQC: skipped (no parameterized gates)")`);
240
+ lines.push(``);
241
+ break;
242
+ }
243
+
244
+ case "qshot": {
245
+ const snapshot = String(b.params.noise_snapshot ?? "pittsburgh_1");
246
+ const alpha = Number(b.params.alpha ?? 0.95);
247
+ lines.push(`# Step ${stepNum}: Qshot — noise-aware shot-count recommendation`);
248
+ lines.push(`from qlib.qshot import get_recommender, resolve_noise_snapshot`);
249
+ lines.push(``);
250
+ lines.push(`if qc.num_parameters > 0:`);
251
+ lines.push(` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`);
252
+ lines.push(`else:`);
253
+ lines.push(` qc_shot = qc`);
254
+ lines.push(``);
255
+ lines.push(`noise_path = resolve_noise_snapshot("${snapshot}")`);
256
+ lines.push(`recommender = get_recommender()`);
257
+ lines.push(`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`);
258
+ lines.push(`if result:`);
259
+ lines.push(` print(f"Qshot: recommended {result['recommended_shots']} shots")`);
260
+ lines.push(` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`);
261
+ lines.push(`else:`);
262
+ lines.push(` print("Qshot: could not produce recommendation")`);
263
+ lines.push(``);
264
+ break;
265
+ }
266
+
267
+ case "fidelity": {
268
+ lines.push(`# Step ${stepNum}: Fidelity estimate`);
269
+ lines.push(`from qlib.qiskit_utils import simpleFidelityEstimator`);
270
+ lines.push(``);
271
+ lines.push(`fidelity = simpleFidelityEstimator(qc)`);
272
+ lines.push(`print(f"Fidelity (statevector vs noisy): {fidelity:.6f}")`);
273
+ lines.push(``);
274
+ break;
275
+ }
276
+
277
+ case "output": {
278
+ lines.push(`# Step ${stepNum}: Output summary`);
279
+ lines.push(`print("\\n" + "=" * 60)`);
280
+ lines.push(`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`);
281
+ lines.push(`print(f"Gate counts: {dict(qc.count_ops())}")`);
282
+ lines.push(`print(qc.draw(output='text', fold=120))`);
283
+ lines.push(``);
284
+ break;
285
+ }
286
+ }
287
+ }
288
+
289
+ // Footer
290
+ lines.push(`# ${"─".repeat(60)}`);
291
+ lines.push(`# End of exported pipeline`);
292
+ lines.push(`# To run: python pipeline.py`);
293
+ lines.push(`# Make sure qlib/ is on your PYTHONPATH (or run from the backend/ dir)`);
294
+
295
+ return lines.join("\n");
296
+ }