| import os |
| import torch |
| import dataset4eo as eodata |
| import jsonlines |
| import numpy as np |
| import pdb |
|
|
| from mistral_inference.transformer import Transformer |
| from mistral_inference.generate import generate |
|
|
| from mistral_common.tokens.tokenizers.mistral import MistralTokenizer |
| from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageChunk |
| from mistral_common.protocol.instruct.request import ChatCompletionRequest |
|
|
|
|
| def get_caption_from_id(model, captions, id): |
| caption_item = captions[id] |
| caption = caption_item["caption"] |
| |
|
|
| 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 |
| import json |
| import argparse |
|
|
| parser = argparse.ArgumentParser(description="Process some integers.") |
| |
| parser.add_argument('--part', type=int, required=True, help="Specify the part number as an integer.") |
| |
| |
| args = parser.parse_args() |
| |
| part = args.part |
|
|
| |
| 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] |
|
|
| |
| mistral_models_path = "../Pixtral-12B" |
| tokenizer = MistralTokenizer.from_file(f"{mistral_models_path}/tekken.json") |
| model = Transformer.from_folder(mistral_models_path) |
|
|
| |
| filename = "hyper_id_text_nlcd.jsonl" |
| |
| captions = [] |
| with open(filename, 'r', encoding='utf-8') as file: |
| for line in file: |
| |
| 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} |
| with jsonlines.open(out_filename, mode='a') as writer: |
| writer.write(record) |
|
|
|
|