Spaces:
Running
Running
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import os, requests
|
| 3 |
from groq import Groq
|
| 4 |
|
| 5 |
GROQ_KEY = os.environ.get("GROQ_API_KEY","")
|
| 6 |
-
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN","")
|
| 7 |
client = Groq(api_key=GROQ_KEY)
|
| 8 |
|
| 9 |
KNOWHOW = """
|
|
@@ -17,19 +16,20 @@ CKD Stages: 1 below 1.5, 2 1.5-3.0, 3-4 3.0-6.0, 5 above 6.0 mg/dL
|
|
| 17 |
Equipment: Heska HT5, time-resolved PIV, Tygon tubing, Arduino
|
| 18 |
"""
|
| 19 |
|
| 20 |
-
def search_pubmed(query, n=
|
| 21 |
try:
|
| 22 |
r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
|
| 23 |
-
params={"db":"pubmed","term":query,"retmax":n,"retmode":"json"}, timeout=10)
|
| 24 |
ids = r.json()["esearchresult"]["idlist"]
|
| 25 |
-
if not ids: return ""
|
| 26 |
r2 = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi",
|
| 27 |
params={"db":"pubmed","id":",".join(ids),"retmode":"xml","rettype":"abstract"}, timeout=10)
|
| 28 |
import xmltodict
|
| 29 |
data = xmltodict.parse(r2.content)
|
| 30 |
articles = data.get("PubmedArticleSet",{}).get("PubmedArticle",[])
|
| 31 |
if isinstance(articles, dict): articles = [articles]
|
| 32 |
-
|
|
|
|
| 33 |
for a in articles[:n]:
|
| 34 |
try:
|
| 35 |
c = a["MedlineCitation"]
|
|
@@ -38,66 +38,70 @@ def search_pubmed(query, n=3):
|
|
| 38 |
if isinstance(abstract, list): abstract = " ".join([str(x) for x in abstract])
|
| 39 |
if isinstance(abstract, dict): abstract = str(abstract.get("#text",""))
|
| 40 |
pmid = str(c["PMID"]["#text"] if isinstance(c["PMID"],dict) else c["PMID"])
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
except: continue
|
| 43 |
-
return
|
| 44 |
-
except: return ""
|
| 45 |
|
| 46 |
-
def search_scholar(query, n=
|
| 47 |
try:
|
| 48 |
r = requests.get("https://api.semanticscholar.org/graph/v1/paper/search",
|
| 49 |
params={"query":query,"limit":n,"fields":"title,abstract,year,url"}, timeout=10)
|
| 50 |
papers = r.json().get("data",[])
|
| 51 |
-
|
|
|
|
| 52 |
for p in papers:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
"Authorization": "Bearer " + GITHUB_TOKEN,
|
| 63 |
-
"Content-Type": "application/json"
|
| 64 |
-
}
|
| 65 |
-
payload = {
|
| 66 |
-
"messages": [{"role": "user", "content": query}],
|
| 67 |
-
"model": "gpt-4o",
|
| 68 |
-
"tools": [{"type": "bing_search"}]
|
| 69 |
-
}
|
| 70 |
-
r = requests.post(
|
| 71 |
-
"https://api.githubcopilot.com/chat/completions",
|
| 72 |
-
headers=headers,
|
| 73 |
-
json=payload,
|
| 74 |
-
timeout=15
|
| 75 |
-
)
|
| 76 |
-
if r.status_code == 200:
|
| 77 |
-
data = r.json()
|
| 78 |
-
content = data["choices"][0]["message"]["content"]
|
| 79 |
-
return "[Real-time Web Search]\n" + str(content)[:600]
|
| 80 |
-
return ""
|
| 81 |
-
except Exception as e:
|
| 82 |
-
return ""
|
| 83 |
|
| 84 |
def ask_agent(question):
|
| 85 |
if not GROQ_KEY:
|
| 86 |
-
return "Error: GROQ_API_KEY not set."
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
| 92 |
response = client.chat.completions.create(
|
| 93 |
model="llama-3.3-70b-versatile",
|
| 94 |
messages=[
|
| 95 |
-
{"role":"system","content":"You are CardioLab AI built on Biomni from Stanford SNAP Lab.
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
],
|
| 98 |
-
max_tokens=
|
| 99 |
)
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
def piv_tool(velocity, shear, hr):
|
| 103 |
v = "HIGH - stenosis risk" if float(velocity)>2.0 else "NORMAL"
|
|
@@ -116,12 +120,12 @@ def upad_tool(r, g, b):
|
|
| 116 |
|
| 117 |
with gr.Blocks(title="CardioLab AI - SJSU") as demo:
|
| 118 |
gr.Markdown("# CardioLab AI Agent")
|
| 119 |
-
gr.Markdown("### SJSU Biomedical Engineering | Biomni + Llama 70B + PubMed +
|
| 120 |
-
gr.Markdown("GitHub: github.com/pranatechsol/Cardio-Lab-Ai")
|
| 121 |
with gr.Tab("Research Assistant"):
|
| 122 |
-
gr.Markdown("### Searches
|
| 123 |
-
q = gr.Textbox(label="Research question", placeholder="e.g.
|
| 124 |
-
a = gr.Textbox(label="Answer with citations", lines=
|
| 125 |
gr.Button("Search & Answer").click(ask_agent, inputs=q, outputs=a)
|
| 126 |
with gr.Tab("PIV Analysis"):
|
| 127 |
gr.Markdown("### Analyze PIV flow data from Mock Circulatory Loop")
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os, requests
|
| 3 |
from groq import Groq
|
| 4 |
|
| 5 |
GROQ_KEY = os.environ.get("GROQ_API_KEY","")
|
|
|
|
| 6 |
client = Groq(api_key=GROQ_KEY)
|
| 7 |
|
| 8 |
KNOWHOW = """
|
|
|
|
| 16 |
Equipment: Heska HT5, time-resolved PIV, Tygon tubing, Arduino
|
| 17 |
"""
|
| 18 |
|
| 19 |
+
def search_pubmed(query, n=5):
|
| 20 |
try:
|
| 21 |
r = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
|
| 22 |
+
params={"db":"pubmed","term":query,"retmax":n,"retmode":"json","sort":"date"}, timeout=10)
|
| 23 |
ids = r.json()["esearchresult"]["idlist"]
|
| 24 |
+
if not ids: return [], ""
|
| 25 |
r2 = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi",
|
| 26 |
params={"db":"pubmed","id":",".join(ids),"retmode":"xml","rettype":"abstract"}, timeout=10)
|
| 27 |
import xmltodict
|
| 28 |
data = xmltodict.parse(r2.content)
|
| 29 |
articles = data.get("PubmedArticleSet",{}).get("PubmedArticle",[])
|
| 30 |
if isinstance(articles, dict): articles = [articles]
|
| 31 |
+
real_links = []
|
| 32 |
+
context = ""
|
| 33 |
for a in articles[:n]:
|
| 34 |
try:
|
| 35 |
c = a["MedlineCitation"]
|
|
|
|
| 38 |
if isinstance(abstract, list): abstract = " ".join([str(x) for x in abstract])
|
| 39 |
if isinstance(abstract, dict): abstract = str(abstract.get("#text",""))
|
| 40 |
pmid = str(c["PMID"]["#text"] if isinstance(c["PMID"],dict) else c["PMID"])
|
| 41 |
+
real_url = "https://pubmed.ncbi.nlm.nih.gov/" + pmid
|
| 42 |
+
real_links.append("- " + title[:100] + "\n URL: " + real_url)
|
| 43 |
+
context += "[PubMed PMID:" + pmid + "] " + title + ". " + str(abstract)[:300] + "\n\n"
|
| 44 |
except: continue
|
| 45 |
+
return real_links, context
|
| 46 |
+
except: return [], ""
|
| 47 |
|
| 48 |
+
def search_scholar(query, n=5):
|
| 49 |
try:
|
| 50 |
r = requests.get("https://api.semanticscholar.org/graph/v1/paper/search",
|
| 51 |
params={"query":query,"limit":n,"fields":"title,abstract,year,url"}, timeout=10)
|
| 52 |
papers = r.json().get("data",[])
|
| 53 |
+
real_links = []
|
| 54 |
+
context = ""
|
| 55 |
for p in papers:
|
| 56 |
+
title = p.get("title","")
|
| 57 |
+
abstract = (p.get("abstract") or "")[:300]
|
| 58 |
+
year = str(p.get("year",""))
|
| 59 |
+
url = p.get("url","")
|
| 60 |
+
if url:
|
| 61 |
+
real_links.append("- " + title[:100] + " (" + year + ")\n URL: " + url)
|
| 62 |
+
context += "[Scholar " + year + "] " + title + ". " + abstract + "\n\n"
|
| 63 |
+
return real_links, context
|
| 64 |
+
except: return [], ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
def ask_agent(question):
|
| 67 |
if not GROQ_KEY:
|
| 68 |
+
return "Error: GROQ_API_KEY not set in Space secrets."
|
| 69 |
+
|
| 70 |
+
cardio_query = question + " mechanical heart valve OR microfluidic creatinine OR PIV hemodynamics OR thrombogenicity"
|
| 71 |
+
|
| 72 |
+
pubmed_links, pubmed_context = search_pubmed(cardio_query, n=5)
|
| 73 |
+
scholar_links, scholar_context = search_scholar(question + " biomedical", n=5)
|
| 74 |
+
|
| 75 |
+
all_context = pubmed_context + scholar_context
|
| 76 |
+
|
| 77 |
response = client.chat.completions.create(
|
| 78 |
model="llama-3.3-70b-versatile",
|
| 79 |
messages=[
|
| 80 |
+
{"role":"system","content":"""You are CardioLab AI built on Biomni from Stanford SNAP Lab.
|
| 81 |
+
Expert in SJSU Biomedical Engineering research.
|
| 82 |
+
IMPORTANT RULES:
|
| 83 |
+
1. NEVER invent or generate paper titles or URLs
|
| 84 |
+
2. ONLY refer to papers provided in the context below
|
| 85 |
+
3. Always say which source you are using
|
| 86 |
+
4. If you do not know something say so clearly
|
| 87 |
+
|
| 88 |
+
CARDIOLAB KNOW-HOW:
|
| 89 |
+
""" + KNOWHOW},
|
| 90 |
+
{"role":"user","content":"Research question: " + question + "\n\nReal papers found (use ONLY these):\n" + all_context[:4000] + "\n\nAnswer the question using only the above sources."}
|
| 91 |
],
|
| 92 |
+
max_tokens=600
|
| 93 |
)
|
| 94 |
+
|
| 95 |
+
answer = response.choices[0].message.content
|
| 96 |
+
|
| 97 |
+
# Add REAL links section — only verified URLs
|
| 98 |
+
real_links_section = ""
|
| 99 |
+
if pubmed_links:
|
| 100 |
+
real_links_section += "\n\n📚 VERIFIED PUBMED LINKS:\n" + "\n".join(pubmed_links[:5])
|
| 101 |
+
if scholar_links:
|
| 102 |
+
real_links_section += "\n\n🎓 VERIFIED SCHOLAR LINKS:\n" + "\n".join(scholar_links[:5])
|
| 103 |
+
|
| 104 |
+
return answer + real_links_section
|
| 105 |
|
| 106 |
def piv_tool(velocity, shear, hr):
|
| 107 |
v = "HIGH - stenosis risk" if float(velocity)>2.0 else "NORMAL"
|
|
|
|
| 120 |
|
| 121 |
with gr.Blocks(title="CardioLab AI - SJSU") as demo:
|
| 122 |
gr.Markdown("# CardioLab AI Agent")
|
| 123 |
+
gr.Markdown("### SJSU Biomedical Engineering | Biomni + Llama 70B + PubMed + Semantic Scholar")
|
| 124 |
+
gr.Markdown("**All paper links are verified real URLs only** | GitHub: github.com/pranatechsol/Cardio-Lab-Ai")
|
| 125 |
with gr.Tab("Research Assistant"):
|
| 126 |
+
gr.Markdown("### Searches PubMed + Semantic Scholar — only real verified links")
|
| 127 |
+
q = gr.Textbox(label="Research question", placeholder="e.g. Methods for MHV thrombogenicity detection")
|
| 128 |
+
a = gr.Textbox(label="Answer with verified citations", lines=14)
|
| 129 |
gr.Button("Search & Answer").click(ask_agent, inputs=q, outputs=a)
|
| 130 |
with gr.Tab("PIV Analysis"):
|
| 131 |
gr.Markdown("### Analyze PIV flow data from Mock Circulatory Loop")
|