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 # Generate partitions n_total = 15000 n_parts = 5 step = n_total // n_parts partitions = { i: {"start": (i - 1) * step, "end": i * step} for i in range(1, n_parts + 1) } 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 = "hyper_id_text_nlcd.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_hyper_id_text_nlcd_part{part}.jsonl" for id in tqdm.tqdm(range(index_dict['start'], index_dict['end'])): 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