File size: 14,997 Bytes
cc61381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""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()