Update: add distributed inference code
Browse files- distributed_inference/distribute_llama_caption_generation.py +94 -0
- distributed_inference/distribute_llama_question_generation.py +91 -0
- distributed_inference/distribute_llama_rephrase.py +86 -0
- distributed_inference/gpt4.py +102 -0
- distributed_inference/gpt_generate_caption_pwiseg.py +111 -0
- distributed_inference/gpt_generate_count_pwiseg.py +111 -0
- distributed_inference/prompt_config.py +157 -0
- distributed_inference/utils.py +131 -0
distributed_inference/distribute_llama_caption_generation.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from accelerate import PartialState
|
3 |
+
import transformers
|
4 |
+
import torch
|
5 |
+
import json
|
6 |
+
from tqdm import tqdm
|
7 |
+
import os
|
8 |
+
from distributed_inference.utils import caption_repharse
|
9 |
+
import random
|
10 |
+
from distributed_inference.prompt_config import prompt_dict, instruction_dict
|
11 |
+
|
12 |
+
def main(num_gpu = 1):
|
13 |
+
distributed_state = PartialState()
|
14 |
+
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
|
15 |
+
|
16 |
+
pipeline = transformers.pipeline(
|
17 |
+
"text-generation",
|
18 |
+
model=model_id,
|
19 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
20 |
+
device=distributed_state.device
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
instruction = instruction_dict['general']
|
25 |
+
|
26 |
+
user_prompt = prompt_dict['caption_generation']
|
27 |
+
|
28 |
+
|
29 |
+
# file_list = [ '4dor_count_dataset_0702.json', '4dor_phase_dataset_0702.json']
|
30 |
+
# file_list = ['4dor_recognition_dataset_0702.json']
|
31 |
+
file_list = ['./pwiseg_info.json']
|
32 |
+
img_path = '/mnt1/wjl/InternLM-XComposer/data/pwiseg/train/'
|
33 |
+
|
34 |
+
for file in file_list:
|
35 |
+
with open(file, 'r') as f:
|
36 |
+
data = json.load(f)
|
37 |
+
data_keys = list(data.keys())
|
38 |
+
data_keys.sort()
|
39 |
+
output_name = '4dor_caption_dataset_pwiseg_llama3.json'
|
40 |
+
output_data = []
|
41 |
+
if os.path.exists(output_name):
|
42 |
+
with open(output_name, 'r') as f:
|
43 |
+
output_data = json.load(f)
|
44 |
+
start_index = len(output_data)
|
45 |
+
for i in tqdm(range(start_index, len(data_keys), num_gpu)):
|
46 |
+
tempature = random.uniform(0.8, 0.9)
|
47 |
+
top_p = random.uniform(0.7, 0.9)
|
48 |
+
indices = list(range(i, min(i+num_gpu, len(data_keys))))
|
49 |
+
input_list = [data[data_keys[j]] for j in indices]
|
50 |
+
temp_output = {}
|
51 |
+
with distributed_state.split_between_processes(input_list, apply_padding=True) as s_input:
|
52 |
+
messages = [
|
53 |
+
{"role": "system", "content": instruction},
|
54 |
+
{"role": "user", "content": user_prompt.format(position=s_input)},
|
55 |
+
]
|
56 |
+
prompt = pipeline.tokenizer.apply_chat_template(
|
57 |
+
messages,
|
58 |
+
tokenize=False,
|
59 |
+
add_generation_prompt=True
|
60 |
+
)
|
61 |
+
terminators = [
|
62 |
+
pipeline.tokenizer.eos_token_id,
|
63 |
+
pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
64 |
+
]
|
65 |
+
outputs = pipeline(
|
66 |
+
prompt,
|
67 |
+
max_new_tokens=500,
|
68 |
+
eos_token_id=terminators,
|
69 |
+
do_sample=True,
|
70 |
+
temperature=tempature,
|
71 |
+
top_p=top_p,
|
72 |
+
)
|
73 |
+
results = outputs[0]["generated_text"][len(prompt):]
|
74 |
+
results = caption_repharse(results)
|
75 |
+
with open(f'{distributed_state.process_index}.json', 'w') as f:
|
76 |
+
json.dump(results, f, indent=4)
|
77 |
+
distributed_state.wait_for_everyone()
|
78 |
+
if distributed_state.is_last_process:
|
79 |
+
for j in range(len(indices)):
|
80 |
+
with open(f'{j}.json', 'r') as f:
|
81 |
+
temp_output = json.load(f)
|
82 |
+
llava_dict = {}
|
83 |
+
llava_dict["id"] = data_keys[indices[j]]
|
84 |
+
llava_dict["image"] = os.path.join(img_path, data_keys[indices[j]])
|
85 |
+
llava_dict["caption"] = temp_output
|
86 |
+
output_data.append(llava_dict)
|
87 |
+
with open(output_name, 'w') as f:
|
88 |
+
json.dump(output_data, f, indent=4)
|
89 |
+
distributed_state.wait_for_everyone()
|
90 |
+
for j in range(num_gpu):
|
91 |
+
if os.path.exists(f'{j}.json'):
|
92 |
+
os.remove(f'{j}.json')
|
93 |
+
if __name__ == '__main__':
|
94 |
+
main(num_gpu = 4)
|
distributed_inference/distribute_llama_question_generation.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from accelerate import PartialState
|
3 |
+
import transformers
|
4 |
+
import torch
|
5 |
+
import json
|
6 |
+
from tqdm import tqdm
|
7 |
+
import os
|
8 |
+
from distributed_inference.utils import repharse
|
9 |
+
from distributed_inference.prompt_config import prompt_dict
|
10 |
+
|
11 |
+
def main(num_gpu = 1):
|
12 |
+
distributed_state = PartialState()
|
13 |
+
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
|
14 |
+
|
15 |
+
pipeline = transformers.pipeline(
|
16 |
+
"text-generation",
|
17 |
+
model=model_id,
|
18 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
19 |
+
device=distributed_state.device
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
instruction = ' You are an AI visual assistant, and you are looking at a picture of many surgical tools.'
|
24 |
+
user_prompt = prompt_dict['question_generation_with_ex']
|
25 |
+
|
26 |
+
|
27 |
+
# file_list = [ '4dor_count_dataset_0702.json', '4dor_phase_dataset_0702.json']
|
28 |
+
# file_list = ['4dor_recognition_dataset_0702.json']
|
29 |
+
file_list = ['./pwiseg_info.json']
|
30 |
+
img_path = '/mnt1/wjl/InternLM-XComposer/data/pwiseg/train/'
|
31 |
+
|
32 |
+
for file in file_list:
|
33 |
+
with open(file, 'r') as f:
|
34 |
+
data = json.load(f)
|
35 |
+
data_keys = list(data.keys())
|
36 |
+
data_keys.sort()
|
37 |
+
output_name = '4dor_count_dataset_pwiseg_llama3.json'
|
38 |
+
output_data = []
|
39 |
+
if os.path.exists(output_name):
|
40 |
+
with open(output_name, 'r') as f:
|
41 |
+
output_data = json.load(f)
|
42 |
+
start_index = len(output_data)
|
43 |
+
print(start_index)
|
44 |
+
for i in tqdm(range(start_index, len(data_keys), num_gpu)):
|
45 |
+
indices = list(range(i, min(i+num_gpu, len(data_keys))))
|
46 |
+
input_list = [data[data_keys[j]] for j in indices]
|
47 |
+
temp_output = {}
|
48 |
+
with distributed_state.split_between_processes(input_list, apply_padding=True) as s_input:
|
49 |
+
messages = [
|
50 |
+
{"role": "system", "content": instruction},
|
51 |
+
{"role": "user", "content": user_prompt.format(position=s_input)},
|
52 |
+
]
|
53 |
+
prompt = pipeline.tokenizer.apply_chat_template(
|
54 |
+
messages,
|
55 |
+
tokenize=False,
|
56 |
+
add_generation_prompt=True
|
57 |
+
)
|
58 |
+
terminators = [
|
59 |
+
pipeline.tokenizer.eos_token_id,
|
60 |
+
pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
61 |
+
]
|
62 |
+
outputs = pipeline(
|
63 |
+
prompt,
|
64 |
+
max_new_tokens=500,
|
65 |
+
eos_token_id=terminators,
|
66 |
+
do_sample=True,
|
67 |
+
temperature=0.6,
|
68 |
+
top_p=0.9,
|
69 |
+
)
|
70 |
+
results = outputs[0]["generated_text"][len(prompt):]
|
71 |
+
results = repharse(results)
|
72 |
+
with open(f'{distributed_state.process_index}.json', 'w') as f:
|
73 |
+
json.dump(results, f, indent=4)
|
74 |
+
distributed_state.wait_for_everyone()
|
75 |
+
if distributed_state.is_last_process:
|
76 |
+
for j in range(len(indices)):
|
77 |
+
with open(f'{j}.json', 'r') as f:
|
78 |
+
temp_output = json.load(f)
|
79 |
+
llava_dict = {}
|
80 |
+
llava_dict["id"] = data_keys[indices[j]]
|
81 |
+
llava_dict["image"] = os.path.join(img_path, data_keys[indices[j]])
|
82 |
+
llava_dict["caption"] = temp_output
|
83 |
+
output_data.append(llava_dict)
|
84 |
+
with open(output_name, 'w') as f:
|
85 |
+
json.dump(output_data, f, indent=4)
|
86 |
+
distributed_state.wait_for_everyone()
|
87 |
+
for j in range(len(indices)):
|
88 |
+
if os.path.exists(f'{j}.json'):
|
89 |
+
os.remove(f'{j}.json')
|
90 |
+
if __name__ == '__main__':
|
91 |
+
main(num_gpu = 4)
|
distributed_inference/distribute_llama_rephrase.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from accelerate import PartialState
|
3 |
+
import transformers
|
4 |
+
import torch
|
5 |
+
import json
|
6 |
+
from tqdm import tqdm
|
7 |
+
import os
|
8 |
+
from distributed_inference.utils import repharse
|
9 |
+
from distributed_inference.prompt_config import prompt_dict
|
10 |
+
|
11 |
+
def main(num_gpu = 1):
|
12 |
+
distributed_state = PartialState()
|
13 |
+
model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
|
14 |
+
|
15 |
+
pipeline = transformers.pipeline(
|
16 |
+
"text-generation",
|
17 |
+
model=model_id,
|
18 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
19 |
+
device=distributed_state.device
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
instruction = prompt_dict['rephrase_with_ex']
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
# file_list = [ '4dor_count_dataset_0702.json', '4dor_phase_dataset_0702.json']
|
29 |
+
# file_list = ['4dor_recognition_dataset_0702.json']
|
30 |
+
file_list = ['./data/count_dataset_pwiseg_0710.json']
|
31 |
+
for file in file_list:
|
32 |
+
with open(file, 'r') as f:
|
33 |
+
data = json.load(f)
|
34 |
+
output_name = file.replace('.json', '_rephrased.json')
|
35 |
+
existing_data = []
|
36 |
+
if os.path.exists(output_name):
|
37 |
+
with open(output_name, 'r') as f:
|
38 |
+
existing_data = json.load(f)
|
39 |
+
data[:len(existing_data)] = existing_data
|
40 |
+
start_index = len(existing_data)
|
41 |
+
for i in tqdm(range(start_index, len(data), num_gpu)):
|
42 |
+
indices = list(range(i, min(i+num_gpu, len(data))))
|
43 |
+
caption_list = [data[j]['caption'] for j in indices]
|
44 |
+
|
45 |
+
temp_output = {}
|
46 |
+
with distributed_state.split_between_processes(caption_list, apply_padding=True) as caption:
|
47 |
+
messages = [
|
48 |
+
{"role": "system", "content": instruction},
|
49 |
+
{"role": "user", "content": caption},
|
50 |
+
]
|
51 |
+
prompt = pipeline.tokenizer.apply_chat_template(
|
52 |
+
messages,
|
53 |
+
tokenize=False,
|
54 |
+
add_generation_prompt=True
|
55 |
+
)
|
56 |
+
terminators = [
|
57 |
+
pipeline.tokenizer.eos_token_id,
|
58 |
+
pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
|
59 |
+
]
|
60 |
+
outputs = pipeline(
|
61 |
+
prompt,
|
62 |
+
max_new_tokens=500,
|
63 |
+
eos_token_id=terminators,
|
64 |
+
do_sample=True,
|
65 |
+
temperature=0.6,
|
66 |
+
top_p=0.9,
|
67 |
+
)
|
68 |
+
results = outputs[0]["generated_text"][len(prompt):]
|
69 |
+
|
70 |
+
output_data = repharse(results)
|
71 |
+
with open(f'{distributed_state.process_index}.json', 'w') as f:
|
72 |
+
json.dump(output_data, f, indent=4)
|
73 |
+
distributed_state.wait_for_everyone()
|
74 |
+
if distributed_state.is_last_process:
|
75 |
+
output_data = data[:indices[-1] + 1].copy()
|
76 |
+
for j in range(len(indices)):
|
77 |
+
with open(f'{j}.json', 'r') as f:
|
78 |
+
temp_output = json.load(f)
|
79 |
+
output_data[j + i]['caption'] = temp_output
|
80 |
+
with open(output_name, 'w') as f:
|
81 |
+
json.dump(output_data, f, indent=4)
|
82 |
+
distributed_state.wait_for_everyone()
|
83 |
+
for j in range(len(indices)):
|
84 |
+
os.remove(f'{j}.json')
|
85 |
+
if __name__ == '__main__':
|
86 |
+
main(num_gpu = 4)
|
distributed_inference/gpt4.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from openai import OpenAI
|
2 |
+
from utils import repharse
|
3 |
+
from tqdm import tqdm
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
|
7 |
+
def get_result(prompt, instruction, client, base64_image=None, ):
|
8 |
+
response = client.chat.completions.create(
|
9 |
+
model="gpt-4o",
|
10 |
+
messages=[
|
11 |
+
{"role": "system", "content": instruction},
|
12 |
+
{"role": "user", "content":
|
13 |
+
[
|
14 |
+
{"type": "text", "text": prompt}
|
15 |
+
]
|
16 |
+
},
|
17 |
+
],
|
18 |
+
stream=False,
|
19 |
+
temperature=0.0
|
20 |
+
)
|
21 |
+
return response.choices[0].message.content
|
22 |
+
def get_result_video(prompt, instruction, client, base64_image=None, ):
|
23 |
+
response = client.chat.completions.create(
|
24 |
+
model="gpt-4o",
|
25 |
+
messages=[
|
26 |
+
{"role": "system", "content": "You are generating a video summary. Please provide a summary of the video. Respond in Markdown."},
|
27 |
+
{"role": "user", "content": [
|
28 |
+
"These are the frames from the video.",
|
29 |
+
*map(lambda x: {"type": "image_url",
|
30 |
+
"image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames)
|
31 |
+
],
|
32 |
+
}
|
33 |
+
],
|
34 |
+
temperature=0,
|
35 |
+
)
|
36 |
+
def main():
|
37 |
+
instruction = f'Given the some sentences, rewrite it into a regular format. It contain some pairs of questions and answers. For each pair, the output should be formulated as: \n' + \
|
38 |
+
'Q: <question>\n' + \
|
39 |
+
'A: <answer>\n' + \
|
40 |
+
'Please do not output anything else. The output should only contain the pairs of questions and answers. \n' + \
|
41 |
+
'Here are some examples.\n' +\
|
42 |
+
'Example 1: \n' + \
|
43 |
+
'Input: \n' + \
|
44 |
+
"### Question 1:\nWhat equipment can be found in the operating room?\n\n**Answer:** The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n---\n\n### Question 2:\nWhat is positioned in the center of the operating room?\n\n**Answer:** There's an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n---\n\n### Question 3:\nIs there any anesthesia equipment present in the operating room?\n\n**Answer:** Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n" + \
|
45 |
+
'Output: \n' + \
|
46 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
47 |
+
'A: The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n' + \
|
48 |
+
'Q: What is positioned in the center of the operating room?\n' + \
|
49 |
+
'A: There\'s an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n' + \
|
50 |
+
'Q: Is there any anesthesia equipment present in the operating room?\n' + \
|
51 |
+
'A: Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n' + \
|
52 |
+
'Example 2: \n' + \
|
53 |
+
'Input: \n' + \
|
54 |
+
"Sure, I'll describe the current phase and generate related questions and answers that pertain to maintaining the sterile field during surgery.\n\n### Description\nIn the image, the medical staff are wearing blue sterile gowns, gloves, masks, and caps, indicating adherence to strict aseptic techniques. There is equipment carefully covered with sterile coverings, and positions are maintained near the required instruments such as the instrument table and anesthesia equipment. Staff members seem to be in diligent preparation and monitoring phases prior to more active surgical intervention.\n\n### Questions and Answers about the Sterile Phase\n\n#### Question 1:\nWhat is the current surgical phase, and how should it be maintained?\n##### Answer:\nThe current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n#### Question 2:\nWhy is it essential to maintain the sterile phase during surgery?\n##### Answer:\nMaintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n#### Question 3:\nWhat suggestions could help surgeons improve the quality of surgery during the sterile phase?\n##### Answer:\nTo improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n\nBy following these suggestions, the sterility of the procedure can be maintained, resulting in higher surgery quality and better patient outcomes." + \
|
55 |
+
'Output: \n' + \
|
56 |
+
'Q: What is the current surgical phase, and how should it be maintained?\n' + \
|
57 |
+
'A: The current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n' + \
|
58 |
+
'Q: Why is it essential to maintain the sterile phase during surgery?\n' + \
|
59 |
+
'A: Maintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n' + \
|
60 |
+
'Q: What suggestions could help surgeons improve the quality of surgery during the sterile phase?\n' + \
|
61 |
+
'A: To improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n' + \
|
62 |
+
'Example 3: \n' + \
|
63 |
+
'Input: \n' + \
|
64 |
+
"Question: What equipment can be found in the operating room?\nAnswer: Anesthesia equipment.\n\nQuestion: What is placed on the instrument table?\nAnswer: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\nQuestion: Where can the secondary table be found, and what might it be used for?\nAnswer: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure." + \
|
65 |
+
'Output: \n' + \
|
66 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
67 |
+
'A: Anesthesia equipment.\n\n' + \
|
68 |
+
'Q: What is placed on the instrument table?\n' + \
|
69 |
+
'A: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\n' + \
|
70 |
+
'Q: Where can the secondary table be found, and what might it be used for?\n' + \
|
71 |
+
'A: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure.\n'
|
72 |
+
|
73 |
+
|
74 |
+
client = OpenAI(api_key="sk-sqilImjoPeMWLosGC7EbB5Dc215d4320BbDa49C59f73Eb85",
|
75 |
+
base_url="https://vip.yi-zhan.top/v1")
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
file_list = ['./data/4dor_recognition_dataset_0702.json']
|
81 |
+
for file in file_list:
|
82 |
+
|
83 |
+
with open(file, 'r') as f:
|
84 |
+
data = json.load(f)
|
85 |
+
output_name = file.replace('.json', '_rephrased.json')
|
86 |
+
existing_data = []
|
87 |
+
if os.path.exists(output_name):
|
88 |
+
with open(output_name, 'r') as f:
|
89 |
+
existing_data = json.load(f)
|
90 |
+
# data[:len(existing_data)] = existing_data
|
91 |
+
# start_index = len(existing_data)
|
92 |
+
start_index = 0
|
93 |
+
for i in tqdm(range(start_index, len(data))):
|
94 |
+
prompt = data[i]['caption']
|
95 |
+
results = get_result(prompt, instruction, client)
|
96 |
+
data[i]['caption'] = repharse(results)
|
97 |
+
exit()
|
98 |
+
with open(output_name, 'w') as f:
|
99 |
+
json.dump(data[:i+1], f, indent=4)
|
100 |
+
|
101 |
+
if __name__ == '__main__':
|
102 |
+
main()
|
distributed_inference/gpt_generate_caption_pwiseg.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# python3
|
2 |
+
# Please install OpenAI SDK first:`pip3 install openai`
|
3 |
+
from openai import OpenAI
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
|
9 |
+
|
10 |
+
QUESTION_HEAD = ["Describe the target object in the 3D scene concisely.",
|
11 |
+
"Provide a brief description of the given target object in the 3D scene.",
|
12 |
+
"Offer a succinct explanation of the target object in the 3D scene presented.",
|
13 |
+
"Summarize the visual content of the target object in the 3D scene.",
|
14 |
+
"Give a short and clear explanation of the previous target object in the 3D scene.",
|
15 |
+
"Share a concise interpretation of the target object in the 3D scene provided.",
|
16 |
+
"Present a compact description of the the target object's key features in the 3D scene.",
|
17 |
+
"Relay a brief, clear account of the target object shown in the 3D scene.",
|
18 |
+
"Render a clear and concise summary of the target object in the 3D scene.",
|
19 |
+
"Write a terse but informative summary of the target object in the 3D scene.",
|
20 |
+
"Create a compact narrative representing the target object in the 3D scene presented."]
|
21 |
+
|
22 |
+
api_key = "sk-3I6se0vPc8lYCIXH8eDd7e1fBe6341Ae92025dBd8cF9A426"
|
23 |
+
base_url = "https://vip.yi-zhan.top/v1"
|
24 |
+
model = "gpt-4o-2024-05-13"
|
25 |
+
client = OpenAI(api_key=api_key,
|
26 |
+
base_url="https://vip.yi-zhan.top/v1")
|
27 |
+
|
28 |
+
|
29 |
+
def get_result(prompt):
|
30 |
+
response = client.chat.completions.create(
|
31 |
+
model=model,
|
32 |
+
messages=[
|
33 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
34 |
+
{"role": "user", "content": prompt},
|
35 |
+
],
|
36 |
+
stream=False,
|
37 |
+
temperature=1.25
|
38 |
+
)
|
39 |
+
return response.choices[0].message.content
|
40 |
+
|
41 |
+
|
42 |
+
if __name__ == '__main__':
|
43 |
+
output_path = "/mnt1/wjl/InternLM-XComposer/instruct_gen_v3/pwiseg/caption_dataset_pwiseg_0710.json"
|
44 |
+
with open("/mnt1/wjl/InternLM-XComposer/instruct_gen_v3/pwiseg/pwiseg_info.json","r") as f:
|
45 |
+
info = json.load(f)
|
46 |
+
|
47 |
+
prompt = """
|
48 |
+
## Role
|
49 |
+
- You are an AI visual assistant, and you are looking at a picture of many surgical tools.
|
50 |
+
|
51 |
+
## Information
|
52 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
53 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
54 |
+
- The list is as follows:
|
55 |
+
```json
|
56 |
+
{position}
|
57 |
+
```
|
58 |
+
|
59 |
+
## Task
|
60 |
+
- Your task is to generate a comprehensive description of the surgical table, including what is on the table, where they are, and their positional relationship.
|
61 |
+
|
62 |
+
## Constraints
|
63 |
+
- Don't mention any specific numbers for its bounding box, using rough positions such as left, top right, etc.
|
64 |
+
- Don't make up anything not mentioned in the list, just an objective and direct description.
|
65 |
+
- The description should be more than 100 words and less than 150 words.
|
66 |
+
|
67 |
+
Now take a deep breath and start your response step by step.
|
68 |
+
"""
|
69 |
+
img_path = '/mnt1/wjl/InternLM-XComposer/data/pwiseg/train/'
|
70 |
+
llava_dataset = []
|
71 |
+
import ipdb
|
72 |
+
|
73 |
+
# 读取已处理的数据,如果文件存在
|
74 |
+
if os.path.exists(output_path):
|
75 |
+
with open(output_path, "r") as f:
|
76 |
+
llava_dataset = json.load(f)
|
77 |
+
else:
|
78 |
+
llava_dataset = []
|
79 |
+
|
80 |
+
# 获取已处理的IDs
|
81 |
+
processed_ids = [data["id"] for data in llava_dataset]
|
82 |
+
|
83 |
+
count, all_number = 0, len(info)
|
84 |
+
for ix, (i,v) in enumerate(info.items()):
|
85 |
+
|
86 |
+
if ix in processed_ids:
|
87 |
+
continue # 跳过已处理的数据
|
88 |
+
|
89 |
+
llava_dict = {}
|
90 |
+
info_dict = v
|
91 |
+
|
92 |
+
final_prompt = prompt.format(position=info_dict)
|
93 |
+
|
94 |
+
try:
|
95 |
+
answer = get_result(final_prompt)
|
96 |
+
print("## {count}/{all_number}, {answer}".format(count=ix,
|
97 |
+
all_number=all_number,
|
98 |
+
answer=answer))
|
99 |
+
llava_dict["id"] = ix
|
100 |
+
llava_dict["image"] = os.path.join(img_path, i)
|
101 |
+
llava_dict["caption"] = answer
|
102 |
+
|
103 |
+
llava_dataset.append(llava_dict)
|
104 |
+
#print(llava_dataset)
|
105 |
+
with open(output_path,"w") as f:
|
106 |
+
f.write(json.dumps(llava_dataset,indent=2))
|
107 |
+
|
108 |
+
except Exception as e:
|
109 |
+
print(f"Error processing {i}: {e}")
|
110 |
+
continue
|
111 |
+
|
distributed_inference/gpt_generate_count_pwiseg.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# python3
|
2 |
+
# Please install OpenAI SDK first:`pip3 install openai`
|
3 |
+
from openai import OpenAI
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
|
9 |
+
api_key = "sk-WVJp2orFuuvPTf5P5dD936B1De78421b9eEa2c99D70b8a06"
|
10 |
+
base_url = "https://vip.yi-zhan.top/v1"
|
11 |
+
model = "gpt-4o-2024-05-13"
|
12 |
+
client = OpenAI(api_key=api_key,
|
13 |
+
base_url="https://vip.yi-zhan.top/v1")
|
14 |
+
|
15 |
+
|
16 |
+
def get_result(prompt):
|
17 |
+
response = client.chat.completions.create(
|
18 |
+
model=model,
|
19 |
+
messages=[
|
20 |
+
{"role": "system", "content": "You are a helpful assistant"},
|
21 |
+
{"role": "user", "content": prompt},
|
22 |
+
],
|
23 |
+
stream=False,
|
24 |
+
temperature=1.25
|
25 |
+
)
|
26 |
+
return response.choices[0].message.content
|
27 |
+
|
28 |
+
|
29 |
+
if __name__ == '__main__':
|
30 |
+
output_path = "/mnt1/wjl/InternLM-XComposer/instruct_gen_v3/pwiseg/count_dataset_pwiseg_0710.json"
|
31 |
+
with open("/mnt1/wjl/InternLM-XComposer/instruct_gen_v3/pwiseg/pwiseg_info.json", "r") as f:
|
32 |
+
infos = json.load(f)
|
33 |
+
|
34 |
+
prompt = """
|
35 |
+
## Role
|
36 |
+
- You are an AI visual assistant, and you are looking at a picture of many surgical tools.
|
37 |
+
|
38 |
+
## Information
|
39 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
40 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
41 |
+
- The list is as follows:
|
42 |
+
```json
|
43 |
+
{position}
|
44 |
+
```
|
45 |
+
|
46 |
+
## Task
|
47 |
+
Based on the list, Your task is to generate several questions and corresponding answers about counting surgical tools on the table.
|
48 |
+
|
49 |
+
## Example:
|
50 |
+
- "Question: How many scalpals are on the table? Answer: Two scalpels are on the table",
|
51 |
+
- "Question: How many forceps are on the table? Answer: There is no forcep on the table",
|
52 |
+
- "Question: How many surgical tools in total are on the table? Answer: There are 2 scalpals on the table and 3 tweezers on the table",
|
53 |
+
|
54 |
+
## Constraints
|
55 |
+
- Remeber, all the questions must can be clearly answered based on the information of given lists.
|
56 |
+
- Do not make up any questions and answers without solid evidence in the given lists.
|
57 |
+
- Importantly, you do not need to give any reasoning process, just give a straightforward answers.
|
58 |
+
- Do not use coordinates to generate answers and questions.
|
59 |
+
|
60 |
+
Now take a deep breath and start your response step by step.
|
61 |
+
"""
|
62 |
+
|
63 |
+
# 读取已处理的数据,如果文件存在
|
64 |
+
if os.path.exists(output_path):
|
65 |
+
with open(output_path, "r") as f:
|
66 |
+
llava_dataset = json.load(f)
|
67 |
+
else:
|
68 |
+
llava_dataset = []
|
69 |
+
|
70 |
+
# 获取已处理的IDs
|
71 |
+
processed_ids = [data["id"] for data in llava_dataset]
|
72 |
+
count = len(processed_ids)
|
73 |
+
count, total = 0, len(infos)
|
74 |
+
img_path = '/mnt1/wjl/InternLM-XComposer/data/pwiseg/train/'
|
75 |
+
|
76 |
+
for ix, (i, v) in enumerate(infos.items()):
|
77 |
+
|
78 |
+
# import ipdb; ipdb.set_trace()
|
79 |
+
# count = count + 1
|
80 |
+
if ix in processed_ids:
|
81 |
+
continue # 跳过已处理的数据
|
82 |
+
|
83 |
+
llava_dict = {}
|
84 |
+
|
85 |
+
info_dict = v
|
86 |
+
|
87 |
+
final_prompt = prompt.format(position=info_dict)
|
88 |
+
|
89 |
+
try:
|
90 |
+
answer = get_result(final_prompt)
|
91 |
+
#print(answer)
|
92 |
+
llava_dict["id"] = ix
|
93 |
+
llava_dict["image"] = os.path.join(img_path, i)
|
94 |
+
llava_dict["caption"] = answer
|
95 |
+
llava_dataset.append(llava_dict)
|
96 |
+
#print(llava_dataset)
|
97 |
+
print("## {count}/{all_number}, {answer}".format(count=ix,
|
98 |
+
all_number=total,
|
99 |
+
answer=answer))
|
100 |
+
|
101 |
+
with open(output_path,"w") as f:
|
102 |
+
f.write(json.dumps(llava_dataset,indent=2))
|
103 |
+
except Exception as e:
|
104 |
+
print(f"Error processing {i}: {e}")
|
105 |
+
continue
|
106 |
+
|
107 |
+
if count > 20:
|
108 |
+
break
|
109 |
+
|
110 |
+
|
111 |
+
|
distributed_inference/prompt_config.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
prompt_dict = {
|
2 |
+
'caption_generation':
|
3 |
+
"""
|
4 |
+
## Information
|
5 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
6 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
7 |
+
- The list is as follows:
|
8 |
+
```json
|
9 |
+
{position}
|
10 |
+
```
|
11 |
+
|
12 |
+
## Task
|
13 |
+
- Your task is to generate a comprehensive description of the instrument table, including what is on the table, where they are, and their positional relationship.
|
14 |
+
|
15 |
+
## Constraints
|
16 |
+
- Don't mention any specific numbers for its bounding box, using rough positions such as left, top right, etc.
|
17 |
+
- Don't make up anything not mentioned in the list, just an objective and direct description.
|
18 |
+
- The description should be more than 100 words and less than 150 words.
|
19 |
+
- Don't include any special characters such as "#" and don't include any next line character in your response
|
20 |
+
- You response should start with "Here is a comprehensive description of the instrument table:\n\n"
|
21 |
+
|
22 |
+
Now take a deep breath and start your response step by step.
|
23 |
+
""",
|
24 |
+
'relationship_generation':
|
25 |
+
"""
|
26 |
+
""",
|
27 |
+
'question_generation':
|
28 |
+
"""
|
29 |
+
## Information
|
30 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
31 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
32 |
+
- The list is as follows:
|
33 |
+
```json
|
34 |
+
{position}
|
35 |
+
```
|
36 |
+
|
37 |
+
## Task
|
38 |
+
Based on the list, Your task is to generate several questions and corresponding answers about counting surgical tools on the table.
|
39 |
+
|
40 |
+
## Example:
|
41 |
+
- "Question: How many scalpals are on the table? Answer: Two scalpels are on the table",
|
42 |
+
- "Question: How many forceps are on the table? Answer: There is no forcep on the table",
|
43 |
+
- "Question: How many surgical tools in total are on the table? Answer: There are 2 scalpals on the table and 3 tweezers on the table",
|
44 |
+
|
45 |
+
## Constraints
|
46 |
+
- Remeber, all the questions must can be clearly answered based on the information of given lists.
|
47 |
+
- Do not make up any questions and answers without solid evidence in the given lists.
|
48 |
+
- Importantly, you do not need to give any reasoning process, just give a straightforward answers.
|
49 |
+
- Do not use coordinates to generate answers and questions.
|
50 |
+
|
51 |
+
Now take a deep breath and start your response step by step.
|
52 |
+
""",
|
53 |
+
'question_generation_with_ex':
|
54 |
+
"""
|
55 |
+
## Information
|
56 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
57 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
58 |
+
- The list is as follows:
|
59 |
+
```json
|
60 |
+
{position}
|
61 |
+
```
|
62 |
+
|
63 |
+
## Task
|
64 |
+
Based on the list, Your task is to generate several questions and corresponding answers about counting surgical tools on the table.
|
65 |
+
|
66 |
+
## Example:
|
67 |
+
- Q: How many people are there in the operating room?
|
68 |
+
A: There are five people in the operating room.
|
69 |
+
|
70 |
+
Q: Which human roles are present in the operating room?
|
71 |
+
A: The team includes a patient, an anesthetist, and circulating nurses.
|
72 |
+
|
73 |
+
Q: How many devices are in the operating room?
|
74 |
+
A: There are four individual devices in the operating room: an anesthesia equipment, an operating table, an instrument table, and a secondary table.
|
75 |
+
- Q: "How many medical staff members are in the operating room?",
|
76 |
+
A: "Two, Staff 2 and Staff 3 are in the operating room."
|
77 |
+
|
78 |
+
Q: "Can you list the names of all the medical equipment in the operating room?",
|
79 |
+
A: "Yes, the equipment in the operating room includes the anesthesia equipment, instrument table, and secondary table."
|
80 |
+
|
81 |
+
Q: "Who is closer to the secondary table?",
|
82 |
+
A: "According to the provided positions, neither Staff 2 nor Staff 3 is specifically close to the secondary table."
|
83 |
+
- Q: How many people are present in the operating room?
|
84 |
+
A: Four, the patient and three medical staff members are in the operating room.
|
85 |
+
|
86 |
+
Q: How many items of equipment are there on the left side of the room?
|
87 |
+
A: Two, the anesthesia equipment and the secondary table are on the left side of the room.
|
88 |
+
|
89 |
+
Q: How many tables are in the operating room?
|
90 |
+
A: Three, there are an operating table, an instrument table, and a secondary table in the operating room.
|
91 |
+
|
92 |
+
Q: Which medical staff members are closest to the patient?
|
93 |
+
A: The circulating nurse and the anaesthetist are closest to the patient.
|
94 |
+
|
95 |
+
Q: How many pieces of equipment are being used close by the medical staff around the patient?
|
96 |
+
A: Two, the operating table and the anesthesia equipment are being used close by the medical staff around the patient.
|
97 |
+
|
98 |
+
## Constraints
|
99 |
+
- Remeber, all the questions must can be clearly answered based on the information of given lists.
|
100 |
+
- Do not make up any questions and answers without solid evidence in the given lists.
|
101 |
+
- Importantly, you do not need to give any reasoning process, just give a straightforward answers.
|
102 |
+
- Do not use coordinates to generate answers and questions.
|
103 |
+
- The questions and answers should be strictly follow the format, without any starting and ending words.:
|
104 |
+
Q: ...
|
105 |
+
A: ...
|
106 |
+
|
107 |
+
Q: ...
|
108 |
+
A: ...
|
109 |
+
|
110 |
+
Q: ...
|
111 |
+
A: ...
|
112 |
+
|
113 |
+
Now take a deep breath and start your response step by step.
|
114 |
+
"""
|
115 |
+
}
|
116 |
+
|
117 |
+
instruction_dict = {
|
118 |
+
'general':
|
119 |
+
'You are an AI visual assistant, and you are looking at a picture of many surgical tools.',
|
120 |
+
'rephrase_with_ex':
|
121 |
+
'Given the some sentences, rewrite it into a regular format. It contain some pairs of questions and answers. For each pair, the output should be formulated as: \n' + \
|
122 |
+
'Q: <question>\n' + \
|
123 |
+
'A: <answer>\n' + \
|
124 |
+
'Please do not output anything else. The output should only contain the pairs of questions and answers. \n' + \
|
125 |
+
'Here are some examples.\n' +\
|
126 |
+
'Example 1: \n' + \
|
127 |
+
'Input: \n' + \
|
128 |
+
"### Question 1:\nWhat equipment can be found in the operating room?\n\n**Answer:** The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n---\n\n### Question 2:\nWhat is positioned in the center of the operating room?\n\n**Answer:** There's an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n---\n\n### Question 3:\nIs there any anesthesia equipment present in the operating room?\n\n**Answer:** Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n" + \
|
129 |
+
'Output: \n' + \
|
130 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
131 |
+
'A: The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n' + \
|
132 |
+
'Q: What is positioned in the center of the operating room?\n' + \
|
133 |
+
'A: There\'s an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n' + \
|
134 |
+
'Q: Is there any anesthesia equipment present in the operating room?\n' + \
|
135 |
+
'A: Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n' + \
|
136 |
+
'Example 2: \n' + \
|
137 |
+
'Input: \n' + \
|
138 |
+
"Sure, I'll describe the current phase and generate related questions and answers that pertain to maintaining the sterile field during surgery.\n\n### Description\nIn the image, the medical staff are wearing blue sterile gowns, gloves, masks, and caps, indicating adherence to strict aseptic techniques. There is equipment carefully covered with sterile coverings, and positions are maintained near the required instruments such as the instrument table and anesthesia equipment. Staff members seem to be in diligent preparation and monitoring phases prior to more active surgical intervention.\n\n### Questions and Answers about the Sterile Phase\n\n#### Question 1:\nWhat is the current surgical phase, and how should it be maintained?\n##### Answer:\nThe current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n#### Question 2:\nWhy is it essential to maintain the sterile phase during surgery?\n##### Answer:\nMaintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n#### Question 3:\nWhat suggestions could help surgeons improve the quality of surgery during the sterile phase?\n##### Answer:\nTo improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n\nBy following these suggestions, the sterility of the procedure can be maintained, resulting in higher surgery quality and better patient outcomes." + \
|
139 |
+
'Output: \n' + \
|
140 |
+
'Q: What is the current surgical phase, and how should it be maintained?\n' + \
|
141 |
+
'A: The current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n' + \
|
142 |
+
'Q: Why is it essential to maintain the sterile phase during surgery?\n' + \
|
143 |
+
'A: Maintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n' + \
|
144 |
+
'Q: What suggestions could help surgeons improve the quality of surgery during the sterile phase?\n' + \
|
145 |
+
'A: To improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n' + \
|
146 |
+
'Example 3: \n' + \
|
147 |
+
'Input: \n' + \
|
148 |
+
"Question: What equipment can be found in the operating room?\nAnswer: Anesthesia equipment.\n\nQuestion: What is placed on the instrument table?\nAnswer: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\nQuestion: Where can the secondary table be found, and what might it be used for?\nAnswer: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure." + \
|
149 |
+
'Output: \n' + \
|
150 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
151 |
+
'A: Anesthesia equipment.\n\n' + \
|
152 |
+
'Q: What is placed on the instrument table?\n' + \
|
153 |
+
'A: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\n' + \
|
154 |
+
'Q: Where can the secondary table be found, and what might it be used for?\n' + \
|
155 |
+
'A: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure.\n'
|
156 |
+
|
157 |
+
}
|
distributed_inference/utils.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
sys_instructions = {
|
3 |
+
'question_rephrase': 'Given the some sentences, rewrite it into a regular format. It contain some pairs of questions and answers. For each pair, the output should be formulated as: \n' + \
|
4 |
+
'Q: <question>\n' + \
|
5 |
+
'A: <answer>\n' + \
|
6 |
+
'Please do not output anything else. The output should only contain the pairs of questions and answers. \n' + \
|
7 |
+
'Here are some examples.\n' +\
|
8 |
+
'Example 1: \n' + \
|
9 |
+
'Input: \n' + \
|
10 |
+
"### Question 1:\nWhat equipment can be found in the operating room?\n\n**Answer:** The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n---\n\n### Question 2:\nWhat is positioned in the center of the operating room?\n\n**Answer:** There's an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n---\n\n### Question 3:\nIs there any anesthesia equipment present in the operating room?\n\n**Answer:** Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n" + \
|
11 |
+
'Output: \n' + \
|
12 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
13 |
+
'A: The operating room contains anesthesia equipment, an instrument table, and a secondary table.\n\n' + \
|
14 |
+
'Q: What is positioned in the center of the operating room?\n' + \
|
15 |
+
'A: There\'s an instrument table in the center of the operating room. It is typically used to keep surgical instruments in a readily accessible location doing to an operation.\n\n' + \
|
16 |
+
'Q: Is there any anesthesia equipment present in the operating room?\n' + \
|
17 |
+
'A: Yes, there is anesthesia equipment present in the operating room, which is used to administer anesthesia to patients in order to keep them unconscious or pain-free during surgical procedures.\n' + \
|
18 |
+
'Example 2: \n' + \
|
19 |
+
'Input: \n' + \
|
20 |
+
"Sure, I'll describe the current phase and generate related questions and answers that pertain to maintaining the sterile field during surgery.\n\n### Description\nIn the image, the medical staff are wearing blue sterile gowns, gloves, masks, and caps, indicating adherence to strict aseptic techniques. There is equipment carefully covered with sterile coverings, and positions are maintained near the required instruments such as the instrument table and anesthesia equipment. Staff members seem to be in diligent preparation and monitoring phases prior to more active surgical intervention.\n\n### Questions and Answers about the Sterile Phase\n\n#### Question 1:\nWhat is the current surgical phase, and how should it be maintained?\n##### Answer:\nThe current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n#### Question 2:\nWhy is it essential to maintain the sterile phase during surgery?\n##### Answer:\nMaintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n#### Question 3:\nWhat suggestions could help surgeons improve the quality of surgery during the sterile phase?\n##### Answer:\nTo improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n\nBy following these suggestions, the sterility of the procedure can be maintained, resulting in higher surgery quality and better patient outcomes." + \
|
21 |
+
'Output: \n' + \
|
22 |
+
'Q: What is the current surgical phase, and how should it be maintained?\n' + \
|
23 |
+
'A: The current surgical phase is sterile. It is crucial to maintain strict aseptic techniques: all personnel must continue to wear sterile gowns, gloves, and masks while thoroughly disinfecting the surgical site using sterilized instruments and materials. The team should minimize unnecessary movement and contact to reduce contamination risks. Clear communication within the team is important to promptly address any breaches in sterility.\n\n' + \
|
24 |
+
'Q: Why is it essential to maintain the sterile phase during surgery?\n' + \
|
25 |
+
'A: Maintaining the sterile phase during surgery is essential to prevent infections. It ensures the surgical site and instruments remain free from harmful bacteria and other microorganisms. Proper sterilization reduces the risk of postoperative complications, speeds up patient recovery, and enhances the overall success of the surgical procedure.\n\n' + \
|
26 |
+
'Q: What suggestions could help surgeons improve the quality of surgery during the sterile phase?\n' + \
|
27 |
+
'A: To improve the quality of surgery during the sterile phase, it is important to:\n1. Ensure a thorough hand washing and use of sterilizing solutions before scrubbing in.\n2. Use sterile drapes to isolate the surgical site efficiently.\n3. Maintain constant surveillance of sterilization procedures.\n4. Label and organize sterile instruments properly on the instrument table.\n5. Implement a clear protocol for notifying the team if the sterile field is compromised, so corrective actions can be taken immediately.\n6. Avoid over-cluttering the sterile field with non-essential equipment.\n' + \
|
28 |
+
'Example 3: \n' + \
|
29 |
+
'Input: \n' + \
|
30 |
+
"Question: What equipment can be found in the operating room?\nAnswer: Anesthesia equipment.\n\nQuestion: What is placed on the instrument table?\nAnswer: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\nQuestion: Where can the secondary table be found, and what might it be used for?\nAnswer: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure." + \
|
31 |
+
'Output: \n' + \
|
32 |
+
'Q: What equipment can be found in the operating room?\n' + \
|
33 |
+
'A: Anesthesia equipment.\n\n' + \
|
34 |
+
'Q: What is placed on the instrument table?\n' + \
|
35 |
+
'A: Various surgical instruments needed for the procedure are typically placed on the instrument table for easy access by the surgical team.\n\n' + \
|
36 |
+
'Q: Where can the secondary table be found, and what might it be used for?\n' + \
|
37 |
+
'A: The secondary table is part of the auxiliary equipment in the operating room and may be used to hold additional surgical instruments or supplies needed during the procedure.\n',
|
38 |
+
|
39 |
+
'count_generate': 'You are an AI visual assistant, and you are looking at a picture of many surgical tools.'
|
40 |
+
|
41 |
+
}
|
42 |
+
|
43 |
+
user_prompt = {
|
44 |
+
'count_generate': """
|
45 |
+
## Information
|
46 |
+
- You will receive a list of dictionaries of annotated tools that can be seen on the table.
|
47 |
+
- Note that each dictionary contains "name":"bbox", "name is the name of the surgical tool that can be seen on the table, and "bbox" is the numerical value of the corresponding surgical tool position (top left x, top left y, bottom right x, bottom right y.
|
48 |
+
- The list is as follows:
|
49 |
+
```json
|
50 |
+
{position}
|
51 |
+
```
|
52 |
+
|
53 |
+
## Task
|
54 |
+
Based on the list, Your task is to generate several questions and corresponding answers about counting surgical tools on the table.
|
55 |
+
|
56 |
+
## Example:
|
57 |
+
- "Question: How many scalpals are on the table? Answer: Two scalpels are on the table",
|
58 |
+
- "Question: How many forceps are on the table? Answer: There is no forcep on the table",
|
59 |
+
- "Question: How many surgical tools in total are on the table? Answer: There are 2 scalpals on the table and 3 tweezers on the table",
|
60 |
+
|
61 |
+
## Constraints
|
62 |
+
- Remeber, all the questions must can be clearly answered based on the information of given lists.
|
63 |
+
- Do not make up any questions and answers without solid evidence in the given lists.
|
64 |
+
- Importantly, you do not need to give any reasoning process, just give a straightforward answers.
|
65 |
+
- Do not use coordinates to generate answers and questions.
|
66 |
+
|
67 |
+
Now take a deep breath and start your response step by step.
|
68 |
+
"""
|
69 |
+
}
|
70 |
+
|
71 |
+
def repharse(results):
|
72 |
+
try:
|
73 |
+
results = results.split('\n\n')
|
74 |
+
repharse_list = []
|
75 |
+
for r in results:
|
76 |
+
|
77 |
+
split_temp = r.split('\n')
|
78 |
+
if len(split_temp) != 2 or \
|
79 |
+
split_temp[0][:2] != 'Q:' or \
|
80 |
+
split_temp[1][:2] != 'A:':
|
81 |
+
continue
|
82 |
+
r = r.split('Q: ')[1]
|
83 |
+
r = r.split('A: ')
|
84 |
+
qa_pair = {}
|
85 |
+
for i in range(len(r)):
|
86 |
+
if i == 0:
|
87 |
+
qa_pair['question'] = r[i][:-1]
|
88 |
+
elif i == 1:
|
89 |
+
qa_pair['answer'] = r[i]
|
90 |
+
repharse_list.append(qa_pair)
|
91 |
+
except:
|
92 |
+
repharse_list = []
|
93 |
+
return repharse_list
|
94 |
+
|
95 |
+
def caption_repharse(results):
|
96 |
+
try:
|
97 |
+
caption = ""
|
98 |
+
results = results.split('\n\n')
|
99 |
+
if len(results) == 2:
|
100 |
+
caption = results[1]
|
101 |
+
return caption
|
102 |
+
except:
|
103 |
+
return ""
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
def get_output_data(data, output_data, indices, instruction):
|
108 |
+
if instruction == 'question_rephrase':
|
109 |
+
return data[:indices[-1] + 1].copy()
|
110 |
+
elif instruction == 'count_generate':
|
111 |
+
return output_data.copy()
|
112 |
+
def clean_caption(file):
|
113 |
+
output_name = file.replace('.json', '_rephrased.json')
|
114 |
+
with open(file, 'r') as f:
|
115 |
+
data = json.load(f)
|
116 |
+
|
117 |
+
for i in range(len(data)):
|
118 |
+
caption = data[i]['caption']
|
119 |
+
caption = caption.replace('\n\n', ' ').replace('\n', ' ')
|
120 |
+
caption = caption.replace('\u2019', '\'').replace('\u2013', '-')
|
121 |
+
caption = caption.replace('### ', '').replace('## ', '').replace('###', '').replace('##', '')
|
122 |
+
caption = caption.replace('**', '')
|
123 |
+
caption = caption.replace('- ', '')
|
124 |
+
data[i]['caption'] = caption
|
125 |
+
with open(output_name, 'w') as f:
|
126 |
+
json.dump(data[:i+1], f, indent=4)
|
127 |
+
|
128 |
+
if __name__=='__main__':
|
129 |
+
file_list = ['./data/caption_dataset_pwiseg_0710.json']
|
130 |
+
for file in file_list:
|
131 |
+
clean_caption(file)
|