File size: 7,586 Bytes
9ee6f68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# %%
import os
import sys
import argparse


script_dir = os.path.dirname(os.path.abspath(__file__))
# sys.path.append("d:/workplace/scene_graph/task_generation/")
# NOTE: VLM-only imports (visualize_scene_sapien / VLMVoter /
# TaskFeasibilityEvaluator / vlm_interactor) are deferred to the point of use
# so that ``--skip_vlm_vote`` can run without VLMEvalKit or Vulkan installed.
from src.preprocessing import RawSceneParserFactory
from src.utils.config_manager import ConfigManager
from src.core import gen_scene_graph
from src.core.outcome_based_task_generation import (
    OutcomeBasedTaskGenerator,
    OutcomeBasedTaskPattern,
)


import pickle
import random
import time
from enum import Enum
import colorama
from colorama import Fore, Style
import glog

import copy
import json

# %%


def parse_arguments():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(description="Task Generation System")

    # Basic configuration
    parser.add_argument(
        "--config",
        type=str,
        default=None,
        help="Path to the configuration file, None for default config.",
    )

    parser.add_argument(
        "--output_dir",
        type=str,
        default=None,
        help="Output directory for results",
    )

    

    parser.add_argument(
        "--scene_graph_pkl_load_path",
        type=str,
        default=None,
        help="Path to load pre-generated scene graph pickle file, None to generate from JSON.",
    )

    parser.add_argument(
        "--rename_dict_path",
        type=str,
        default=None,
        help="Path to the renaming dictionary JSON file, None to skip renaming.",
    )

    # The default value is set the same as in config_manager.py.

    parser.add_argument(
        "--vlm_list",
        type=str,
        nargs="+",
        default=[
            "openai/gpt-4.1",
            "anthropic/claude-3.5-haiku",
            "google/gemini-2.5-flash-lite-preview-06-17",
        ],
        help="List of VLM models to use.",
    )

    parser.add_argument(
        "--manitaskot_pattern_file",
        type=str,
        default="./src/utils/manitask-ot200/manitask_ot200.txt",
        help="Path to the file containing ManiTaskOT patterns, one per line.",
    )

    parser.add_argument(
        "--outcome_based_task_txt_save_path",
        type=str,
        default="./data/output/outcome_based_task.txt",
        help="Directory to save outputs like images and logs.",
    )

    parser.add_argument(
        "--skip_vlm_vote",
        action="store_true",
        default=False,
        help="Skip VLM feasibility voting entirely (no API keys, no SAPIEN "
        "render scene needed). All successfully-bound candidates are written "
        "out with voting_status='not_run'.",
    )

    return parser.parse_args()


def update_config_from_args(config_manager, args):
    """Update configuration using command line arguments, command line args have higher priority"""
    config_dict = {}

    args_dict = vars(args)
    for key, value in args_dict.items():
        if value is not None:
            config_dict[key] = value

    config_manager._update_config_from_dict(config_dict)


def main(args):

    os.environ["KMP_DUPLICATE_LIB_OK"] = "True"

    # 0. Initialize the configuration manager
    # We only need to load the config once.

    config_path = args.config
    run_dir = args.output_dir

    glog.info(args.output_dir)
    glog.info(args.config)
    config_manager = ConfigManager(config_file_path=config_path, run_dir=run_dir)

    update_config_from_args(config_manager, args)
    # export the final config in this run, named by the timestamp

    if not os.path.exists(config_manager.config_file_export_dir):
        os.makedirs(config_manager.config_file_export_dir)

    config_manager.save_to_yaml_staged(
        os.path.join(
            config_manager.config_file_export_dir,
            f"used_config_{int(time.time())}.yaml",
        )
    )

    glog.info(args.output_dir)
    glog.info(args.config)


    main_config = config_manager.config

    input_json_path = main_config.input_json_path
    output_json_path = main_config.output_json_path
    entity_json_path = main_config.entity_json_path


    scene_graph_pkl_load_path = main_config.scene_graph_pkl_load_path

    rename_dict_path = main_config.rename_dict_path

    skip_vlm_vote = bool(getattr(args, "skip_vlm_vote", False))

    # The SAPIEN render scene is only needed for VLM voting images (and the
    # renaming engine). When voting is skipped, do not create it at all so the
    # entry can run on CPU-only machines without Vulkan.
    scene = None
    if not skip_vlm_vote:
        from src.preprocessing import visualize_scene_sapien

        sapien_scene_manager = visualize_scene_sapien.SapienSceneManager()
        scene = sapien_scene_manager.create_scene()

    # 2 Generate the scene graph
    scene_graph = None
    if scene_graph_pkl_load_path is not None and os.path.exists(
        scene_graph_pkl_load_path
    ):
        glog.info(f"Loading scene graph from {scene_graph_pkl_load_path}")
        with open(scene_graph_pkl_load_path, "rb") as f:
            scene_graph = pickle.load(f)
    else:

        ts = time.perf_counter()
        json_tree_path = gen_scene_graph.load_json_file(entity_json_path)
        scene_graph = gen_scene_graph.gen_multi_layer_graph_with_free_space(
            json_tree_path
        )
        glog.info(f"scene graph tree generation time:  {time.perf_counter() - ts}")

    rename_dict_path = main_config.rename_dict_path
    rename_dict = {}
    if rename_dict_path is not None and os.path.exists(rename_dict_path):
        with open(rename_dict_path, "r") as f:
            rename_dict = json.load(f)
    else:
        glog.warning("No renaming dict found, using empty dict.")
        rename_dict = {}

    scene_graph.rename_all_features(rename_dict)
    if scene is not None:
        scene_graph.corresponding_scene = scene
    outcome_based_task_generator = OutcomeBasedTaskGenerator(scene_graph=scene_graph)
    outcome_based_task_generator.load_task_patterns(main_config.manitaskot_pattern_file)
    outcome_based_task_generator.generate_task_with_all_patterns()

    output_dir = main_config.outcome_based_task_txt_save_path
    os.makedirs(os.path.dirname(os.path.abspath(output_dir)), exist_ok=True)

    if skip_vlm_vote:
        # Vote-free mode: keep every successfully-bound candidate and record
        # that voting has not been run.
        candidates = outcome_based_task_generator.task_list
        skipped = 0
        with open(output_dir, "w") as f:
            for task in candidates:
                if task.task_description is None:
                    skipped += 1
                    continue
                f.write(f"[voting_status: not_run] {task}\n")
        glog.info(
            f"Skipped VLM voting. Wrote {len(candidates) - skipped} candidates "
            f"({skipped} unbindable pattern instantiations dropped) to {output_dir}"
        )
        return

    from src.core.outcome_based_task_generation import VLMVoter

    vlm_voter = VLMVoter()

    feasible_task_list = []
    for task in outcome_based_task_generator.task_list:
        task_is_feasible = vlm_voter.is_task_feasible(task, scene_graph)
        if task_is_feasible:
            feasible_task_list.append(task)

    with open(output_dir, "w") as f:
        for task in feasible_task_list:
            f.write(str(task) + "\n")


# %%

if __name__ == "__main__":

    """
    Args:




    """

    args = parse_arguments()
    main(args)


# %%