import os import torch import dataset4eo as eodata import jsonlines import numpy as np import pdb from mistral_inference.transformer import Transformer #type:ignore from mistral_inference.generate import generate #type:ignore from mistral_common.tokens.tokenizers.mistral import MistralTokenizer #type:ignore from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageChunk #type:ignore from mistral_common.protocol.instruct.request import ChatCompletionRequest #type:ignore def get_caption_from_id(model, captions, id): caption_item = captions[id] caption = caption_item["caption"] #pdb.set_trace() prompt = ("You are an AI assistant tasked with creating a concise", f"30-word caption that effectively summarizes the key points of the following content: {caption}") prompt = "\n".join(prompt) completion_request = ChatCompletionRequest(messages=[UserMessage(content=[TextChunk(text=prompt)])]) encoded = tokenizer.encode_chat_completion(completion_request) images = encoded.images tokens = encoded.tokens out_tokens, _ = generate([tokens], model, images=[images], max_tokens=256, temperature=0.35, eos_id=tokenizer.instruct_tokenizer.tokenizer.eos_id) result = tokenizer.decode(out_tokens[0]) result = result.replace("\"","") return result if __name__=="__main__": import tqdm #type: ignore import json import argparse parser = argparse.ArgumentParser(description="Process some integers.") # Add the --part argument parser.add_argument('--part', type=int, required=True, help="Specify the part number as an integer.") # Parse the command-line arguments args = parser.parse_args() # Access the --part argument part = args.part partitions = { 1: {'start': 0, 'end': 12343}, 2: {'start': 12343, 'end': 24686}, 3: {'start': 24686, 'end': 37028}, 4: {'start': 37028, 'end': 49370}, 5: {'start': 49370, 'end': 61711} } index_dict = partitions[part] # load model mistral_models_path = "../Pixtral-12B" tokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json") model = Transformer.from_folder(mistral_models_path) # load data #filename = "rgb_id_text_flair2_train.jsonl" #filename = "elevation_id_text_flair2_test.jsonl" filename = "elevation_id_text_flair2_train.jsonl" #Read the captions captions = [] with open(filename, 'r', encoding='utf-8') as file: for line in file: # Parse each line as JSON captions.append(json.loads(line.strip())) out_filename = f"caption_elevation_id_text_flair2_train_part{part}.jsonl" #out_filename = "caption_elevation_id_text_flair2_test.jsonl" for id in tqdm.tqdm(range(index_dict['start'], index_dict['end'])): #for id in tqdm.tqdm(range(len(captions))): caption = get_caption_from_id(model, captions, id) record = {"id": id, "caption": caption} # Create a structured record with jsonlines.open(out_filename, mode='a') as writer: writer.write(record) # Write one record per line