Spaces:
Sleeping
Sleeping
Download api/graph.py from hodoly163/krishibondhu-api: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/spaces/hodoly163/krishibondhu-api/resolve/main/api/graph.py
- Command line
-
hf download hf://spaces/hodoly163/krishibondhu-api/api/graph.py
-
curl -L -o graph.py https://huggingface.co/spaces/hodoly163/krishibondhu-api/resolve/main/api/graph.py
5.05 kB
| """Embedded Kuzu graph DB for the crop -> disease -> treatment knowledge graph. | |
| Seeded from the same dict the retriever uses; any failure degrades to the | |
| dict-based fallback in api.rag.store. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| DB_PATH = ROOT / "data" / "kb_graph.kuzu" | |
| _conn = None | |
| _ready = False | |
| def _c(): | |
| global _conn | |
| if _conn is None: | |
| import kuzu | |
| DB_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| _conn = kuzu.Connection(kuzu.Database(str(DB_PATH))) | |
| for stmt in ( | |
| "CREATE NODE TABLE IF NOT EXISTS Crop(name STRING, PRIMARY KEY(name))", | |
| "CREATE NODE TABLE IF NOT EXISTS Disease(name STRING, PRIMARY KEY(name))", | |
| "CREATE NODE TABLE IF NOT EXISTS Treatment(name STRING, PRIMARY KEY(name))", | |
| "CREATE NODE TABLE IF NOT EXISTS Meta(name STRING, PRIMARY KEY(name))", | |
| "CREATE REL TABLE IF NOT EXISTS HAS_DISEASE(FROM Crop TO Disease)", | |
| "CREATE REL TABLE IF NOT EXISTS TREATS(FROM Disease TO Treatment)", | |
| "CREATE REL TABLE IF NOT EXISTS RELATED(FROM Disease TO Disease)", | |
| ): | |
| _conn.execute(stmt) | |
| return _conn | |
| def _rows(result): | |
| out = [] | |
| while result.has_next(): | |
| out.append(result.get_next()) | |
| return out | |
| def ensure(graph: dict) -> bool: | |
| """Seed the graph once from {entity: {diseases, crops, treatments, related}}.""" | |
| global _ready | |
| if _ready: | |
| return True | |
| try: | |
| c = _c() | |
| if _rows(c.execute("MATCH (m:Meta {name:'seeded'}) RETURN m.name")): | |
| _ready = True | |
| return True | |
| crops = {k for k, v in graph.items() if v.get("diseases")} | |
| diseases = {k for k, v in graph.items() if v.get("crops") or v.get("treatments")} | |
| treatments = {t for v in graph.values() for t in v.get("treatments", [])} | |
| for name in crops: | |
| c.execute("CREATE (:Crop {name:$n})", {"n": name}) | |
| for name in diseases | {"general"}: | |
| c.execute("CREATE (:Disease {name:$n})", {"n": name}) | |
| for name in treatments: | |
| c.execute("CREATE (:Treatment {name:$n})", {"n": name}) | |
| for crop, node in graph.items(): | |
| for disease in node.get("diseases", []): | |
| c.execute( | |
| "MATCH (a:Crop {name:$a}), (b:Disease {name:$b}) " | |
| "CREATE (a)-[:HAS_DISEASE]->(b)", | |
| {"a": crop, "b": disease}, | |
| ) | |
| for treatment in node.get("treatments", []): | |
| c.execute( | |
| "MATCH (a:Disease {name:$a}), (b:Treatment {name:$b}) " | |
| "CREATE (a)-[:TREATS]->(b)", | |
| {"a": crop, "b": treatment}, | |
| ) | |
| for related in node.get("related", []): | |
| c.execute( | |
| "MATCH (a:Disease {name:$a}), (b:Disease {name:$b}) " | |
| "CREATE (a)-[:RELATED]->(b)", | |
| {"a": crop, "b": related}, | |
| ) | |
| c.execute("CREATE (:Meta {name:'seeded'})") | |
| _ready = True | |
| return True | |
| except Exception: | |
| return False | |
| def docs_for_entities(names) -> set: | |
| """Doc ids reachable in <=2 hops from query-mentioned entities.""" | |
| names = [n for n in set(names or []) if n] | |
| if not names: | |
| return set() | |
| try: | |
| c = _c() | |
| docs = set() | |
| for q in ( | |
| "MATCH (c:Crop)-[:HAS_DISEASE]->(d:Disease) WHERE c.name IN $names " | |
| "RETURN d.name", | |
| "MATCH (c:Crop)-[:HAS_DISEASE]->(d:Disease)-[:RELATED]->(r:Disease) " | |
| "WHERE c.name IN $names RETURN r.name", | |
| "MATCH (d:Disease)-[:RELATED]->(r:Disease) WHERE d.name IN $names " | |
| "RETURN r.name", | |
| ): | |
| docs.update(row[0] for row in _rows(c.execute(q, {"names": names}))) | |
| return docs | |
| except Exception: | |
| return set() | |
| def neighbors(entity: str) -> dict: | |
| key = (entity or "").lower().strip().replace(" ", "_") | |
| try: | |
| c = _c() | |
| diseases = [r[0] for r in _rows(c.execute( | |
| "MATCH (a:Crop)-[:HAS_DISEASE]->(d:Disease) WHERE a.name=$n RETURN d.name", | |
| {"n": key}, | |
| ))] | |
| crops = [r[0] for r in _rows(c.execute( | |
| "MATCH (a:Crop)-[:HAS_DISEASE]->(d:Disease) WHERE d.name=$n RETURN a.name", | |
| {"n": key}, | |
| ))] | |
| treatments = [r[0] for r in _rows(c.execute( | |
| "MATCH (d:Disease)-[:TREATS]->(t:Treatment) WHERE d.name=$n RETURN t.name", | |
| {"n": key}, | |
| ))] | |
| related = [r[0] for r in _rows(c.execute( | |
| "MATCH (d:Disease)-[:RELATED]->(r:Disease) WHERE d.name=$n RETURN r.name", | |
| {"n": key}, | |
| ))] | |
| return {"entity": entity, "diseases": diseases, "crops": crops, | |
| "treatments": treatments, "related": related} | |
| except Exception: | |
| return {"entity": entity, "diseases": [], "crops": [], "treatments": [], "related": []} | |