Medic / visualization.py
mgbam's picture
Add application file
b8986a1
raw
history blame
1.4 kB
import re
import tempfile
import os
from pyvis.network import Network
def extract_key_terms(text: str):
"""
A naive approach to extract key terms by matching capitalized words.
"""
return re.findall(r"\b[A-Z][a-zA-Z]+\b", text)
def create_medical_graph(query: str, docs: list) -> str:
"""
Builds a PyVis network:
- A central "QUERY" node.
- A node for each retrieved document.
- Sub-nodes for extracted key terms.
Returns the full HTML of the generated graph.
"""
net = Network(height="600px", width="100%", directed=False)
net.add_node("QUERY", label=f"Query: {query}", color="red", shape="star")
for i, doc in enumerate(docs):
doc_id = f"Doc_{i}"
net.add_node(doc_id, label=f"Abstract {i+1}", color="blue")
net.add_edge("QUERY", doc_id)
terms = extract_key_terms(doc)
for term in set(terms):
term_id = f"{doc_id}_{term}"
net.add_node(term_id, label=term, color="green")
net.add_edge(doc_id, term_id)
# Write the network HTML to a temporary file and return its content
with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as tmp:
temp_filename = tmp.name
net.show(temp_filename)
with open(temp_filename, "r", encoding="utf-8") as f:
html_content = f.read()
os.remove(temp_filename)
return html_content