Spaces:
Runtime error
Runtime error
Download scripts/query_neo4j.py from derangedsaturnian/NasaKnowledgeEngine2025: direct link, hf CLI and curl.
- Browser
- Download file 8.72 kB
-
https://huggingface.co/spaces/derangedsaturnian/NasaKnowledgeEngine2025/resolve/main/scripts/query_neo4j.py
- Command line
-
hf download hf://spaces/derangedsaturnian/NasaKnowledgeEngine2025/scripts/query_neo4j.py
-
curl -L -o query_neo4j.py https://huggingface.co/spaces/derangedsaturnian/NasaKnowledgeEngine2025/resolve/main/scripts/query_neo4j.py
8.72 kB
| import os | |
| import json | |
| import numpy as np | |
| import requests | |
| from neo4j import GraphDatabase | |
| from dotenv import load_dotenv | |
| from pathlib import Path | |
| import time | |
| import re | |
| load_dotenv() | |
| NEO4J_URI = os.getenv("NEO4J_URI") | |
| NEO4J_USER = os.getenv("NEO4J_USERNAME") | |
| NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD") | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| if not HF_TOKEN: | |
| raise ValueError("HF_TOKEN not set") | |
| print(f"connecting to Neo4j at {NEO4J_URI} ...") | |
| driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD)) | |
| driver.verify_connectivity() | |
| print("neo4j connected") | |
| EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2" | |
| HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| def hf_embed_batch(texts, batch_size=16, retries=3, backoff=2): | |
| """generate embeddings using Hugging Face API""" | |
| all_embeddings = [] | |
| texts = [t if t is not None else "" for t in texts] | |
| for i in range(0, len(texts), batch_size): | |
| batch = texts[i:i+batch_size] | |
| for attempt in range(1, retries + 1): | |
| try: | |
| r = requests.post( | |
| "https://router.huggingface.co/hf-inference/models/sentence-transformers/all-MiniLM-L6-v2/pipeline/feature-extraction", | |
| headers=HF_HEADERS, | |
| json={"inputs": batch} | |
| ) | |
| r.raise_for_status() | |
| data = r.json() | |
| all_embeddings.extend(data) | |
| break | |
| except requests.exceptions.RequestException as e: | |
| print(f"attempt {attempt} failed: {e}") | |
| if attempt < retries: | |
| wait = backoff ** attempt | |
| print(f"retrying in {wait}s...") | |
| time.sleep(wait) | |
| else: | |
| raise RuntimeError(f"failed to get embeddings after {retries} attempts") from e | |
| return np.array(all_embeddings) | |
| def extract_keywords(query): | |
| """extraction of important keywords from query""" | |
| stopwords = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', | |
| 'of', 'with', 'by', 'from', 'about', 'which', 'what', 'where', 'when', | |
| 'who', 'how', 'is', 'are', 'was', 'were', 'be', 'been', 'being', | |
| 'relate', 'related', 'relates', 'research', 'study', 'studies', | |
| 'project', 'projects', 'publication', 'publications'} | |
| words = re.findall(r'\b[a-zA-Z]{3,}\b', query.lower()) | |
| keywords = [w for w in words if w not in stopwords] | |
| return keywords | |
| def cypher_search(query, session): | |
| keywords = extract_keywords(query) | |
| results = {} | |
| if keywords: | |
| keyword_pattern = '|'.join([f'(?i).*{kw}.*' for kw in keywords[:3]]) | |
| # Search by topics | |
| topic_query = """ | |
| MATCH (pub:Publication)-[:HAS_TOPIC]->(t:Topic) | |
| WHERE t.name =~ $pattern | |
| RETURN DISTINCT pub.pmc_id AS pmc_id, pub.title AS title, | |
| pub.abstract AS abstract, collect(t.name) AS topics | |
| LIMIT 10 | |
| """ | |
| topic_results = session.run(topic_query, pattern=keyword_pattern) | |
| results['by_topic'] = [dict(r) for r in topic_results] | |
| entity_query = """ | |
| MATCH (pub:Publication)-[:MENTIONS_ENTITY]->(e:Entity) | |
| WHERE e.name =~ $pattern OR e.type =~ $pattern | |
| RETURN DISTINCT pub.pmc_id AS pmc_id, pub.title AS title, | |
| pub.abstract AS abstract, collect(e.name + ' (' + e.type + ')') AS entities | |
| LIMIT 10 | |
| """ | |
| entity_results = session.run(entity_query, pattern=keyword_pattern) | |
| results['by_entity'] = [dict(r) for r in entity_results] | |
| text_query = """ | |
| MATCH (pub:Publication) | |
| WHERE pub.title =~ $pattern OR pub.abstract =~ $pattern | |
| RETURN pub.pmc_id AS pmc_id, pub.title AS title, pub.abstract AS abstract | |
| LIMIT 10 | |
| """ | |
| text_results = session.run(text_query, pattern=keyword_pattern) | |
| results['by_text'] = [dict(r) for r in text_results] | |
| project_query = """ | |
| MATCH (p:Project)-[:LINKS_TO]->(pub:Publication) | |
| WHERE pub.title =~ $pattern OR p.title =~ $pattern | |
| RETURN p.id AS project_id, p.title AS project_title, | |
| collect(DISTINCT pub.title) AS publications | |
| LIMIT 10 | |
| """ | |
| project_results = session.run(project_query, pattern=keyword_pattern) | |
| results['projects'] = [dict(r) for r in project_results] | |
| return results | |
| def format_answer(query, cypher_results, semantic_results=None): | |
| answer_parts = [] | |
| keywords = extract_keywords(query) | |
| if keywords: | |
| answer_parts.append(f"found results related to: {', '.join(keywords[:5])}\n") | |
| all_pubs = set() | |
| # topics | |
| if cypher_results.get('by_topic'): | |
| answer_parts.append("**Publications by Topic:**") | |
| for i, pub in enumerate(cypher_results['by_topic'][:3], 1): | |
| all_pubs.add(pub['pmc_id']) | |
| topics = ', '.join(pub.get('topics', [])[:3]) | |
| answer_parts.append(f"{i}. {pub['title']} (Topics: {topics})") | |
| answer_parts.append("") | |
| # entities | |
| if cypher_results.get('by_entity'): | |
| answer_parts.append("**Publications by Entities:**") | |
| for i, pub in enumerate(cypher_results['by_entity'][:3], 1): | |
| if pub['pmc_id'] not in all_pubs: | |
| all_pubs.add(pub['pmc_id']) | |
| entities = ', '.join(pub.get('entities', [])[:3]) | |
| answer_parts.append(f"{i}. {pub['title']} (Mentions: {entities})") | |
| answer_parts.append("") | |
| # proj | |
| if cypher_results.get('projects'): | |
| answer_parts.append("**Related Projects:**") | |
| for i, proj in enumerate(cypher_results['projects'][:3], 1): | |
| pubs = len(proj.get('publications', [])) | |
| answer_parts.append(f"{i}. {proj['project_title']} ({pubs} publications)") | |
| answer_parts.append("") | |
| # text matches | |
| if cypher_results.get('by_text'): | |
| answer_parts.append("**Direct Text Matches:**") | |
| for i, pub in enumerate(cypher_results['by_text'][:3], 1): | |
| if pub['pmc_id'] not in all_pubs: | |
| abstract = pub.get('abstract', '')[:150] + "..." if pub.get('abstract') else "" | |
| answer_parts.append(f"{i}. {pub['title']}\n {abstract}") | |
| answer_parts.append("") | |
| # adding semantic results if available | |
| if semantic_results: | |
| answer_parts.append("**Semantically Similar Publications:**") | |
| for i, (pmc_id, title, abstract) in enumerate(semantic_results[:3], 1): | |
| if pmc_id not in all_pubs: | |
| abstract_preview = abstract[:150] + "..." if abstract else "" | |
| answer_parts.append(f"{i}. {title}\n {abstract_preview}") | |
| if not answer_parts or len(answer_parts) <= 1: | |
| return "no results found! try rephrasing your query or using different keywords." | |
| return "\n".join(answer_parts) | |
| def get_pub_texts(): | |
| with driver.session() as session: | |
| res = session.run( | |
| "MATCH (p:Publication) RETURN p.pmc_id AS id, p.title AS title, p.abstract AS abstract" | |
| ) | |
| return [(r["id"], r["title"], r["abstract"]) for r in res] | |
| pub = get_pub_texts() | |
| print(f"loaded {len(pub)} publications from Neo4j") | |
| pub_texts = [f"{title} {abstract or ''}" for _, title, abstract in pub] | |
| cache_path = Path("/tmp/pub_embeddings.npy") | |
| if cache_path.exists(): | |
| print("loading cached embeddings...") | |
| embeddings = np.load(cache_path) | |
| else: | |
| print("generating embeddings (batched)...") | |
| embeddings = hf_embed_batch(pub_texts, batch_size=16) | |
| np.save(cache_path, embeddings) | |
| print(f"saved embeddings cache to {cache_path}") | |
| def semantic_search(query, top_k=5): | |
| q_emb = hf_embed_batch([query])[0] | |
| sims = [ | |
| (i, np.dot(q_emb, emb) / (np.linalg.norm(q_emb) * np.linalg.norm(emb))) | |
| for i, emb in enumerate(embeddings) | |
| ] | |
| sims.sort(key=lambda x: x[1], reverse=True) | |
| return [pub[i] for i, _ in sims[:top_k]] | |
| def hybrid_search(query): | |
| with driver.session() as session: | |
| cypher_results = cypher_search(query, session) | |
| semantic_results = semantic_search(query, top_k=5) | |
| answer = format_answer(query, cypher_results, semantic_results) | |
| return answer | |
| if __name__ == "__main__": | |
| test_queries = [ | |
| "which projects relate to mitochondrial research?", | |
| "what publications discuss cell biology?", | |
| "show me research about space radiation effects" | |
| ] | |
| for q in test_queries: | |
| print(f"\n{'='*60}") | |
| print(f"QUERY: {q}") | |
| print('='*60) | |
| ans = hybrid_search(q) | |
| print(ans) | |
| print() |