cemag commited on
Commit
50493b4
·
verified ·
1 Parent(s): a77d0eb

Upload data_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. data_utils.py +135 -0
data_utils.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from PIL import Image
3
+ import json
4
+ import random
5
+ from qwen_vl_utils import process_vision_info
6
+
7
+ prompt_template="What do you see?"
8
+ expert_template = """{{flowrate:{FLOW_RATE_VALUE}}}"""
9
+ answer_template="""The flowrate is {FLOW_RATE_VALUE}."""
10
+
11
+ with open("/home/cm2161/rds/hpc-work/llama-manufacturing/pr-intern/src/data/general_statements.json", 'r') as file:
12
+ general_statements = json.load(file)["general_statements"]
13
+ with open("/home/cm2161/rds/hpc-work/llama-manufacturing/pr-intern/src/data/qual_over_extrusion.json", 'r') as file:
14
+ qual_over_extrusion = json.load(file)["over_extrusion_statements"]
15
+ with open("/home/cm2161/rds/hpc-work/llama-manufacturing/pr-intern/src/data/qual_under_extrusion.json", 'r') as file:
16
+ qual_under_extrusion = json.load(file)["under_extrusion_statements"]
17
+ with open("/home/cm2161/rds/hpc-work/llama-manufacturing/pr-intern/src/data/qual_good_extrusion.json", 'r') as file:
18
+ qual_good_extrusion = json.load(file)["good_extrusion_statements"]
19
+ with open("/home/cm2161/rds/hpc-work/llama-manufacturing/pr-intern/src/data/quant_templates.json", 'r') as file:
20
+ quant_templates = json.load(file)["flow_rate_statements"]
21
+
22
+ ## note: reinstall bitsandbytes if not working. enforced version 0.37.2.
23
+
24
+ def synthesize_answer(sample, general=True, quant=True, qual=True):
25
+ final_statement = ""
26
+
27
+ # General statement
28
+ if general:
29
+ gs = random.choice(general_statements)["statement"]
30
+ final_statement += f"{gs} "
31
+
32
+ # Quantitative statement
33
+ if quant:
34
+ quant_statement = random.choice(quant_templates)["statement"]
35
+ quant_statement = quant_statement.format(flow_rate=sample["flow_rate"])
36
+ final_statement += f"{quant_statement} "
37
+
38
+ # Qualitative statement
39
+ if qual:
40
+ flow_rate = float(sample['flow_rate'])
41
+ if flow_rate < 90:
42
+ qual_statement = random.choice(qual_under_extrusion)["statement"]
43
+ elif flow_rate > 110:
44
+ qual_statement = random.choice(qual_over_extrusion)["statement"]
45
+ else:
46
+ qual_statement = random.choice(qual_good_extrusion)["statement"]
47
+ final_statement += f"{qual_statement}"
48
+
49
+ return final_statement.strip()
50
+
51
+
52
+ def format_data(sample, image=True, fr= False, train=True):
53
+
54
+ formatted_data = {"messages": [{"role": "user","content": []}]}
55
+
56
+ if image:
57
+ formatted_data["messages"][0]["content"].append(
58
+ {
59
+ "type": "image","image": Image.open(sample["full_img_path"]),
60
+ }
61
+ )
62
+
63
+ if fr:
64
+ formatted_data["messages"][0]["content"].append(
65
+ {
66
+ "type": "text", "text": expert_template.format(FLOW_RATE_VALUE=fr)+prompt_template
67
+ }
68
+ )
69
+ else:
70
+ formatted_data["messages"][0]["content"].append(
71
+ {
72
+ "type": "text", "text": prompt_template
73
+ }
74
+ )
75
+
76
+ if train:
77
+ formatted_data["messages"].append(
78
+ {
79
+ "role": "assistant",
80
+ "content": synthesize_answer(sample=sample)
81
+ }
82
+ )
83
+
84
+ return formatted_data
85
+
86
+
87
+ def collate_vqa(examples, processor, expert):
88
+
89
+ if expert:
90
+ _,_,expert_batch = expert.active_learning(examples)
91
+ templates = [format_data(example, fr=fr, image=True, train=True) for example,fr in zip(examples,expert_batch)]
92
+ else:
93
+ templates = [format_data(example, image=True, train=True) for example in examples]
94
+
95
+ image_inputs = [process_vision_info(template["messages"])[0] for template in templates]
96
+ texts = [processor.apply_chat_template(template["messages"], tokenize=False) for template in templates] # puts in template, and <image> token is isolated from img
97
+
98
+ batch = processor(text=texts, images=image_inputs, return_tensors="pt", padding=True)
99
+
100
+ labels = batch["input_ids"].clone()
101
+ labels[labels == processor.tokenizer.pad_token_id] = -100 #
102
+ image_tokens = [processor.tokenizer.convert_tokens_to_ids(processor.image_token)]
103
+ for image_token_id in image_tokens:
104
+ labels[labels == image_token_id] = -100
105
+
106
+ batch["labels"] = labels
107
+
108
+ return batch
109
+
110
+
111
+ def val_collate_fn(examples, processor, expert=False):
112
+
113
+ if expert:
114
+ _, _, expert_batch = expert.validate_step(examples)
115
+ templates= [format_data(example, fr=fr, image=True, train=False) for example,fr in zip(examples, expert_batch)]
116
+ else:
117
+ templates= [format_data(example, image=True, train=False) for example in examples]
118
+
119
+ image_inputs = [process_vision_info(template["messages"])[0] for template in templates]
120
+ texts = [processor.apply_chat_template(template["messages"], tokenize=False) for template in templates] # puts in template, and <image> token is isolated from img
121
+
122
+ batch = processor(text=texts, images=image_inputs, return_tensors="pt", padding=True)
123
+
124
+ return batch
125
+
126
+
127
+ def load_dataset(file_path, base_dir):
128
+ data = pd.read_csv(file_path)
129
+ data= data.drop(
130
+ columns=["nozzle_tip_x", "nozzle_tip_y"]
131
+ )
132
+ data["full_img_path"] = base_dir + data["img_path"].astype(str)
133
+ data= [row for _, row in data.iterrows()]
134
+ return data
135
+