File size: 2,889 Bytes
b8f1589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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