Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,234 Bytes
52e4f53 |
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
import argparse
import copy
import hashlib
import io
import itertools
import json
import logging
import os
import re
from typing import Dict, Sequence, Tuple
import numpy as np
import xlsxwriter
from datasets import concatenate_datasets, load_dataset
from PIL import Image
from tabulate import tabulate
from termcolor import colored
def buffer_image(image: Image, format: str = "JPEG"):
# Store image in buffer, so we don't have to write it to disk.
buffer = io.BytesIO()
image.save(buffer, format=format)
return buffer, image
def resize(img_or_path: str, size: Tuple[int, int], format="JPEG"):
if isinstance(img_or_path, str):
image = Image.open(img_or_path)
else:
image = img_or_path
# image = image.resize(size)
image.thumbnail(size, Image.LANCZOS)
image = image.convert("RGB")
return buffer_image(image, format)
def calculate_scale(file_path, bound_size):
# check the image size without loading it into memory
im = Image.open(file_path)
original_width, original_height = im.size
# calculate the resize factor, keeping original aspect and staying within boundary
bound_width, bound_height = bound_size
ratios = (float(bound_width) / original_width, float(bound_height) / original_height)
return min(ratios)
def draw_data(all_datasets, output_path, tokenizer=None, image_processor=None):
if hasattr(tokenizer, "image_start_tag"):
image_start_tag = tokenizer.image_start_tag
image_end_tag = tokenizer.image_end_tag
else:
from ..constants import IMG_START_TOKEN, IMG_END_TOKEN
image_start_tag = IMG_START_TOKEN
image_end_tag = IMG_END_TOKEN
workbook = xlsxwriter.Workbook(output_path)
cell_format = workbook.add_format({"text_wrap": True, "font_size": 12})
worksheet = workbook.add_worksheet("ALL")
worksheet.set_column(1, 2, 20, cell_format)
worksheet.set_column(3, 3, 240, cell_format)
worksheet.write(0, 1, "total_num")
worksheet.write(0, 2, "used_num")
worksheet.write(0, 3, "name")
row = 1
for this_name, this_dataset in all_datasets.items():
total_num = this_dataset["total_num"]
used_num = this_dataset["used_num"]
worksheet.write(row, 1, total_num)
worksheet.write(row, 2, used_num)
worksheet.write(row, 3, this_name)
row += 1
worksheet.write(
row, 2, sum([this_dataset["used_num"] for this_dataset in all_datasets.values()])
)
all_base_name = ["all"]
for this_name, this_dataset in all_datasets.items():
base_name = os.path.basename(this_name)
base_name = os.path.splitext(base_name)[0]
base_name = base_name[:24]
all_base_name.append(base_name)
if all_base_name.count(base_name) > 1:
base_name = base_name + "_" + str(all_base_name.count(base_name))
worksheet = workbook.add_worksheet(base_name)
worksheet.set_column(1, 2, 120, cell_format)
worksheet.write(0, 1, "user")
worksheet.write(0, 2, "assistant")
row = 1
data = this_dataset["data"]
for this_data in data:
# print(this_data)
if isinstance(this_data, Dict):
# print(this_data.keys())
messages = this_data["messages"]
if "images" in this_data:
images = this_data["images"]
if "videos" in this_data:
videos = this_data["videos"]
else:
messages = this_data
image_count = 0
video_count = 0
for message in messages:
content = message["content"]
role = message["role"]
if role == "user" or role == "human":
col = 1
else:
col = 2
worksheet.write(row, col, content)
row += 1
bos_pos = [m.start() for m in re.finditer(image_start_tag, content)]
eos_pos = [m.start() for m in re.finditer(image_end_tag, content)]
# print(bos_pos, eos_pos)
for a, b in zip(bos_pos, eos_pos):
# print(content[a+len(image_start_tag:b])
img_path = content[a + len(image_start_tag) : b]
# print(img_path)
worksheet.set_row(row, 200)
try:
image_buffer, image = resize(img_path, (512, 512), format="JPEG")
except:
continue
scale = min(256 / image.width, 256 / image.height)
data = {"x_scale": scale, "y_scale": scale, "object_position": 1}
worksheet.insert_image(row, col, img_path, {"image_data": image_buffer, **data})
row += 1
for _ in range(content.count("<image>") + content.count("<|image|>")):
if images is None:
continue
img_path = images[image_count]
# print(img_path)
worksheet.set_row(row, 200)
try:
image_buffer, image = resize(img_path, (512, 512), format="JPEG")
except:
continue
scale = min(256 / image.width, 256 / image.height)
data = {"x_scale": scale, "y_scale": scale, "object_position": 1}
worksheet.insert_image(row, col, img_path, {"image_data": image_buffer, **data})
row += 1
image_count += 1
for _ in range(content.count("<video>") + content.count("<|video|>")):
if videos is None:
continue
vid_path = videos[video_count]
try:
_, video_frames = image_processor.process_video(vid_path, max_num_frame=4)
# print(vid_path)
except:
continue
for video_frame in video_frames:
worksheet.set_row(row, 200)
try:
image_buffer, image = resize(video_frame, (512, 512), format="JPEG")
except:
continue
scale = min(256 / image.width, 256 / image.height)
data = {"x_scale": scale, "y_scale": scale, "object_position": 1}
if isinstance(video_frame, str):
video_path = video_frame
else:
video_file = hashlib.md5(video_frame.tobytes()).hexdigest() + ".png"
video_path = os.path.join("/tmp/", video_file)
video_frame.save(video_path)
worksheet.insert_image(
row, col, video_path, {"image_data": image_buffer, **data}
)
row += 1
video_count += 1
row += 8
workbook.close()
|