File size: 12,731 Bytes
a2ffd07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Convert bathroom_toilet/all_captions.json + checkpoint data into EFUF training format.

Produces:
  - pos_neg.json: Per-object/subsentence entries for positive and negative training
  - sentences.json: Whole-caption positive reinforcement entries
  - dummy_vqa.json: Minimal VQA data for EFUF DataLoader compatibility

Usage:
    python scripts/format_bathroom_data.py \
        --all_captions data/bathroom_toilet/all_captions.json \
        --ckpt_json data/bathroom_toilet/all_captions.json.ckpt.json \
        --visedit_ckpt ../VisEdit/data/hallucination/bathroom_toilet/checkpoint.json \
        --image_dir ../VisEdit/data/hallucination/bathroom_toilet/images \
        --output_dir data/bathroom_toilet \
        --mode synthetic
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shutil
from pathlib import Path


SUBSENTENCE_SPLITTER = ",.;!?:"

TARGET_WORDS = ["toilet", "toilets"]

NEGATIVE_SCORE = 0.0
POSITIVE_SCORE = 40.0
SENTENCE_MEAN_POS = 40.0
SENTENCE_MIN_POS = 35.0
SENTENCE_MEAN_NEG = 10.0
SENTENCE_MIN_NEG = 5.0


def find_subsentence(text: str, target_words: list[str]) -> tuple[int, int] | None:
    """Find the subsentence containing any of the target words.

    Returns (start, end) character indices of the subsentence within text,
    or None if not found.
    """
    sub_sentences = re.split(f"[{SUBSENTENCE_SPLITTER}]+", text)
    for sub in sub_sentences:
        for word in target_words:
            pattern = r"\b" + re.escape(word) + r"\b"
            if re.search(pattern, sub, re.IGNORECASE):
                start = text.find(sub)
                end = start + len(sub)
                return start, end
    return None


def is_valid_toilet_mention(caption: str) -> bool:
    """Check if 'toilet' (or 'toilets') appears as a whole word, not as part
    of 'toiletries' etc."""
    lower = caption.lower()
    for word in TARGET_WORDS:
        pattern = r"\b" + re.escape(word) + r"\b"
        if re.search(pattern, lower):
            return True
    return False


