same899 commited on
Commit
b089945
·
verified ·
1 Parent(s): d39393f

Upload caption.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. caption.py +135 -0
caption.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import json
4
+ import os
5
+
6
+ import torch
7
+ from accelerate import PartialState
8
+ from PIL import Image
9
+ from tqdm import tqdm
10
+ from transformers import AutoModel, AutoTokenizer
11
+
12
+
13
+ class caption_processor:
14
+ def __init__(self, vlm_name, device):
15
+ self.vlm = AutoModel.from_pretrained(
16
+ vlm_name,
17
+ trust_remote_code=True,
18
+ attn_implementation="flash_attention_2",
19
+ torch_dtype=torch.bfloat16,
20
+ )
21
+ self.vlm_tokenizer = AutoTokenizer.from_pretrained(
22
+ vlm_name, trust_remote_code=True
23
+ )
24
+
25
+ self.vlm = self.vlm.eval().to(device)
26
+ self.prompt = """
27
+ 1. describe the image in brief, Avoid using phrases in [In the/The image/scene shows/contains/is a] in the captions, directly describe the contents.
28
+ 2. Imagine this picture is the first frame of a 5-second video. Please describe the video and add dynamics, including the movement of objects and themes, as well as the overall camera movement.Avoid using phrases in [In the/The video/scene shows/contains/is a] in the descriptions, directly describe the contents.
29
+ 3. Please output in JSON format.{"caption": "...","video_description": "..."}
30
+ """ # noqa: E501
31
+
32
+ def str_2_json(self, str):
33
+ # Find the first occurrence of '{'
34
+ start_idx = str.find("{")
35
+ if start_idx == -1:
36
+ return None
37
+
38
+ # Find the last occurrence of '}'
39
+ end_idx = str.rfind("}")
40
+ if end_idx == -1 or end_idx <= start_idx:
41
+ return None
42
+
43
+ # Extract the JSON string
44
+ json_str = str[start_idx : end_idx + 1]
45
+
46
+ # Load and return the JSON
47
+ try:
48
+ import json
49
+
50
+ return json.loads(json_str)
51
+ except json.JSONDecodeError:
52
+ return None
53
+
54
+ def process(self, image):
55
+ msgs = [{"role": "user", "content": [image, self.prompt]}]
56
+
57
+ answer = self.vlm.chat(
58
+ msgs=msgs, tokenizer=self.vlm_tokenizer, enable_thinking=False, stream=False
59
+ )
60
+
61
+ dict_answer = self.str_2_json(answer)
62
+ if dict_answer is None:
63
+ return {"response": answer}
64
+
65
+ return dict_answer
66
+
67
+
68
+ def get_images_from_path(path):
69
+ if os.path.isdir(path):
70
+ return glob.glob(os.path.join(path, "*.jpg")) + glob.glob(
71
+ os.path.join(path, "*.png")
72
+ )
73
+ elif os.path.isfile(path) and (path.endswith(".jpg") or path.endswith(".png")):
74
+ return [path]
75
+ else:
76
+ return []
77
+
78
+
79
+ def parse_args():
80
+ parser = argparse.ArgumentParser(description="Caption processor")
81
+ parser.add_argument("--vlm_name", type=str, required=True)
82
+ parser.add_argument("--output_dir", type=str, required=True)
83
+ parser.add_argument("--paths", type=str, required=True, nargs="+")
84
+ return parser.parse_args()
85
+
86
+
87
+ if __name__ == "__main__":
88
+ distributed_state = PartialState()
89
+ args = parse_args()
90
+ output_dir = args.output_dir
91
+ os.makedirs(output_dir, exist_ok=True)
92
+
93
+ vlm_name = args.vlm_name
94
+ paths = args.paths
95
+ all_paths = []
96
+ for path in paths:
97
+ images = get_images_from_path(path)
98
+ all_paths.extend(images)
99
+ print("found", len(all_paths), "images")
100
+
101
+ processor = caption_processor(
102
+ vlm_name,
103
+ distributed_state.device,
104
+ )
105
+ with distributed_state.split_between_processes(
106
+ all_paths, apply_padding=False
107
+ ) as batched_paths:
108
+ print("GPU", distributed_state.device, "found", len(batched_paths), "images")
109
+
110
+ for path in tqdm(batched_paths, desc="Processing images"):
111
+ try:
112
+ json_path = os.path.join(output_dir, os.path.basename(path) + ".json")
113
+ if os.path.exists(json_path):
114
+ print(f"File {json_path} already exists, skipping.")
115
+ continue
116
+
117
+ image = Image.open(path)
118
+ output = None
119
+
120
+ for _ in range(3):
121
+ output = processor.process(image)
122
+ if output is not None:
123
+ break
124
+
125
+ if output is None:
126
+ raise Exception("Failed to process image after 3 attempts")
127
+ else:
128
+ with open(
129
+ json_path,
130
+ "w",
131
+ encoding="utf-8",
132
+ ) as f:
133
+ json.dump(output, f, ensure_ascii=False, indent=2)
134
+ except Exception as e:
135
+ print(f"Error processing {path}: {e}")