Saicharan21 commited on
Commit
b9c6f5c
Β·
verified Β·
1 Parent(s): 54d94bd

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +1346 -5
app.py CHANGED
@@ -48,6 +48,1295 @@ button.secondary { background: #f3f4f6 !important; color: #374151 !important; bo
48
  input[type=number] { background: #f9fafb !important; color: #1a202c !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; }
49
  """
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  HEADER = """<div style="background:linear-gradient(135deg,#0a0f2e 0%,#1a0a0a 100%);padding:0;border-bottom:3px solid #c1121f;overflow:hidden;">
52
  <svg style="position:absolute;opacity:0.07;width:100%;height:100%;" viewBox="0 0 1200 120" preserveAspectRatio="none">
53
  <polyline points="0,60 100,60 130,20 150,100 170,10 200,90 220,60 400,60 430,20 450,100 470,10 500,90 520,60 700,60 730,20 750,100 770,10 800,90 820,60 1000,60 1030,20 1050,100 1070,10 1100,90 1120,60 1200,60" fill="none" stroke="#c1121f" stroke-width="3"/>
@@ -648,20 +1937,52 @@ def tgt_manual(t,p,h,pl,tm):
648
  return "TAT:"+str(t)+" PF1.2:"+str(p)+chr(10)+"Hemo:"+str(h)+" Plt:"+str(pl)+chr(10)+"RESULT: "+("HIGH RISK" if risk>=3 else "MODERATE" if risk>=2 else "LOW RISK")
649
 
650
  # ── UI ─────────────────────────────────────────────────────────────
651
- with gr.Blocks(title="CardioLab AI - SJSU") as demo:
652
  gr.HTML(HEADER)
653
 
654
  papers_count = len(set(m["paper"] for m in METADATA)) if PAPERS_LOADED else 0
655
  model_status = "Fine-tuned Model LOADED" if CARDIOLAB_MODEL_LOADED else "Fine-tuned model loading..."
656
  rag_status = "RAG: " + str(len(CHUNKS)) + " chunks from " + str(papers_count) + " SJSU papers" if PAPERS_LOADED else "RAG: loading..."
657
- gr.HTML("<div style='background:#1a7340;color:white;text-align:center;padding:7px;font-size:0.82em;font-weight:700;'>" + rag_status + " | " + model_status + " | Select CardioLab Fine-tuned in Model dropdown!</div>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
 
659
  with gr.Tabs():
660
 
661
  with gr.Tab("Chat"):
662
  with gr.Row():
663
  with gr.Column(scale=1, min_width=200):
664
- gr.HTML("<div style='background:#202123;padding:10px;border-radius:8px;margin-bottom:6px;'><div style='color:#e8a020;font-weight:700;font-size:0.85em;'>SJSU CARDIOLAB</div><div style='color:#9ca3af;font-size:0.7em;'>Conversations</div></div>")
 
665
  new_chat_btn = gr.Button("New Chat", variant="secondary")
666
  session_dropdown = gr.Dropdown(choices=get_session_list(), label="Saved Sessions", interactive=True)
667
  load_btn = gr.Button("Load Session", variant="primary")
@@ -825,7 +2146,27 @@ with gr.Blocks(title="CardioLab AI - SJSU") as demo:
825
  hyp_output = gr.Textbox(label="Research Hypotheses", lines=25)
826
  hyp_btn.click(generate_hypothesis, inputs=[hyp_area, hyp_findings], outputs=hyp_output)
827
 
828
- gr.HTML("""<div style="text-align:center;padding:10px;border-top:1px solid #e5e7eb;background:#f9fafb;">
829
- <span style="color:#9ca3af;font-size:0.75em;">CardioLab AI v38 | SJSU Biomedical Engineering | RAG + Fine-tuned + Phase D | Inspired by <a href="https://github.com/snap-stanford/Biomni" style="color:#c1121f;">Biomni Stanford</a> | Apache 2.0 | $0 Cost</span></div>""")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
 
831
  demo.launch(css=CSS)
 
48
  input[type=number] { background: #f9fafb !important; color: #1a202c !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; }
49
  """
50
 
51
+ HEADER = """<div style="
52
+ background: linear-gradient(135deg, #0a0f1e 0%, #0d0508 50%, #0a0f1e 100%);
53
+ border-bottom: 1px solid rgba(193,18,31,0.3);
54
+ position: relative;
55
+ overflow: hidden;
56
+ padding: 0;
57
+ ">
58
+ <!-- Animated grid background -->
59
+ <div style="
60
+ position: absolute; top: 0; left: 0; right: 0; bottom: 0;
61
+ background-image:
62
+ linear-gradient(rgba(193,18,31,0.05) 1px, transparent 1px),
63
+ linear-gradient(90deg, rgba(193,18,31,0.05) 1px, transparent 1px);
64
+ background-size: 40px 40px;
65
+ animation: gridMove 20s linear infinite;
66
+ "></div>
67
+
68
+ <!-- Glow orbs -->
69
+ <div style="position:absolute;top:-50%;left:-10%;width:500px;height:500px;background:radial-gradient(circle,rgba(193,18,31,0.08) 0%,transparent 70%);pointer-events:none;"></div>
70
+ <div style="position:absolute;top:-50%;right:-10%;width:400px;height:400px;background:radial-gradient(circle,rgba(0,87,168,0.08) 0%,transparent 70%);pointer-events:none;"></div>
71
+
72
+ <style>
73
+ @keyframes gridMove { from { transform: translateY(0); } to { transform: translateY(40px); } }
74
+ @keyframes ecgDraw { from { stroke-dashoffset: 800; } to { stroke-dashoffset: 0; } }
75
+ @keyframes hb { 0%,100%{transform:scale(1)} 15%{transform:scale(1.18)} 30%{transform:scale(1)} 45%{transform:scale(1.12)} 60%{transform:scale(1)} }
76
+ @keyframes shimmer { 0%{opacity:0.4} 50%{opacity:1} 100%{opacity:0.4} }
77
+ </style>
78
+
79
+ <div style="
80
+ max-width: 1400px; margin: 0 auto;
81
+ padding: 18px 28px;
82
+ display: flex; align-items: center; justify-content: space-between;
83
+ position: relative; z-index: 1;
84
+ ">
85
+ <!-- LEFT: SJSU Identity -->
86
+ <div style="display:flex;align-items:center;gap:16px;">
87
+ <div style="position:relative;">
88
+ <!-- Spartan SVG with glow -->
89
+ <div style="width:52px;height:52px;background:linear-gradient(135deg,rgba(0,87,168,0.3),rgba(0,87,168,0.1));border:1px solid rgba(0,87,168,0.4);border-radius:14px;display:flex;align-items:center;justify-content:center;box-shadow:0 0 20px rgba(0,87,168,0.3);">
90
+ <svg width="32" height="32" viewBox="0 0 100 100">
91
+ <circle cx="50" cy="35" r="28" fill="#0057a8" opacity="0.9"/>
92
+ <ellipse cx="50" cy="14" rx="22" ry="10" fill="#0057a8"/>
93
+ <polygon points="30,14 33,4 36,14" fill="#e8a020"/>
94
+ <polygon points="36,12 39,2 42,12" fill="#e8a020"/>
95
+ <polygon points="42,11 45,1 48,11" fill="#e8a020"/>
96
+ <polygon points="48,11 51,1 54,11" fill="#e8a020"/>
97
+ <polygon points="54,12 57,2 60,12" fill="#e8a020"/>
98
+ <polygon points="60,14 63,4 66,14" fill="#e8a020"/>
99
+ <rect x="36" y="30" width="28" height="22" rx="4" fill="#0057a8"/>
100
+ <rect x="40" y="35" width="8" height="12" rx="2" fill="#e8a020"/>
101
+ <rect x="34" y="50" width="32" height="8" rx="4" fill="#0057a8"/>
102
+ </svg>
103
+ </div>
104
+ </div>
105
+ <div>
106
+ <div style="color:rgba(232,160,32,0.9);font-size:0.65em;font-weight:600;letter-spacing:3px;text-transform:uppercase;margin-bottom:2px;">San Jose State University</div>
107
+ <div style="color:white;font-size:0.92em;font-weight:700;letter-spacing:0.5px;">Biomedical Engineering</div>
108
+ <div style="color:rgba(255,255,255,0.35);font-size:0.65em;letter-spacing:1px;margin-top:1px;">Dr. Alessandro Bellofiore β€” CardioLab</div>
109
+ </div>
110
+ </div>
111
+
112
+ <!-- CENTER: CardioLab AI Brand -->
113
+ <div style="text-align:center;flex:1;padding:0 30px;">
114
+ <!-- ECG animation -->
115
+ <div style="display:flex;align-items:center;justify-content:center;gap:14px;margin-bottom:6px;">
116
+ <svg width="110" height="30" viewBox="0 0 140 30" style="opacity:0.8;">
117
+ <polyline
118
+ points="0,15 25,15 32,15 38,3 42,27 46,1 50,25 56,15 140,15"
119
+ fill="none" stroke="#c1121f" stroke-width="2"
120
+ stroke-linecap="round" stroke-linejoin="round"
121
+ stroke-dasharray="800"
122
+ style="animation: ecgDraw 2s ease forwards, shimmer 3s ease 2s infinite;"
123
+ />
124
+ <circle cx="46" cy="1" r="2.5" fill="#c1121f" style="animation:shimmer 3s ease 2s infinite;"/>
125
+ </svg>
126
+
127
+ <div>
128
+ <div style="font-size:2.4em;font-weight:900;letter-spacing:1px;line-height:1;font-family:'Space Grotesk',sans-serif;">
129
+ <span style="color:white;">Cardio</span><span style="color:#c1121f;">Lab</span><span style="color:white;"> AI</span>
130
+ </div>
131
+ </div>
132
+
133
+ <svg width="110" height="30" viewBox="0 0 140 30" style="opacity:0.8;transform:scaleX(-1);">
134
+ <polyline
135
+ points="0,15 25,15 32,15 38,3 42,27 46,1 50,25 56,15 140,15"
136
+ fill="none" stroke="#c1121f" stroke-width="2"
137
+ stroke-linecap="round" stroke-linejoin="round"
138
+ stroke-dasharray="800"
139
+ style="animation: ecgDraw 2s ease 0.3s forwards, shimmer 3s ease 2.3s infinite;"
140
+ />
141
+ </svg>
142
+ </div>
143
+
144
+ <!-- Animated badge pills -->
145
+ <div style="display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap;">
146
+ <span style="background:rgba(193,18,31,0.2);border:1px solid rgba(193,18,31,0.4);color:rgba(255,255,255,0.8);padding:3px 10px;border-radius:20px;font-size:0.62em;font-weight:600;letter-spacing:0.05em;">RAG 16 PAPERS</span>
147
+ <span style="background:rgba(0,87,168,0.2);border:1px solid rgba(0,87,168,0.4);color:rgba(255,255,255,0.8);padding:3px 10px;border-radius:20px;font-size:0.62em;font-weight:600;letter-spacing:0.05em;">FINE-TUNED MODEL</span>
148
+ <span style="background:rgba(232,160,32,0.15);border:1px solid rgba(232,160,32,0.3);color:rgba(255,255,255,0.8);padding:3px 10px;border-radius:20px;font-size:0.62em;font-weight:600;letter-spacing:0.05em;">5 AI MODELS</span>
149
+ <span style="background:rgba(46,204,113,0.15);border:1px solid rgba(46,204,113,0.3);color:rgba(255,255,255,0.8);padding:3px 10px;border-radius:20px;font-size:0.62em;font-weight:600;letter-spacing:0.05em;">$0 COST</span>
150
+ </div>
151
+ </div>
152
+
153
+ <!-- RIGHT: Animated Heart + Stats -->
154
+ <div style="display:flex;align-items:center;gap:18px;">
155
+ <div style="text-align:right;">
156
+ <div style="color:rgba(255,255,255,0.35);font-size:0.62em;letter-spacing:2px;text-transform:uppercase;margin-bottom:6px;">Research Pillars</div>
157
+ <div style="display:flex;flex-direction:column;gap:4px;align-items:flex-end;">
158
+ <span style="background:rgba(193,18,31,0.15);border:1px solid rgba(193,18,31,0.2);color:rgba(255,255,255,0.7);padding:2px 10px;border-radius:6px;font-size:0.65em;font-weight:500;">MHV β€” MCL Β· PIV Β· TGT</span>
159
+ <span style="background:rgba(0,87,168,0.15);border:1px solid rgba(0,87,168,0.2);color:rgba(255,255,255,0.7);padding:2px 10px;border-radius:6px;font-size:0.65em;font-weight:500;">CKD β€” uPAD Β· Jaffe</span>
160
+ <span style="background:rgba(232,160,32,0.1);border:1px solid rgba(232,160,32,0.2);color:rgba(255,255,255,0.7);padding:2px 10px;border-radius:6px;font-size:0.65em;font-weight:500;">FSI β€” COMSOL</span>
161
+ </div>
162
+ </div>
163
+
164
+ <!-- Animated beating heart -->
165
+ <div style="animation: hb 1.5s ease infinite;">
166
+ <svg width="52" height="48" viewBox="0 0 100 90">
167
+ <defs>
168
+ <radialGradient id="hg" cx="50%" cy="40%">
169
+ <stop offset="0%" stop-color="#e63946"/>
170
+ <stop offset="100%" stop-color="#7d0a11"/>
171
+ </radialGradient>
172
+ <filter id="glow">
173
+ <feGaussianBlur stdDeviation="3" result="blur"/>
174
+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
175
+ </filter>
176
+ </defs>
177
+ <path d="M50 85 C50 85 5 55 5 30 C5 15 18 5 30 5 C38 5 45 9 50 15 C55 9 62 5 70 5 C82 5 95 15 95 30 C95 55 50 85 50 85Z"
178
+ fill="url(#hg)" filter="url(#glow)" opacity="0.95"/>
179
+ <polyline points="20,48 30,48 36,35 40,60 44,28 48,52 54,48 80,48"
180
+ fill="none" stroke="white" stroke-width="3"
181
+ stroke-linecap="round" stroke-linejoin="round" opacity="0.9"/>
182
+ </svg>
183
+ </div>
184
+ </div>
185
+ </div>
186
+
187
+ <!-- Bottom gradient bar -->
188
+ <div style="height:2px;background:linear-gradient(90deg,transparent,#0057a8,#c1121f,#e8a020,#c1121f,#0057a8,transparent);"></div>
189
+ </div>"""
190
+
191
+ # ── PAPER DATABASE ─────────────────────────────────────────────────
192
+ CHUNKS = []
193
+ METADATA = []
194
+ EMBEDDINGS = None
195
+ PAPERS_LOADED = False
196
+ EMBEDDER = None
197
+ CARDIOLAB_TOKENIZER = None
198
+ CARDIOLAB_LLM = None
199
+ CARDIOLAB_MODEL_LOADED = False
200
+
201
+ def load_papers():
202
+ global CHUNKS, METADATA, EMBEDDINGS, PAPERS_LOADED, EMBEDDER
203
+ try:
204
+ from sentence_transformers import SentenceTransformer
205
+ chunks_path = hf_hub_download(repo_id=PAPERS_DB_REPO, filename="chunks.json", repo_type="dataset", token=HF_TOKEN)
206
+ meta_path = hf_hub_download(repo_id=PAPERS_DB_REPO, filename="metadata.json", repo_type="dataset", token=HF_TOKEN)
207
+ emb_path = hf_hub_download(repo_id=PAPERS_DB_REPO, filename="embeddings.npy", repo_type="dataset", token=HF_TOKEN)
208
+ with open(chunks_path) as f: CHUNKS = json.load(f)
209
+ with open(meta_path) as f: METADATA = json.load(f)
210
+ EMBEDDINGS = np.load(emb_path)
211
+ EMBEDDER = SentenceTransformer("all-MiniLM-L6-v2")
212
+ PAPERS_LOADED = True
213
+ print("Papers loaded: " + str(len(CHUNKS)) + " chunks")
214
+ return True
215
+ except Exception as e:
216
+ print("Paper load error: " + str(e))
217
+ return False
218
+
219
+ def load_cardiolab_model():
220
+ global CARDIOLAB_TOKENIZER, CARDIOLAB_LLM, CARDIOLAB_MODEL_LOADED
221
+ try:
222
+ import torch
223
+ from transformers import AutoModelForCausalLM, AutoTokenizer
224
+ print("Loading CardioLab fine-tuned model...")
225
+ CARDIOLAB_TOKENIZER = AutoTokenizer.from_pretrained(CARDIOLAB_MODEL, token=HF_TOKEN)
226
+ CARDIOLAB_TOKENIZER.pad_token = CARDIOLAB_TOKENIZER.eos_token
227
+ device = "cuda" if torch.cuda.is_available() else "cpu"
228
+ CARDIOLAB_LLM = AutoModelForCausalLM.from_pretrained(
229
+ CARDIOLAB_MODEL, token=HF_TOKEN,
230
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
231
+ device_map="auto" if device == "cuda" else None,
232
+ low_cpu_mem_usage=True
233
+ )
234
+ CARDIOLAB_MODEL_LOADED = True
235
+ print("CardioLab model loaded!")
236
+ return True
237
+ except Exception as e:
238
+ print("CardioLab model error: " + str(e))
239
+ return False
240
+
241
+ load_papers()
242
+ load_cardiolab_model()
243
+
244
+ def search_papers(query, n=4):
245
+ if not PAPERS_LOADED or EMBEDDINGS is None or EMBEDDER is None:
246
+ return "", []
247
+ try:
248
+ q_emb = EMBEDDER.encode([query])
249
+ norms = np.linalg.norm(EMBEDDINGS, axis=1, keepdims=True)
250
+ emb_norm = EMBEDDINGS / (norms + 1e-10)
251
+ q_norm = q_emb / (np.linalg.norm(q_emb) + 1e-10)
252
+ scores = (emb_norm @ q_norm.T).flatten()
253
+ top_idx = np.argsort(scores)[::-1][:n]
254
+ context = ""
255
+ results = []
256
+ seen = set()
257
+ for idx in top_idx:
258
+ chunk = CHUNKS[idx]
259
+ meta = METADATA[idx]
260
+ score = float(scores[idx])
261
+ if score > 0.25:
262
+ results.append({"chunk": chunk, "paper": meta["paper"], "score": score})
263
+ if meta["paper"] not in seen:
264
+ context += chr(10) + "=== FROM: " + meta["paper"] + " ===" + chr(10)
265
+ seen.add(meta["paper"])
266
+ context += chunk[:500] + chr(10)
267
+ return context, results
268
+ except Exception as e:
269
+ return "", []
270
+
271
+ # ── SESSION MANAGEMENT ─────────────────────────────────────────────
272
+ def load_all_sessions():
273
+ if not HF_TOKEN: return {}
274
+ try:
275
+ path = hf_hub_download(repo_id=HISTORY_REPO, filename="chat_history.json", repo_type="dataset", token=HF_TOKEN)
276
+ with open(path) as f: return json.load(f)
277
+ except: return {}
278
+
279
+ def save_all_sessions(sessions):
280
+ if not HF_TOKEN: return False
281
+ try:
282
+ api2 = HfApi(token=HF_TOKEN)
283
+ api2.upload_file(path_or_fileobj=json.dumps(sessions, indent=2).encode(),
284
+ path_in_repo="chat_history.json", repo_id=HISTORY_REPO,
285
+ repo_type="dataset", token=HF_TOKEN, commit_message="Update")
286
+ return True
287
+ except: return False
288
+
289
+ def get_session_list():
290
+ s = load_all_sessions()
291
+ return list(reversed(list(s.keys()))) if s else ["No saved sessions"]
292
+
293
+ def save_session(history, name):
294
+ if not history: return "Nothing to save", gr.update()
295
+ if not name or not name.strip(): name = "Chat " + datetime.now().strftime("%b %d %H:%M")
296
+ sessions = load_all_sessions()
297
+ sessions[name] = {"messages": history, "saved_at": datetime.now().isoformat()}
298
+ ok = save_all_sessions(sessions)
299
+ choices = get_session_list()
300
+ return ("Saved: " + name if ok else "Save failed"), gr.update(choices=choices, value=name)
301
+
302
+ def load_session(name):
303
+ if not name or "No saved" in name: return [], "Select a session"
304
+ sessions = load_all_sessions()
305
+ return (sessions[name]["messages"], "Loaded: " + name) if name in sessions else ([], "Not found")
306
+
307
+ def delete_session(name):
308
+ if not name or "No saved" in name: return "Select a session", gr.update()
309
+ sessions = load_all_sessions()
310
+ if name in sessions:
311
+ del sessions[name]; save_all_sessions(sessions)
312
+ choices = get_session_list()
313
+ return "Deleted: " + name, gr.update(choices=choices, value=choices[0] if choices else None)
314
+ return "Not found", gr.update()
315
+
316
+ def new_chat(): return [], "", "New chat started"
317
+
318
+ # ── SEARCH ────────────────────────────────────────────────────��────
319
+ def get_pubmed_chat(query, n=3):
320
+ try:
321
+ r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
322
+ params={"db":"pubmed","term":query+" AND (heart valve OR hemodynamics OR microfluidic OR thrombogen OR creatinine OR CKD)","retmax":n,"retmode":"json","sort":"date","field":"tiab"},timeout=10)
323
+ ids = r.json()["esearchresult"]["idlist"]
324
+ return chr(10).join(["https://pubmed.ncbi.nlm.nih.gov/"+i for i in ids]) if ids else ""
325
+ except: return ""
326
+
327
+ def expand_query_ai(query):
328
+ if not GROQ_KEY: return query
329
+ try:
330
+ client = Groq(api_key=GROQ_KEY)
331
+ resp = client.chat.completions.create(model="llama-3.1-8b-instant",
332
+ messages=[{"role":"system","content":"Biomedical PubMed expert. Convert to MeSH terms for heart valves hemodynamics PIV thrombogenicity FSI microfluidics CKD. Return ONLY terms."},
333
+ {"role":"user","content":"Optimize: " + query}], max_tokens=80)
334
+ return resp.choices[0].message.content.strip() or query
335
+ except: return query
336
+
337
+ def quick_search(query, search_model="Llama 3.3 70B (Best)"):
338
+ if not query.strip(): return "Please enter a topic."
339
+ expanded = expand_query_ai(query)
340
+ results = []
341
+ try:
342
+ forced = expanded + " AND (heart valve OR hemodynamics OR microfluidic OR thrombogen OR creatinine OR PIV OR CFD OR CKD)"
343
+ r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
344
+ params={"db":"pubmed","term":forced,"retmax":8,"retmode":"json","sort":"date","field":"tiab"},timeout=12)
345
+ ids = r.json()["esearchresult"]["idlist"]
346
+ if ids:
347
+ r2 = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi",
348
+ params={"db":"pubmed","id":",".join(ids),"retmode":"xml","rettype":"abstract"},timeout=12)
349
+ import xml.etree.ElementTree as ET
350
+ root = ET.fromstring(r2.content)
351
+ for article in root.findall(".//PubmedArticle"):
352
+ try:
353
+ title = article.find(".//ArticleTitle").text or "No title"
354
+ pmid = article.find(".//PMID").text or ""
355
+ year_el = article.find(".//PubDate/Year")
356
+ year = year_el.text if year_el is not None else ""
357
+ results.append({"source":"PubMed","title":str(title),"year":year,"url":"https://pubmed.ncbi.nlm.nih.gov/"+pmid})
358
+ except: continue
359
+ except: pass
360
+ try:
361
+ r = requests.get("https://api.semanticscholar.org/graph/v1/paper/search",
362
+ params={"query":expanded,"limit":6,"fields":"title,year,url,citationCount"},timeout=12)
363
+ for p in r.json().get("data",[]):
364
+ year = p.get("year",0) or 0
365
+ if int(year) >= 2015:
366
+ results.append({"source":"Scholar","title":p.get("title",""),"year":str(year),"url":p.get("url",""),"citations":str(p.get("citationCount",0))})
367
+ except: pass
368
+ out = "QUERY: " + query + chr(10) + "AI EXPANDED: " + expanded + chr(10) + "="*45 + chr(10) + chr(10)
369
+ groups = {"PubMed":[],"Scholar":[]}
370
+ seen = set()
371
+ for r in results:
372
+ key = r["title"][:50].lower()
373
+ if key not in seen and r["url"]:
374
+ seen.add(key); groups[r["source"]].append(r)
375
+ for source, papers in groups.items():
376
+ if not papers: continue
377
+ out += "--- " + source + " ---" + chr(10)
378
+ for p in papers[:8]:
379
+ out += p["title"][:85] + " (" + p["year"] + ")" + chr(10)
380
+ out += " " + p["url"] + chr(10) + chr(10)
381
+ out += "--- SJSU ScholarWorks ---" + chr(10)
382
+ out += "https://scholarworks.sjsu.edu/do/search/?q=" + requests.utils.quote(query) + "&context=6781027"
383
+ return out
384
+
385
+ # ── CHAT ───────────────────────────────────────────────────────────
386
+ def answer_with_cardiolab_model(question, paper_context=""):
387
+ if not CARDIOLAB_MODEL_LOADED: return None
388
+ try:
389
+ import torch
390
+ system = "You are CardioLab AI for SJSU Biomedical Engineering."
391
+ if paper_context: system += " Use these SJSU research papers: " + paper_context[:400]
392
+ prompt = "<|system|>" + system + "</s><|user|>" + question + "</s><|assistant|>"
393
+ inputs = CARDIOLAB_TOKENIZER(prompt, return_tensors="pt", truncation=True, max_length=512)
394
+ device = next(CARDIOLAB_LLM.parameters()).device
395
+ inputs = {k: v.to(device) for k, v in inputs.items()}
396
+ with torch.no_grad():
397
+ outputs = CARDIOLAB_LLM.generate(**inputs, max_new_tokens=200, do_sample=True,
398
+ temperature=0.3, pad_token_id=CARDIOLAB_TOKENIZER.eos_token_id)
399
+ response = CARDIOLAB_TOKENIZER.decode(outputs[0], skip_special_tokens=True)
400
+ if "<|assistant|>" in response:
401
+ answer = response.split("<|assistant|>")[-1].strip()
402
+ else:
403
+ answer = response[-300:].strip()
404
+ return answer if len(answer) > 20 else None
405
+ except Exception as e:
406
+ print("CardioLab model error: " + str(e))
407
+ return None
408
+
409
+ def research_chat(message, history, chat_model="Llama 3.3 70B (Best)"):
410
+ if not message.strip(): return "", history
411
+ paper_context, paper_results = search_papers(message, n=4)
412
+ if chat_model == "CardioLab Fine-tuned (SJSU)" and CARDIOLAB_MODEL_LOADED:
413
+ answer = answer_with_cardiolab_model(message, paper_context)
414
+ if answer:
415
+ if paper_results:
416
+ unique_papers = list(dict.fromkeys([r["paper"] for r in paper_results]))
417
+ answer += chr(10) + chr(10) + "Sources from SJSU CardioLab papers:"
418
+ for p in unique_papers[:3]:
419
+ answer += chr(10) + " - " + p.replace(".pdf","").replace("_"," ")
420
+ pubmed = get_pubmed_chat(message, n=2)
421
+ if pubmed: answer += chr(10) + "PubMed: " + pubmed
422
+ history.append({"role":"user","content":message})
423
+ history.append({"role":"assistant","content":"[CardioLab Fine-tuned] " + answer})
424
+ return "", history
425
+ if not GROQ_KEY:
426
+ history.append({"role":"user","content":message})
427
+ history.append({"role":"assistant","content":"Error: Add GROQ_API_KEY to Space Settings."})
428
+ return "", history
429
+ try:
430
+ model_id = CHAT_MODELS.get(chat_model, "llama-3.3-70b-versatile")
431
+ client = Groq(api_key=GROQ_KEY)
432
+ if paper_context:
433
+ system_prompt = ("You are CardioLab AI for SJSU Biomedical Engineering. "
434
+ "Answer using SJSU CardioLab research papers below. Cite paper names with specific data." +
435
+ chr(10) + chr(10) + "SJSU CARDIOLAB PAPERS:" + chr(10) + paper_context +
436
+ chr(10) + chr(10) + "ADDITIONAL KNOWLEDGE: " + KNOWHOW)
437
+ else:
438
+ system_prompt = "You are CardioLab AI for SJSU Biomedical Engineering. Expert in MHV MCL PIV TGT uPAD CKD FSI. " + KNOWHOW
439
+ msgs = [{"role":"system","content":system_prompt}]
440
+ for item in history:
441
+ if isinstance(item, dict): msgs.append({"role":item["role"],"content":item["content"]})
442
+ msgs.append({"role":"user","content":message})
443
+ resp = client.chat.completions.create(model=model_id, messages=msgs, max_tokens=800)
444
+ answer = resp.choices[0].message.content
445
+ if paper_results:
446
+ unique_papers = list(dict.fromkeys([r["paper"] for r in paper_results]))
447
+ answer += chr(10) + chr(10) + "Sources from SJSU CardioLab papers:"
448
+ for p in unique_papers[:3]:
449
+ answer += chr(10) + " - " + p.replace(".pdf","").replace("_"," ")
450
+ pubmed = get_pubmed_chat(message, n=2)
451
+ if pubmed: answer += chr(10) + "PubMed: " + pubmed
452
+ history.append({"role":"user","content":message})
453
+ history.append({"role":"assistant","content":answer})
454
+ return "", history
455
+ except Exception as e:
456
+ history.append({"role":"user","content":message})
457
+ history.append({"role":"assistant","content":"Error: " + str(e)})
458
+ return "", history
459
+
460
+ def voice_chat(audio, history):
461
+ if audio is None:
462
+ history.append({"role":"assistant","content":"Please record your question first."})
463
+ return history
464
+ try:
465
+ client = Groq(api_key=GROQ_KEY)
466
+ with open(audio, "rb") as f:
467
+ tx = client.audio.transcriptions.create(file=("audio.wav", f, "audio/wav"), model="whisper-large-v3")
468
+ paper_context, _ = search_papers(tx.text, n=3)
469
+ system = "You are CardioLab AI. " + KNOWHOW
470
+ if paper_context: system = "You are CardioLab AI. Use these SJSU papers:" + chr(10) + paper_context + chr(10) + KNOWHOW
471
+ msgs = [{"role":"system","content":system}]
472
+ for item in history:
473
+ if isinstance(item, dict): msgs.append({"role":item["role"],"content":item["content"]})
474
+ msgs.append({"role":"user","content":tx.text})
475
+ resp = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=msgs, max_tokens=500)
476
+ history.append({"role":"user","content":"Voice: " + tx.text})
477
+ history.append({"role":"assistant","content":resp.choices[0].message.content})
478
+ return history
479
+ except Exception as e:
480
+ history.append({"role":"assistant","content":"Voice error: " + str(e)})
481
+ return history
482
+
483
+ # ── PHASE D: PROTOCOL GENERATOR + REPORT WRITER + HYPOTHESIS ──────
484
+ def generate_protocol(experiment_type, specific_params):
485
+ # CRITICAL DEFINITIONS - never interpret these wrong
486
+ DEFINITIONS = (
487
+ "CRITICAL: TGT = Thrombogenicity Tester device. "
488
+ "TGT measures blood CLOTTING and THROMBOSIS using Arduino Uno stepper motor rotating blood samples. "
489
+ "TGT does NOT measure glucose. TGT biomarkers are TAT PF1.2 free hemoglobin platelets. "
490
+ "TAT = Thrombin-Antithrombin complex normal below 8 ng/mL. "
491
+ "PF1.2 = Prothrombin Fragment 1.2 normal below 2.0 nmol/L. "
492
+ "Free hemoglobin normal below 20 mg/L. Platelet count normal above 150 thousand per uL. "
493
+ "MCL = Mock Circulatory Loop cardiovascular simulation. "
494
+ "PIV = Particle Image Velocimetry laser flow measurement. "
495
+ "uPAD = microfluidic Paper Analytical Device for creatinine kidney disease detection. "
496
+ )
497
+ experiment_type = experiment_type # use as is
498
+ if not GROQ_KEY: return "Error: Add GROQ_API_KEY to Space Settings."
499
+ if not experiment_type: return "Please select an experiment type."
500
+ try:
501
+ client = Groq(api_key=GROQ_KEY)
502
+ paper_context, _ = search_papers(experiment_type, n=4)
503
+ lab_context = {
504
+ "MCL": "Sylgard 184 PDMS 10:1 ratio 48hr cure. Tygon tubing. 70bpm 5L/min 80-120mmHg.",
505
+ "PIV": "Green laser 532nm time-resolved. Normal velocity 0.5-2.0 m/s. Shear below 5 Pa.",
506
+ "Thrombogenicity": "Arduino Uno stepper motor 48V. 150mL fresh blood. Sample at 0 20 40 60 min. Heska HT5. Measures TAT PF1.2 free hemoglobin platelets. TAT normal below 8 ng/mL. PF1.2 normal below 2.0 nmol/L.",
507
+ "uPAD": "Whatman filter paper. Wax printer 120C. Picric acid alkaline solution. Jaffe reaction.",
508
+ "FSI": "COMSOL Multiphysics ALE mesh. Blood 1060 kg/m3 0.0035 Pa.s. SJM bileaflet geometry.",
509
+ }
510
+ extra = next((v for k, v in lab_context.items() if k.lower() in experiment_type.lower()), "")
511
+ system_msg = ("You are CardioLab AI protocol generator for SJSU Biomedical Engineering. "
512
+ "Generate a COMPLETE detailed lab protocol with these sections: "
513
+ "1. OBJECTIVE "
514
+ "2. MATERIALS AND EQUIPMENT with exact quantities "
515
+ "3. SAFETY CONSIDERATIONS "
516
+ "4. STEP-BY-STEP PROCEDURE numbered and detailed "
517
+ "5. DATA COLLECTION "
518
+ "6. ANALYSIS METHOD "
519
+ "7. EXPECTED RESULTS with normal ranges "
520
+ "8. TROUBLESHOOTING "
521
+ "Use exact SJSU CardioLab values and equipment.")
522
+ user_msg = "Generate complete protocol for: " + experiment_type
523
+ if specific_params and specific_params.strip():
524
+ user_msg += chr(10) + "Parameters: " + specific_params
525
+ if extra:
526
+ user_msg += chr(10) + "CardioLab context: " + extra
527
+ if paper_context:
528
+ user_msg += chr(10) + "From SJSU papers: " + paper_context[:600]
529
+ resp = client.chat.completions.create(
530
+ model="llama-3.3-70b-versatile",
531
+ messages=[{"role":"system","content":system_msg},{"role":"user","content":user_msg}],
532
+ max_tokens=1200)
533
+ return resp.choices[0].message.content
534
+ except Exception as e:
535
+ return "Error generating protocol: " + str(e)
536
+
537
+ def generate_report(data_description, experiment_type, results):
538
+ if not GROQ_KEY: return "Error: Add GROQ_API_KEY to Space Settings."
539
+ if not experiment_type: return "Please select a study type."
540
+ try:
541
+ client = Groq(api_key=GROQ_KEY)
542
+ paper_context, _ = search_papers(experiment_type, n=3)
543
+ system_msg = ("You are CardioLab AI report writer for SJSU Biomedical Engineering. "
544
+ "Generate a professional research report with these sections: "
545
+ "1. ABSTRACT 150 words "
546
+ "2. INTRODUCTION background and objectives "
547
+ "3. MATERIALS AND METHODS "
548
+ "4. RESULTS AND DISCUSSION "
549
+ "5. CONCLUSION "
550
+ "6. RECOMMENDATIONS "
551
+ "7. REFERENCES cite SJSU CardioLab papers "
552
+ "Use specific values. Write in professional academic style.")
553
+ user_msg = "Write research report for: " + experiment_type
554
+ if data_description and data_description.strip():
555
+ user_msg += chr(10) + "Description: " + data_description
556
+ if results and results.strip():
557
+ user_msg += chr(10) + "Results: " + results
558
+ if paper_context:
559
+ user_msg += chr(10) + "SJSU papers: " + paper_context[:600]
560
+ resp = client.chat.completions.create(
561
+ model="llama-3.3-70b-versatile",
562
+ messages=[{"role":"system","content":system_msg},{"role":"user","content":user_msg}],
563
+ max_tokens=1500)
564
+ return resp.choices[0].message.content
565
+ except Exception as e:
566
+ return "Error generating report: " + str(e)
567
+
568
+ def generate_hypothesis(research_area, current_findings):
569
+ if not GROQ_KEY: return "Error: Add GROQ_API_KEY to Space Settings."
570
+ if not research_area: return "Please select a research area."
571
+ try:
572
+ client = Groq(api_key=GROQ_KEY)
573
+ paper_context, _ = search_papers(research_area, n=3)
574
+ system_msg = ("You are CardioLab AI research assistant for SJSU Biomedical Engineering. "
575
+ "Generate 3 specific testable research hypotheses. For each provide: "
576
+ "H0 null hypothesis, "
577
+ "H1 alternative hypothesis, "
578
+ "Scientific rationale, "
579
+ "Suggested experiment, "
580
+ "Expected outcome and measurable metrics. "
581
+ "Base on SJSU CardioLab research.")
582
+ user_msg = "Generate hypotheses for: " + research_area
583
+ if current_findings and current_findings.strip():
584
+ user_msg += chr(10) + "Current findings: " + current_findings
585
+ if paper_context:
586
+ user_msg += chr(10) + "SJSU papers: " + paper_context[:500]
587
+ resp = client.chat.completions.create(
588
+ model="llama-3.3-70b-versatile",
589
+ messages=[{"role":"system","content":system_msg},{"role":"user","content":user_msg}],
590
+ max_tokens=1000)
591
+ return resp.choices[0].message.content
592
+ except Exception as e:
593
+ return "Error: " + str(e)
594
+
595
+ # ── ANALYSIS TOOLS ─────────────────────────────────────────────────
596
+ def analyze_upad_photo(image):
597
+ if image is None: return None, "Upload a uPAD photo first."
598
+ try:
599
+ img = Image.fromarray(image) if not isinstance(image, Image.Image) else image
600
+ arr = np.array(img); h,w = arr.shape[:2]
601
+ y1,y2,x1,x2 = int(h*0.35),int(h*0.65),int(w*0.35),int(w*0.65)
602
+ zone = arr[y1:y2,x1:x2]
603
+ R,G,B = float(np.mean(zone[:,:,0])),float(np.mean(zone[:,:,1])),float(np.mean(zone[:,:,2]))
604
+ c = max(0,round(0.018*(R-B)-0.3,2))
605
+ if c<1.2: s,a="Normal","Monitor annually."
606
+ elif c<1.5: s,a="Borderline","Repeat in 3 months."
607
+ elif c<3.0: s,a="Stage 2 CKD","Consult nephrologist."
608
+ elif c<6.0: s,a="Stage 3-4 CKD","Immediate consultation."
609
+ else: s,a="Stage 5 CKD","Emergency care."
610
+ ri=img.copy()
611
+ import PIL.ImageDraw as D; D.Draw(ri).rectangle([x1,y1,x2,y2],outline=(0,255,0),width=3)
612
+ return ri,("uPAD ANALYSIS"+chr(10)+"R:"+str(round(R,1))+" G:"+str(round(G,1))+" B:"+str(round(B,1))+chr(10)+"Creatinine: "+str(c)+" mg/dL"+chr(10)+"Stage: "+s+chr(10)+"Action: "+a)
613
+ except Exception as e: return None,"Error: "+str(e)
614
+
615
+ def mk_chart(fn,title,bg,fg,gc,ac,pb):
616
+ fig2,ax=plt.subplots(figsize=(8,5)); fig2.patch.set_facecolor(bg); ax.set_facecolor(pb)
617
+ fn(ax); ax.set_title(title,color=fg,fontweight="bold",fontsize=13,pad=8)
618
+ ax.tick_params(colors=ac,labelsize=10); ax.grid(True,alpha=0.3,color=gc,linestyle="--")
619
+ for sp in ["top","right"]: ax.spines[sp].set_visible(False)
620
+ for sp in ["bottom","left"]: ax.spines[sp].set_color(gc)
621
+ plt.tight_layout(); buf=io.BytesIO(); plt.savefig(buf,format="png",facecolor=bg,bbox_inches="tight",dpi=130); buf.seek(0)
622
+ res=Image.open(buf).copy(); plt.close(); return res
623
+
624
+ def analyze_piv_csv(file,theme="White"):
625
+ if file is None: return None,None,None,None,"Upload PIV CSV first."
626
+ try:
627
+ df=pd.read_csv(file.name); cols=[c.lower().strip() for c in df.columns]; df.columns=cols
628
+ num_cols=df.select_dtypes(include=[np.number]).columns.tolist()
629
+ if not num_cols: return None,None,None,None,"No numeric columns."
630
+ bg="#fff" if theme=="White" else "#0a1628"; fg="#1a202c" if theme=="White" else "white"
631
+ gc="#e2e8f0" if theme=="White" else "#2d4a8a"; ac="#4a5568" if theme=="White" else "#a8b2d8"
632
+ pb="#f7fafc" if theme=="White" else "#132340"
633
+ x=np.arange(len(df))
634
+ vc=next((c for c in cols if any(k in c for k in ["vel","speed","v_mag"])),num_cols[0] if num_cols else None)
635
+ sc2=next((c for c in cols if any(k in c for k in ["shear","stress","tau","wss"])),num_cols[1] if len(num_cols)>1 else None)
636
+ tc=next((c for c in cols if "time" in c or "frame" in c),None); xv=df[tc] if tc else x
637
+ def pv(ax):
638
+ if vc:
639
+ ax.plot(xv,df[vc],color="#c1121f",linewidth=2.5,marker="o",markersize=5)
640
+ ax.fill_between(xv,df[vc],alpha=0.15,color="#c1121f")
641
+ ax.axhline(y=2.0,color="#f59e0b",linestyle="--",linewidth=2,label="Risk 2.0 m/s")
642
+ ax.set_ylabel("Velocity (m/s)",color=ac); ax.legend(fontsize=9,labelcolor=fg,facecolor=pb)
643
+ def ps(ax):
644
+ if sc2:
645
+ xp=xv.values if tc else x
646
+ ax.plot(xp,df[sc2],color="#0057a8",linewidth=2.5,marker="s",markersize=5)
647
+ ax.fill_between(xp,df[sc2],alpha=0.15,color="#0057a8")
648
+ ax.axhline(y=5,color="#f59e0b",linestyle="--",linewidth=2,label="Caution 5 Pa")
649
+ ax.axhline(y=10,color="#c1121f",linestyle="--",linewidth=2,label="Risk 10 Pa")
650
+ ax.set_ylabel("Shear (Pa)",color=ac); ax.legend(fontsize=9,labelcolor=fg,facecolor=pb)
651
+ def psc(ax):
652
+ if vc and sc2:
653
+ s3=ax.scatter(df[vc],df[sc2],c=x,cmap="RdYlGn_r",s=90,edgecolors=fg,linewidth=0.5,zorder=5)
654
+ cb=plt.colorbar(s3,ax=ax,label="Time"); cb.ax.yaxis.label.set_color(fg); cb.ax.tick_params(colors=ac)
655
+ ax.axvline(x=2.0,color="#f59e0b",linestyle="--",linewidth=2); ax.axhline(y=10,color="#c1121f",linestyle="--",linewidth=2)
656
+ ax.set_xlabel("Velocity (m/s)",color=ac); ax.set_ylabel("Shear (Pa)",color=ac)
657
+ def psum(ax):
658
+ ax.axis("off"); risk=[]
659
+ st="CLINICAL SUMMARY"+chr(10)+"="*20+chr(10)+chr(10)
660
+ for col in num_cols[:3]:
661
+ mn=round(df[col].mean(),3); mx=round(df[col].max(),3)
662
+ st+=col[:14]+":"+chr(10)+" Mean: "+str(mn)+chr(10)+" Max: "+str(mx)+chr(10)+chr(10)
663
+ if "vel" in col and mx>2.0: risk.append("HIGH VELOCITY")
664
+ if "shear" in col and mx>10: risk.append("HIGH SHEAR")
665
+ bc="#c1121f" if risk else "#2ecc71"
666
+ st+="="*20+chr(10)+("OVERALL: HIGH RISK" if risk else "OVERALL: LOW RISK")
667
+ ax.text(0.05,0.97,st,transform=ax.transAxes,color=fg,fontsize=10,va="top",fontfamily="monospace",
668
+ bbox=dict(boxstyle="round,pad=0.8",facecolor=pb,edgecolor=bc,linewidth=2.5))
669
+ i1=mk_chart(pv,"Velocity Profile",bg,fg,gc,ac,pb); i2=mk_chart(ps,"Wall Shear Stress",bg,fg,gc,ac,pb)
670
+ i3=mk_chart(psc,"Velocity vs Shear",bg,fg,gc,ac,pb); i4=mk_chart(psum,"Clinical Summary",bg,fg,gc,ac,pb)
671
+ ai=""
672
+ if GROQ_KEY:
673
+ try:
674
+ client=Groq(api_key=GROQ_KEY)
675
+ resp=client.chat.completions.create(model="llama-3.3-70b-versatile",
676
+ messages=[{"role":"system","content":"PIV expert SJSU CardioLab."},
677
+ {"role":"user","content":"PIV from 27mm SJM Regent:"+chr(10)+df.describe().to_string()[:500]}],max_tokens=250)
678
+ ai=chr(10)+"AI: "+resp.choices[0].message.content
679
+ except: pass
680
+ return i1,i2,i3,i4,"PIV: "+str(len(df))+" rows"+ai
681
+ except Exception as e: return None,None,None,None,"Error: "+str(e)
682
+
683
+ def analyze_tgt_csv(file,theme="White"):
684
+ if file is None: return None,None,None,None,"Upload TGT CSV first."
685
+ try:
686
+ df=pd.read_csv(file.name); cols=[c.lower().strip() for c in df.columns]; df.columns=cols
687
+ num_cols=df.select_dtypes(include=[np.number]).columns.tolist()
688
+ bg="#fff" if theme=="White" else "#0a1628"; fg="#1a202c" if theme=="White" else "white"
689
+ gc="#e2e8f0" if theme=="White" else "#2d4a8a"; ac="#4a5568" if theme=="White" else "#a8b2d8"
690
+ pb="#f7fafc" if theme=="White" else "#132340"
691
+ tc=next((c for c in cols if "time" in c or "min" in c),None)
692
+ tatc=next((c for c in cols if "tat" in c),num_cols[0] if num_cols else None)
693
+ pfc=next((c for c in cols if "pf" in c),num_cols[1] if len(num_cols)>1 else None)
694
+ hc=next((c for c in cols if "hemo" in c),num_cols[2] if len(num_cols)>2 else None)
695
+ plc=next((c for c in cols if "platelet" in c or "plt" in c),num_cols[3] if len(num_cols)>3 else None)
696
+ def mk2(dc,color,yl,lim,ll,title,bar=False):
697
+ def fn(ax):
698
+ if dc and dc in df.columns:
699
+ xp=df[tc].values if tc else range(len(df)); yp=df[dc].values
700
+ if bar:
701
+ bs=ax.bar(range(len(yp)),yp,color=color,alpha=0.85,edgecolor=bg,width=0.6)
702
+ for b,v in zip(bs,yp): ax.text(b.get_x()+b.get_width()/2,b.get_height()+0.5,str(round(v,1)),ha="center",va="bottom",color=fg,fontsize=10,fontweight="bold")
703
+ else:
704
+ ax.plot(xp,yp,color=color,linewidth=3,marker="o",markersize=8)
705
+ ax.fill_between(xp,yp,alpha=0.15,color=color)
706
+ for xi,yi in zip(xp,yp): ax.annotate(str(round(yi,1)),(xi,yi),textcoords="offset points",xytext=(0,10),ha="center",color=fg,fontsize=10,fontweight="bold")
707
+ ax.axhline(y=lim,color="#f59e0b",linestyle="--",linewidth=2.5,label=ll)
708
+ ax.legend(fontsize=10,labelcolor=fg,facecolor=pb); ax.set_ylabel(yl,color=ac)
709
+ mv=round(float(np.max(yp)),2)
710
+ ax.set_title(title+chr(10)+"Max: "+str(mv)+" - "+("HIGH" if mv>lim else "NORMAL"),color=fg,fontweight="bold",fontsize=12)
711
+ return mk_chart(fn,title,bg,fg,gc,ac,pb)
712
+ i1=mk2(tatc,"#c1121f","TAT (ng/mL)",8,"Normal: 8","TAT"); i2=mk2(pfc,"#0057a8","PF1.2",2.0,"Normal: 2.0","PF1.2")
713
+ i3=mk2(hc,"#2ecc71","Free Hgb (mg/L)",20,"Normal: 20","Free Hemoglobin",bar=True); i4=mk2(plc,"#e8a020","Platelets",150,"Normal>150","Platelets")
714
+ ai=""
715
+ if GROQ_KEY:
716
+ try:
717
+ client=Groq(api_key=GROQ_KEY)
718
+ resp=client.chat.completions.create(model="llama-3.3-70b-versatile",
719
+ messages=[{"role":"system","content":"Hematology expert. Thrombogenicity risk."},
720
+ {"role":"user","content":"TGT:"+chr(10)+df.describe().to_string()[:500]}],max_tokens=250)
721
+ ai=chr(10)+"AI: "+resp.choices[0].message.content
722
+ except: pass
723
+ return i1,i2,i3,i4,"TGT: "+str(len(df))+" rows"+ai
724
+ except Exception as e: return None,None,None,None,"Error: "+str(e)
725
+
726
+ def generate_image(prompt):
727
+ if not prompt.strip(): return None,"Enter description.","";
728
+ if not HF_TOKEN: return None,"Add HF_TOKEN to Space secrets.","";
729
+ try:
730
+ enhanced,desc=prompt,""
731
+ if GROQ_KEY:
732
+ try:
733
+ client=Groq(api_key=GROQ_KEY)
734
+ resp=client.chat.completions.create(model="llama-3.3-70b-versatile",
735
+ messages=[{"role":"system","content":"Format: DESCRIPTION: [2 sentences] PROMPT: [detailed image prompt]"},
736
+ {"role":"user","content":"Biomedical image: "+prompt}],max_tokens=200)
737
+ full=resp.choices[0].message.content
738
+ if "DESCRIPTION:" in full and "PROMPT:" in full:
739
+ desc=full.split("DESCRIPTION:")[1].split("PROMPT:")[0].strip()
740
+ enhanced=full.split("PROMPT:")[1].strip()
741
+ except: pass
742
+ headers={"Authorization":"Bearer "+HF_TOKEN,"Content-Type":"application/json"}
743
+ for url in ["https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-schnell",
744
+ "https://router.huggingface.co/hf-inference/models/stabilityai/stable-diffusion-xl-base-1.0"]:
745
+ try:
746
+ r=requests.post(url,headers=headers,json={"inputs":enhanced,"parameters":{"num_inference_steps":8}},timeout=60)
747
+ if r.status_code==200: return Image.open(io.BytesIO(r.content)),"Generated!",desc
748
+ except: continue
749
+ return None,"Models busy.",desc
750
+ except Exception as e: return None,"Error: "+str(e),""
751
+
752
+ def piv_manual(v,s,h):
753
+ vr="HIGH-stenosis" if float(v)>2.0 else "NORMAL"
754
+ sr="HIGH-thrombosis" if float(s)>10 else "ELEVATED" if float(s)>5 else "NORMAL"
755
+ return "Velocity: "+str(v)+" m/s - "+vr+chr(10)+"Shear: "+str(s)+" Pa - "+sr+chr(10)+"HR: "+str(h)+" bpm"
756
+
757
+ def tgt_manual(t,p,h,pl,tm):
758
+ risk=sum([float(t)>15,float(p)>2.0,float(h)>50,float(pl)<150])
759
+ return "TAT:"+str(t)+" PF1.2:"+str(p)+chr(10)+"Hemo:"+str(h)+" Plt:"+str(pl)+chr(10)+"RESULT: "+("HIGH RISK" if risk>=3 else "MODERATE" if risk>=2 else "LOW RISK")
760
+
761
+ # ── UI ─────────────────────────────────────────────────────────────
762
+ with gr.Blocks(title="CardioLab AI v39 - SJSU") as demo:
763
+ gr.HTML(HEADER)
764
+
765
+ papers_count = len(set(m["paper"] for m in METADATA)) if PAPERS_LOADED else 0
766
+ model_status = "Fine-tuned Model LOADED" if CARDIOLAB_MODEL_LOADED else "Fine-tuned model loading..."
767
+ rag_status = "RAG: " + str(len(CHUNKS)) + " chunks from " + str(papers_count) + " SJSU papers" if PAPERS_LOADED else "RAG: loading..."
768
+ gr.HTML("""<div style="
769
+ background: linear-gradient(135deg, rgba(26,115,64,0.9), rgba(21,87,49,0.9));
770
+ backdrop-filter: blur(20px);
771
+ border: 1px solid rgba(46,204,113,0.3);
772
+ border-radius: 12px;
773
+ margin: 8px 0;
774
+ padding: 10px 20px;
775
+ display: flex;
776
+ align-items: center;
777
+ justify-content: center;
778
+ gap: 20px;
779
+ box-shadow: 0 4px 20px rgba(46,204,113,0.15);
780
+ ">
781
+ <div style="display:flex;align-items:center;gap:8px;">
782
+ <div style="width:8px;height:8px;background:#2ecc71;border-radius:50%;box-shadow:0 0 8px #2ecc71;animation:pulse 2s infinite;"></div>
783
+ <span style="color:white;font-size:0.8em;font-weight:600;">RAG ACTIVE</span>
784
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">417 chunks Β· 16 SJSU papers</span>
785
+ </div>
786
+ <div style="width:1px;height:20px;background:rgba(255,255,255,0.2);"></div>
787
+ <div style="display:flex;align-items:center;gap:8px;">
788
+ <div style="width:8px;height:8px;background:#e8a020;border-radius:50%;box-shadow:0 0 8px #e8a020;animation:pulse 2s 0.5s infinite;"></div>
789
+ <span style="color:white;font-size:0.8em;font-weight:600;">FINE-TUNED MODEL</span>
790
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">CardioLab SJSU</span>
791
+ </div>
792
+ <div style="width:1px;height:20px;background:rgba(255,255,255,0.2);"></div>
793
+ <div style="display:flex;align-items:center;gap:8px;">
794
+ <div style="width:8px;height:8px;background:#0057a8;border-radius:50%;box-shadow:0 0 8px #0057a8;animation:pulse 2s 1s infinite;"></div>
795
+ <span style="color:white;font-size:0.8em;font-weight:600;">5 AI MODELS</span>
796
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">Select in dropdown</span>
797
+ </div>
798
+ <style>@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(1.3)}}</style>
799
+ </div>""")
800
+
801
+ with gr.Tabs():
802
+
803
+ with gr.Tab("Chat"):
804
+ with gr.Row():
805
+ with gr.Column(scale=1, min_width=200):
806
+ gr.HTML("<div style="
807
+ background: linear-gradient(180de<div style='color:#e8a020;font-weight:700;font-size:0.85em;'>SJSU CARDIOLAB</div><div style='color:#9ca3af;font-size:0.7em;'>Conversations</div></div>")
808
+ new_chat_btn = gr.Button("New Chat", variant="secondary")
809
+ session_dropdown = gr.Dropdown(choices=get_session_list(), label="Saved Sessions", interactive=True)
810
+ load_btn = gr.Button("Load Session", variant="primary")
811
+ session_name_box = gr.Textbox(placeholder="Session name...", label="", lines=1, container=False)
812
+ with gr.Row():
813
+ save_btn = gr.Button("Save", variant="primary", scale=2)
814
+ delete_btn = gr.Button("Del", variant="secondary", scale=1)
815
+ session_status = gr.Textbox(label="", lines=1, interactive=False, container=False)
816
+ with gr.Column(scale=4):
817
+ chatbot = gr.Chatbot(label="", height=460, show_label=False, container=False)
818
+ with gr.Row():
819
+ msg_box = gr.Textbox(placeholder="Ask anything β€” AI searches 16 SJSU papers + PubMed...", label="", lines=2, scale=4, container=False)
820
+ with gr.Column(scale=1, min_width=160):
821
+ chat_model_dd = gr.Dropdown(choices=list(CHAT_MODELS.keys()), value="Llama 3.3 70B (Best)", label="AI Model")
822
+ send_btn = gr.Button("Send", variant="primary")
823
+ clear_btn = gr.Button("Clear", variant="secondary")
824
+ send_btn.click(research_chat, inputs=[msg_box, chatbot, chat_model_dd], outputs=[msg_box, chatbot])
825
+ msg_box.submit(research_chat, inputs=[msg_box, chatbot, chat_model_dd], outputs=[msg_box, chatbot])
826
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg_box])
827
+ new_chat_btn.click(new_chat, outputs=[chatbot, msg_box, session_status])
828
+ save_btn.click(save_session, inputs=[chatbot, session_name_box], outputs=[session_status, session_dropdown])
829
+ load_btn.click(load_session, inputs=session_dropdown, outputs=[chatbot, session_status])
830
+ delete_btn.click(delete_session, inputs=session_dropdown, outputs=[session_status, session_dropdown])
831
+
832
+ with gr.Tab("Voice"):
833
+ voice_chatbot = gr.Chatbot(label="", height=360, show_label=False)
834
+ audio_input = gr.Audio(sources=["microphone"], type="filepath", label="Record Question")
835
+ with gr.Row():
836
+ voice_btn = gr.Button("Ask by Voice", variant="primary")
837
+ voice_clear = gr.Button("Clear", variant="secondary")
838
+ voice_btn.click(voice_chat, inputs=[audio_input, voice_chatbot], outputs=voice_chatbot)
839
+ voice_clear.click(lambda: [], outputs=voice_chatbot)
840
+
841
+ with gr.Tab("Papers"):
842
+ gr.Markdown("### Search PubMed + Semantic Scholar + SJSU ScholarWorks")
843
+ with gr.Row():
844
+ search_input = gr.Textbox(placeholder="e.g. bileaflet mechanical heart valve thrombogenicity hemodynamics", label="Research Topic", scale=3)
845
+ search_model_dd = gr.Dropdown(choices=list(CHAT_MODELS.keys()), value="Llama 3.3 70B (Best)", label="AI Model", scale=1)
846
+ search_btn = gr.Button("Search", variant="primary", scale=1)
847
+ search_output = gr.Textbox(label="Results", lines=22)
848
+ search_btn.click(quick_search, inputs=[search_input, search_model_dd], outputs=search_output)
849
+ search_input.submit(quick_search, inputs=[search_input, search_model_dd], outputs=search_output)
850
+
851
+ with gr.Tab("PIV CSV"):
852
+ with gr.Row():
853
+ piv_file = gr.File(label="Upload PIV CSV", file_types=[".csv"], scale=3)
854
+ piv_theme = gr.Radio(["White","Dark"], value="White", label="Theme", scale=1)
855
+ piv_btn = gr.Button("Analyze PIV Data", variant="primary")
856
+ piv_result = gr.Textbox(label="AI Analysis", lines=4)
857
+ with gr.Row():
858
+ piv_c1=gr.Image(label="Velocity",type="pil"); piv_c2=gr.Image(label="Shear Stress",type="pil")
859
+ with gr.Row():
860
+ piv_c3=gr.Image(label="Vel vs Shear",type="pil"); piv_c4=gr.Image(label="Clinical Summary",type="pil")
861
+ piv_btn.click(analyze_piv_csv, inputs=[piv_file,piv_theme], outputs=[piv_c1,piv_c2,piv_c3,piv_c4,piv_result])
862
+
863
+ with gr.Tab("TGT CSV"):
864
+ with gr.Row():
865
+ tgt_file = gr.File(label="Upload TGT CSV", file_types=[".csv"], scale=3)
866
+ tgt_theme = gr.Radio(["White","Dark"], value="White", label="Theme", scale=1)
867
+ tgt_btn = gr.Button("Analyze TGT Data", variant="primary")
868
+ tgt_result = gr.Textbox(label="AI Assessment", lines=4)
869
+ with gr.Row():
870
+ tgt_c1=gr.Image(label="TAT",type="pil"); tgt_c2=gr.Image(label="PF1.2",type="pil")
871
+ with gr.Row():
872
+ tgt_c3=gr.Image(label="Hemoglobin",type="pil"); tgt_c4=gr.Image(label="Platelets",type="pil")
873
+ tgt_btn.click(analyze_tgt_csv, inputs=[tgt_file,tgt_theme], outputs=[tgt_c1,tgt_c2,tgt_c3,tgt_c4,tgt_result])
874
+
875
+ with gr.Tab("uPAD"):
876
+ with gr.Row():
877
+ with gr.Column():
878
+ photo_input = gr.Image(label="Upload uPAD Photo", type="numpy", height=260)
879
+ analyze_btn = gr.Button("Analyze uPAD", variant="primary")
880
+ with gr.Column():
881
+ photo_img = gr.Image(label="Detection Zone", type="pil", height=260)
882
+ photo_text = gr.Textbox(label="CKD Result", lines=8)
883
+ analyze_btn.click(analyze_upad_photo, inputs=photo_input, outputs=[photo_img, photo_text])
884
+ with gr.Row():
885
+ r=gr.Number(label="R",value=210); g=gr.Number(label="G",value=140); b=gr.Number(label="B",value=80)
886
+ out3=gr.Textbox(label="Result",lines=3)
887
+ gr.Button("Analyze RGB",variant="secondary").click(
888
+ lambda r,g,b:"Creatinine: "+str(max(0,round(0.02*(r-b)-0.5,2)))+" mg/dL"+chr(10)+("Normal" if max(0,round(0.02*(r-b)-0.5,2))<1.2 else "Borderline" if max(0,round(0.02*(r-b)-0.5,2))<1.5 else "CKD"),
889
+ inputs=[r,g,b],outputs=out3)
890
+
891
+ with gr.Tab("AI Image"):
892
+ with gr.Row():
893
+ img_prompt = gr.Textbox(placeholder="e.g. 27mm bileaflet mechanical heart valve cross section", label="Describe image", lines=2, scale=4)
894
+ with gr.Column(scale=1):
895
+ img_btn = gr.Button("Generate", variant="primary")
896
+ img_status = gr.Textbox(label="Status", lines=1)
897
+ img_desc = gr.Textbox(label="AI Description", lines=2, interactive=False)
898
+ img_output = gr.Image(label="Generated Image", type="pil", height=400)
899
+ img_btn.click(generate_image, inputs=img_prompt, outputs=[img_output,img_status,img_desc])
900
+
901
+ with gr.Tab("PIV Manual"):
902
+ with gr.Row():
903
+ with gr.Column():
904
+ v=gr.Number(label="Max Velocity m/s",value=1.8); s=gr.Number(label="Wall Shear Pa",value=6.5)
905
+ h=gr.Number(label="Heart Rate bpm",value=72); piv_out=gr.Textbox(label="Result",lines=4)
906
+ gr.Button("Analyze PIV",variant="primary").click(piv_manual,inputs=[v,s,h],outputs=piv_out)
907
+
908
+ with gr.Tab("TGT Manual"):
909
+ with gr.Row():
910
+ with gr.Column():
911
+ t1=gr.Number(label="TAT ng/mL",value=18); t2=gr.Number(label="PF1.2",value=2.5)
912
+ t3=gr.Number(label="Hemoglobin mg/L",value=60); t4=gr.Number(label="Platelets",value=140)
913
+ t5=gr.Number(label="Time min",value=40); out2=gr.Textbox(label="Result",lines=6)
914
+ gr.Button("Analyze TGT",variant="primary").click(tgt_manual,inputs=[t1,t2,t3,t4,t5],outputs=out2)
915
+
916
+ with gr.Tab("Protocol Generator"):
917
+ gr.Markdown("### Generate complete lab protocols from SJSU CardioLab knowledge")
918
+ with gr.Row():
919
+ with gr.Column(scale=1):
920
+ proto_type = gr.Dropdown(
921
+ choices=["MCL Setup","PIV Experiment","Thrombogenicity Tester Blood Clotting Test",
922
+ "uPAD Fabrication","uPAD Creatinine Test",
923
+ "FSI COMSOL Simulation","Valve Testing"],
924
+ value="Thrombogenicity Tester Blood Clotting Test", label="Experiment Type")
925
+ proto_params = gr.Textbox(placeholder="e.g. 27mm SJM valve 70bpm porcine blood",
926
+ label="Specific Parameters", lines=2)
927
+ proto_btn = gr.Button("Generate Protocol", variant="primary")
928
+ with gr.Column(scale=2):
929
+ proto_output = gr.Textbox(label="Generated Protocol", lines=28)
930
+ proto_btn.click(generate_protocol, inputs=[proto_type, proto_params], outputs=proto_output)
931
+
932
+ with gr.Tab("Report Writer"):
933
+ gr.Markdown("### Generate professional research reports from your data")
934
+ with gr.Row():
935
+ with gr.Column(scale=1):
936
+ report_exp = gr.Dropdown(
937
+ choices=["MCL PIV Flow Analysis","TGT Thrombogenicity Study",
938
+ "uPAD CKD Detection","FSI Simulation Study",
939
+ "Heart Valve Comparison"],
940
+ value="TGT Thrombogenicity Study", label="Study Type")
941
+ report_desc = gr.Textbox(
942
+ placeholder="e.g. TGT with 27mm SJM bileaflet at 70bpm 150mL porcine blood",
943
+ label="Experiment Description", lines=3)
944
+ report_results = gr.Textbox(
945
+ placeholder="e.g. TAT=12.3 ng/mL PF1.2=2.8 Hemo=45 Plt=142",
946
+ label="Your Results", lines=2)
947
+ report_btn = gr.Button("Generate Report", variant="primary")
948
+ with gr.Column(scale=2):
949
+ report_output = gr.Textbox(label="Generated Report", lines=28)
950
+ report_btn.click(generate_report, inputs=[report_desc, report_exp, report_results], outputs=report_output)
951
+
952
+ with gr.Tab("Hypothesis Generator"):
953
+ gr.Markdown("### Generate testable research hypotheses for CardioLab projects")
954
+ with gr.Row():
955
+ with gr.Column(scale=1):
956
+ hyp_area = gr.Dropdown(
957
+ choices=["Bileaflet MHV Thrombogenicity",
958
+ "uPAD CKD Detection Accuracy",
959
+ "PIV Flow Characterization",
960
+ "FSI Simulation Validation",
961
+ "Valve Design Comparison"],
962
+ value="Bileaflet MHV Thrombogenicity", label="Research Area")
963
+ hyp_findings = gr.Textbox(
964
+ placeholder="Current observations from your experiments",
965
+ label="Current Findings", lines=3)
966
+ hyp_btn = gr.Button("Generate Hypotheses", variant="primary")
967
+ with gr.Column(scale=2):
968
+ hyp_output = gr.Textbox(label="Research Hypotheses", lines=25)
969
+ hyp_btn.click(generate_hypothesis, inputs=[hyp_area, hyp_findings], outputs=hyp_output)
970
+
971
+ gr.HTML("""<div style="
972
+ text-align:center;
973
+ padding: 16px;
974
+ margin-top: 12px;
975
+ border-top: 1px solid rgba(255,255,255,0.06);
976
+ background: rgba(255,255,255,0.02);
977
+ border-radius: 0 0 16px 16px;
978
+ backdrop-filter: blur(20px);
979
+ ">
980
+ <div style="display:flex;align-items:center;justify-content:center;gap:20px;flex-wrap:wrap;">
981
+ <span style="color:rgba(255,255,255,0.3);font-size:0.72em;">CardioLab AI v39</span>
982
+ <span style="color:rgba(255,255,255,0.1);">|</span>
983
+ <span style="color:rgba(255,255,255,0.3);font-size:0.72em;">SJSU Biomedical Engineering</span>
984
+ <span style="color:rgba(255,255,255,0.1);">|</span>
985
+ <a href="https://github.com/snap-stanford/Biomni" style="color:rgba(193,18,31,0.7);font-size:0.72em;text-decoration:none;">Inspired by Biomni Stanford</a>
986
+ <span style="color:rgba(255,255,255,0.1);">|</span>
987
+ <a href="https://github.com/pranatechsol/Cardio-Lab-Ai" style="color:rgba(0,87,168,0.7);font-size:0.72em;text-decoration:none;">GitHub</a>
988
+ <span style="color:rgba(255,255,255,0.1);">|</span>
989
+ <span style="color:rgba(46,204,113,0.6);font-size:0.72em;font-weight:600;">$0 Cost Forever</span>
990
+ </div>
991
+ </div>
992
+ <span style="color:#9ca3af;font-size:0.75em;">CardioLab AI v39 | SJSU Biomedical Engineering | RAG + Fine-tuned + Phase D | Inspired by <a href="https://github.com/snap-stanford/Biomni" style="color:#c1121f;">Biomni Stanford</a> | Apache 2.0 | $0 Cost</span></div>""")
993
+
994
+ demo.launch(css=CSS)CSS = '''
995
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&family=Space+Grotesk:wght@400;500;700&family=JetBrains+Mono:wght@400;500&display=swap');
996
+
997
+ /* ── ANIMATED BACKGROUND ─────────────────────────── */
998
+ body {
999
+ background: #050a14 !important;
1000
+ font-family: "Inter", sans-serif !important;
1001
+ min-height: 100vh;
1002
+ overflow-x: hidden;
1003
+ }
1004
+
1005
+ body::before {
1006
+ content: "";
1007
+ position: fixed;
1008
+ top: 0; left: 0;
1009
+ width: 100%; height: 100%;
1010
+ background:
1011
+ radial-gradient(ellipse 80% 60% at 20% 10%, rgba(193,18,31,0.12) 0%, transparent 60%),
1012
+ radial-gradient(ellipse 60% 80% at 80% 90%, rgba(0,87,168,0.10) 0%, transparent 60%),
1013
+ radial-gradient(ellipse 40% 40% at 50% 50%, rgba(232,160,32,0.04) 0%, transparent 70%);
1014
+ pointer-events: none;
1015
+ z-index: 0;
1016
+ animation: bgShift 12s ease-in-out infinite alternate;
1017
+ }
1018
+
1019
+ @keyframes bgShift {
1020
+ 0% { opacity: 1; transform: scale(1); }
1021
+ 100% { opacity: 0.7; transform: scale(1.05); }
1022
+ }
1023
+
1024
+ /* ── GRADIO CONTAINER ────────────────────────────── */
1025
+ .gradio-container {
1026
+ background: transparent !important;
1027
+ max-width: 1600px !important;
1028
+ margin: 0 auto !important;
1029
+ position: relative;
1030
+ z-index: 1;
1031
+ }
1032
+
1033
+ /* ── TABS β€” PILL STYLE ───────────────────────────── */
1034
+ .tab-nav {
1035
+ background: rgba(255,255,255,0.03) !important;
1036
+ backdrop-filter: blur(20px) !important;
1037
+ border: 1px solid rgba(255,255,255,0.08) !important;
1038
+ border-radius: 16px !important;
1039
+ padding: 6px !important;
1040
+ margin: 10px 0 !important;
1041
+ display: flex !important;
1042
+ flex-wrap: wrap !important;
1043
+ gap: 4px !important;
1044
+ }
1045
+
1046
+ .tab-nav button {
1047
+ background: transparent !important;
1048
+ color: rgba(255,255,255,0.5) !important;
1049
+ border: none !important;
1050
+ border-radius: 10px !important;
1051
+ padding: 8px 14px !important;
1052
+ font-weight: 500 !important;
1053
+ font-size: 0.78em !important;
1054
+ white-space: nowrap !important;
1055
+ transition: all 0.25s cubic-bezier(0.4,0,0.2,1) !important;
1056
+ letter-spacing: 0.02em !important;
1057
+ }
1058
+
1059
+ .tab-nav button:hover {
1060
+ background: rgba(255,255,255,0.08) !important;
1061
+ color: rgba(255,255,255,0.9) !important;
1062
+ transform: translateY(-1px) !important;
1063
+ }
1064
+
1065
+ .tab-nav button.selected {
1066
+ background: linear-gradient(135deg, #c1121f, #e63946) !important;
1067
+ color: white !important;
1068
+ font-weight: 700 !important;
1069
+ box-shadow: 0 4px 20px rgba(193,18,31,0.4), 0 0 0 1px rgba(193,18,31,0.3) !important;
1070
+ transform: translateY(-1px) !important;
1071
+ }
1072
+
1073
+ /* ── CHATBOT MESSAGES ─────────────��──────────────── */
1074
+ .message-wrap {
1075
+ padding: 6px 0 !important;
1076
+ }
1077
+
1078
+ .message.user {
1079
+ background: linear-gradient(135deg, rgba(193,18,31,0.2), rgba(230,57,70,0.15)) !important;
1080
+ border: 1px solid rgba(193,18,31,0.3) !important;
1081
+ color: rgba(255,255,255,0.95) !important;
1082
+ border-radius: 18px 18px 4px 18px !important;
1083
+ padding: 14px 18px !important;
1084
+ backdrop-filter: blur(10px) !important;
1085
+ animation: msgIn 0.3s cubic-bezier(0.34,1.56,0.64,1) !important;
1086
+ }
1087
+
1088
+ .message.bot {
1089
+ background: rgba(255,255,255,0.05) !important;
1090
+ border: 1px solid rgba(255,255,255,0.1) !important;
1091
+ color: rgba(255,255,255,0.9) !important;
1092
+ border-radius: 18px 18px 18px 4px !important;
1093
+ padding: 14px 18px !important;
1094
+ backdrop-filter: blur(10px) !important;
1095
+ border-left: 3px solid #c1121f !important;
1096
+ animation: msgIn 0.3s cubic-bezier(0.34,1.56,0.64,1) !important;
1097
+ }
1098
+
1099
+ @keyframes msgIn {
1100
+ from { opacity: 0; transform: translateY(10px) scale(0.97); }
1101
+ to { opacity: 1; transform: translateY(0) scale(1); }
1102
+ }
1103
+
1104
+ /* ── CHATBOT CONTAINER ───────────────────────────── */
1105
+ .chatbot {
1106
+ background: rgba(255,255,255,0.02) !important;
1107
+ border: 1px solid rgba(255,255,255,0.08) !important;
1108
+ border-radius: 20px !important;
1109
+ backdrop-filter: blur(20px) !important;
1110
+ }
1111
+
1112
+ /* ── INPUT FIELDS ────────────────────────────────── */
1113
+ textarea, input[type=text], input[type=number] {
1114
+ background: rgba(255,255,255,0.06) !important;
1115
+ color: rgba(255,255,255,0.9) !important;
1116
+ border: 1px solid rgba(255,255,255,0.12) !important;
1117
+ border-radius: 14px !important;
1118
+ font-family: "Inter", sans-serif !important;
1119
+ font-size: 0.9em !important;
1120
+ transition: all 0.25s ease !important;
1121
+ backdrop-filter: blur(10px) !important;
1122
+ }
1123
+
1124
+ textarea:focus, input:focus {
1125
+ border-color: rgba(193,18,31,0.6) !important;
1126
+ box-shadow: 0 0 0 3px rgba(193,18,31,0.15), 0 0 30px rgba(193,18,31,0.1) !important;
1127
+ outline: none !important;
1128
+ background: rgba(255,255,255,0.08) !important;
1129
+ }
1130
+
1131
+ textarea::placeholder { color: rgba(255,255,255,0.3) !important; }
1132
+
1133
+ /* ── BUTTONS ─────────────────────────────────────── */
1134
+ button.primary {
1135
+ background: linear-gradient(135deg, #c1121f 0%, #e63946 100%) !important;
1136
+ color: white !important;
1137
+ border: none !important;
1138
+ border-radius: 12px !important;
1139
+ font-weight: 700 !important;
1140
+ font-size: 0.88em !important;
1141
+ letter-spacing: 0.03em !important;
1142
+ box-shadow: 0 4px 20px rgba(193,18,31,0.35) !important;
1143
+ transition: all 0.2s cubic-bezier(0.4,0,0.2,1) !important;
1144
+ position: relative !important;
1145
+ overflow: hidden !important;
1146
+ }
1147
+
1148
+ button.primary::after {
1149
+ content: "";
1150
+ position: absolute;
1151
+ top: 0; left: -100%;
1152
+ width: 100%; height: 100%;
1153
+ background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
1154
+ transition: left 0.5s ease;
1155
+ }
1156
+
1157
+ button.primary:hover::after { left: 100%; }
1158
+
1159
+ button.primary:hover {
1160
+ transform: translateY(-2px) !important;
1161
+ box-shadow: 0 8px 30px rgba(193,18,31,0.5) !important;
1162
+ }
1163
+
1164
+ button.primary:active { transform: translateY(0) !important; }
1165
+
1166
+ button.secondary {
1167
+ background: rgba(255,255,255,0.07) !important;
1168
+ color: rgba(255,255,255,0.7) !important;
1169
+ border: 1px solid rgba(255,255,255,0.15) !important;
1170
+ border-radius: 12px !important;
1171
+ font-weight: 500 !important;
1172
+ transition: all 0.2s ease !important;
1173
+ backdrop-filter: blur(10px) !important;
1174
+ }
1175
+
1176
+ button.secondary:hover {
1177
+ background: rgba(255,255,255,0.12) !important;
1178
+ color: white !important;
1179
+ transform: translateY(-1px) !important;
1180
+ }
1181
+
1182
+ /* ── LABELS ──────────────────────────────────────── */
1183
+ label span {
1184
+ color: rgba(255,255,255,0.55) !important;
1185
+ font-weight: 500 !important;
1186
+ font-size: 0.78em !important;
1187
+ letter-spacing: 0.06em !important;
1188
+ text-transform: uppercase !important;
1189
+ }
1190
+
1191
+ /* ── DROPDOWNS ───────────────────────────────────── */
1192
+ .wrap-inner, select, .multiselect {
1193
+ background: rgba(255,255,255,0.06) !important;
1194
+ border: 1px solid rgba(255,255,255,0.12) !important;
1195
+ border-radius: 12px !important;
1196
+ color: rgba(255,255,255,0.85) !important;
1197
+ }
1198
+
1199
+ /* ── GLASSMORPHISM PANELS ────────────────────────── */
1200
+ .block, .panel {
1201
+ background: rgba(255,255,255,0.03) !important;
1202
+ border: 1px solid rgba(255,255,255,0.07) !important;
1203
+ border-radius: 20px !important;
1204
+ backdrop-filter: blur(20px) !important;
1205
+ }
1206
+
1207
+ /* ── MARKDOWN TEXT ────────────────────────��──────── */
1208
+ .prose, .md {
1209
+ color: rgba(255,255,255,0.8) !important;
1210
+ }
1211
+
1212
+ /* ── FILE UPLOAD ─────────────────────────────────── */
1213
+ .upload-container, .file-preview {
1214
+ background: rgba(255,255,255,0.04) !important;
1215
+ border: 2px dashed rgba(255,255,255,0.15) !important;
1216
+ border-radius: 16px !important;
1217
+ transition: all 0.25s ease !important;
1218
+ }
1219
+
1220
+ .upload-container:hover {
1221
+ border-color: rgba(193,18,31,0.5) !important;
1222
+ background: rgba(193,18,31,0.05) !important;
1223
+ }
1224
+
1225
+ /* ── SIDEBAR ─────────────────────────────────────── */
1226
+ .sidebar-card {
1227
+ background: rgba(255,255,255,0.04);
1228
+ border: 1px solid rgba(255,255,255,0.08);
1229
+ border-radius: 16px;
1230
+ padding: 16px;
1231
+ margin-bottom: 8px;
1232
+ backdrop-filter: blur(20px);
1233
+ }
1234
+
1235
+ /* ── SCROLLBAR ───────────────────────────────────── */
1236
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
1237
+ ::-webkit-scrollbar-track { background: transparent; }
1238
+ ::-webkit-scrollbar-thumb {
1239
+ background: rgba(255,255,255,0.15);
1240
+ border-radius: 10px;
1241
+ }
1242
+ ::-webkit-scrollbar-thumb:hover { background: rgba(193,18,31,0.5); }
1243
+
1244
+ /* ── IMAGES ──────────────────────────────────────── */
1245
+ img {
1246
+ border-radius: 14px !important;
1247
+ border: 1px solid rgba(255,255,255,0.08) !important;
1248
+ }
1249
+
1250
+ /* ── NUMBER INPUTS ───────────────────────────────── */
1251
+ input[type=number] {
1252
+ background: rgba(255,255,255,0.06) !important;
1253
+ color: rgba(255,255,255,0.9) !important;
1254
+ border: 1px solid rgba(255,255,255,0.12) !important;
1255
+ border-radius: 12px !important;
1256
+ }
1257
+
1258
+ /* ── RADIO BUTTONS ───────────────────────────────── */
1259
+ .wrap {
1260
+ color: rgba(255,255,255,0.8) !important;
1261
+ }
1262
+
1263
+ /* ── ANIMATIONS ──────────────────────────────────── */
1264
+ @keyframes pulse {
1265
+ 0%, 100% { opacity: 1; }
1266
+ 50% { opacity: 0.5; }
1267
+ }
1268
+
1269
+ @keyframes fadeSlideUp {
1270
+ from { opacity: 0; transform: translateY(20px); }
1271
+ to { opacity: 1; transform: translateY(0); }
1272
+ }
1273
+
1274
+ @keyframes ecgLine {
1275
+ 0% { stroke-dashoffset: 1000; }
1276
+ 100% { stroke-dashoffset: 0; }
1277
+ }
1278
+
1279
+ @keyframes heartbeat {
1280
+ 0%, 100% { transform: scale(1); }
1281
+ 14% { transform: scale(1.15); }
1282
+ 28% { transform: scale(1); }
1283
+ 42% { transform: scale(1.1); }
1284
+ 56% { transform: scale(1); }
1285
+ }
1286
+
1287
+ .gradio-container > * {
1288
+ animation: fadeSlideUp 0.5s ease forwards;
1289
+ }
1290
+ '''port gradio as gr
1291
+ import os, requests, io, json
1292
+ import numpy as np
1293
+ import pandas as pd
1294
+ import matplotlib
1295
+ matplotlib.use("Agg")
1296
+ import matplotlib.pyplot as plt
1297
+ from groq import Groq
1298
+ from PIL import Image
1299
+ from datetime import datetime
1300
+ from huggingface_hub import HfApi, hf_hub_download
1301
+
1302
+ GROQ_KEY = os.environ.get("GROQ_API_KEY", "")
1303
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
1304
+ HISTORY_REPO = "Saicharan21/cardiolab-chat-history"
1305
+ PAPERS_DB_REPO = "Saicharan21/cardiolab-papers-db"
1306
+ CARDIOLAB_MODEL = "Saicharan21/CardioLab-AI-Model"
1307
+
1308
+ CHAT_MODELS = {
1309
+ "CardioLab Fine-tuned (SJSU)": "cardiolab",
1310
+ "Llama 3.3 70B (Best)": "llama-3.3-70b-versatile",
1311
+ "Llama 3.1 8B (Fast)": "llama-3.1-8b-instant",
1312
+ "Llama 4 Scout (New)": "meta-llama/llama-4-scout-17b-16e-instruct",
1313
+ "Llama 4 Maverick": "meta-llama/llama-4-maverick-17b-128e-instruct",
1314
+ }
1315
+
1316
+ KNOWHOW = ("MCL: Sylgard 184 PDMS 10:1 ratio 48hr cure green laser PIV 70bpm 5L/min cardiac output 80-120mmHg. "
1317
+ "TGT: Arduino Uno Stepper Motor 150mL blood sampled at 0 20 40 60 minutes. "
1318
+ "NORMAL RANGES: TAT below 8 ng/mL. PF1.2 below 2.0 nmol/L. Free hemoglobin below 20 mg/L. Platelets above 150 thousand per uL. "
1319
+ "HIGH RISK: TAT above 15. PF1.2 above 3.0. Hemoglobin above 50. Platelets below 100. "
1320
+ "uPAD: Jaffe reaction creatinine picric acid orange-red. Normal creatinine 0.6-1.2 mg/dL. Borderline 1.2-1.5. CKD above 1.5. "
1321
+ "Stage2 1.5-3.0. Stage3-4 3.0-6.0. Stage5 above 6.0. "
1322
+ "MHV: 27mm SJM Regent bileaflet also trileaflet monoleaflet pediatric. "
1323
+ "PIV: green laser 532nm time-resolved. Normal velocity 0.5-2.0 m/s. Normal shear below 5 Pa. Risk above 10 Pa. "
1324
+ "Equipment: Heska Element HT5 hematology analyzer time-resolved PIV Tygon tubing Arduino Uno stepper motor.")
1325
+
1326
+ CSS = """
1327
+ body, .gradio-container { background: #f7f7f8 !important; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif !important; }
1328
+ .tab-nav { background: #ffffff !important; border-bottom: 1px solid #e5e7eb !important; padding: 0 16px !important; display: flex !important; flex-wrap: wrap !important; }
1329
+ .tab-nav button { background: transparent !important; color: #6b7280 !important; border: none !important; border-bottom: 2px solid transparent !important; padding: 10px 12px !important; font-weight: 500 !important; font-size: 0.8em !important; white-space: nowrap !important; border-radius: 0 !important; }
1330
+ .tab-nav button:hover { color: #111827 !important; background: #f9fafb !important; }
1331
+ .tab-nav button.selected { color: #c1121f !important; border-bottom: 2px solid #c1121f !important; font-weight: 700 !important; background: transparent !important; }
1332
+ .message.user { background: #f3f4f6 !important; color: #1a202c !important; border-radius: 12px !important; }
1333
+ .message.bot { background: #ffffff !important; color: #1a202c !important; border-left: 3px solid #c1121f !important; }
1334
+ textarea { background: #ffffff !important; color: #1a202c !important; border: 1px solid #d1d5db !important; border-radius: 10px !important; }
1335
+ button.primary { background: #c1121f !important; color: white !important; border: none !important; border-radius: 8px !important; font-weight: 600 !important; }
1336
+ button.secondary { background: #f3f4f6 !important; color: #374151 !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; }
1337
+ input[type=number] { background: #f9fafb !important; color: #1a202c !important; border: 1px solid #d1d5db !important; border-radius: 8px !important; }
1338
+ """
1339
+
1340
  HEADER = """<div style="background:linear-gradient(135deg,#0a0f2e 0%,#1a0a0a 100%);padding:0;border-bottom:3px solid #c1121f;overflow:hidden;">
1341
  <svg style="position:absolute;opacity:0.07;width:100%;height:100%;" viewBox="0 0 1200 120" preserveAspectRatio="none">
1342
  <polyline points="0,60 100,60 130,20 150,100 170,10 200,90 220,60 400,60 430,20 450,100 470,10 500,90 520,60 700,60 730,20 750,100 770,10 800,90 820,60 1000,60 1030,20 1050,100 1070,10 1100,90 1120,60 1200,60" fill="none" stroke="#c1121f" stroke-width="3"/>
 
1937
  return "TAT:"+str(t)+" PF1.2:"+str(p)+chr(10)+"Hemo:"+str(h)+" Plt:"+str(pl)+chr(10)+"RESULT: "+("HIGH RISK" if risk>=3 else "MODERATE" if risk>=2 else "LOW RISK")
1938
 
1939
  # ── UI ─────────────────────────────────────────────────────────────
1940
+ with gr.Blocks(title="CardioLab AI v39 - SJSU") as demo:
1941
  gr.HTML(HEADER)
1942
 
1943
  papers_count = len(set(m["paper"] for m in METADATA)) if PAPERS_LOADED else 0
1944
  model_status = "Fine-tuned Model LOADED" if CARDIOLAB_MODEL_LOADED else "Fine-tuned model loading..."
1945
  rag_status = "RAG: " + str(len(CHUNKS)) + " chunks from " + str(papers_count) + " SJSU papers" if PAPERS_LOADED else "RAG: loading..."
1946
+ gr.HTML("""<div style="
1947
+ background: linear-gradient(135deg, rgba(26,115,64,0.9), rgba(21,87,49,0.9));
1948
+ backdrop-filter: blur(20px);
1949
+ border: 1px solid rgba(46,204,113,0.3);
1950
+ border-radius: 12px;
1951
+ margin: 8px 0;
1952
+ padding: 10px 20px;
1953
+ display: flex;
1954
+ align-items: center;
1955
+ justify-content: center;
1956
+ gap: 20px;
1957
+ box-shadow: 0 4px 20px rgba(46,204,113,0.15);
1958
+ ">
1959
+ <div style="display:flex;align-items:center;gap:8px;">
1960
+ <div style="width:8px;height:8px;background:#2ecc71;border-radius:50%;box-shadow:0 0 8px #2ecc71;animation:pulse 2s infinite;"></div>
1961
+ <span style="color:white;font-size:0.8em;font-weight:600;">RAG ACTIVE</span>
1962
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">417 chunks Β· 16 SJSU papers</span>
1963
+ </div>
1964
+ <div style="width:1px;height:20px;background:rgba(255,255,255,0.2);"></div>
1965
+ <div style="display:flex;align-items:center;gap:8px;">
1966
+ <div style="width:8px;height:8px;background:#e8a020;border-radius:50%;box-shadow:0 0 8px #e8a020;animation:pulse 2s 0.5s infinite;"></div>
1967
+ <span style="color:white;font-size:0.8em;font-weight:600;">FINE-TUNED MODEL</span>
1968
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">CardioLab SJSU</span>
1969
+ </div>
1970
+ <div style="width:1px;height:20px;background:rgba(255,255,255,0.2);"></div>
1971
+ <div style="display:flex;align-items:center;gap:8px;">
1972
+ <div style="width:8px;height:8px;background:#0057a8;border-radius:50%;box-shadow:0 0 8px #0057a8;animation:pulse 2s 1s infinite;"></div>
1973
+ <span style="color:white;font-size:0.8em;font-weight:600;">5 AI MODELS</span>
1974
+ <span style="color:rgba(255,255,255,0.6);font-size:0.75em;">Select in dropdown</span>
1975
+ </div>
1976
+ <style>@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(1.3)}}</style>
1977
+ </div>""")
1978
 
1979
  with gr.Tabs():
1980
 
1981
  with gr.Tab("Chat"):
1982
  with gr.Row():
1983
  with gr.Column(scale=1, min_width=200):
1984
+ gr.HTML("<div style="
1985
+ background: linear-gradient(180de<div style='color:#e8a020;font-weight:700;font-size:0.85em;'>SJSU CARDIOLAB</div><div style='color:#9ca3af;font-size:0.7em;'>Conversations</div></div>")
1986
  new_chat_btn = gr.Button("New Chat", variant="secondary")
1987
  session_dropdown = gr.Dropdown(choices=get_session_list(), label="Saved Sessions", interactive=True)
1988
  load_btn = gr.Button("Load Session", variant="primary")
 
2146
  hyp_output = gr.Textbox(label="Research Hypotheses", lines=25)
2147
  hyp_btn.click(generate_hypothesis, inputs=[hyp_area, hyp_findings], outputs=hyp_output)
2148
 
2149
+ gr.HTML("""<div style="
2150
+ text-align:center;
2151
+ padding: 16px;
2152
+ margin-top: 12px;
2153
+ border-top: 1px solid rgba(255,255,255,0.06);
2154
+ background: rgba(255,255,255,0.02);
2155
+ border-radius: 0 0 16px 16px;
2156
+ backdrop-filter: blur(20px);
2157
+ ">
2158
+ <div style="display:flex;align-items:center;justify-content:center;gap:20px;flex-wrap:wrap;">
2159
+ <span style="color:rgba(255,255,255,0.3);font-size:0.72em;">CardioLab AI v39</span>
2160
+ <span style="color:rgba(255,255,255,0.1);">|</span>
2161
+ <span style="color:rgba(255,255,255,0.3);font-size:0.72em;">SJSU Biomedical Engineering</span>
2162
+ <span style="color:rgba(255,255,255,0.1);">|</span>
2163
+ <a href="https://github.com/snap-stanford/Biomni" style="color:rgba(193,18,31,0.7);font-size:0.72em;text-decoration:none;">Inspired by Biomni Stanford</a>
2164
+ <span style="color:rgba(255,255,255,0.1);">|</span>
2165
+ <a href="https://github.com/pranatechsol/Cardio-Lab-Ai" style="color:rgba(0,87,168,0.7);font-size:0.72em;text-decoration:none;">GitHub</a>
2166
+ <span style="color:rgba(255,255,255,0.1);">|</span>
2167
+ <span style="color:rgba(46,204,113,0.6);font-size:0.72em;font-weight:600;">$0 Cost Forever</span>
2168
+ </div>
2169
+ </div>
2170
+ <span style="color:#9ca3af;font-size:0.75em;">CardioLab AI v39 | SJSU Biomedical Engineering | RAG + Fine-tuned + Phase D | Inspired by <a href="https://github.com/snap-stanford/Biomni" style="color:#c1121f;">Biomni Stanford</a> | Apache 2.0 | $0 Cost</span></div>""")
2171
 
2172
  demo.launch(css=CSS)