Saicharan21 commited on
Commit
1715a23
·
verified ·
1 Parent(s): 047466c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +62 -56
app.py CHANGED
@@ -9,92 +9,98 @@ KNOWHOW = """SJSU CardioLab:
9
  MCL: Sylgard 184 PDMS 10:1 ratio 48hr cure green laser PIV 70bpm 5L/min.
10
  TGT: Arduino Uno Stepper Motor 150mL blood sampled at 0 20 40 60min measures TAT PF1.2 hemolysis platelets.
11
  uPAD: Jaffe reaction creatinine plus picric acid gives orange-red color normal 0.6-1.2 mg/dL CKD above 1.5.
12
- FSI: COMSOL ALE mesh blood 1060 kg/m3 0.0035 Pa.s St Jude geometry.
13
  MHV: 27mm SJM Regent bileaflet also trileaflet monoleaflet pediatric.
14
  Equipment: Heska HT5 hematology analyzer time-resolved PIV Tygon tubing Arduino Uno."""
15
 
16
  def get_pubmed(query):
17
  try:
18
- r = requests.get(
19
- "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
20
- params={"db":"pubmed","term":query,"retmax":3,"retmode":"json","sort":"date"},
21
- timeout=8
22
- )
23
  ids = r.json()["esearchresult"]["idlist"]
24
- if not ids:
25
- return ""
26
- links = ["https://pubmed.ncbi.nlm.nih.gov/"+i for i in ids]
27
- return "\n\nPubMed: " + " | ".join(links)
28
- except:
29
- return ""
30
 
31
  def chat(message, history):
32
  if not GROQ_KEY:
33
- return "Error: Add GROQ_API_KEY to Space Settings under Secrets tab."
34
  try:
35
  client = Groq(api_key=GROQ_KEY)
36
- 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}]
37
  for item in history:
38
  if isinstance(item, dict):
39
  msgs.append({"role":item["role"],"content":item["content"]})
40
- elif isinstance(item, (list,tuple)) and len(item)==2:
41
  if item[0]: msgs.append({"role":"user","content":str(item[0])})
42
  if item[1]: msgs.append({"role":"assistant","content":str(item[1])})
43
- pubmed = get_pubmed(message)
44
  msgs.append({"role":"user","content":message})
45
  resp = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=msgs,max_tokens=600)
46
- return resp.choices[0].message.content + pubmed
47
- except Exception as e:
48
- return "Error: "+str(e)
49
 
50
  def piv_tool(velocity, shear, hr):
51
- v = "HIGH - stenosis risk" if float(velocity)>2.0 else "NORMAL"
52
- s = "HIGH - thrombosis risk" if float(shear)>10 else "ELEVATED" if float(shear)>5 else "NORMAL"
53
- return "Velocity: "+str(velocity)+" m/s - "+v+"\nShear: "+str(shear)+" Pa - "+s+"\nHeart Rate: "+str(hr)+" bpm"
54
 
55
- def tgt_tool(tat, pf12, hemo, platelets, time):
56
- risk = sum([float(tat)>15,float(pf12)>2.0,float(hemo)>50,float(platelets)<150])
57
- r = "HIGH THROMBOGENIC RISK" if risk>=3 else "MODERATE RISK" if risk>=2 else "LOW RISK"
58
- return "TAT:"+str(tat)+" PF1.2:"+str(pf12)+"\nHemo:"+str(hemo)+" Platelets:"+str(platelets)+"\nTime:"+str(time)+" min\nResult: "+r
59
 
60
- def upad_tool(r, g, b):
61
- c = max(0,round(0.02*(float(r)-float(b))-0.5,2))
62
- 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"
63
- return "Creatinine: "+str(c)+" mg/dL\nStage: "+s+"\nConfirm with: Heska Element HT5"
64
 
65
- with gr.Blocks(title="CardioLab AI - SJSU") as demo:
66
  gr.Markdown("# CardioLab AI Agent")
67
- gr.Markdown("### SJSU Biomedical Engineering | Biomni Stanford + Llama 70B + Chat Memory + PubMed")
68
- gr.Markdown("Open Source: github.com/pranatechsol/Cardio-Lab-Ai")
 
69
  with gr.Tab("Research Chat"):
