import re import tempfile import os from pyvis.network import Network def extract_key_terms(text: str): """ A simple method to extract key terms by matching capitalized words. In a clinical context, this may highlight important entities. """ return re.findall(r"\b[A-Z][a-zA-Z]+\b", text) def create_medical_graph(query: str, docs: list) -> str: """ Creates an interactive knowledge graph using PyVis: - A central node for the query. - One node per abstract. - Sub-nodes for key terms extracted from each abstract. Returns the HTML content of the 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 graph to a temporary HTML 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