Download runtime/graphkit/_graph.py from VISAI-AI/icj-citation-graph: direct link, hf CLI and curl.
- Browser
- Download file 2.17 kB
-
https://huggingface.co/datasets/VISAI-AI/icj-citation-graph/resolve/main/runtime/graphkit/_graph.py
- Command line
-
hf download hf://datasets/VISAI-AI/icj-citation-graph/runtime/graphkit/_graph.py
-
curl -L -o _graph.py https://huggingface.co/datasets/VISAI-AI/icj-citation-graph/resolve/main/runtime/graphkit/_graph.py
2.17 kB
| import os | |
| import re | |
| from neo4j import GraphDatabase | |
| def identifier(value): | |
| if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', value): | |
| raise ValueError('Invalid Cypher identifier: ' + value) | |
| return '`' + value + '`' | |
| class Graph: | |
| def __init__(self): | |
| self.driver = GraphDatabase.driver(os.getenv('NEO4J_URI', 'bolt://neo4j:7687'), auth=(os.getenv('NEO4J_USERNAME', 'neo4j'), os.environ['NEO4J_PASSWORD']), notifications_min_severity='OFF') | |
| self.database = os.getenv('NEO4J_DATABASE', 'neo4j') | |
| def run(self, query, **params): | |
| with self.driver.session(database=self.database) as session: | |
| return [dict(record) for record in session.run(query, **params)] | |
| def check_source(self, target, prop, source): | |
| p = identifier(prop) | |
| marker = identifier(prop + '__source') | |
| mismatch = self.run(f'MATCH (n:{target.label}) WHERE n.{p} IS NOT NULL AND (n.{marker} IS NULL OR n.{marker} <> $source) RETURN count(n) AS n', source=source)[0]['n'] | |
| if mismatch: | |
| raise ValueError(f'{mismatch} existing vectors have different or unknown provenance. Use a different --property or a fresh graph.') | |
| def missing(self, target, ids, prop): | |
| rows = self.run(f'UNWIND $ids AS key OPTIONAL MATCH (n:{target.label} {{{target.key}:key}}) RETURN key,n IS NOT NULL AS found,n.{identifier(prop)} IS NULL AS missing', ids=ids) | |
| if len(rows) != len(ids) or not all(row['found'] for row in rows): | |
| raise ValueError('Parquet keys do not match this graph snapshot.') | |
| return {row['key'] for row in rows if row['missing']} | |
| def write(self, target, prop, source, rows): | |
| if not rows: | |
| return | |
| result = self.run(f'UNWIND $rows AS row MATCH (n:{target.label} {{{target.key}:row.key}}) WHERE n.{identifier(prop)} IS NULL SET n.{identifier(prop)}=row.vector,n.{identifier(prop + "__source")}=$source RETURN count(n) AS n', rows=rows, source=source) | |
| if result[0]['n'] != len(rows): | |
| raise RuntimeError('Graph changed during writing; stop concurrent vector writers and retry.') | |
| def close(self): | |
| self.driver.close() | |