Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -47,13 +47,11 @@ NON_FEATURE_COLS = {
|
|
| 47 |
|
| 48 |
_ASSET_CACHE = {}
|
| 49 |
|
| 50 |
-
# --- CORE LOGIC ---
|
| 51 |
def fetch_remote_json(url: str) -> Optional[dict]:
|
| 52 |
try:
|
| 53 |
response = requests.get(url, timeout=5)
|
| 54 |
return response.json() if response.status_code == 200 else None
|
| 55 |
-
except
|
| 56 |
-
logger.error(f"Error: {e}")
|
| 57 |
return None
|
| 58 |
|
| 59 |
def load_all_assets(key: str) -> Dict:
|
|
@@ -70,29 +68,39 @@ def generate_guide_markdown(assets: Dict) -> str:
|
|
| 70 |
meta = assets.get("meta", {})
|
| 71 |
params = meta.get("parameters", {})
|
| 72 |
report = assets.get("report", {})
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
|
|
|
|
| 75 |
families = report.get("families", {})
|
| 76 |
fam_table = "| Family | Samples | Description |\n| :--- | :--- | :--- |\n"
|
| 77 |
for f, count in families.items():
|
| 78 |
-
fam_table += f"|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
"""
|
|
|
|
| 96 |
|
| 97 |
def update_explorer_view(ds_name: str, split_name: str):
|
| 98 |
assets = load_all_assets(ds_name)
|
|
@@ -116,7 +124,6 @@ def sync_ml_inputs(ds_name: str):
|
|
| 116 |
|
| 117 |
def train_baseline_model(ds_name: str, selected_features: List[str]):
|
| 118 |
if not selected_features: return None, "### ❌ Error: Select features."
|
| 119 |
-
|
| 120 |
assets = load_all_assets(ds_name)
|
| 121 |
df = assets["df"]
|
| 122 |
target = "ideal_expval_Z_global" if "ideal_expval_Z_global" in df.columns else df.filter(like="expval").columns[0]
|
|
@@ -129,35 +136,30 @@ def train_baseline_model(ds_name: str, selected_features: List[str]):
|
|
| 129 |
model.fit(X_train, y_train)
|
| 130 |
preds = model.predict(X_test)
|
| 131 |
|
| 132 |
-
# Улучшенная визуализация (исправляет обрезку)
|
| 133 |
sns.set_theme(style="whitegrid", context="talk")
|
| 134 |
-
fig, axes = plt.subplots(1, 3, figsize=(
|
| 135 |
|
| 136 |
-
|
| 137 |
-
axes[0].scatter(y_test, preds, alpha=0.4, color='#34495e')
|
| 138 |
axes[0].plot([y.min(), y.max()], [y.min(), y.max()], 'r--', lw=2)
|
| 139 |
axes[0].set_title(f"Accuracy (R²: {r2_score(y_test, preds):.3f})")
|
| 140 |
|
| 141 |
-
# 2. Importance (с поправкой на длинные названия)
|
| 142 |
imp = model.feature_importances_
|
| 143 |
idx = np.argsort(imp)[-10:]
|
| 144 |
-
axes[1].barh([selected_features[i] for i in idx], imp[idx], color='#
|
| 145 |
-
axes[1].set_title("
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
axes[2].set_title("Prediction Error")
|
| 150 |
|
| 151 |
-
plt.tight_layout()
|
| 152 |
-
return fig, f"**
|
| 153 |
|
| 154 |
-
# --- UI ---
|
| 155 |
with gr.Blocks(theme=gr.themes.Soft(), title="QSBench Hub") as demo:
|
| 156 |
gr.Markdown("# 🌌 QSBench: Quantum Analytics Hub")
|
| 157 |
|
| 158 |
with gr.Tabs():
|
| 159 |
with gr.TabItem("🔎 Explorer"):
|
| 160 |
-
metadata_box = gr.Markdown("###
|
| 161 |
with gr.Row():
|
| 162 |
ds_select = gr.Dropdown(choices=list(REPO_CONFIG.keys()), value="Core (Clean)", label="Dataset Pack")
|
| 163 |
split_select = gr.Dropdown(choices=["train"], value="train", label="Subset")
|
|
@@ -176,18 +178,16 @@ with gr.Blocks(theme=gr.themes.Soft(), title="QSBench Hub") as demo:
|
|
| 176 |
plot_out = gr.Plot(); txt_out = gr.Markdown()
|
| 177 |
|
| 178 |
with gr.TabItem("📖 Methodology & Guide"):
|
| 179 |
-
guide_md = gr.Markdown("Loading guide...")
|
| 180 |
|
| 181 |
-
# FOOTER
|
| 182 |
gr.Markdown(f"""
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
""")
|
| 189 |
|
| 190 |
-
# Handlers
|
| 191 |
ds_select.change(update_explorer_view, [ds_select, split_select], [split_select, data_table, code_raw, code_tr, metadata_box, guide_md])
|
| 192 |
ml_ds.change(sync_ml_inputs, [ml_ds], [ml_feat])
|
| 193 |
btn.click(train_baseline_model, [ml_ds, ml_feat], [plot_out, txt_out])
|
|
|
|
| 47 |
|
| 48 |
_ASSET_CACHE = {}
|
| 49 |
|
|
|
|
| 50 |
def fetch_remote_json(url: str) -> Optional[dict]:
|
| 51 |
try:
|
| 52 |
response = requests.get(url, timeout=5)
|
| 53 |
return response.json() if response.status_code == 200 else None
|
| 54 |
+
except:
|
|
|
|
| 55 |
return None
|
| 56 |
|
| 57 |
def load_all_assets(key: str) -> Dict:
|
|
|
|
| 68 |
meta = assets.get("meta", {})
|
| 69 |
params = meta.get("parameters", {})
|
| 70 |
report = assets.get("report", {})
|
| 71 |
+
|
| 72 |
+
if not meta:
|
| 73 |
+
return "### ⚠️ Metadata Unreachable"
|
| 74 |
|
| 75 |
+
# Формируем таблицу БЕЗ лишних отступов слева (это ломает Markdown)
|
| 76 |
families = report.get("families", {})
|
| 77 |
fam_table = "| Family | Samples | Description |\n| :--- | :--- | :--- |\n"
|
| 78 |
for f, count in families.items():
|
| 79 |
+
fam_table += f"| {f.upper()} | {count} | Synthetic {f} circuits |\n"
|
| 80 |
|
| 81 |
+
guide = f"""
|
| 82 |
+
## 📖 Methodology & Release Notes: {meta.get('dataset_version', '1.0.0-demo')}
|
| 83 |
+
|
| 84 |
+
### 1. Generation Engine
|
| 85 |
+
Dataset produced by **QSBench v{meta.get('generator_version', '5.0')}**.
|
| 86 |
+
- **Hardware Profile:** {params.get('n_qubits')} Qubits | Depth: {params.get('depth')}
|
| 87 |
+
- **Noise Model:** `{params.get('noise', 'None')}` (p={params.get('noise_prob', 0)})
|
| 88 |
+
- **Backend:** {meta.get('backend_device', 'GPU')} | {meta.get('precision_mode', 'double')}
|
| 89 |
+
|
| 90 |
+
### 2. Structural Metrics
|
| 91 |
+
- **Gate Entropy:** Measures circuit complexity and gate distribution diversity.
|
| 92 |
+
- **Meyer-Wallach:** Global entanglement scalar.
|
| 93 |
+
- **Adjacency:** Topological density of the interaction graph.
|
| 94 |
+
|
| 95 |
+
### 3. Circuit Family Coverage
|
| 96 |
+
{fam_table}
|
| 97 |
+
|
| 98 |
+
### 4. Split distribution
|
| 99 |
+
- **Train:** {report.get('splits', {}).get('train')}
|
| 100 |
+
- **Validation:** {report.get('splits', {}).get('val')}
|
| 101 |
+
- **Test:** {report.get('splits', {}).get('test')}
|
| 102 |
"""
|
| 103 |
+
return guide
|
| 104 |
|
| 105 |
def update_explorer_view(ds_name: str, split_name: str):
|
| 106 |
assets = load_all_assets(ds_name)
|
|
|
|
| 124 |
|
| 125 |
def train_baseline_model(ds_name: str, selected_features: List[str]):
|
| 126 |
if not selected_features: return None, "### ❌ Error: Select features."
|
|
|
|
| 127 |
assets = load_all_assets(ds_name)
|
| 128 |
df = assets["df"]
|
| 129 |
target = "ideal_expval_Z_global" if "ideal_expval_Z_global" in df.columns else df.filter(like="expval").columns[0]
|
|
|
|
| 136 |
model.fit(X_train, y_train)
|
| 137 |
preds = model.predict(X_test)
|
| 138 |
|
|
|
|
| 139 |
sns.set_theme(style="whitegrid", context="talk")
|
| 140 |
+
fig, axes = plt.subplots(1, 3, figsize=(24, 8))
|
| 141 |
|
| 142 |
+
axes[0].scatter(y_test, preds, alpha=0.4, color='#2c3e50')
|
|
|
|
| 143 |
axes[0].plot([y.min(), y.max()], [y.min(), y.max()], 'r--', lw=2)
|
| 144 |
axes[0].set_title(f"Accuracy (R²: {r2_score(y_test, preds):.3f})")
|
| 145 |
|
|
|
|
| 146 |
imp = model.feature_importances_
|
| 147 |
idx = np.argsort(imp)[-10:]
|
| 148 |
+
axes[1].barh([selected_features[i] for i in idx], imp[idx], color='#27ae60')
|
| 149 |
+
axes[1].set_title("Feature Importance")
|
| 150 |
|
| 151 |
+
sns.histplot(y_test - preds, kde=True, ax=axes[2], color='#d35400')
|
| 152 |
+
axes[2].set_title("Residuals")
|
|
|
|
| 153 |
|
| 154 |
+
plt.tight_layout(pad=4.0)
|
| 155 |
+
return fig, f"**Model Performance** | MAE: {mean_absolute_error(y_test, preds):.4f}"
|
| 156 |
|
|
|
|
| 157 |
with gr.Blocks(theme=gr.themes.Soft(), title="QSBench Hub") as demo:
|
| 158 |
gr.Markdown("# 🌌 QSBench: Quantum Analytics Hub")
|
| 159 |
|
| 160 |
with gr.Tabs():
|
| 161 |
with gr.TabItem("🔎 Explorer"):
|
| 162 |
+
metadata_box = gr.Markdown("### Synchronizing data...")
|
| 163 |
with gr.Row():
|
| 164 |
ds_select = gr.Dropdown(choices=list(REPO_CONFIG.keys()), value="Core (Clean)", label="Dataset Pack")
|
| 165 |
split_select = gr.Dropdown(choices=["train"], value="train", label="Subset")
|
|
|
|
| 178 |
plot_out = gr.Plot(); txt_out = gr.Markdown()
|
| 179 |
|
| 180 |
with gr.TabItem("📖 Methodology & Guide"):
|
| 181 |
+
guide_md = gr.Markdown("Loading research guide...")
|
| 182 |
|
|
|
|
| 183 |
gr.Markdown(f"""
|
| 184 |
+
---
|
| 185 |
+
### 🔗 Official Links & Resources
|
| 186 |
+
* **🤗 Hugging Face:** [**QSBench Organization**](https://huggingface.co/QSBench)
|
| 187 |
+
* **💻 GitHub:** [**QSBench Repository**](https://github.com/QSBench)
|
| 188 |
+
* **🌐 Website:** [**qsbench.github.io**](https://qsbench.github.io)
|
| 189 |
""")
|
| 190 |
|
|
|
|
| 191 |
ds_select.change(update_explorer_view, [ds_select, split_select], [split_select, data_table, code_raw, code_tr, metadata_box, guide_md])
|
| 192 |
ml_ds.change(sync_ml_inputs, [ml_ds], [ml_feat])
|
| 193 |
btn.click(train_baseline_model, [ml_ds, ml_feat], [plot_out, txt_out])
|