70
- gr.Markdown("### Chat with memory like ChatGPT for CardioLab research")
71
- gr.ChatInterface(
72
- fn=chat,
73
- chatbot=gr.Chatbot(height=450, label="CardioLab AI"),
74
- textbox=gr.Textbox(placeholder="Ask anything about CardioLab research...", lines=2, label="Your message")
75
- )
 
 
 
 
 
 
 
 
 
 
 
 
76
  with gr.Tab("PIV Analysis"):
77
  gr.Markdown("### Analyze PIV flow data from Mock Circulatory Loop")
78
- v = gr.Number(label="Max Velocity m/s", value=1.8)
79
- s = gr.Number(label="Shear Stress Pa", value=6.5)
80
- h = gr.Number(label="Heart Rate bpm", value=72)
81
- out = gr.Textbox(label="Result", lines=4)
82
- gr.Button("Analyze PIV").click(piv_tool, inputs=[v,s,h], outputs=out)
 
83
  with gr.Tab("TGT Results"):
84
  gr.Markdown("### Interpret Thrombogenicity Tester blood results")
85
- t1 = gr.Number(label="TAT", value=18)
86
- t2 = gr.Number(label="PF1.2", value=2.5)
87
- t3 = gr.Number(label="Free Hemoglobin mg/L", value=60)
88
- t4 = gr.Number(label="Platelet Count", value=140)
89
- t5 = gr.Number(label="Time minutes", value=40)
90
- out2 = gr.Textbox(label="Result", lines=5)
91
- gr.Button("Analyze TGT").click(tgt_tool, inputs=[t1,t2,t3,t4,t5], outputs=out2)
 
92
  with gr.Tab("uPAD CKD"):
93
  gr.Markdown("### Analyze uPAD colorimetric result - Jaffe Reaction")
94
- r = gr.Number(label="R value", value=210)
95
- g = gr.Number(label="G value", value=140)
96
- b = gr.Number(label="B value", value=80)
97
- out3 = gr.Textbox(label="Result", lines=4)
98
- gr.Button("Analyze uPAD").click(upad_tool, inputs=[r,g,b], outputs=out3)
99
 
100
  demo.launch()
 
9
  MCL: Sylgard 184 PDMS 10:1 ratio 48hr cure green laser PIV 70bpm 5L/min.
10
  TGT: Arduino Uno Stepper Motor 150mL blood sampled at 0 20 40 60min measures TAT PF1.2 hemolysis platelets.
11
  uPAD: Jaffe reaction creatinine plus picric acid gives orange-red color normal 0.6-1.2 mg/dL CKD above 1.5.
 
12
  MHV: 27mm SJM Regent bileaflet also trileaflet monoleaflet pediatric.
