Spaces:
Sleeping
Sleeping
File size: 37,678 Bytes
bff0c70 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 | """
DVNC.AI β root app.py
Refactored to fix Gradio runtime startup and preserve current
dvncaiv2hf self-learning graph integration.
"""
# ββ Standard library ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import html
import random
import re
from typing import Dict, List, Optional
# ββ Third-party βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import gradio as gr
# ββ Internal modules ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
from dvncaiv2hf.agentroutecards import buildagentroutecardshtml
from dvncaiv2hf.discoveryappbridge import (
getdefaultroutestate,
getdiscoverycss,
getinitialdiscoverytimelinehtml,
)
from dvncaiv2hf.dvncuilayout import getdvnclayoutcss
from dvncaiv2hf.graphcanvaspatch import rendergraphcanvashtml
from dvncaiv2hf.selflearninggraph import (
DEFAULTSOURCES,
SEARCHMODES,
SOURCEOPTIONS,
buildjournalhtml,
ingestselectedpapers,
parseuploadedpdf,
renderparseresult,
runpaperdiscovery,
safetext,
)
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MODELS = [
{
"name": "DVNC Sovereign",
"tag": "flagship",
"desc": "Maximum depth orchestration for frontier discovery",
},
{
"name": "DVNC Atlas",
"tag": "research",
"desc": "Balanced reasoning, graph traversal, and synthesis",
},
{
"name": "DVNC Curie",
"tag": "lab",
"desc": "Experimental hypothesis generation for anomalous signals",
},
]
AGENTS = [
"Query Interpreter",
"Graph Divergence Mapper",
"Evidence Harvester",
"Analogy Engine",
"Hypothesis Composer",
"Adversarial Critic",
"Experimental Program Designer",
]
NODES = [
{"id": "seed", "label": "Seed Query", "group": "core", "x": 10, "y": 0, "z": 0},
{"id": "bio", "label": "Biomaterials", "group": "domain", "x": 24, "y": 12, "z": -8},
{"id": "card", "label": "Cardiac Repair", "group": "domain", "x": 38, "y": 3, "z": 14},
{"id": "nano", "label": "Nanostructure", "group": "bridge", "x": 24, "y": -18, "z": 16},
{"id": "selfasm", "label": "Self-Assembly", "group": "bridge", "x": 40, "y": -16, "z": -16},
{"id": "electro", "label": "Electro-signalling", "group": "mechanism", "x": 58, "y": 10, "z": -10},
{"id": "immune", "label": "Immune Modulation", "group": "mechanism", "x": 64, "y": -8, "z": 10},
{"id": "trial", "label": "Validation Path", "group": "outcome", "x": 80, "y": 0, "z": 0},
{"id": "alt1", "label": "Piezoelectric Scaffold", "group": "candidate", "x": 56, "y": 26, "z": 14},
{"id": "alt2", "label": "Peptide Mesh", "group": "candidate", "x": 54, "y": -27, "z": -14},
]
EDGES = [
("seed", "bio"),
("seed", "nano"),
("bio", "card"),
("nano", "selfasm"),
("selfasm", "electro"),
("card", "immune"),
("electro", "trial"),
("immune", "trial"),
("card", "alt1"),
("selfasm", "alt2"),
("alt1", "trial"),
("alt2", "trial"),
]
DEFAULTPATH = ["seed", "nano", "selfasm", "electro", "trial"]
CANDIDATES = [
{
"title": "Piezoelectric Scaffold Cascade",
"front": "Use mechano-electric scaffolds to convert cardiac strain into micro-current signalling.",
"back": "Discovery path: anomalous healing signal -> piezoelectric analog -> ion-channel entrainment -> tissue regeneration. Risk: power density and fibrosis coupling.",
"score": 92,
"novelty": "High",
"agent": "Hypothesis Composer",
},
{
"title": "Peptide Self-Assembly Mesh",
"front": "Deploy dynamic peptide meshes that self-assemble around damaged myocardium and guide repair.",
"back": "Discovery path: self-assembly -> local immune choreography -> regenerative substrate formation. Risk: degradation timing and targeting specificity.",
"score": 88,
"novelty": "High",
"agent": "Analogy Engine",
},
{
"title": "Immune-Tuned Conductive Hydrogel",
"front": "Blend conductivity with macrophage-state modulation to reduce scarring and restore conduction.",
"back": "Discovery path: inflammation mismatch -> conductive medium -> macrophage polarization -> synchronized healing. Risk: persistence and biocompatibility.",
"score": 85,
"novelty": "Medium-High",
"agent": "Adversarial Critic",
},
]
ACADEMICINSIGHTS = [
{
"hypothesis": "Implementation of mechano-electric scaffolds to transduce cardiac strain into localized micro-current signalling for myocardial regeneration.",
"metrics": {
"Novelty": 92,
"Mechanistic clarity": 85,
"Experimental tractability": 78,
"Cross-domain distance": 94,
},
"outline": (
"1. Synthesize candidate piezoelectric biomaterial scaffolds with tunable strain-electric coupling.\n"
"2. Evaluate in vitro electromechanical transduction and subsequent ion-channel entrainment.\n"
"3. Conduct in vivo comparative models to assess regenerative efficacy against gold-standard substrates.\n"
"4. Rigorously validate to exclude pathological fibrosis and power-density toxicity."
),
"path": ["seed", "bio", "card", "alt1", "trial"],
},
{
"hypothesis": "Deployment of dynamic peptide networks that self-assemble post-infarction to orchestrate local immunological responses and guide substrate regeneration.",
"metrics": {
"Novelty": 88,
"Mechanistic clarity": 82,
"Experimental tractability": 86,
"Cross-domain distance": 85,
},
"outline": (
"1. Formulate peptide sequences programmed for triggered in situ self-assembly within the myocardial infarct zone.\n"
"2. Quantify macrophage polarization and local immune choreography post-deployment.\n"
"3. Map the temporospatial degradation profile against de novo tissue formation.\n"
"4. Falsify against off-target aggregation and delayed clearance risks."
),
"path": ["seed", "nano", "selfasm", "alt2", "trial"],
},
{
"hypothesis": "Integration of conductive hydrogels with immunomodulatory properties to simultaneously bridge electrical uncoupling and mitigate adverse fibrotic scarring.",
"metrics": {
"Novelty": 85,
"Mechanistic clarity": 90,
"Experimental tractability": 88,
"Cross-domain distance": 79,
},
"outline": (
"1. Fabricate biocompatible hydrogels featuring precisely tuned electrical conductivity and immunomodulatory motifs.\n"
"2. Monitor electrophysiological synchronization across the scaffold-tissue interface.\n"
"3. Assess macrophage state transitions and suppression of adverse fibrotic remodelling.\n"
"4. Validate long-term persistence, hemocompatibility, and mechanical integration."
),
"path": ["seed", "bio", "card", "immune", "trial"],
},
]
# ββ Utility helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def normtext(x: Optional[str]) -> str:
return re.sub(r"\s+", " ", (x or "")).strip()
def buildlearninggraphhtml(nodes, edges, title="Self-Learning Knowledge Graph"):
return rendergraphcanvashtml(
{
"status": "ok" if nodes or edges else "empty",
"nodes": nodes or [],
"edges": edges or [],
},
title=title,
height=780,
)
# ββ HTML builders βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def buildconnectomehtml(pathids: List[str]) -> str:
active = set(pathids)
nodemap = {n["id"]: n for n in NODES}
pathpairs = {
pair
for i in range(len(pathids) - 1)
for pair in [(pathids[i], pathids[i + 1]), (pathids[i + 1], pathids[i])]
}
baselines, activelines, circles, labels = [], [], [], []
for a, b in EDGES:
na, nb = nodemap[a], nodemap[b]
x1, y1 = na["x"] * 8 + 80, na["y"] * 6 + 280
x2, y2 = nb["x"] * 8 + 80, nb["y"] * 6 + 280
baselines.append(
f'<line class="edge" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" />'
)
if (a, b) in pathpairs:
activelines.append(
f'<line class="edge active" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" />'
)
for n in NODES:
cx, cy = n["x"] * 8 + 80, n["y"] * 6 + 280
isactive = n["id"] in active
state = "chosen" if isactive else "idle"
halocls = "halo active" if isactive else "halo"
lblcls = "label active" if isactive else "label"
radius = 18 if isactive else 13
halor = 30 if isactive else 0
circles.append(
f'<g class="node-wrap">'
f'<circle class="{halocls}" cx="{cx:.1f}" cy="{cy:.1f}" r="{halor}" />'
f'<circle class="node {n["group"]} {state}" cx="{cx:.1f}" cy="{cy:.1f}" r="{radius}" />'
f"</g>"
)
labels.append(
f'<text class="{lblcls}" x="{cx + 18:.1f}" y="{cy - 16:.1f}">{safe_text(n["label"])}</text>'
)
return f"""
<div class="panel brain-shell">
<div class="brain-header">
<div>
<p class="eyebrow">Connectome</p>
<h3>3D Connectome</h3>
</div>
<div class="brain-legend">
<span><i class="dot dot-live"></i> lit path</span>
<span><i class="dot dot-chosen"></i> chosen node</span>
<span><i class="dot dot-idle"></i> available node</span>
</div>
</div>
<div class="brain-stage">
<svg viewBox="0 0 780 560" class="brain-svg" role="img" aria-label="DVNC 3D connectome visualisation">
{''.join(baselines)}
{''.join(activelines)}
{''.join(circles)}
{''.join(labels)}
</svg>
</div>
</div>
"""
def buildcardshtml(cards: List[Dict]) -> str:
items = []
for i, c in enumerate(cards):
items.append(
f"""
<article class="candidate-card" tabindex="0">
<div class="candidate-card-inner">
<div class="candidate-face candidate-front">
<div class="candidate-top">
<span class="chip">{safe_text(c["agent"])}</span>
<span class="score">{safe_text(c["score"])}</span>
</div>
<h4>{safe_text(c["title"])}</h4>
<p>{safe_text(c["front"])}</p>
<div class="meta-row"><span>Novelty</span><strong>{safe_text(c["novelty"])}</strong></div>
<button class="mini" type="button" onclick="triggerRouteSwap('{i}')">Use as main insight</button>
</div>
<div class="candidate-face candidate-back">
<div class="candidate-top">
<span class="chip alt">Alternative path</span>
<span class="score">{safe_text(c["score"])}</span>
</div>
<h4>{safe_text(c["title"])}</h4>
<p>{safe_text(c["back"])}</p>
<div class="meta-row"><span>Swap into route</span><strong>Enabled</strong></div>
<button class="mini" type="button" onclick="triggerRouteSwap('{i}')">Use as main insight</button>
</div>
</div>
</article>
"""
)
return '<div class="panel" style="padding:20px;"><div class="candidate-grid">' + "".join(items) + "</div></div>"
def buildchathtml(query: str, result: Dict) -> str:
return f"""
<div class="panel chat-panel">
<div class="chat-thread">
<div class="bubble bubble-user">
<span class="role">You</span>
<p>{safe_text(query)}</p>
</div>
<div class="bubble bubble-ai">
<span class="role">DVNC Sovereign</span>
<p>{safe_text(result["summary"])}</p>
</div>
<div class="bubble bubble-system">
<span class="role">Discovery Signal</span>
<p><strong>Primary hypothesis:</strong> {safe_text(result["primary_hypothesis"])}</p>
</div>
</div>
</div>
"""
def buildmodelshtml(selected: str) -> str:
items = []
for m in MODELS:
active = "active" if m["name"] == selected else ""
items.append(
f"""
<div class="model-pill {active}">
<span class="model-name">{safe_text(m["name"])}</span>
<span class="model-tag">{safe_text(m["tag"])}</span>
<small>{safe_text(m["desc"])}</small>
</div>
"""
)
return '<div class="panel" style="padding:18px;"><div class="model-switcher">' + "".join(items) + "</div></div>"
# ββ Discovery logic βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def rundiscovery(query: str, modelname: str):
random.seed(len(query or "") + len(modelname or ""))
if "curie" in (query or "").lower() or "einstein" in (query or "").lower():
primary = "Map the anomaly first, then force a distant analogy before composing the experimental programme."
path = ["seed", "bio", "card", "immune", "trial"]
else:
primary = (
"Utilization of a self-assembling conductive scaffold to transduce mechanical "
"strain into localized regenerative signalling pathways."
)
path = DEFAULTPATH
summaries = [
"Normalises the user prompt into a graph-searchable seed and isolates the tension inside the question.",
"Finds remote conceptual bridges instead of staying near the starting domain cluster.",
"Pulls evidence packets and conflict signals required for grounded hypothesis formation.",
"Generates cross-domain analogies with a bias toward mechanism transfer rather than keyword similarity.",
"Composes the lead hypothesis and two structurally different variants.",
"Attacks weak assumptions, hidden confounders, and feasibility gaps.",
"Produces a staged validation plan with measurable falsification criteria.",
]
tags = ["input", "graph", "evidence", "analogy", "compose", "critique", "experiment"]
reasoning = [
{"step": i + 1, "agent": AGENTS[i], "tag": tags[i], "summary": summaries[i]}
for i in range(7)
]
result = {
"summary": (
"A deeper route was chosen through the connectome, with live alternatives preserved "
"as swappable cards so the reasoning path can be inspected rather than hidden."
),
"primary_hypothesis": primary,
"reasoning": reasoning,
"cards": CANDIDATES,
"path": path,
"metrics": {
"Novelty": 93,
"Mechanistic clarity": 89,
"Experimental tractability": 82,
"Cross-domain distance": 91,
},
}
chathtml = buildchathtml(query, result)
connectomehtml = buildconnectomehtml(path)
timelinehtml = buildagentroutecardshtml(reasoning)
metricsmd = "\n".join(f"- {k}: {v}/100" for k, v in result["metrics"].items())
hypothesismd = (
"# Discovery Output\n\n"
f"**Model:** {modelname}\n\n"
f"**Primary hypothesis:** {result['primary_hypothesis']}\n\n"
"## Scoring\n"
f"{metricsmd}\n\n"
"## Experimental outline\n"
"1. Construct the candidate material or protocol.\n"
"2. Test mechanistic signal expression under controlled conditions.\n"
"3. Compare against baseline and nearest-neighbour alternatives.\n"
"4. Falsify using the adversarial risk criteria surfaced in the reasoning path.\n"
)
cardshtml = buildcardshtml(CANDIDATES)
routestate = getdefaultroutestate()
return (
chathtml,
connectomehtml,
timelinehtml,
cardshtml,
hypothesismd,
buildmodelshtml(modelname),
routestate,
)
def applyrouteswap(query: str, modelname: str, routeswappayload: str, routestate):
try:
idx = int(routeswappayload)
except Exception:
idx = 0
if not (0 <= idx < len(ACADEMICINSIGHTS)):
idx = 0
academic = ACADEMICINSIGHTS[idx]
connectomehtml = buildconnectomehtml(academic["path"])
result = {
"summary": (
"Main insight formally adopted. The connectome pathway and validation protocol "
"have been realigned to the selected candidate methodology."
),
"primary_hypothesis": academic["hypothesis"],
}
chathtml = buildchathtml(query, result)
metricsmd = "\n".join(f"- {k}: {v}/100" for k, v in academic["metrics"].items())
hypothesismd = (
"# Discovery Output\n\n"
f"**Model:** {modelname}\n\n"
f"**Primary hypothesis:** {academic['hypothesis']}\n\n"
"## Scoring\n"
f"{metricsmd}\n\n"
"## Experimental outline\n"
f"{academic['outline']}\n"
)
return chathtml, connectomehtml, gr.update(), hypothesismd, routestate
# ββ Example loaders ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def loadexample() -> str:
return "How could a self-assembling conductive biomaterial improve cardiac tissue regeneration by converting mechanical strain into repair signalling?"
def loadpapertopic() -> str:
return "self-assembling conductive biomaterials for cardiac repair"
# ββ CSS / HEAD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BASECSS = r"""
:root {
--bg: #ffffff; --panel: #ffffff; --line: rgba(0,0,0,.12);
--text: #111111; --muted: #5b5b5b; --soft: rgba(0,0,0,.62);
--gold: #ff6600; --teal: #17b8a6; --blue: #628dff;
--chosen: #ff7a1a; --idle: #b8d8ff; --idle-stroke: #5e8fe6;
--query-node: #ffd8b3; --paper-node: #d7f6f2; --upload-node: #e7defe;
--shadow: 0 16px 40px rgba(0,0,0,.12);
}
html,body,.gradio-container { background:#ffffff !important; font-family:Inter,ui-sans-serif,system-ui,sans-serif; }
.gradio-container { max-width:1640px !important; padding:20px !important; }
#dvnc-shell { border:1px solid var(--line); border-radius:28px; overflow:hidden; background:#ffffff; box-shadow:var(--shadow); padding:20px 22px 22px; }
.hero-bar { display:flex; justify-content:space-between; align-items:center; gap:16px; padding-bottom:12px; border-bottom:1px solid rgba(0,0,0,.06); margin-bottom:16px; }
.brand { display:flex; align-items:center; gap:14px; }
.logo { width:42px; height:42px; border-radius:14px; display:grid; place-items:center; color:var(--gold); background:linear-gradient(135deg,rgba(255,122,26,.12),rgba(23,184,166,.10)); border:1px solid rgba(0,0,0,.08); }
.logo svg { width:24px; height:24px; }
.brand h1 { font-size:1.05rem; margin:0; font-weight:700; letter-spacing:.12em; text-transform:uppercase; }
.brand p { margin:3px 0 0; color:var(--muted); font-size:.84rem; }
.status { display:flex; gap:10px; align-items:center; color:var(--soft); font-size:.85rem; }
.status-dot { width:10px; height:10px; border-radius:50%; background:var(--teal); box-shadow:0 0 0 6px rgba(23,184,166,.10),0 0 14px rgba(23,184,166,.25); }
.panel { background:#ffffff; border:1px solid var(--line); border-radius:22px; box-shadow:inset 0 1px 0 rgba(255,255,255,.8); }
.querybox textarea,.querybox input { background:transparent !important; color:var(--text) !important; }
.querybox,.querybox>div { background:#ffffff !important; border-radius:18px !important; border-color:var(--line) !important; }
.chat-panel { padding:18px; min-height:280px; }
.chat-thread { display:flex; flex-direction:column; gap:14px; }
.bubble { max-width:88%; padding:16px 18px; border-radius:22px; border:1px solid var(--line); }
.bubble p { margin:8px 0 0; line-height:1.6; font-size:.96rem; color:var(--text); }
.bubble .role { font-size:.72rem; letter-spacing:.12em; text-transform:uppercase; color:var(--muted); }
.bubble-user { align-self:flex-end; background:linear-gradient(135deg,rgba(98,141,255,.16),rgba(98,141,255,.08)); }
.bubble-ai { align-self:flex-start; background:#ffffff; }
.bubble-system { align-self:flex-start; background:linear-gradient(135deg,rgba(255,122,26,.10),rgba(255,122,26,.04)); }
.model-switcher { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; }
.model-pill { padding:14px; border:1px solid var(--line); border-radius:18px; display:flex; flex-direction:column; gap:4px; min-height:98px; background:#ffffff; }
.model-pill.active { border-color:rgba(255,122,26,.40); background:linear-gradient(135deg,rgba(255,122,26,.10),rgba(255,255,255,.96)); }
.model-name { font-weight:650; color:var(--text); }
.model-tag { font-size:.76rem; text-transform:uppercase; letter-spacing:.12em; color:var(--gold); }
.model-pill small { color:var(--muted); line-height:1.45; }
.brain-shell { padding:18px; }
.brain-header { display:flex; justify-content:space-between; align-items:flex-end; gap:16px; margin-bottom:10px; }
.eyebrow { font-size:.72rem; letter-spacing:.16em; text-transform:uppercase; color:var(--gold); margin:0 0 4px; }
.brain-header h3 { margin:0; font-size:1.12rem; color:var(--text); }
.brain-legend { display:flex; gap:14px; color:var(--muted); font-size:.8rem; flex-wrap:wrap; }
.dot { width:10px; height:10px; display:inline-block; border-radius:50%; margin-right:6px; }
.dot-live { background:var(--chosen); box-shadow:0 0 10px rgba(255,122,26,.35); }
.dot-chosen { background:var(--chosen); }
.dot-idle { background:var(--idle); border:1px solid var(--idle-stroke); }
.dot-query { background:var(--query-node); border:1px solid #de9e58; }
.dot-paper { background:var(--paper-node); border:1px solid #4fb3a5; }
.dot-upload { background:var(--upload-node); border:1px solid #8f73d9; }
.brain-stage { position:relative; min-height:420px; overflow:hidden; background:linear-gradient(180deg,rgba(250,250,250,1),rgba(255,255,255,1)); border:1px solid rgba(0,0,0,.05); border-radius:20px; }
.brain-svg { width:100%; height:520px; display:block; }
.edge { stroke:rgba(0,0,0,.12); stroke-width:2.4; }
.edge.active { stroke:var(--chosen); stroke-width:4.2; stroke-linecap:round; filter:drop-shadow(0 0 6px rgba(255,122,26,.45)); stroke-dasharray:8 12; animation:pulseEdge 1.5s linear infinite; }
.node { stroke-width:2.2; transition:all .25s ease; }
.node.idle { fill:var(--idle); stroke:var(--idle-stroke); }
.node.chosen { fill:var(--chosen); stroke:#ffb16d; }
.halo { fill:none; }
.halo.active { stroke:rgba(255,122,26,.18); stroke-width:12; }
.label { fill:#2c2c2c; font-size:13px; font-weight:500; letter-spacing:.01em; }
.label.active { fill:#111111; font-weight:700; }
.timeline { display:flex; flex-direction:column; gap:10px; }
.agent-step { border:1px solid var(--line); border-radius:18px; background:#ffffff; overflow:hidden; }
.agent-summary { list-style:none; display:grid; grid-template-columns:42px 1fr; gap:12px; align-items:center; padding:12px; cursor:pointer; }
.agent-summary::-webkit-details-marker { display:none; }
.agent-index { width:42px; height:42px; border-radius:14px; display:grid; place-items:center; font-weight:700; color:var(--gold); background:rgba(255,122,26,.08); border:1px solid rgba(255,122,26,.18); }
.agent-head { display:flex; justify-content:space-between; gap:12px; align-items:center; }
.agent-head h4 { margin:0; font-size:.98rem; color:var(--text); }
.agent-head span { font-size:.72rem; letter-spacing:.12em; text-transform:uppercase; color:var(--muted); }
.agent-copy { padding:0 14px 16px 66px; }
.agent-copy p { margin:0; color:#2d2d2d; font-size:.93rem; line-height:1.6; }
.candidate-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:18px; }
.candidate-card { background:none; perspective:1400px; min-height:330px; }
.candidate-card-inner { position:relative; width:100%; min-height:330px; transition:transform .8s cubic-bezier(.2,.7,.1,1); transform-style:preserve-3d; }
.candidate-card:hover .candidate-card-inner,.candidate-card:focus .candidate-card-inner,.candidate-card:focus-within .candidate-card-inner { transform:rotateY(180deg); }
.candidate-face { position:absolute; inset:0; padding:20px; border-radius:22px; border:1px solid var(--line); background:#ffffff; color:var(--text); backface-visibility:hidden; box-shadow:0 12px 24px rgba(0,0,0,.06); display:flex; flex-direction:column; gap:14px; }
.candidate-back { transform:rotateY(180deg); }
.candidate-top { display:flex; justify-content:space-between; align-items:center; gap:8px; }
.chip { font-size:.72rem; text-transform:uppercase; letter-spacing:.12em; color:#0b6f66; padding:7px 10px; border-radius:999px; background:rgba(23,184,166,.08); border:1px solid rgba(23,184,166,.18); }
.chip.alt { color:var(--gold); background:rgba(255,122,26,.08); border-color:rgba(255,122,26,.18); }
.score { font-weight:700; color:var(--gold); }
.candidate-face h4 { margin:0; font-size:1.08rem; line-height:1.35; }
.candidate-face p { margin:0; color:#1e1e1e; line-height:1.65; font-size:.96rem; overflow-wrap:anywhere; }
.meta-row { margin-top:auto; display:flex; justify-content:space-between; color:var(--muted); font-size:.88rem; gap:14px; }
.mini { cursor:pointer; margin-top:8px; align-self:flex-start; color:var(--text); padding:10px 12px; border-radius:14px; border:1px solid var(--line); background:#ffffff; transition:all 0.2s; }
.mini:hover { background:#f5f5f5; border-color:var(--chosen); }
.papers-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; }
.paper-card { border:1px solid var(--line); border-radius:18px; padding:16px; background:#ffffff; }
.paper-topline { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:10px; }
.paper-badge { font-size:.72rem; padding:6px 10px; border-radius:999px; background:rgba(98,141,255,.08); color:#3456b5; border:1px solid rgba(98,141,255,.18); }
.paper-badge.alt { background:rgba(0,0,0,.04); color:#444; border-color:rgba(0,0,0,.08); }
.doi-badge { background:rgba(255,122,26,.08); color:#8a4105; border-color:rgba(255,122,26,.18); }
.paper-card h4 { margin:0 0 10px; line-height:1.35; font-size:1rem; }
.paper-card p { margin:0 0 12px; line-height:1.6; color:#222; }
.paper-links { display:flex; gap:12px; flex-wrap:wrap; }
.paper-meta-stack { display:flex; flex-direction:column; gap:6px; color:#444; margin-bottom:12px; font-size:.9rem; }
.paper-links a,.journal-card,.upload-note a { color:#0b63ce; text-decoration:none; }
.journal-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; }
.journal-card { border:1px solid var(--line); border-radius:18px; padding:16px; display:flex; justify-content:space-between; gap:14px; align-items:center; background:#ffffff; }
.journal-card h4 { margin:0 0 6px; }
.journal-card p { margin:0; color:var(--muted); line-height:1.5; }
.selection-panel { padding:18px; }
.parse-grid { display:grid; grid-template-columns:1.2fr 1fr; gap:14px; }
.parse-card { border:1px solid var(--line); border-radius:18px; padding:16px; background:#ffffff; }
.ref-list { margin:0; padding-left:18px; }
.ref-list li { margin-bottom:8px; line-height:1.5; }
.gr-button-primary { background:linear-gradient(135deg,rgba(255,122,26,.92),rgba(240,108,22,.92)) !important; color:#ffffff !important; border:none !important; }
.gr-button-secondary { background:#ffffff !important; color:var(--text) !important; border:1px solid var(--line) !important; }
footer { display:none !important; }
@keyframes pulseEdge { to { stroke-dashoffset:-40; } }
@media (max-width:1180px) {
.model-switcher,.candidate-grid,.papers-grid,.journal-grid,.parse-grid { grid-template-columns:1fr; }
.brain-svg { height:460px; }
}
"""
CSS = BASECSS + "\n" + getdvnclayoutcss() + "\n" + getdiscoverycss()
HEAD = """
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script>
function triggerRouteSwap(idx) {
const container = document.getElementById('route_swap_payload');
if (!container) return;
const input = container.querySelector('textarea') || container.querySelector('input');
if (input) {
input.value = idx.toString();
input.dispatchEvent(new Event('input', { bubbles: true }));
setTimeout(() => {
const btn = document.getElementById('route_swap_apply');
if (btn) btn.click();
}, 150);
}
}
</script>
"""
# ββ Gradio layout βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Blocks(css=CSS, head=HEAD, theme=gr.themes.Base(), fill_height=True) as demo:
papersstate = gr.State([])
parsedpdfstate = gr.State({})
ingestpayloadstate = gr.State({})
routestate = gr.State(getdefaultroutestate())
gr.HTML(
"""
<div id="dvnc-shell">
<div class="hero-bar">
<div class="brand">
<div class="logo" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
<path d="M5 17L12 4l7 13"/>
<path d="M8.5 12.5h7"/>
<circle cx="12" cy="12" r="1.8" fill="currentColor" stroke="none"/>
</svg>
</div>
<div>
<h1>DVNC.AI</h1>
<p>Sovereign discovery instrument Β· connectome-native reasoning</p>
</div>
</div>
<div class="status"><span class="status-dot"></span><span>Live orchestration</span></div>
</div>
</div>
"""
)
with gr.Tabs():
with gr.Tab("Discovery Engine"):
modelhtml = gr.HTML(buildmodelshtml("DVNC Sovereign"))
with gr.Row():
with gr.Column(scale=2):
model = gr.Dropdown(
choices=[m["name"] for m in MODELS],
value="DVNC Sovereign",
label="Model tier",
)
query = gr.Textbox(
label="Discovery query",
elem_classes=["querybox"],
placeholder="Enter a scientific question, anomaly, or breakthrough directionβ¦",
lines=4,
)
with gr.Row():
runbtn = gr.Button("Run discovery", variant="primary")
examplebtn = gr.Button("Load example", variant="secondary")
chat = gr.HTML(
"""
<div class="panel chat-panel">
<div class="chat-thread">
<div class="bubble bubble-ai">
<span class="role">DVNC</span>
<p>Enter a query to activate the 7-agent discovery stack and illuminate the chosen path through the 3D connectome.</p>
</div>
</div>
</div>
"""
)
with gr.Column(scale=3):
connectome = gr.HTML(buildconnectomehtml(DEFAULTPATH))
cards = gr.HTML("")
output = gr.Markdown("# Discovery Output\n\nAwaiting query.")
timeline = gr.HTML(getinitialdiscoverytimelinehtml())
routeswappayload = gr.Textbox(value="", visible=False, elem_id="route_swap_payload")
routeswapapply = gr.Button("Apply route swap", visible=False, elem_id="route_swap_apply")
with gr.Tab("Self-Learning Graph"):
with gr.Row():
with gr.Column(scale=2):
paperquery = gr.Textbox(
label="Research topic / title / DOI / link",
elem_classes=["querybox"],
placeholder="e.g. self-assembling conductive biomaterials for cardiac repair",
lines=3,
)
searchmode = gr.Dropdown(
choices=SEARCHMODES,
value="topic",
label="Search mode",
)
sourceselector = gr.CheckboxGroup(
choices=SOURCEOPTIONS,
value=DEFAULTSOURCES,
label="Sources",
)
pdfupload = gr.File(
label="Upload PDF papers",
file_types=[".pdf"],
file_count="single",
)
with gr.Row():
learnbtn = gr.Button("Discover papers", variant="primary")
loadtopicbtn = gr.Button("Load example topic", variant="secondary")
uploadstatus = gr.Markdown("No PDF uploaded yet.")
discoverystatus = gr.Markdown("### No discovery results yet.")
journalpanel = gr.HTML(buildjournalhtml("biomaterials cardiac repair"))
gr.HTML(
'<div class="panel selection-panel"><h3 style="margin:0 0 12px;">Select papers to ingest</h3></div>'
)
selectionbox = gr.CheckboxGroup(
choices=[],
value=[],
label="Candidate papers",
)
parserorder = gr.CheckboxGroup(
choices=["grobid", "docling", "pymupdf"],
value=["grobid", "docling", "pymupdf"],
label="Parser routing order",
)
with gr.Row():
parsebtn = gr.Button("Parse uploaded PDF", variant="secondary")
ingestbtn = gr.Button("Ingest selected into graph", variant="primary")
with gr.Column(scale=3):
learninggraph = gr.HTML(buildlearninggraphhtml([], []))
paperspanel = gr.HTML(
'<div class="panel papers-panel" style="padding:18px"><p>Search by topic, title, DOI, or link, then select papers before graph ingestion.</p></div>'
)
parsesummary = gr.Markdown("### PDF parse status\n\nAwaiting upload.")
parsepanel = gr.HTML(
'<div class="panel" style="padding:18px"><p>No parsed document yet.</p></div>'
)
ingestsummary = gr.Markdown("### Graph ingest status\n\nAwaiting paper selection.")
ingestpayload = gr.JSON(
label="Graph ingest payload",
value={"status": "empty", "nodes": [], "edges": []},
)
# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
examplebtn.click(fn=loadexample, outputs=query)
runbtn.click(
fn=rundiscovery,
inputs=[query, model],
outputs=[chat, connectome, timeline, cards, output, modelhtml, routestate],
)
routeswapapply.click(
fn=applyrouteswap,
inputs=[query, model, routeswappayload, routestate],
outputs=[chat, connectome, timeline, output, routestate],
)
loadtopicbtn.click(fn=loadpapertopic, outputs=paperquery)
learnbtn.click(
fn=runpaperdiscovery,
inputs=[paperquery, searchmode, sourceselector, pdfupload],
outputs=[
learninggraph,
paperspanel,
journalpanel,
uploadstatus,
selectionbox,
papersstate,
discoverystatus,
],
)
parsebtn.click(
fn=parseuploadedpdf,
inputs=[pdfupload, parserorder],
outputs=[parsesummary, parsedpdfstate],
).then(
fn=renderparseresult,
inputs=[parsedpdfstate],
outputs=[parsepanel],
)
ingestbtn.click(
fn=ingestselectedpapers,
inputs=[paperquery, selectionbox, papersstate, pdfupload, parsedpdfstate],
outputs=[learninggraph, ingestsummary, ingestpayload],
)
if __name__ == "__main__":
demo.launch() |