"""Generate a leveled reference-question CSV from a knowledge graph. Authors: Simon Schramm (simon.schramm@bmw.de) and Dominik Sammet (dominik.sammet@bmw.de) This standalone script reads a graph JSON file containing ``nodes`` and ``relationships`` and writes a CSV with the columns user_group, reference_question, category, level, reference_answer, reference_evidence, and all_node_ids. A template CSV can optionally be supplied to match its question distribution. Requirements: Python 3.11 or newer. Uses only the Python standard library. Usage: python create_reference_questions_standalone.py graph.json python create_reference_questions_standalone.py graph.json \ --template reference_questions_template.csv \ --output reference_questions.csv """ import argparse import csv import itertools import json import re from pathlib import Path from typing import Optional class KnowledgeGraphQuestionGenerator: def __init__(self, json_path: Path): with json_path.open("r", encoding="utf-8") as graph_file: self.data = json.load(graph_file) self.nodes = self.data["nodes"] self.relationships = self.data["relationships"] self.node_by_id = {node["id"]: node for node in self.nodes} self.caption_to_ids = {} for node in self.nodes: self.caption_to_ids.setdefault(normalize(node["caption"]), []).append(node["id"]) self.labels = set( itertools.chain.from_iterable(node.get("labels", []) for node in self.nodes) ) self.property_keys = set( itertools.chain.from_iterable( node.get("properties", {}).keys() for node in self.nodes ) ) def questions_node_and_label(self): questions = [] for label in self.labels: questions.append(f"Which nodes have the label '{label}'?") for node in self.nodes: questions.append( f"Which nodes are labeled as '{', '.join(node.get('labels', []))}'?" ) questions.append(f"Which node represents '{node['caption']}'?") return questions def questions_node_properties(self): questions = [] for node in self.nodes: for prop in node.get("properties", {}): questions.append( f"What is the value of property '{prop}' for node '{node['caption']}'?" ) questions.append( f"What properties are associated with the node '{node['caption']}'?" ) for prop in self.property_keys: questions.append(f"Which nodes have the property '{prop}'?") return questions def questions_relationships(self): questions = [] rel_types = set(rel["type"] for rel in self.relationships) for rel_type in rel_types: for node in self.nodes: questions.append( f"Which nodes are connected to '{node['caption']}' via a '{rel_type}' relationship?" ) for rel in self.relationships: from_caption = self.node_by_id[rel["fromId"]]["caption"] to_caption = self.node_by_id[rel["toId"]]["caption"] questions.append( f"What is the relationship type between '{from_caption}' and '{to_caption}'?" ) return questions def questions_paths(self): questions = [] captions = [node["caption"] for node in self.nodes] for start, end in itertools.permutations(captions, 2): questions.append(f"What is the shortest path from '{start}' to '{end}'?") for rel_type in set(rel["type"] for rel in self.relationships): for node in self.nodes: questions.append( f"Which nodes form a chain of '{rel_type}' relationships starting from '{node['caption']}'?" ) return questions def questions_topology(self): questions = [] for node in self.nodes: questions.append(f"How many nodes are connected to '{node['caption']}'?") questions.append("Which node has the highest number of outgoing relationships?") questions.append( f"Are there any cycles present in the graph starting from '{node['caption']}'?" ) questions.append( "Which nodes act as hubs, connecting multiple scenarios or events?" ) return questions def questions_scenarios(self): questions = [] scenario_nodes = [ node for node in self.nodes if "Scenario" in node.get("labels", []) ] for scenario in scenario_nodes: questions.append( f"What are the key events and effects in the '{scenario['caption']}' scenario?" ) questions.append( f"Which events are unique to the '{scenario['caption']}' scenario?" ) questions.append( f"In the '{scenario['caption']}' scenario, what sequence of events leads to a given effect?" ) return questions def questions_attribute_filtering(self): questions = [] for prop in self.property_keys: for node in self.nodes: value = node.get("properties", {}).get(prop) if value: questions.append(f"List all nodes with the property '{prop}': '{value}'") for node in self.nodes: if len(node.get("labels", [])) > 1: questions.append( f"Which nodes have both the labels {', '.join(node['labels'])}?" ) return questions def questions_temporal(self): questions = [f"Which events are scheduled to occur in {year}?" for year in range(2020, 2031)] for scenario in [ node for node in self.nodes if "Scenario" in node.get("labels", []) ]: questions.append( f"What is the earliest event in the '{scenario['caption']}' scenario?" ) for node in self.nodes: if not node.get("properties", {}).get("END"): questions.append("Which nodes have an undefined END date?") return questions def questions_navigation(self): questions = [] captions = [node["caption"] for node in self.nodes] for start, end in itertools.permutations(captions, 2): questions.append(f"How would you reach '{end}' starting from '{start}'?") questions.append(f"Which nodes are two steps away from '{start}'?") return questions def all_questions(self): return { "Node and Label Identification": self.questions_node_and_label(), "Node Properties": self.questions_node_properties(), "Relationships and Connections": self.questions_relationships(), "Path and Sequence Analysis": self.questions_paths(), "Topological Queries": self.questions_topology(), "Scenario-Specific Questions": self.questions_scenarios(), "Attribute-Based Filtering": self.questions_attribute_filtering(), "Temporal Reasoning": self.questions_temporal(), "Graph Navigation": self.questions_navigation(), } def normalize(text: str) -> str: return re.sub(r"\s+", " ", text.strip().lower()) def unique_preserve_order(items: list[str]) -> list[str]: seen = set() result = [] for item in items: if item not in seen: seen.add(item) result.append(item) return result def extract_quoted_terms(text: str) -> list[str]: terms = re.findall(r"'([^']+)'|\"([^\"]+)\"", text) return [single or double for single, double in terms if single or double] def infer_node_ids_from_question(question: str, caption_to_ids: dict[str, list[str]]) -> str: matched_ids = [] for term in extract_quoted_terms(question): matched_ids.extend(caption_to_ids.get(normalize(term), [])) return "[" + ", ".join(unique_preserve_order(matched_ids)) + "]" def compose_level_question(base_question: str, user_group: str, level: int) -> str: question = base_question.strip() if level == 1: return question if user_group == "Graph Maintainer": if level == 2: return ( f"Could you please provide a thorough and detailed answer to: '{question}' " "Including any relevant context or associated information to facilitate " "graph management and future updates?" ) return ( "For comprehensive scenario planning and continued data integrity, kindly " f"elaborate fully on the following: '{question}' Please include expanded explanations, " "related graph concepts, synonyms, and any practical recommendations for " "maintaining and updating the scenario knowledge graph." ) if level == 2: return ( f"I would like to know {question.rstrip('?')}. " "They are seeking additional context." ) return ( "Could you provide a detailed explanation for the following: " f"'{question}' including practical implications for scenario planning?" ) def compose_scenario_level1_variant(base_question: str, variant_index: int) -> str: question = base_question.strip() stem = question.rstrip("?").rstrip(".") lower_stem = stem[:1].lower() + stem[1:] if stem else stem variants = [ question, f"I would like to know {lower_stem}.", f"Tell me about {lower_stem}.", f"{question} They are looking for this information.", ] return variants[variant_index % len(variants)] def get_target_distribution(template_csv: Optional[Path]) -> dict[tuple[str, str, int], int]: if template_csv is None: return {} counts = {} with template_csv.open(newline="", encoding="utf-8-sig") as infile: for row in csv.DictReader(infile): user_group = (row.get("user_group") or "").strip() level_raw = (row.get("level") or "").strip() category = (row.get("category") or "").strip() if ( user_group in {"Graph Maintainer", "Scenario Team Member"} and level_raw in {"1", "2", "3"} and category ): key = (category, user_group, int(level_raw)) counts[key] = counts.get(key, 0) + 1 return counts def generate_reference_questions_table( generator: KnowledgeGraphQuestionGenerator, output_file: Path, gold_template_csv: Optional[Path] = None, ) -> Path: questions_by_category = generator.all_questions() target_distribution = get_target_distribution(gold_template_csv) fieldnames = [ "user_group", "reference_question", "category", "level", "reference_answer", "reference_evidence", "all_node_ids", ] output_file.parent.mkdir(parents=True, exist_ok=True) with output_file.open("w", newline="", encoding="utf-8") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for category, questions in questions_by_category.items(): base_questions = unique_preserve_order(questions) if not base_questions: continue category_has_target = any(key[0] == category for key in target_distribution) if category_has_target: for user_group in ("Scenario Team Member", "Graph Maintainer"): for level in (1, 2, 3): target_count = target_distribution.get((category, user_group, level), 0) for index in range(target_count): base_question = base_questions[index % len(base_questions)] if user_group == "Scenario Team Member" and level == 1: question = compose_scenario_level1_variant(base_question, index) else: question = compose_level_question(base_question, user_group, level) writer.writerow({ "user_group": user_group, "reference_question": question, "category": category, "level": level, "reference_answer": "", "reference_evidence": "", "all_node_ids": infer_node_ids_from_question( question, generator.caption_to_ids ), }) else: for base_question in base_questions: for user_group in ("Scenario Team Member", "Graph Maintainer"): for level in (1, 2, 3): question = compose_level_question(base_question, user_group, level) writer.writerow({ "user_group": user_group, "reference_question": question, "category": category, "level": level, "reference_answer": "", "reference_evidence": "", "all_node_ids": infer_node_ids_from_question( question, generator.caption_to_ids ), }) return output_file def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__.split("\n", maxsplit=1)[0]) parser.add_argument("graph", type=Path, help="Path to the knowledge-graph JSON file") parser.add_argument( "--template", type=Path, help="Optional reference-question CSV used to match category/user-group/level counts", ) parser.add_argument( "--output", type=Path, default=Path("reference_questions.csv"), help="Output CSV path (default: reference_questions.csv)", ) return parser.parse_args() def main() -> None: args = parse_args() generator = KnowledgeGraphQuestionGenerator(args.graph) questions_by_category = generator.all_questions() for category, questions in questions_by_category.items(): print(f"## {category}: {len(questions)} generated base questions") output_file = generate_reference_questions_table( generator, args.output, gold_template_csv=args.template, ) print(f"Reference question table generated: {output_file}") if __name__ == "__main__": main()