def main():
    parser = argparse.ArgumentParser(description="Format bathroom_toilet data for EFUF training")
    parser.add_argument("--all_captions", default="data/bathroom_toilet/all_captions.json")
    parser.add_argument("--ckpt_json", default="data/bathroom_toilet/all_captions.json.ckpt.json")
    parser.add_argument(
        "--visedit_ckpt", default="../VisEdit/data/hallucination/bathroom_toilet/checkpoint.json"
    )
    parser.add_argument(
        "--image_dir", default="../VisEdit/data/hallucination/bathroom_toilet/images"
    )
    parser.add_argument("--output_dir", default="data/bathroom_toilet")
    parser.add_argument(
        "--mode",
        choices=["synthetic", "clip"],
        default="synthetic",
        help="synthetic: use fixed scores; clip: compute CLIP scores (not implemented yet)",
    )
    parser.add_argument("--unlearn_target", choices=["subsentence", "object"], default="subsentence")
    parser.add_argument("--symlink_dir", default=None, help="Create merged image directory with symlinks")
    args = parser.parse_args()

    with open(args.all_captions) as f:
        all_captions = json.load(f)

    with open(args.ckpt_json) as f:
        step_data = json.load(f)

    with open(args.visedit_ckpt) as f:
        visedit_ckpt = json.load(f)

    step2_judge = step_data.get("step2_judge_done", {})
    step3_rewrite = step_data.get("step3_rewrite_done", {})
    step4_strict = step_data.get("step4_strict_done", {})

    train_ids = set(visedit_ckpt["train_ids"])
    val_ids = set(visedit_ckpt["val_ids"])
    train_pos_ids = set(visedit_ckpt.get("train_pos_ids", []))
    val_pos_ids = set(visedit_ckpt.get("val_pos_ids", []))

    id_map = {item["image_id"]: item for item in all_captions}

    pos_neg_entries = []
    sentence_entries = []
    skipped_no_toilet = 0
    skipped_no_subsentence = 0
    skipped_no_image = 0

    train_img_dir = os.path.join(args.image_dir, "train")
    val_img_dir = os.path.join(args.image_dir, "val")

    def get_image_path(image_id: str) -> str | None:
        for d in [train_img_dir, val_img_dir]:
            p = os.path.join(d, f"{image_id}.jpg")
            if os.path.exists(p):
                return p
        return None

    def get_image_relpath(image_id: str) -> str:
        """Return relative path from image_dir for the image."""
        if image_id in train_ids or image_id in train_pos_ids:
            return f"train/{image_id}.jpg"
        elif image_id in val_ids or image_id in val_pos_ids:
            return f"val/{image_id}.jpg"
        else:
            for d in ["train", "val"]:
                if os.path.exists(os.path.join(args.image_dir, d, f"{image_id}.jpg")):
                    return f"{d}/{image_id}.jpg"
            return f"train/{image_id}.jpg"

    for item in all_captions:
        image_id = item["image_id"]
        caption = item["llava_caption"]
        toilet = item["toilet"]
        bathroom = item["bathroom"]

        if not is_valid_toilet_mention(caption):
            if toilet == 0 and bathroom == 1:
                sentence_entries.append(
                    {
                        "image": get_image_relpath(image_id),
                        "sentence": caption,
                        "mean": SENTENCE_MEAN_POS,
                        "min": SENTENCE_MIN_POS,
                    }
                )
            elif toilet == 1 and bathroom == 1:
                sentence_entries.append(
                    {
                        "image": get_image_relpath(image_id),
                        "sentence": caption,
                        "mean": SENTENCE_MEAN_POS,
                        "min": SENTENCE_MIN_POS,
                    }
                )
            continue

        if not get_image_path(image_id):
            skipped_no_image += 1
            continue

        if toilet == 0:
            # Check if this is a confirmed hallucination
            judgment = step2_judge.get(image_id)
            if judgment != "YES":
                skipped_no_toilet += 1
                continue

            result = find_subsentence(caption, TARGET_WORDS)
            if result is None:
                skipped_no_subsentence += 1
                continue
            start, end = result

            if args.unlearn_target == "subsentence":
                sentence = caption[:end].rstrip()
                position = start
                while position > 0 and sentence[position - 1] == " ":
                    position -= 1
                if position == 0:
                    position = start
            else:
                word_match = re.search(r"\b(toilet|toilets)\b", caption, re.IGNORECASE)
                if word_match is None:
                    skipped_no_subsentence += 1
                    continue
                start_pos = word_match.start()
                end_pos = word_match.end()
                sentence = caption[:end_pos]
                position = start_pos

            pos_neg_entries.append(
                {
                    "image": get_image_relpath(image_id),
                    "sentence": sentence,
                    "position": position,
                    "score": NEGATIVE_SCORE,
                    "type": "negative",
                }
            )

        elif toilet == 1:
            result = find_subsentence(caption, TARGET_WORDS)
            if result is None:
                skipped_no_subsentence += 1
                continue
            start, end = result

            if args.unlearn_target == "subsentence":
                sentence = caption[:end].rstrip()
                position = start
                while position > 0 and sentence[position - 1] == " ":
                    position -= 1
                if position == 0:
                    position = start
            else:
                word_match = re.search(r"\b(toilet|toilets)\b", caption, re.IGNORECASE)
                if word_match is None:
                    skipped_no_subsentence += 1
                    continue
                start_pos = word_match.start()
                end_pos = word_match.end()
                sentence = caption[:end_pos]
                position = start_pos

            pos_neg_entries.append(
                {
                    "image": get_image_relpath(image_id),
                    "sentence": sentence,
                    "position": position,
                    "score": POSITIVE_SCORE,
                    "type": "positive",
                }
            )

            sentence_entries.append(
                {
                    "image": get_image_relpath(image_id),
                    "sentence": caption,
                    "mean": SENTENCE_MEAN_POS,
                    "min": SENTENCE_MIN_POS,
                }
            )

    neg_count = sum(1 for e in pos_neg_entries if e["type"] == "negative")
    pos_count = sum(1 for e in pos_neg_entries if e["type"] == "positive")

    print(f"pos_neg.json: {len(pos_neg_entries)} entries ({neg_count} negative, {pos_count} positive)")
    print(f"sentences.json: {len(sentence_entries)} entries")
    print(f"Skipped: no_toilet_mention={skipped_no_toilet}, no_subsentence={skipped_no_subsentence}, no_image={skipped_no_image}")

    final_pos_neg = [
        {k: v for k, v in e.items() if k != "type"} for e in pos_neg_entries
    ]

    all_ids = train_ids | val_ids | train_pos_ids | val_pos_ids

    def split(entries):
        train_entries = [e for e in entries if e["image"].split("/")[0] == "train"]
        val_entries = [e for e in entries if e["image"].split("/")[0] == "val"]
        return train_entries, val_entries

    train_pos_neg, val_pos_neg = split(final_pos_neg)
    train_sentences, val_sentences = split(sentence_entries)

    print(f"Train pos_neg: {len(train_pos_neg)}, Val pos_neg: {len(val_pos_neg)}")
    train_neg = sum(1 for e in train_pos_neg if e["score"] == NEGATIVE_SCORE)
    train_pos = sum(1 for e in train_pos_neg if e["score"] == POSITIVE_SCORE)
    val_neg = sum(1 for e in val_pos_neg if e["score"] == NEGATIVE_SCORE)
    val_pos = sum(1 for e in val_pos_neg if e["score"] == POSITIVE_SCORE)
    print(f"  Train: {train_pos} positive, {train_neg} negative")
    print(f"  Val: {val_pos} positive, {val_neg} negative")
    print(f"Train sentences: {len(train_sentences)}, Val sentences: {len(val_sentences)}")

    os.makedirs(args.output_dir, exist_ok=True)

    for split_name, data in [("train", train_pos_neg), ("val", val_pos_neg)]:
        path = os.path.join(args.output_dir, f"pos_neg_{args.mode}_{split_name}.json")
        with open(path, "w") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        print(f"Saved {path} ({len(data)} entries)")

    for split_name, data in [("train", train_sentences), ("val", val_sentences)]:
        path = os.path.join(args.output_dir, f"sentences_{args.mode}_{split_name}.json")
        with open(path, "w") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        print(f"Saved {path} ({len(data)} entries)")

    pos_neg_path = os.path.join(args.output_dir, f"pos_neg_{args.mode}.json")
    with open(pos_neg_path, "w") as f:
        json.dump(final_pos_neg, f, indent=2, ensure_ascii=False)
    print(f"Saved {pos_neg_path}")

    sentences_path = os.path.join(args.output_dir, f"sentences_{args.mode}.json")
    with open(sentences_path, "w") as f:
        json.dump(sentence_entries, f, indent=2, ensure_ascii=False)
    print(f"Saved {sentences_path}")

    # Create a minimal dummy VQA dataset so the GoldData DataLoader doesn't crash
    dummy_vqa = [
        {
            "id": "dummy_001",
            "image": get_image_relpath(all_captions[0]["image_id"]),
            "conversations": [
                {"from": "human", "value": "<image>\nWhat is in this image?"},
                {"from": "gpt", "value": all_captions[0]["llava_caption"][:100]},
            ],
        }
    ]
    vqa_path = os.path.join(args.output_dir, "dummy_vqa.json")
    with open(vqa_path, "w") as f:
        json.dump(dummy_vqa, f, indent=2)
    print(f"Saved {vqa_path}")

    if args.symlink_dir:
        os.makedirs(args.symlink_dir, exist_ok=True)
        for entry in pos_neg_entries + sentence_entries:
            src = get_image_path(entry["image"].split("/")[-1].replace(".jpg", ""))
            if src and os.path.exists(src):
                dst = os.path.join(args.symlink_dir, os.path.basename(src))
                if not os.path.exists(dst):
                    os.symlink(os.path.abspath(src), dst)
        print(f"Created symlink directory at {args.symlink_dir}")


if __name__ == "__main__":
    main()