| import torch |
| from PIL import Image |
| from transformers import AutoModelForCausalLM |
| import dataset4eo as eodata |
| import json |
| import numpy as np |
| import pdb |
| from prompt_utils import generate_prompt_for_segmentation,\ |
| generate_color_coded_segmentation_map, get_significant_classes,\ |
| get_tableau_colors, resize_and_encode_image |
|
|
| from openai import OpenAI |
|
|
|
|
| def get_caption_from_id(dataset, class_names, id): |
| class_colors = get_tableau_colors() |
| sample = dataset[id] |
| label = sample["label"] |
| |
| |
| |
| |
|
|
| current_classes = get_significant_classes(label) |
| unknownId = 12 |
| current_class_names = {ind:class_names[str(ind)] for ind in current_classes if ind!=unknownId} |
|
|
| color_names = list(class_colors.keys()) |
| current_color_names = {ind:color_names[ind] for ind in current_classes} |
|
|
| prompt = generate_prompt_for_segmentation(current_color_names, current_class_names) |
| image = generate_color_coded_segmentation_map(label, class_colors) |
|
|
| |
| |
|
|
| base_img = resize_and_encode_image(image) |
|
|
| messages = [ |
| {"role": "user", "content": [ |
| {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base_img}"}}, |
| {"type": "text", "text": prompt} |
| ]} |
| ] |
| chat_completion = openai.chat.completions.create( |
| model="meta-llama/Llama-3.2-90B-Vision-Instruct", |
| messages=messages, |
| ) |
| return chat_completion.choices[0].message.content |
|
|
|
|
|
|
|
|
| if __name__=="__main__": |
| import tqdm |
| import json |
| |
| openai = OpenAI( |
| api_key="uTu2kzPb6L08aXsmwwRI462UExeUtTBZ", |
| base_url="https://api.deepinfra.com/v1/openai", |
| ) |
|
|
| |
| dataset = eodata.StreamingDataset(input_dir="optimized_flair2_test", num_channels=5, channels_to_select=[0,1,2], shuffle=True, drop_last=True) |
| meta_data = json.load(open("optimized_flair2_test/metadata.json",'r')) |
| class_names = meta_data["attributes"]["class"] |
|
|
| data = {} |
|
|
| for id in tqdm.tqdm(range(len(dataset))): |
| caption = get_caption_from_id(dataset, class_names, id) |
| data[id] = caption |
| if id%10==0: |
| with open(f"rgb_captions_{id}.json", "w") as json_file: |
| json.dump(data, json_file) |
|
|
| |
| with open("rgb_captions.json", "w") as json_file: |
| json.dump(data, json_file) |
|
|
|
|