13
  Equipment: Heska HT5 hematology analyzer time-resolved PIV Tygon tubing Arduino Uno."""
14
 
15
  def get_pubmed(query):
16
  try:
17
+ r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
18
+ params={"db":"pubmed","term":query,"retmax":3,"retmode":"json","sort":"date"},timeout=8)
 
 
 
19
  ids = r.json()["esearchresult"]["idlist"]
20
+ if not ids: return ""
21
+ return "\n\nPubMed: "+" | ".join(["https://pubmed.ncbi.nlm.nih.gov/"+i for i in ids])
22
+ except: return ""
 
 
 
23
 
24
  def chat(message, history):
25
  if not GROQ_KEY:
26
+ return "Error: Add GROQ_API_KEY to Space Settings Secrets tab."
27
  try:
28
  client = Groq(api_key=GROQ_KEY)
29
+ msgs = [{"role":"system","content":"You are CardioLab AI from SJSU Biomedical Engineering built on Biomni Stanford. Expert in MHV MCL PIV TGT uPAD CKD FSI. Remember full conversation. Never invent URLs.\n\n"+KNOWHOW}]
30
  for item in history:
31
  if isinstance(item, dict):
32
  msgs.append({"role":item["role"],"content":item["content"]})
33
+ elif isinstance(item,(list,tuple)) and len(item)==2:
34
  if item[0]: msgs.append({"role":"user","content":str(item[0])})
35
  if item[1]: msgs.append({"role":"assistant","content":str(item[1])})
 
36
  msgs.append({"role":"user","content":message})
37
  resp = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=msgs,max_tokens=600)
38
+ return resp.choices[0].message.content + get_pubmed(message)
39
+ except Exception as e: return "Error: "+str(e)
 
40
 
41
  def piv_tool(velocity, shear, hr):
42
+ v = "HIGH-stenosis" if float(velocity)>2.0 else "NORMAL"
43
+ s = "HIGH-thrombosis" if float(shear)>10 else "ELEVATED" if float(shear)>5 else "NORMAL"
44
+ return "Velocity:"+str(velocity)+"m/s - "+v+"\nShear:"+str(shear)+"Pa - "+s+"\nHR:"+str(hr)+"bpm"
45
 
46
+ def tgt_tool(tat,pf12,hemo,platelets,time):
47
+ risk=sum([float(tat)>15,float(pf12)>2.0,float(hemo)>50,float(platelets)<150])
48
+ r="HIGH RISK" if risk>=3 else "MODERATE" if risk>=2 else "LOW RISK"
49
+ return "TAT:"+str(tat)+" PF1.2:"+str(pf12)+"\nHemo:"+str(hemo)+" Plt:"+str(platelets)+"\nResult:"+r
50
 
51
+ def upad_tool(r,g,b):
52
+ c=max(0,round(0.02*(float(r)-float(b))-0.5,2))
53
+ s="Normal" if c<1.2 else "Borderline" if c<1.5 else "Stage2CKD" if c<3.0 else "Stage3-4" if c<6.0 else "Stage5"
54
+ return "Creatinine:"+str(c)+"mg/dL\nStage:"+s
55
 
56
+ with gr.Blocks(title="CardioLab AI SJSU") as demo:
57
  gr.Markdown("# CardioLab AI Agent")
58
+ gr.Markdown("### SJSU Biomedical Engineering | Biomni Stanford + Llama 70B + PubMed")
59
+ gr.Markdown("github.com/pranatechsol/Cardio-Lab-Ai")
60
+
61
  with gr.Tab("Research Chat"):
62
+ gr.Markdown("### Chat like ChatGPT for CardioLab research")
63
+ chatbot = gr.Chatbot(height=400, label="CardioLab AI")
64
+ msg_box = gr.Textbox(placeholder="Ask anything about CardioLab...", label="Your message", lines=2)
65
+ with gr.Row():
66
+ send_btn = gr.Button("Send", variant="primary", scale=3)
67
+ clear_btn = gr.Button("Clear", scale=1)
68
+
69
+ def respond(message, history):
70
+ if not message.strip():
71
+ return "", history
72
+ reply = chat(message, history)
73
+ history = history + [[message, reply]]
74
+ return "", history
75
+
76
+ send_btn.click(respond, inputs=[msg_box, chatbot], outputs=[msg_box, chatbot])
77
+ msg_box.submit(respond, inputs=[msg_box, chatbot], outputs=[msg_box, chatbot])
78
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg_box])
79
+
80
  with gr.Tab("PIV Analysis"):
81
  gr.Markdown("### Analyze PIV flow data from Mock Circulatory Loop")
82
+ v=gr.Number(label="Max Velocity m/s",value=1.8)
83
+ s=gr.Number(label="Shear Stress Pa",value=6.5)
84
+ h=gr.Number(label="Heart Rate bpm",value=72)
85
+ out=gr.Textbox(label="Result",lines=4)
86
+ gr.Button("Analyze PIV").click(piv_tool,inputs=[v,s,h],outputs=out)
87
+
88
  with gr.Tab("TGT Results"):
89
  gr.Markdown("### Interpret Thrombogenicity Tester blood results")
90
+ t1=gr.Number(label="TAT",value=18)
91
+ t2=gr.Number(label="PF1.2",value=2.5)
92
+ t3=gr.Number(label="Free Hemoglobin",value=60)
93
+ t4=gr.Number(label="Platelet Count",value=140)
94
+ t5=gr.Number(label="Time minutes",value=40)
95
+ out2=gr.Textbox(label="Result",lines=5)
96
+ gr.Button("Analyze TGT").click(tgt_tool,inputs=[t1,t2,t3,t4,t5],outputs=out2)
97
+
98
  with gr.Tab("uPAD CKD"):
99
  gr.Markdown("### Analyze uPAD colorimetric result - Jaffe Reaction")
100
+ r=gr.Number(label="R value",value=210)
101
+ g=gr.Number(label="G value",value=140)
102
+ b=gr.Number(label="B value",value=80)
103
+ out3=gr.Textbox(label="Result",lines=4)
104
+ gr.Button("Analyze uPAD").click(upad_tool,inputs=[r,g,b],outputs=out3)
105
 
106
  demo.launch()