Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,88 +1,138 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
import requests
|
|
|
|
| 4 |
|
| 5 |
GROQ_KEY = os.environ.get("GROQ_API_KEY", "")
|
| 6 |
|
| 7 |
-
KNOWHOW = """
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
MHV: 27mm SJM Regent, bileaflet trileaflet monoleaflet pediatric
|
| 14 |
-
CKD Stages: 1 below 1.5, 2 1.5-3.0, 3-4 3.0-6.0, 5 above 6.0 mg/dL
|
| 15 |
-
Equipment: Heska HT5, time-resolved PIV, Tygon tubing, Arduino
|
| 16 |
-
"""
|
| 17 |
|
| 18 |
-
def
|
| 19 |
try:
|
| 20 |
-
r = requests.get(
|
| 21 |
-
"
|
| 22 |
-
|
| 23 |
-
timeout=10
|
| 24 |
-
)
|
| 25 |
ids = r.json()["esearchresult"]["idlist"]
|
| 26 |
if not ids:
|
| 27 |
return ""
|
| 28 |
-
links = []
|
| 29 |
-
|
| 30 |
-
links.append("https://pubmed.ncbi.nlm.nih.gov/" + pmid)
|
| 31 |
-
return "PubMed results: " + " | ".join(links)
|
| 32 |
-
except:
|
| 33 |
-
return ""
|
| 34 |
-
|
| 35 |
-
def search_scholar(query, n=3):
|
| 36 |
-
try:
|
| 37 |
-
r = requests.get(
|
| 38 |
-
"https://api.semanticscholar.org/graph/v1/paper/search",
|
| 39 |
-
params={"query":query,"limit":n,"fields":"title,year,url"},
|
| 40 |
-
timeout=10
|
| 41 |
-
)
|
| 42 |
-
papers = r.json().get("data",[])
|
| 43 |
-
out = []
|
| 44 |
-
for p in papers:
|
| 45 |
-
title = p.get("title","")
|
| 46 |
-
year = str(p.get("year",""))
|
| 47 |
-
url = p.get("url","")
|
| 48 |
-
if url:
|
| 49 |
-
out.append(title[:80] + " (" + year + ") - " + url)
|
| 50 |
-
return "\n".join(out)
|
| 51 |
except:
|
| 52 |
return ""
|
| 53 |
|
| 54 |
-
def
|
| 55 |
if not GROQ_KEY:
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
try:
|
| 58 |
-
from groq import Groq
|
| 59 |
client = Groq(api_key=GROQ_KEY)
|
| 60 |
-
|
| 61 |
-
{
|
| 62 |
-
"role": "system",
|
| 63 |
-
"content": "You are CardioLab AI built on Biomni from Stanford. Expert in SJSU Biomedical Engineering. Remember the full conversation. NEVER invent paper URLs.\n\n" + KNOWHOW
|
| 64 |
-
}
|
| 65 |
-
]
|
| 66 |
for msg in history:
|
| 67 |
if isinstance(msg, dict):
|
| 68 |
-
|
| 69 |
-
pubmed =
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
"content": message + "\n\nVerified paper links found:\n" + pubmed + "\n" + scholar
|
| 74 |
-
})
|
| 75 |
-
response = client.chat.completions.create(
|
| 76 |
-
model="llama-3.3-70b-versatile",
|
| 77 |
-
messages=messages,
|
| 78 |
-
max_tokens=600
|
| 79 |
-
)
|
| 80 |
-
answer = response.choices[0].message.content
|
| 81 |
-
links = ""
|
| 82 |
if pubmed:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
return
|
| 87 |
except Exception as e:
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from google.colab import userdata
|
| 2 |
+
from huggingface_hub import HfApi
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
hf_token = userdata.get('HF_TOKEN').strip()
|
| 6 |
+
api = HfApi(token=hf_token)
|
| 7 |
+
repo_id = 'Saicharan21/CardioLab-AI'
|
| 8 |
+
|
| 9 |
+
# Write clean app
|
| 10 |
+
app = """import gradio as gr
|
| 11 |
import os
|
| 12 |
import requests
|
| 13 |
+
from groq import Groq
|
| 14 |
|
| 15 |
GROQ_KEY = os.environ.get("GROQ_API_KEY", "")
|
| 16 |
|
| 17 |
+
KNOWHOW = \"\"\"SJSU CardioLab: MCL uses Sylgard 184 PDMS 10:1 ratio 48hr cure green laser PIV 70bpm 5L/min.
|
| 18 |
+
TGT uses Arduino Uno Stepper Motor 150mL blood sampled at 0 20 40 60min measures TAT PF1.2 hemolysis platelets.
|
| 19 |
+
uPAD uses Jaffe reaction creatinine plus picric acid gives orange-red color normal 0.6-1.2 mg/dL CKD above 1.5.
|
| 20 |
+
FSI uses COMSOL ALE mesh blood 1060 kg/m3 0.0035 Pa.s St Jude geometry.
|
| 21 |
+
MHV is 27mm SJM Regent bileaflet also trileaflet monoleaflet pediatric designs.
|
| 22 |
+
Equipment: Heska HT5 hematology analyzer time-resolved PIV Tygon tubing Arduino Uno.\"\"\"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
def get_pubmed(query):
|
| 25 |
try:
|
| 26 |
+
r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
|
| 27 |
+
params={"db":"pubmed","term":query+" mechanical heart valve OR microfluidic OR CKD","retmax":3,"retmode":"json","sort":"date"},
|
| 28 |
+
timeout=8)
|
|
|
|
|
|
|
| 29 |
ids = r.json()["esearchresult"]["idlist"]
|
| 30 |
if not ids:
|
| 31 |
return ""
|
| 32 |
+
links = ["https://pubmed.ncbi.nlm.nih.gov/"+i for i in ids]
|
| 33 |
+
return "PubMed: " + " | ".join(links)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
except:
|
| 35 |
return ""
|
| 36 |
|
| 37 |
+
def respond(message, history):
|
| 38 |
if not GROQ_KEY:
|
| 39 |
+
history.append({"role":"user","content":message})
|
| 40 |
+
history.append({"role":"assistant","content":"Error: Add GROQ_API_KEY to Space secrets in Settings tab."})
|
| 41 |
+
return "", history
|
| 42 |
try:
|
|
|
|
| 43 |
client = Groq(api_key=GROQ_KEY)
|
| 44 |
+
msgs = [{"role":"system","content":"You are CardioLab AI from SJSU Biomedical Engineering built on Biomni Stanford SNAP Lab. Expert in MHV MCL PIV TGT uPAD CKD FSI COMSOL. Remember the full conversation. Never invent paper URLs.\\n\\n"+KNOWHOW}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
for msg in history:
|
| 46 |
if isinstance(msg, dict):
|
| 47 |
+
msgs.append({"role":msg["role"],"content":msg["content"]})
|
| 48 |
+
pubmed = get_pubmed(message)
|
| 49 |
+
msgs.append({"role":"user","content":message+"\\n\\n"+pubmed})
|
| 50 |
+
resp = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=msgs,max_tokens=600)
|
| 51 |
+
answer = resp.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
if pubmed:
|
| 53 |
+
answer += "\\n\\n📚 "+pubmed
|
| 54 |
+
history.append({"role":"user","content":message})
|
| 55 |
+
history.append({"role":"assistant","content":answer})
|
| 56 |
+
return "", history
|
| 57 |
except Exception as e:
|
| 58 |
+
history.append({"role":"user","content":message})
|
| 59 |
+
history.append({"role":"assistant","content":"Error: "+str(e)})
|
| 60 |
+
return "", history
|
| 61 |
+
|
| 62 |
+
def piv_tool(velocity, shear, hr):
|
| 63 |
+
v = "HIGH - stenosis risk" if float(velocity)>2.0 else "NORMAL"
|
| 64 |
+
s = "HIGH - thrombosis risk" if float(shear)>10 else "ELEVATED" if float(shear)>5 else "NORMAL"
|
| 65 |
+
return "Velocity: "+str(velocity)+" m/s - "+v+"\\nShear: "+str(shear)+" Pa - "+s+"\\nHeart Rate: "+str(hr)+" bpm"
|
| 66 |
+
|
| 67 |
+
def tgt_tool(tat, pf12, hemo, platelets, time):
|
| 68 |
+
risk = sum([float(tat)>15,float(pf12)>2.0,float(hemo)>50,float(platelets)<150])
|
| 69 |
+
r = "HIGH THROMBOGENIC RISK" if risk>=3 else "MODERATE RISK" if risk>=2 else "LOW RISK"
|
| 70 |
+
return "TAT:"+str(tat)+" PF1.2:"+str(pf12)+"\\nHemo:"+str(hemo)+" Platelets:"+str(platelets)+"\\nTime:"+str(time)+"min\\nResult: "+r
|
| 71 |
+
|
| 72 |
+
def upad_tool(r, g, b):
|
| 73 |
+
c = max(0,round(0.02*(float(r)-float(b))-0.5,2))
|
| 74 |
+
s = "Normal" if c<1.2 else "Borderline" if c<1.5 else "Stage 2 CKD" if c<3.0 else "Stage 3-4 CKD" if c<6.0 else "Stage 5 CKD"
|
| 75 |
+
return "Creatinine: "+str(c)+" mg/dL\\nStage: "+s+"\\nConfirm with: Heska Element HT5"
|
| 76 |
+
|
| 77 |
+
with gr.Blocks(title="CardioLab AI - SJSU") as demo:
|
| 78 |
+
gr.Markdown("# CardioLab AI Agent")
|
| 79 |
+
gr.Markdown("### SJSU Biomedical Engineering | Biomni Stanford + Llama 70B + Chat Memory + PubMed")
|
| 80 |
+
gr.Markdown("Open Source: github.com/pranatechsol/Cardio-Lab-Ai")
|
| 81 |
+
with gr.Tab("Research Chat"):
|
| 82 |
+
gr.Markdown("### Chat with memory like ChatGPT — specialized for CardioLab research")
|
| 83 |
+
chatbot = gr.Chatbot(label="CardioLab AI", height=500, type="messages")
|
| 84 |
+
msg = gr.Textbox(label="Ask anything about CardioLab research", placeholder="e.g. How does the TGT measure thrombogenicity?", lines=2)
|
| 85 |
+
with gr.Row():
|
| 86 |
+
send = gr.Button("Send", variant="primary")
|
| 87 |
+
clear = gr.Button("Clear Chat")
|
| 88 |
+
send.click(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
| 89 |
+
msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
| 90 |
+
clear.click(lambda: [], None, chatbot)
|
| 91 |
+
with gr.Tab("PIV Analysis"):
|
| 92 |
+
gr.Markdown("### Analyze PIV flow data from Mock Circulatory Loop")
|
| 93 |
+
v = gr.Number(label="Max Velocity m/s", value=1.8)
|
| 94 |
+
s = gr.Number(label="Shear Stress Pa", value=6.5)
|
| 95 |
+
h = gr.Number(label="Heart Rate bpm", value=72)
|
| 96 |
+
out = gr.Textbox(label="Result", lines=4)
|
| 97 |
+
gr.Button("Analyze PIV").click(piv_tool, inputs=[v,s,h], outputs=out)
|
| 98 |
+
with gr.Tab("TGT Results"):
|
| 99 |
+
gr.Markdown("### Interpret Thrombogenicity Tester blood results")
|
| 100 |
+
t1 = gr.Number(label="TAT", value=18)
|
| 101 |
+
t2 = gr.Number(label="PF1.2", value=2.5)
|
| 102 |
+
t3 = gr.Number(label="Free Hemoglobin mg/L", value=60)
|
| 103 |
+
t4 = gr.Number(label="Platelet Count", value=140)
|
| 104 |
+
t5 = gr.Number(label="Time minutes", value=40)
|
| 105 |
+
out2 = gr.Textbox(label="Result", lines=5)
|
| 106 |
+
gr.Button("Analyze TGT").click(tgt_tool, inputs=[t1,t2,t3,t4,t5], outputs=out2)
|
| 107 |
+
with gr.Tab("uPAD CKD"):
|
| 108 |
+
gr.Markdown("### Analyze uPAD colorimetric result - Jaffe Reaction")
|
| 109 |
+
r = gr.Number(label="R value", value=210)
|
| 110 |
+
g = gr.Number(label="G value", value=140)
|
| 111 |
+
b = gr.Number(label="B value", value=80)
|
| 112 |
+
out3 = gr.Textbox(label="Result", lines=4)
|
| 113 |
+
gr.Button("Analyze uPAD").click(upad_tool, inputs=[r,g,b], outputs=out3)
|
| 114 |
+
|
| 115 |
+
demo.launch()
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
req = "gradio\ngroq\nrequests\n"
|
| 119 |
+
|
| 120 |
+
with open('/content/final_app.py', 'w') as f:
|
| 121 |
+
f.write(app)
|
| 122 |
+
|
| 123 |
+
with open('/content/final_req.txt', 'w') as f:
|
| 124 |
+
f.write(req)
|
| 125 |
+
|
| 126 |
+
# Verify line count
|
| 127 |
+
with open('/content/final_app.py') as f:
|
| 128 |
+
lines = f.readlines()
|
| 129 |
+
print("Lines in app:", len(lines))
|
| 130 |
+
print("First line:", lines[0])
|
| 131 |
+
print("Last line:", lines[-1])
|
| 132 |
+
|
| 133 |
+
api.upload_file(path_or_fileobj='/content/final_app.py', path_in_repo='app.py', repo_id=repo_id, repo_type='space', token=hf_token)
|
| 134 |
+
api.upload_file(path_or_fileobj='/content/final_req.txt', path_in_repo='requirements.txt', repo_id=repo_id, repo_type='space', token=hf_token)
|
| 135 |
+
|
| 136 |
+
print("\nFINAL CLEAN APP DEPLOYED!")
|
| 137 |
+
print("URL: https://huggingface.co/spaces/Saicharan21/CardioLab-AI")
|
| 138 |
+
print("Wait 3 minutes then test!")
|