Spaces:
Runtime error
Runtime error
frappuccino
commited on
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +21 -0
- .ipynb_checkpoints/gpt-caption-checkpoint.py +604 -0
- .ipynb_checkpoints/install_linux_mac-checkpoint.sh +39 -0
- .ipynb_checkpoints/start_linux_mac-checkpoint.sh +8 -0
- LICENSE +674 -0
- README-CN.md +127 -0
- README.md +107 -8
- gpt-caption.py +604 -0
- install_linux_mac.sh +39 -0
- install_script/check.txt +19 -0
- install_script/check_open.py +50 -0
- install_script/deepspeed-0.11.2+8ce7471-py3-none-any.whl +0 -0
- install_script/installcog.bat +43 -0
- install_script/installcog.sh +40 -0
- install_script/require.txt +19 -0
- install_script/requirements.txt +11 -0
- install_windows.bat +72 -0
- lib/Api_Utils.py +382 -0
- lib/Detecter.py +60 -0
- lib/Failed_Tagging_File_Screening.py +73 -0
- lib/GPT_Prompt.py +38 -0
- lib/Img_Processing.py +147 -0
- lib/Tag_Processor.py +231 -0
- lib/Translator.py +79 -0
- moondream/__init__.py +2 -0
- moondream/configuration_moondream.py +74 -0
- moondream/modeling_phi.py +720 -0
- moondream/moondream.py +107 -0
- moondream/util.py +13 -0
- moondream/vision_encoder.py +136 -0
- omnichat.py +219 -0
- omnilmm/__init__.py +0 -0
- omnilmm/constants.py +4 -0
- omnilmm/conversation.py +320 -0
- omnilmm/model/__init__.py +1 -0
- omnilmm/model/omnilmm.py +457 -0
- omnilmm/model/resampler.py +171 -0
- omnilmm/model/utils.py +555 -0
- omnilmm/train/train_utils.py +153 -0
- omnilmm/utils.py +127 -0
- openai_api.py +501 -0
- start_linux_mac.sh +8 -0
- start_windows.bat +9 -0
- utils/__init__.py +0 -0
- utils/merge_model.py +42 -0
- utils/split_dataset.py +35 -0
- utils/utils/__init__.py +5 -0
- utils/utils/chat.py +149 -0
- utils/utils/dataset.py +61 -0
- utils/utils/grounding_parser.py +86 -0
.gitignore
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 忽略环境文件夹
|
2 |
+
myenv/
|
3 |
+
__pycache__/
|
4 |
+
models/
|
5 |
+
releases/
|
6 |
+
huggingface/
|
7 |
+
|
8 |
+
# 忽略特定的配置文件和图片
|
9 |
+
api_settings.json
|
10 |
+
saved_prompts.csv
|
11 |
+
install_temp.txt
|
12 |
+
|
13 |
+
# 忽略系统特定的文件
|
14 |
+
Thumbs.db
|
15 |
+
.DS_Store
|
16 |
+
.vs/
|
17 |
+
*.pyproj
|
18 |
+
*.user
|
19 |
+
*.sln
|
20 |
+
|
21 |
+
flash_attn-2.4.2+cu118torch2.0cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
|
.ipynb_checkpoints/gpt-caption-checkpoint.py
ADDED
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import argparse
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import threading
|
6 |
+
|
7 |
+
import concurrent.futures
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
import subprocess
|
11 |
+
import time
|
12 |
+
import requests
|
13 |
+
import socket
|
14 |
+
|
15 |
+
from lib.Img_Processing import process_images_in_folder, run_script
|
16 |
+
from lib.Tag_Processor import modify_file_content, process_tags
|
17 |
+
from lib.GPT_Prompt import get_prompts_from_csv, save_prompt, delete_prompt
|
18 |
+
from lib.Api_Utils import run_openai_api, save_api_details, get_api_details, downloader, installer, save_state, qwen_api_switch
|
19 |
+
from lib.Detecter import detecter
|
20 |
+
|
21 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
22 |
+
mod_default, saved_api_key, saved_api_url = get_api_details()
|
23 |
+
SUPPORTED_IMAGE_FORMATS = ('.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.tif')
|
24 |
+
|
25 |
+
# 图像打标
|
26 |
+
should_stop = threading.Event()
|
27 |
+
def stop_batch_processing():
|
28 |
+
should_stop.set()
|
29 |
+
return "Attempting to stop batch processing. Please wait for the current image to finish."
|
30 |
+
|
31 |
+
def process_single_image(api_key, prompt, api_url, image_path, quality, timeout, model="gpt-4o"):
|
32 |
+
save_api_details(api_key, api_url)
|
33 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
34 |
+
print(caption)
|
35 |
+
return caption
|
36 |
+
|
37 |
+
def process_batch_images(api_key, prompt, api_url, image_dir, file_handling_mode, quality, timeout, model="gpt-4o"):
|
38 |
+
should_stop.clear()
|
39 |
+
save_api_details(api_key, api_url)
|
40 |
+
results = []
|
41 |
+
|
42 |
+
image_files = []
|
43 |
+
for root, dirs, files in os.walk(image_dir):
|
44 |
+
for file in files:
|
45 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
46 |
+
image_files.append(os.path.join(root, file))
|
47 |
+
|
48 |
+
def process_image(filename, file_handling_mode):
|
49 |
+
image_path = os.path.join(image_dir, filename)
|
50 |
+
base_filename = os.path.splitext(filename)[0]
|
51 |
+
caption_filename = f"{base_filename}.txt"
|
52 |
+
caption_path = os.path.join(image_dir, caption_filename)
|
53 |
+
|
54 |
+
if file_handling_mode != "skip/跳过" or not os.path.exists(caption_path):
|
55 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
56 |
+
|
57 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
58 |
+
return handle_error(image_path, caption_path, caption_filename, filename)
|
59 |
+
else:
|
60 |
+
modify_file_content(caption_path, caption, file_handling_mode)
|
61 |
+
return filename, caption_path
|
62 |
+
else:
|
63 |
+
return filename, "Skipped because caption file already exists."
|
64 |
+
|
65 |
+
def handle_error(image_path, caption_path, caption_filename, filename):
|
66 |
+
parent_dir = os.path.dirname(image_dir)
|
67 |
+
error_image_dir = os.path.join(parent_dir, "error_images")
|
68 |
+
if not os.path.exists(error_image_dir):
|
69 |
+
os.makedirs(error_image_dir)
|
70 |
+
|
71 |
+
error_image_path = os.path.join(error_image_dir, filename)
|
72 |
+
error_caption_path = os.path.join(error_image_dir, caption_filename)
|
73 |
+
|
74 |
+
try:
|
75 |
+
shutil.move(image_path, error_image_path)
|
76 |
+
if os.path.exists(caption_path):
|
77 |
+
shutil.move(caption_path, error_caption_path)
|
78 |
+
return filename, "Error handled and image with its caption moved to error directory."
|
79 |
+
except Exception as e:
|
80 |
+
return filename, f"An unexpected error occurred while moving {filename} or {caption_filename}: {e}"
|
81 |
+
|
82 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
83 |
+
futures = {}
|
84 |
+
for filename in image_files:
|
85 |
+
future = executor.submit(process_image, filename, file_handling_mode)
|
86 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
87 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
88 |
+
|
89 |
+
try:
|
90 |
+
for future in concurrent.futures.as_completed(futures):
|
91 |
+
filename = futures[future]
|
92 |
+
if should_stop.is_set():
|
93 |
+
for f in futures:
|
94 |
+
f.cancel()
|
95 |
+
print("Batch processing was stopped by the user.")
|
96 |
+
break
|
97 |
+
try:
|
98 |
+
result = future.result()
|
99 |
+
except Exception as e:
|
100 |
+
result = (filename, f"An exception occurred: {e}")
|
101 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
102 |
+
results.append(result)
|
103 |
+
progress.update(1)
|
104 |
+
finally:
|
105 |
+
progress.close()
|
106 |
+
executor.shutdown(wait=False)
|
107 |
+
|
108 |
+
print(f"Processing complete. Total images processed: {len(results)}")
|
109 |
+
return results
|
110 |
+
|
111 |
+
def handle_file(image_path, target_path, file_handling_mode):
|
112 |
+
try:
|
113 |
+
if file_handling_mode[:4] == "copy":
|
114 |
+
shutil.copy(image_path, target_path)
|
115 |
+
elif file_handling_mode[:4] == "move":
|
116 |
+
shutil.move(image_path, target_path)
|
117 |
+
except Exception as e:
|
118 |
+
print(f"An exception occurred while handling the file {image_path}: {e}")
|
119 |
+
return f"Error handling file {image_path}: {e}"
|
120 |
+
return
|
121 |
+
|
122 |
+
def process_batch_watermark_detection(api_key, prompt, api_url, image_dir, detect_file_handling_mode, quality, timeout,
|
123 |
+
watermark_dir, model="gpt-4o"):
|
124 |
+
should_stop.clear()
|
125 |
+
save_api_details(api_key, api_url)
|
126 |
+
results = []
|
127 |
+
prompt = 'Is image have watermark'
|
128 |
+
|
129 |
+
image_files = []
|
130 |
+
for root, dirs, files in os.walk(image_dir):
|
131 |
+
for file in files:
|
132 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
133 |
+
image_files.append(os.path.join(root, file))
|
134 |
+
|
135 |
+
def process_image(filename, detect_file_handling_mode, watermark_dir):
|
136 |
+
image_path = os.path.join(image_dir, filename)
|
137 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
138 |
+
|
139 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
140 |
+
return "error"
|
141 |
+
|
142 |
+
# EOI是cog迷之误判?
|
143 |
+
if 'Yes,' in caption and '\'EOI\'' not in caption:
|
144 |
+
target_path = os.path.join(watermark_dir, filename)
|
145 |
+
handle_file(filename, watermark_dir, detect_file_handling_mode)
|
146 |
+
|
147 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
148 |
+
futures = {}
|
149 |
+
for filename in image_files:
|
150 |
+
future = executor.submit(process_image, filename, detect_file_handling_mode, watermark_dir)
|
151 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
152 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
153 |
+
|
154 |
+
try:
|
155 |
+
for future in concurrent.futures.as_completed(futures):
|
156 |
+
filename = futures[future] # 获取正在处理的文件名
|
157 |
+
if should_stop.is_set():
|
158 |
+
for f in futures:
|
159 |
+
f.cancel()
|
160 |
+
print("Batch processing was stopped by the user.")
|
161 |
+
break
|
162 |
+
try:
|
163 |
+
result = future.result()
|
164 |
+
except Exception as e:
|
165 |
+
result = (filename, f"An exception occurred: {e}")
|
166 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
167 |
+
results.append(result)
|
168 |
+
progress.update(1)
|
169 |
+
finally:
|
170 |
+
progress.close()
|
171 |
+
executor.shutdown(wait=False)
|
172 |
+
|
173 |
+
results = f"Total checked images: {len(results)}"
|
174 |
+
return results
|
175 |
+
|
176 |
+
def classify_images(api_key, api_url, quality, prompt, timeout, detect_file_handling_mode, image_dir, o_dir, *list_r):
|
177 |
+
|
178 |
+
# 初始化
|
179 |
+
should_stop.clear()
|
180 |
+
save_api_details(api_key, api_url)
|
181 |
+
results = []
|
182 |
+
|
183 |
+
# 检查输入
|
184 |
+
if not os.path.exists(image_dir):
|
185 |
+
return "Error: Image directory does not exist. / 错误:图片目录不存在"
|
186 |
+
if not o_dir:
|
187 |
+
o_dir = os.path.join(image_dir, "classify_output")
|
188 |
+
if not os.path.exists(o_dir):
|
189 |
+
os.makedirs(o_dir)
|
190 |
+
|
191 |
+
# 获取图像
|
192 |
+
image_files = []
|
193 |
+
for root, dirs, files in os.walk(image_dir):
|
194 |
+
for file in files:
|
195 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
196 |
+
image_files.append(os.path.join(root, file))
|
197 |
+
|
198 |
+
# 转换列表
|
199 |
+
rules = []
|
200 |
+
for i in range(0, len(list_r), 2):
|
201 |
+
rule_type = list_r[i]
|
202 |
+
rule_input = list_r[i + 1]
|
203 |
+
if rule_type and rule_input:
|
204 |
+
rule_type_bool = rule_type == "Involve / 包含"
|
205 |
+
rules.append((rule_type_bool, rule_input))
|
206 |
+
if rules == []:
|
207 |
+
return "Error: All rules are empty. / 错误:未设置规则"
|
208 |
+
|
209 |
+
# 图像处理
|
210 |
+
def process_image(filename, rules, detect_file_handling_mode, image_dir, o_dir, model="gpt-4o"):
|
211 |
+
image_path = os.path.join(image_dir, filename)
|
212 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
213 |
+
|
214 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
215 |
+
return "error"
|
216 |
+
|
217 |
+
matching_rules = []
|
218 |
+
for rule_bool, rule_input in rules:
|
219 |
+
if (rule_bool and rule_input in caption) or (not rule_bool and rule_input not in caption):
|
220 |
+
matching_rules.append(rule_input)
|
221 |
+
|
222 |
+
if matching_rules:
|
223 |
+
folder_name = "-".join(matching_rules)
|
224 |
+
target_folder = os.path.join(o_dir, folder_name)
|
225 |
+
os.makedirs(target_folder, exist_ok=True)
|
226 |
+
handle_file(filename, target_folder, detect_file_handling_mode)
|
227 |
+
elif matching_rules == []:
|
228 |
+
no_match_folder = os.path.join(o_dir, "no_match")
|
229 |
+
os.makedirs(no_match_folder, exist_ok=True)
|
230 |
+
handle_file(filename, no_match_folder, detect_file_handling_mode)
|
231 |
+
|
232 |
+
# 批量处理
|
233 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
234 |
+
futures = {}
|
235 |
+
for filename in image_files:
|
236 |
+
future = executor.submit(process_image, filename, rules, detect_file_handling_mode, image_dir, o_dir)
|
237 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
238 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
239 |
+
|
240 |
+
try:
|
241 |
+
for future in concurrent.futures.as_completed(futures):
|
242 |
+
filename = futures[future] # 获取正在处理的文件名
|
243 |
+
|
244 |
+
if should_stop.is_set():
|
245 |
+
for f in futures:
|
246 |
+
f.cancel()
|
247 |
+
print("Batch processing was stopped by the user.")
|
248 |
+
break
|
249 |
+
|
250 |
+
try:
|
251 |
+
result = future.result()
|
252 |
+
except Exception as e:
|
253 |
+
result = (filename, f"An exception occurred: {e}")
|
254 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
255 |
+
results.append(result)
|
256 |
+
progress.update(1)
|
257 |
+
|
258 |
+
|
259 |
+
finally:
|
260 |
+
progress.close()
|
261 |
+
executor.shutdown(wait=False)
|
262 |
+
|
263 |
+
results = f"Total checked images: {len(results)}"
|
264 |
+
return results
|
265 |
+
|
266 |
+
# api
|
267 |
+
def switch_API(api, state):
|
268 |
+
def is_connection():
|
269 |
+
try:
|
270 |
+
socket.create_connection(("127.0.0.1", 8000), timeout=1)
|
271 |
+
print("API has started.")
|
272 |
+
return True
|
273 |
+
except (socket.timeout, ConnectionRefusedError):
|
274 |
+
return False
|
275 |
+
if api[:3] == 'GPT' or api[:4] == "qwen":
|
276 |
+
if is_connection():
|
277 |
+
requests.post(f"http://127.0.0.1:8000/v1/close")
|
278 |
+
key = saved_api_key
|
279 |
+
url = saved_api_url
|
280 |
+
time_out = 100
|
281 |
+
if api[:4] == "qwen" and url.endswith("/v1/services/aigc/multimodal-generation/generation"):
|
282 |
+
mod = qwen_api_switch(api)
|
283 |
+
else:
|
284 |
+
mod = 'GPT4V'
|
285 |
+
s_state = mod
|
286 |
+
|
287 |
+
elif api[:3] == 'Cog' or api[:4] == "moon" or api[:7] == "MiniCPM":
|
288 |
+
if is_connection():
|
289 |
+
if state != api:
|
290 |
+
requests.post(f"http://127.0.0.1:8000/v1/{api}")
|
291 |
+
else:
|
292 |
+
API_command = f'python openai_api.py --mod {api}'
|
293 |
+
subprocess.Popen(API_command,shell=True)
|
294 |
+
while True:
|
295 |
+
if is_connection():
|
296 |
+
break
|
297 |
+
else:
|
298 |
+
print("Retrying...")
|
299 |
+
time.sleep(2)
|
300 |
+
|
301 |
+
key = ""
|
302 |
+
url = "http://127.0.0.1:8000/v1/chat/completions"
|
303 |
+
time_out = 300
|
304 |
+
s_state = api
|
305 |
+
|
306 |
+
return key, url, time_out, s_state
|
307 |
+
|
308 |
+
# UI界面
|
309 |
+
with gr.Blocks(title="GPT4V captioner") as demo:
|
310 |
+
gr.Markdown("### Image Captioning with GPT-4-Vision API / 使用 GPT-4-Vision API 进行图像打标")
|
311 |
+
|
312 |
+
with gr.Row():
|
313 |
+
api_key_input = gr.Textbox(label="API Key", placeholder="Enter your GPT-4-Vision API Key here", type="password",
|
314 |
+
value=saved_api_key)
|
315 |
+
api_url_input = gr.Textbox(label="API URL", value=saved_api_url or "https://api.openai.com/v1/chat/completions",
|
316 |
+
placeholder="Enter the GPT-4-Vision API URL here")
|
317 |
+
api_model_input = gr.Textbox(label="API Model", value="gpt-4o", placeholder="Enter the model name here")
|
318 |
+
quality_choices = ["auto", "high", "low"]
|
319 |
+
quality = gr.Dropdown(choices=quality_choices, label="Image Quality / 图片质量", value="auto")
|
320 |
+
timeout_input = gr.Number(label="Timeout (seconds) / 超时时间(秒)", value=10, step=1)
|
321 |
+
|
322 |
+
prompt_input = gr.Textbox(label="Prompt / 打标需求",
|
323 |
+
value="As an AI image tagging expert, please provide precise tags for these images to enhance CLIP model's understanding of the content. Employ succinct keywords or phrases, steering clear of elaborate sentences and extraneous conjunctions. Prioritize the tags by relevance. Your tags should capture key elements such as the main subject, setting, artistic style, composition, image quality, color tone, filter, and camera specifications, and any other tags crucial for the image. When tagging photos of people, include specific details like gender, nationality, attire, actions, pose, expressions, accessories, makeup, composition type, age, etc. For other image categories, apply appropriate and common descriptive tags as well. Recognize and tag any celebrities, well-known landmark or IPs if clearly featured in the image. Your tags should be accurate, non-duplicative, and within a 20-75 word count range. These tags will use for image re-creation, so the closer the resemblance to the original image, the better the tag quality. Tags should be comma-separated. Exceptional tagging will be rewarded with $10 per image.",
|
324 |
+
placeholder="Enter a descriptive prompt",
|
325 |
+
lines=5)
|
326 |
+
|
327 |
+
with gr.Accordion("Prompt Saving / 提示词存档", open=False):
|
328 |
+
def update_textbox(prompt):
|
329 |
+
return prompt
|
330 |
+
saved_pro = get_prompts_from_csv()
|
331 |
+
saved_prompts_dropdown = gr.Dropdown(label="Saved Prompts / 提示词存档", choices=saved_pro, type="value",interactive=True)
|
332 |
+
with gr.Row():
|
333 |
+
save_prompt_button = gr.Button("Save Prompt / 保存提示词")
|
334 |
+
delete_prompt_button = gr.Button("Delete Prompt / 删除提示词")
|
335 |
+
load_prompt_button = gr.Button("Load Prompt / 读取到输入框")
|
336 |
+
|
337 |
+
save_prompt_button.click(save_prompt, inputs=prompt_input,outputs=[saved_prompts_dropdown])
|
338 |
+
delete_prompt_button.click(delete_prompt, inputs=saved_prompts_dropdown, outputs=[saved_prompts_dropdown])
|
339 |
+
load_prompt_button.click(update_textbox, inputs=saved_prompts_dropdown, outputs=prompt_input)
|
340 |
+
|
341 |
+
with gr.Tab("Image Process / 图片处理"):
|
342 |
+
|
343 |
+
with gr.Tab("Image Zip / 图像预压缩"):
|
344 |
+
with gr.Row():
|
345 |
+
folder_path_input = gr.Textbox(
|
346 |
+
label="Image Folder Path / 图像文件夹路径",
|
347 |
+
placeholder="Enter the folder path containing images / 输入包含图像的文件夹路径"
|
348 |
+
)
|
349 |
+
process_images_button = gr.Button("Process Images / 压缩图像")
|
350 |
+
|
351 |
+
with gr.Row():
|
352 |
+
# Add a Markdown component to display the warning message
|
353 |
+
gr.Markdown("""
|
354 |
+
⚠ **Warning / 警告**: This preprocessing process will resize and compress all image files into jpg format with a total pixel count ≤ 1024×1024 while maintaining the original aspect ratio, ensuring that both dimensions are multiples of 32. **Please make sure to backup your original files before processing!** This procedure can reduce the size of the training set, help to speed up the labeling process, and decrease the time taken to cache latents to disk during training.
|
355 |
+
|
356 |
+
本预处理过程将会在保持原图长宽比情况下,把所有图像文件裁剪压缩为总像素≤1024×1024的jpg文件,并且长宽像素均为32的倍数。**请务必在处理前备份源文件!**该过程可以缩小训练集体积,有助于加快打标速度,并缩短训练过程中的Cache latents to disk时间。
|
357 |
+
""")
|
358 |
+
|
359 |
+
with gr.Row():
|
360 |
+
image_processing_output = gr.Textbox(
|
361 |
+
label="Image Processing Output / 图像处理输出",
|
362 |
+
lines=3
|
363 |
+
)
|
364 |
+
|
365 |
+
process_images_button.click(process_images_in_folder,
|
366 |
+
inputs=[folder_path_input],
|
367 |
+
outputs=[image_processing_output])
|
368 |
+
|
369 |
+
with gr.Tab("Single Image / 单图处理"):
|
370 |
+
with gr.Row():
|
371 |
+
image_input = gr.Image(type='filepath', label="Upload Image / 上传图片")
|
372 |
+
single_image_output = gr.Textbox(label="Caption Output / 标签输出")
|
373 |
+
with gr.Row():
|
374 |
+
single_image_submit = gr.Button("Caption Single Image / 图片打标", variant='primary')
|
375 |
+
|
376 |
+
with gr.Tab("Batch Image / 多图批处理"):
|
377 |
+
with gr.Row():
|
378 |
+
batch_dir_input = gr.Textbox(label="Batch Directory / 批量目录",
|
379 |
+
placeholder="Enter the directory path containing images for batch processing")
|
380 |
+
with gr.Row():
|
381 |
+
batch_process_submit = gr.Button("Batch Process Images / 批量处理图像", variant='primary')
|
382 |
+
with gr.Row():
|
383 |
+
batch_output = gr.Textbox(label="Batch Processing Output / 批量输出")
|
384 |
+
file_handling_mode = gr.Radio(
|
385 |
+
choices=["overwrite/覆盖", "prepend/前置插入", "append/末尾追加", "skip/跳过"],
|
386 |
+
value="overwrite/覆盖",
|
387 |
+
label="If a caption file exists: / 如果已经存在打标文件: "
|
388 |
+
)
|
389 |
+
with gr.Row():
|
390 |
+
stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
391 |
+
stop_button.click(stop_batch_processing, inputs=[], outputs=batch_output)
|
392 |
+
|
393 |
+
with gr.Tab("Failed File Screening / 打标失败文件筛查"):
|
394 |
+
folder_input = gr.Textbox(label="Folder Input / 文件夹输入", placeholder="Enter the directory path")
|
395 |
+
keywords_input = gr.Textbox(placeholder="Enter keywords, e.g., sorry,error / 请输入检索关键词,例如:sorry,error",
|
396 |
+
label="Keywords (optional) / 检索关键词(可选)")
|
397 |
+
run_button = gr.Button("Run Script / 运行脚本", variant='primary')
|
398 |
+
output_area = gr.Textbox(label="Script Output / 脚本输出")
|
399 |
+
|
400 |
+
run_button.click(fn=run_script, inputs=[folder_input, keywords_input], outputs=output_area)
|
401 |
+
|
402 |
+
with gr.Tab("Extra Function / 额外功能"):
|
403 |
+
|
404 |
+
gr.Markdown("""
|
405 |
+
以下功能基于CogVLM开发(GPT4未经测试),极力推荐使用CogVLM-vqa以达到最佳效果。\n
|
406 |
+
This function is developed based on CogVLM (GPT4 not tested), and it is strongly recommended to use CogVLM-vqa for optimal results.
|
407 |
+
""")
|
408 |
+
|
409 |
+
with gr.Tab("Watermark Detection / 批量水印检测"):
|
410 |
+
with gr.Row():
|
411 |
+
detect_batch_dir_input = gr.Textbox(label="Image Directory / 图片目录",
|
412 |
+
placeholder="Enter the directory path containing images for batch processing")
|
413 |
+
with gr.Row():
|
414 |
+
watermark_dir = gr.Textbox(label="Watermark Detected Image Directory / 检测到水印的图片目录",
|
415 |
+
placeholder="Enter the directory path to move/copy detected images")
|
416 |
+
detect_file_handling_mode = gr.Radio(choices=["move/移动", "copy/复制"], value="move/移动",
|
417 |
+
label="If watermark is detected / 如果图片检测到水印 ")
|
418 |
+
with gr.Row():
|
419 |
+
batch_detect_submit = gr.Button("Batch Detect Images / 批量检测图像", variant='primary')
|
420 |
+
with gr.Row():
|
421 |
+
detect_batch_output = gr.Textbox(label="Output / 结果")
|
422 |
+
with gr.Row():
|
423 |
+
detect_stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
424 |
+
detect_stop_button.click(stop_batch_processing, inputs=[], outputs=detect_batch_output)
|
425 |
+
with gr.Tab("Tag Polishing / 标签润色"):
|
426 |
+
gr.Markdown("""
|
427 |
+
使用其他打标器(如WD1.4)对图片进行打标后,在上方prompt中使用“Describe this image in a very detailed manner and refer these prompt tags:{大括号里替换为放置额外tags文件的目录,会自动读取和图片同名txt。比如 D:\ abc\}”\n
|
428 |
+
After marking the image using other captioner(such as WD1.4), enter the prompt in the “” marks in the prompt box.
|
429 |
+
“Describe this image in a very detailed manner and refer these prompt tags:
|
430 |
+
{This is the txt file path for captions, will automatically read the txt file with the same name as the image. For example, D: \ abc\}”
|
431 |
+
""")
|
432 |
+
with gr.Tab("Image filtering / 图片筛选"):
|
433 |
+
gr.Markdown("""
|
434 |
+
使用自定义规则筛选图片,将回答中包含或不包含对应词的图片放入对应规则的文件夹中。输出目录默认在源目录下的classify_output文件夹下。\n
|
435 |
+
Use custom rules to filter images. Place images containing or not containing corresponding words in the corresponding rule folder in the answer. Output Directory default in source directory \classify_output.
|
436 |
+
""")
|
437 |
+
with gr.Row():
|
438 |
+
classify_output = gr.Textbox(label="Output / 结果")
|
439 |
+
classify_button = gr.Button("Run / 开始", variant='primary')
|
440 |
+
classify_stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
441 |
+
with gr.Row():
|
442 |
+
classify_dir = gr.Textbox(label="Input Image Directory / 输入图片目录",placeholder="Enter the directory path")
|
443 |
+
classify_output_dir = gr.Textbox(label="Output Directory / 输出目录", placeholder="Default source directory / 默认源目录")
|
444 |
+
classify_handling_mode = gr.Radio(label="If meets / 如果符合",choices=["move/移动", "copy/复制"], value="move/移动")
|
445 |
+
|
446 |
+
rule_inputs = []
|
447 |
+
for i in range(1,11):
|
448 |
+
with gr.Row():
|
449 |
+
rule_type = gr.Dropdown(label="Rule / 规则类型", choices=["","Involve / 包含", "Exclude / 不包含"], value="")
|
450 |
+
rule_input = gr.Textbox(label="Custom / 自定义", placeholder="Enter the words you need to filter / 输入你需要筛选的词")
|
451 |
+
rule_inputs.extend([rule_type, rule_input])
|
452 |
+
|
453 |
+
def caption_image(api_key, api_url, prompt, image, quality, timeout, model="gpt-4o"):
|
454 |
+
if image:
|
455 |
+
return process_single_image(api_key, prompt, api_url, image, quality, timeout, model)
|
456 |
+
|
457 |
+
def batch_process(api_key, api_url, prompt, batch_dir, file_handling_mode, quality, timeout, model="gpt-4o"):
|
458 |
+
process_batch_images(api_key, prompt, api_url, batch_dir, file_handling_mode, quality, timeout, model)
|
459 |
+
return "Batch processing complete. Captions saved or updated as '.txt' files next to images."
|
460 |
+
|
461 |
+
def batch_detect(api_key, api_url, prompt, batch_dir, detect_file_handling_mode, quality, timeout, watermark_dir, model="gpt-4o"):
|
462 |
+
results = process_batch_watermark_detection(api_key, prompt, api_url, batch_dir, detect_file_handling_mode,
|
463 |
+
quality, timeout,watermark_dir, model)
|
464 |
+
return results
|
465 |
+
|
466 |
+
single_image_submit.click(caption_image,
|
467 |
+
inputs=[api_key_input, api_url_input, prompt_input, image_input, quality, timeout_input, api_model_input],
|
468 |
+
outputs=single_image_output)
|
469 |
+
batch_process_submit.click(batch_process,
|
470 |
+
inputs=[api_key_input, api_url_input, prompt_input, batch_dir_input,
|
471 |
+
file_handling_mode, quality, timeout_input, api_model_input],
|
472 |
+
outputs=batch_output)
|
473 |
+
batch_detect_submit.click(batch_detect,
|
474 |
+
inputs=[api_key_input, api_url_input, prompt_input, detect_batch_dir_input,
|
475 |
+
detect_file_handling_mode, quality, timeout_input, watermark_dir, api_model_input],
|
476 |
+
outputs=detect_batch_output)
|
477 |
+
|
478 |
+
classify_button.click(classify_images,
|
479 |
+
inputs=[api_key_input, api_url_input, quality, prompt_input, timeout_input,
|
480 |
+
classify_handling_mode, classify_dir, classify_output_dir] + rule_inputs,
|
481 |
+
outputs=classify_output)
|
482 |
+
classify_stop_button.click(stop_batch_processing,inputs=[],outputs=classify_output)
|
483 |
+
|
484 |
+
with gr.Tab("Tag Manage / 标签处理"):
|
485 |
+
|
486 |
+
with gr.Row():
|
487 |
+
folder_path_input = gr.Textbox(label="Folder Path / 文件夹路径",
|
488 |
+
placeholder="Enter folder path / 在此输入文件夹路径")
|
489 |
+
top_n_input = gr.Number(label="Top N Tags / Top N 标签", value=100)
|
490 |
+
translate_tags_input = gr.Radio(label="Translate Tags to Chinese / 翻译标签",
|
491 |
+
choices=["GPT-3.5 translation / GPT3.5翻译",
|
492 |
+
"Free translation / 免费翻译",
|
493 |
+
"No translation / 不翻译"],
|
494 |
+
value="No translation / 不翻译")
|
495 |
+
process_tags_button = gr.Button("Process Tags / 处理标签", variant='primary')
|
496 |
+
output_message = gr.Textbox(label="Output Message / 输出信息", interactive=False)
|
497 |
+
|
498 |
+
with gr.Row():
|
499 |
+
tags_to_remove_input = gr.Textbox(label="Tags to Remove / 删除标签",
|
500 |
+
placeholder="Enter tags to remove, separated by commas / 输入要删除的标签,用逗号分隔",
|
501 |
+
lines=3)
|
502 |
+
tags_to_replace_input = gr.Textbox(label="Tags to Replace / 替换标签",
|
503 |
+
placeholder="Enter tags to replace in 'old_tag:new_tag' format, separated by commas / 输入要替换的标签,格式为 '旧标签:新标签',用逗号分隔",
|
504 |
+
lines=3)
|
505 |
+
new_tag_input = gr.Textbox(label="Add New Tag / 添加新标签",
|
506 |
+
placeholder="Enter a new tag to add / 输入一个新标签以添加", lines=3)
|
507 |
+
insert_position_input = gr.Radio(label="New Tag Insert Position / 新标签插入位置",
|
508 |
+
choices=["Start / 开始", "End / 结束", "Random / 随机"],
|
509 |
+
value="Start / 开始")
|
510 |
+
|
511 |
+
with gr.Row():
|
512 |
+
wordcloud_output = gr.Image(label="Word Cloud / 词云")
|
513 |
+
tag_counts_output = gr.Dataframe(label="Top Tags / 高频标签",
|
514 |
+
headers=["Tag Name", "Frequency", "Chinese Translation"],
|
515 |
+
interactive=True) # 修改 Dataframe 组件以显示三列
|
516 |
+
|
517 |
+
with gr.Row():
|
518 |
+
network_graph_output = gr.Image(label="Network Graph / 网络图")
|
519 |
+
|
520 |
+
process_tags_button.click(process_tags,
|
521 |
+
inputs=[folder_path_input, top_n_input, tags_to_remove_input,
|
522 |
+
tags_to_replace_input, new_tag_input, insert_position_input,
|
523 |
+
translate_tags_input, api_key_input, api_url_input], # 新增翻译复选框
|
524 |
+
outputs=[tag_counts_output, wordcloud_output, network_graph_output, output_message])
|
525 |
+
|
526 |
+
|
527 |
+
# API Config
|
528 |
+
with gr.Tab("API Config / API配置"):
|
529 |
+
# 本地模型配置
|
530 |
+
with gr.Accordion("Local Model / 使用本地模型", open=True):
|
531 |
+
with gr.Row():
|
532 |
+
gr.Markdown("""
|
533 |
+
⚠ **Warning / 警告**:
|
534 |
+
This is the API configuration page. To use local model, you need to configure environment and download it.
|
535 |
+
**Moondream** model **size is about 22g+**, and it takes a long time, Please confirm that the disk space is sufficient.Please confirm that your GPU has sufficient graphics memory ***(approximately 6g)***
|
536 |
+
**CogVLM**, you need to configure environment and download it, which is **approximately 35g+** in size and takes a long time ***(really, really long)***.
|
537 |
+
After installation and download, the total space occupied is about ***40g+***. Please confirm that the disk space is sufficient.
|
538 |
+
In addition, in terms of model selection, the vqa model performs better but slower, while the chat model is faster but slightly weaker.
|
539 |
+
Please confirm that your GPU has sufficient graphics memory ***(approximately 14g ±)*** when using CogVLM
|
540 |
+
|
541 |
+
此为API配置页面,使用本地模型需要配置相关环境并下载模型,
|
542 |
+
***moondream***模型大小约为**22g+**需要较长时间,请确认磁盘空间充足。显存需求约为6g,请确认自己的显卡有足够的显存。
|
543 |
+
***CogVLM***大小约为**35g+**,需要较长时间 **(真的很长)**。安装以及下载完成后,总占用空间约为40g+,请确认磁盘空间充足。
|
544 |
+
模型选择上,vqa模型效果更好但是更慢,chat模型更快但是效果略弱。使用CogVLM请确认自己的显卡有足够的显存 ***(约14g±)***
|
545 |
+
""")
|
546 |
+
with gr.Row():
|
547 |
+
detecter_output = gr.Textbox(label="Check Env / 环境检测", interactive=False)
|
548 |
+
detect_button = gr.Button("Check / 检查", variant='primary')
|
549 |
+
with gr.Row():
|
550 |
+
models_select = gr.Radio(label="Choose Models / 选择模型", choices=["moondream","vqa", "chat", "minicpm"], value="moondream")
|
551 |
+
acceleration_select = gr.Radio(label="Choose Default Plz / 选择是否国内加速(如果使用国内加速,请关闭魔法上网)", choices=["CN", "default"],
|
552 |
+
value="CN")
|
553 |
+
download_button = gr.Button("Download Models / 下载模型", variant='primary')
|
554 |
+
install_button = gr.Button("Install / 安装", variant='primary')
|
555 |
+
|
556 |
+
# API配置
|
557 |
+
mod_list = [
|
558 |
+
"GPT4V",
|
559 |
+
"qwen-vl-plus",
|
560 |
+
"qwen-vl-max",
|
561 |
+
"moondream",
|
562 |
+
"Cog-vqa",
|
563 |
+
"Cog-chat",
|
564 |
+
"MiniCPM"
|
565 |
+
]
|
566 |
+
with gr.Row():
|
567 |
+
switch_select = gr.Dropdown(label="Choose API / 选择API", choices=mod_list, value="GPT4V")
|
568 |
+
A_state = gr.Textbox(label="API State / API状态", interactive=False, value=mod_default)
|
569 |
+
switch_button = gr.Button("Switch / 切换", variant='primary')
|
570 |
+
set_default = gr.Button("Set as default / 设为默认", variant='primary')
|
571 |
+
|
572 |
+
|
573 |
+
detect_button.click(detecter, outputs=detecter_output)
|
574 |
+
download_button.click(downloader, inputs=[models_select, acceleration_select],
|
575 |
+
outputs=detecter_output)
|
576 |
+
install_button.click(installer, outputs=detecter_output)
|
577 |
+
switch_button.click(switch_API, inputs=[switch_select, A_state],
|
578 |
+
outputs=[api_key_input, api_url_input, timeout_input, A_state])
|
579 |
+
set_default.click(save_state, inputs=[switch_select, api_key_input, api_url_input], outputs=A_state)
|
580 |
+
|
581 |
+
|
582 |
+
gr.Markdown("""
|
583 |
+
### Developers: [Jiaye](https://civitai.com/user/jiayev1), [LEOSAM 是只兔狲](https://civitai.com/user/LEOSAM), [SleeeepyZhou](https://civitai.com/user/SleeeepyZhou), [Fok](https://civitai.com/user/fok3827), [gluttony-10](https://github.com/gluttony-10), [327](https://github.com/327), [十字鱼](https://space.bilibili.com/893892) | Welcome everyone to add more new features to this project.
|
584 |
+
""")
|
585 |
+
|
586 |
+
# 启动参数
|
587 |
+
def get_args():
|
588 |
+
parser = argparse.ArgumentParser(description='GPT4V-Image-Captioner启动参数')
|
589 |
+
parser.add_argument("--port", type=int, default="8848", help="占用端口,默认8848")
|
590 |
+
parser.add_argument("--listen", action='store_true', help="打开远程连接,默认关闭")
|
591 |
+
parser.add_argument("--share", action='store_true', help="打开gradio共享,默认关闭")
|
592 |
+
parser.add_argument("--no-browser", action='store_true', help="不要自动打开浏览器,默认关闭")
|
593 |
+
return parser.parse_args()
|
594 |
+
|
595 |
+
args = get_args()
|
596 |
+
|
597 |
+
if __name__ == "__main__":
|
598 |
+
threading.Thread(target=lambda: switch_API(mod_default, 'GPT')).start()
|
599 |
+
demo.launch(
|
600 |
+
server_name="0.0.0.0" if args.listen else None,
|
601 |
+
server_port=args.port,
|
602 |
+
share=args.share,
|
603 |
+
inbrowser=False if args.no_browser else True
|
604 |
+
)
|
.ipynb_checkpoints/install_linux_mac-checkpoint.sh
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Define the Python version
|
4 |
+
PYTHON_VERSION=3.10.
|
5 |
+
|
6 |
+
# Check if Python is installed and the version is as expected
|
7 |
+
if ! command -v python3 --version &>/dev/null || ! python3 --version | grep -q "$PYTHON_VERSION"; then
|
8 |
+
echo "Python is not installed or not the expected version. Please install Python $PYTHON_VERSION."
|
9 |
+
exit 1
|
10 |
+
fi
|
11 |
+
|
12 |
+
echo "Python is installed."
|
13 |
+
|
14 |
+
# Ping google to decide if use mirror
|
15 |
+
target_url="www.google.com"
|
16 |
+
timeout=3000
|
17 |
+
ping -c 1 -W $timeout $target_url -w 3 > /dev/null
|
18 |
+
|
19 |
+
if [ $? -ne 0 ]; then
|
20 |
+
echo "Use CN"
|
21 |
+
export PIP_DISABLE_PIP_VERSION_CHECK=1
|
22 |
+
export PIP_NO_CACHE_DIR=1
|
23 |
+
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
24 |
+
else
|
25 |
+
echo "Use default"
|
26 |
+
fi
|
27 |
+
|
28 |
+
# Upgrade pip to the latest version
|
29 |
+
pip install --upgrade pip
|
30 |
+
|
31 |
+
# Install necessary Python libraries
|
32 |
+
pip install -r ./install_script/requirements.txt
|
33 |
+
|
34 |
+
echo ""
|
35 |
+
echo "Install completed, please run Start to open the GUI"
|
36 |
+
echo "安装完毕,请运行Start打开GUI"
|
37 |
+
echo ""
|
38 |
+
read -p "press any key to continue...
|
39 |
+
按任意键继续..."
|
.ipynb_checkpoints/start_linux_mac-checkpoint.sh
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
export HF_HOME="huggingface"
|
3 |
+
|
4 |
+
python ./install_script/check_open.py
|
5 |
+
|
6 |
+
python gpt-caption.py --share "$@"
|
7 |
+
|
8 |
+
read -p "Press any key to continue . . . "
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README-CN.md
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# GPT4V-Image-Captioner / GPT4V图像打标器
|
2 |
+
|
3 |
+
[软件安装&演示视频](https://www.bilibili.com/video/BV1pw411g7X1/?spm_id_from=333.999.0.0&vd_source=22436c5073194cf38787049c34e04e02)
|
4 |
+
|
5 |
+
[英文版说明](https://github.com/jiayev/GPT4V-Image-Captioner/blob/main/README.md)
|
6 |
+
|
7 |
+
现在我们有SDwebUI插件版本[sd-webui-GPT4V-Image-Captioner](https://github.com/SleeeepyZhou/sd-webui-GPT4V-Image-Captioner)。
|
8 |
+
|
9 |
+
这是一款使用 Gradio 构建,可使用GPT-4-vision API、阿里云[通义千问VL](https://modelscope.cn/organization/qwen)、[Moondream](https://github.com/vikhyat/moondream)模型 或 [CogVLM](https://github.com/THUDM/CogVLM)模型进行图像打标的多功能图像处理工具箱。特色功能包括:
|
10 |
+
|
11 |
+
- 一键安装及使用
|
12 |
+
- 单图反推及批量打标功能
|
13 |
+
- 云端 GPT4V 或 Claude 3 及阿里云[通义千问VL](https://modelscope.cn/organization/qwen) & 本地 [CogVLM](https://github.com/THUDM/CogVLM) 或 [Moondream](https://github.com/vikhyat/moondream)双模型可选
|
14 |
+
- 可视化标签分析与处理
|
15 |
+
- 图像分桶预压缩
|
16 |
+
- 关键词筛查及水印图像识别
|
17 |
+
- 图像自定义识别分类
|
18 |
+
|
19 |
+
开发者: [Jiaye](https://civitai.com/user/jiayev1), [LEOSAM是只兔狲](https://civitai.com/user/LEOSAM), [SleeeepyZhou](https://space.bilibili.com/360375877), [Fok](https://civitai.com/user/fok3827), GPT4。 欢迎有兴趣的朋友加入,对本项目进行进一步的完善改进。
|
20 |
+
|
21 |
+
|
22 |
+
![下载](https://github.com/jiayev/GPT4V-Image-Captioner/assets/16369810/90612e2b-aac1-4368-84d6-482bb660f5aa)
|
23 |
+
|
24 |
+
要使用Claude 3,只需将API密钥和URL替换为Claude 3的API密钥和URL (/v1/messages),并将模型名称更改为"claude-3-opus"(或sonnet)。
|
25 |
+
|
26 |
+
# 安装和启动指南
|
27 |
+
|
28 |
+
### Windows(如自动安装失败,请参考[手动安装说明](#windows-手动安装说明))
|
29 |
+
|
30 |
+
1. 以管理员权限打开命令提示符,并导航到您想要克隆仓库的目录。
|
31 |
+
2. 使用以下命令克隆仓库:
|
32 |
+
```
|
33 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
34 |
+
```
|
35 |
+
3. 双击 `install_windows.bat` 运行,并安装所有必要的依赖项。
|
36 |
+
4. 安装完成后,您可以通过双击 `start_windows.bat`来在终端中启动GPT4V-Image-Captioner。
|
37 |
+
5. 按住ctrl并点击终端中的URL地址(或复制URL地址在浏览器打开),将在默认浏览器中跳转打开Gradio应用界面。
|
38 |
+
6. 请在界面最上方输入OpenAI官方或者第三方的GPT-4V API Key与API Url,设置图像地址后,就可以图像打标了。
|
39 |
+
|
40 |
+
|
41 |
+
### Linux / macOS
|
42 |
+
|
43 |
+
1. 打开终端,并导航到您想要克隆仓库的目录。
|
44 |
+
2. 使用以下命令克隆仓库:
|
45 |
+
```
|
46 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
47 |
+
```
|
48 |
+
3. 导航到克隆的目录:
|
49 |
+
```
|
50 |
+
cd GPT4V-Image-Captioner
|
51 |
+
```
|
52 |
+
4. 使用以下命令使安装脚本和启动脚本变为可执行:
|
53 |
+
```
|
54 |
+
chmod +x install_linux_mac.sh; chmod +x Start_linux_mac.sh
|
55 |
+
```
|
56 |
+
5. 执行安装脚本:
|
57 |
+
```
|
58 |
+
./install_linux_mac.sh
|
59 |
+
```
|
60 |
+
6. 在终端中执行启动脚本来启动GPT4V-Image-Captioner。
|
61 |
+
```
|
62 |
+
./start_linux_mac.sh
|
63 |
+
```
|
64 |
+
7. 复制终端中显示的URL地址,在浏览器中打开Gradio应用界面。
|
65 |
+
8. 请在界面最上方输入OpenAI官方或者第三方的GPT-4V API Key与API Url,设置图像地址后,就可以图像打标了。
|
66 |
+
|
67 |
+
|
68 |
+
### Windows 手动安装说明
|
69 |
+
|
70 |
+
1. 按 `Win + R` 打开命令提示符。键入 `cmd` 然后按 `Enter` 。
|
71 |
+
|
72 |
+
2. 使用下面的命令克隆仓库至本地:
|
73 |
+
```
|
74 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
75 |
+
```
|
76 |
+
|
77 |
+
3. 克隆完成后,切换到克隆的目录中:
|
78 |
+
```
|
79 |
+
cd GPT4V-Image-Captioner
|
80 |
+
```
|
81 |
+
|
82 |
+
4. 在安装依赖库之前,在命令提示符中输入以下命令并按 `Enter` 来检查是否电脑已经安装了 Python:
|
83 |
+
```
|
84 |
+
python --version
|
85 |
+
```
|
86 |
+
如果未安装,会显示错误信息。请访问 [Python 官方下载页面](https://www.python.org/downloads/) 并按照指示进行安装。
|
87 |
+
|
88 |
+
5. 创建一个名为 `myenv` 的虚拟环境以避免污染全局 Python 环境:
|
89 |
+
```
|
90 |
+
python -m venv myenv
|
91 |
+
```
|
92 |
+
|
93 |
+
6. 激活你刚创建的虚拟环境:
|
94 |
+
```
|
95 |
+
myenv\Scripts\activate
|
96 |
+
```
|
97 |
+
|
98 |
+
7. 更新 `pip`至最新版本:
|
99 |
+
```
|
100 |
+
python -m pip install --upgrade pip
|
101 |
+
```
|
102 |
+
|
103 |
+
8. 在虚拟环境中安装 `requests`、`gradio` 、 `tqdm` 等库:
|
104 |
+
```
|
105 |
+
pip install scipy networkx wordcloud matplotlib Pillow tqdm gradio requests
|
106 |
+
```
|
107 |
+
|
108 |
+
9. 完成上述步骤后,可通过双击 `Start_windows.bat` 文件来启动 GPT4V-Image-Captioner。
|
109 |
+
|
110 |
+
|
111 |
+
## 更新内容
|
112 |
+
|
113 |
+
### 2024年1月6日
|
114 |
+
- **更智能的一键安装**: 增加了更智能的一键安装 (`install_windows.bat`) 功能,国内的小伙伴不用再看着pip十几kb慢慢爬了,更加国际化(×,简化了程序的安装。
|
115 |
+
- **CogVLM支持**: 增加了CogVLM模型的一键安装以及切换页面,没有GPT4的小伙伴也可以靠本地多模态快乐玩耍了(穷哥们狂喜。
|
116 |
+
|
117 |
+
### 2024年1月2日
|
118 |
+
- **一键安装和一键启动**: 增加了一键安装 (`install_windows.bat` / `install_linux_mac.sh`) 和一键启动 (`Start_windows.bat` / `Start_linux_mac.sh`) 功能,简化了程序的安装和启动过程。
|
119 |
+
- **环境说明补充**: 补充了在Windows和Linux环境下程序的安装和启动说明。
|
120 |
+
|
121 |
+
### 2024年1月1日
|
122 |
+
- **运行加速**: 提高了程序的打标速度。现在可以在2-3秒内完成一张图片的标注。
|
123 |
+
- **标签处理**: 对于已有标签的图像文件,提供了以下不同处理选项:"覆盖", "前置插入", "结尾追加" 和 "跳过"。
|
124 |
+
- **子文件夹处理**: 新程序能够处理文件夹及其子文件夹中的所有图像文件,支持的图像格式包括:'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.tif'。
|
125 |
+
- **程序中断**: 增加了在批量打标签过程中中断打标的功能。
|
126 |
+
- **报错筛查**: 可以根据关键词,将所有GPT标记失败的图像(例如NSFW内容)移动到新的文件夹中。
|
127 |
+
- **本地化**: 增加了对中文的支持。
|
README.md
CHANGED
@@ -1,12 +1,111 @@
|
|
1 |
---
|
2 |
-
title: GPT4V
|
3 |
-
|
4 |
-
colorFrom: green
|
5 |
-
colorTo: purple
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 4.
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
---
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
title: GPT4V-Image-Captioner
|
3 |
+
app_file: gpt-caption.py
|
|
|
|
|
4 |
sdk: gradio
|
5 |
+
sdk_version: 4.21.0
|
|
|
|
|
6 |
---
|
7 |
+
# GPT4V-Image-Captioner / GPT4V图像打标器
|
8 |
|
9 |
+
[中文版说明](https://github.com/jiayev/GPT4V-Image-Captioner/blob/main/README-CN.md)
|
10 |
+
|
11 |
+
We now have [sd-webui-GPT4V-Image-Captioner](https://github.com/SleeeepyZhou/sd-webui-GPT4V-Image-Captioner) for SD WebUI
|
12 |
+
|
13 |
+
This is a multifunctional image processing toolbox built with Gradio, capable of tagging images using the GPT-4-vision or Claude 3 API, the [cogVLM](https://github.com/THUDM/CogVLM) model, [Qwen-VL](https://huggingface.co/Qwen)(Alibaba Cloud), the [Moondream](https://github.com/vikhyat/moondream) model.
|
14 |
+
|
15 |
+
Key features include:
|
16 |
+
|
17 |
+
- One-click installation and use
|
18 |
+
- Single image and multi-image batch tagging
|
19 |
+
- Choice of online GPT4V or Claude 3 or [Qwen-VL](https://huggingface.co/Qwen)(Alibaba Cloud) & local CogVLM and Moondream models
|
20 |
+
- Visual tag analysis and processing
|
21 |
+
- Image pre-compression
|
22 |
+
- Keyword filtering and watermark image recognition
|
23 |
+
|
24 |
+
Developers: [Jiaye](https://civitai.com/user/jiayev1), [LEOSAM是只兔狲](https://civitai.com/user/LEOSAM), [SleeeepyZhou](https://civitai.com/user/SleeeepyZhou), [Fok](https://civitai.com/user/fok3827), GPT4. Welcome everyone to add more new features to this project.
|
25 |
+
|
26 |
+
![下载](https://github.com/jiayev/GPT4V-Image-Captioner/assets/16369810/90612e2b-aac1-4368-84d6-482bb660f5aa)
|
27 |
+
|
28 |
+
### Please note that the Claude 3 feature is not finished yet.
|
29 |
+
To use Claude 3, simply replace the API key and URL with the Claude 3 API key and URL (/v1/messages), and changing the model name to "claude-3-opus" (or sonnet).
|
30 |
+
|
31 |
+
# Installation and Startup Guide
|
32 |
+
|
33 |
+
### Windows (If the automatic installation fails, please refer to the [Manual Installation Instructions](#windows-manual-installation-instructions))
|
34 |
+
|
35 |
+
1. Open Command Prompt as administrator and navigate to the directory where you want to clone the repository.
|
36 |
+
2. Clone the repository using the following command:
|
37 |
+
```
|
38 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
39 |
+
```
|
40 |
+
3. Double-click `install_windows.bat` to run and install all necessary dependencies.
|
41 |
+
4. After the installation is complete, you can launch the GPT4V-Image-Captioner by double-clicking `start_windows.bat`.
|
42 |
+
5. Hold down Ctrl and click on the URL in the terminal (or copy the URL to your browser), which will open the Gradio app interface in your default browser.
|
43 |
+
6. Enter the official OpenAI or third-party GPT-4V API Key and API Url at the top of the interface. After setting the image address, you can start tagging the image.
|
44 |
+
|
45 |
+
### Linux / macOS
|
46 |
+
|
47 |
+
1. Open a terminal and navigate to the directory where you want to clone the repository.
|
48 |
+
2. Clone the repository using the following command:
|
49 |
+
```
|
50 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
51 |
+
```
|
52 |
+
3. Navigate to the cloned directory:
|
53 |
+
```
|
54 |
+
cd GPT4V-Image-Captioner
|
55 |
+
```
|
56 |
+
4. Make the install and start scripts executable with the following command:
|
57 |
+
```
|
58 |
+
chmod +x install_linux_mac.sh; chmod +x start_linux_mac.sh
|
59 |
+
```
|
60 |
+
5. Execute the install script:
|
61 |
+
```
|
62 |
+
./install_linux_mac.sh
|
63 |
+
```
|
64 |
+
6. Launch the GPT4V-Image-Captioner in the terminal by executing the launch script:
|
65 |
+
```
|
66 |
+
./start_linux_mac.sh
|
67 |
+
```
|
68 |
+
7. Copy the URL displayed in the terminal and open it in your browser to access the Gradio app interface.
|
69 |
+
8. Enter the official OpenAI or third-party GPT-4V API Key and API Url at the top of the interface. After setting the image address, you can start tagging the image.
|
70 |
+
|
71 |
+
### Windows Manual Installation Instructions
|
72 |
+
|
73 |
+
1. Open the Command Prompt by pressing `Win + R`, typing `cmd`, and then pressing `Enter`.
|
74 |
+
|
75 |
+
2. Clone the repository to your local machine using the following command:
|
76 |
+
```
|
77 |
+
git clone https://github.com/jiayev/GPT4V-Image-Captioner
|
78 |
+
```
|
79 |
+
|
80 |
+
3. Once cloning is complete, navigate to the cloned directory:
|
81 |
+
```
|
82 |
+
cd GPT4V-Image-Captioner
|
83 |
+
```
|
84 |
+
|
85 |
+
4. Before installing any dependencies, make sure that Python is installed on your system. Check for Python's presence by typing the following command and pressing `Enter` in the Command Prompt:
|
86 |
+
```
|
87 |
+
python --version
|
88 |
+
```
|
89 |
+
If Python is not installed, you will get an error message. In that case, please visit the [Python official download page](https://www.python.org/downloads/) and follow the instructions to install it.
|
90 |
+
|
91 |
+
5. Create a virtual environment named `myenv` to avoid contaminating the global Python environment:
|
92 |
+
```
|
93 |
+
python -m venv myenv
|
94 |
+
```
|
95 |
+
|
96 |
+
6. Activate the virtual environment you just created:
|
97 |
+
```
|
98 |
+
myenv\Scripts\activate
|
99 |
+
```
|
100 |
+
|
101 |
+
7. Update `pip` to date:
|
102 |
+
```
|
103 |
+
python -m pip install --upgrade pip
|
104 |
+
```
|
105 |
+
|
106 |
+
8. Install libraries within the virtual environment:
|
107 |
+
```
|
108 |
+
pip install scipy networkx wordcloud matplotlib Pillow tqdm gradio requests
|
109 |
+
```
|
110 |
+
|
111 |
+
9. After completing the steps above, you can start GPT4V-Image-Captioner by double-clicking the `start_windows.bat` file.
|
gpt-caption.py
ADDED
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import argparse
|
3 |
+
import os
|
4 |
+
import shutil
|
5 |
+
import threading
|
6 |
+
|
7 |
+
import concurrent.futures
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
import subprocess
|
11 |
+
import time
|
12 |
+
import requests
|
13 |
+
import socket
|
14 |
+
|
15 |
+
from lib.Img_Processing import process_images_in_folder, run_script
|
16 |
+
from lib.Tag_Processor import modify_file_content, process_tags
|
17 |
+
from lib.GPT_Prompt import get_prompts_from_csv, save_prompt, delete_prompt
|
18 |
+
from lib.Api_Utils import run_openai_api, save_api_details, get_api_details, downloader, installer, save_state, qwen_api_switch
|
19 |
+
from lib.Detecter import detecter
|
20 |
+
|
21 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
22 |
+
mod_default, saved_api_key, saved_api_url = get_api_details()
|
23 |
+
SUPPORTED_IMAGE_FORMATS = ('.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.tif')
|
24 |
+
|
25 |
+
# 图像打标
|
26 |
+
should_stop = threading.Event()
|
27 |
+
def stop_batch_processing():
|
28 |
+
should_stop.set()
|
29 |
+
return "Attempting to stop batch processing. Please wait for the current image to finish."
|
30 |
+
|
31 |
+
def process_single_image(api_key, prompt, api_url, image_path, quality, timeout, model="gpt-4o"):
|
32 |
+
save_api_details(api_key, api_url)
|
33 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
34 |
+
print(caption)
|
35 |
+
return caption
|
36 |
+
|
37 |
+
def process_batch_images(api_key, prompt, api_url, image_dir, file_handling_mode, quality, timeout, model="gpt-4o"):
|
38 |
+
should_stop.clear()
|
39 |
+
save_api_details(api_key, api_url)
|
40 |
+
results = []
|
41 |
+
|
42 |
+
image_files = []
|
43 |
+
for root, dirs, files in os.walk(image_dir):
|
44 |
+
for file in files:
|
45 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
46 |
+
image_files.append(os.path.join(root, file))
|
47 |
+
|
48 |
+
def process_image(filename, file_handling_mode):
|
49 |
+
image_path = os.path.join(image_dir, filename)
|
50 |
+
base_filename = os.path.splitext(filename)[0]
|
51 |
+
caption_filename = f"{base_filename}.txt"
|
52 |
+
caption_path = os.path.join(image_dir, caption_filename)
|
53 |
+
|
54 |
+
if file_handling_mode != "skip/跳过" or not os.path.exists(caption_path):
|
55 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
56 |
+
|
57 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
58 |
+
return handle_error(image_path, caption_path, caption_filename, filename)
|
59 |
+
else:
|
60 |
+
modify_file_content(caption_path, caption, file_handling_mode)
|
61 |
+
return filename, caption_path
|
62 |
+
else:
|
63 |
+
return filename, "Skipped because caption file already exists."
|
64 |
+
|
65 |
+
def handle_error(image_path, caption_path, caption_filename, filename):
|
66 |
+
parent_dir = os.path.dirname(image_dir)
|
67 |
+
error_image_dir = os.path.join(parent_dir, "error_images")
|
68 |
+
if not os.path.exists(error_image_dir):
|
69 |
+
os.makedirs(error_image_dir)
|
70 |
+
|
71 |
+
error_image_path = os.path.join(error_image_dir, filename)
|
72 |
+
error_caption_path = os.path.join(error_image_dir, caption_filename)
|
73 |
+
|
74 |
+
try:
|
75 |
+
shutil.move(image_path, error_image_path)
|
76 |
+
if os.path.exists(caption_path):
|
77 |
+
shutil.move(caption_path, error_caption_path)
|
78 |
+
return filename, "Error handled and image with its caption moved to error directory."
|
79 |
+
except Exception as e:
|
80 |
+
return filename, f"An unexpected error occurred while moving {filename} or {caption_filename}: {e}"
|
81 |
+
|
82 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
83 |
+
futures = {}
|
84 |
+
for filename in image_files:
|
85 |
+
future = executor.submit(process_image, filename, file_handling_mode)
|
86 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
87 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
88 |
+
|
89 |
+
try:
|
90 |
+
for future in concurrent.futures.as_completed(futures):
|
91 |
+
filename = futures[future]
|
92 |
+
if should_stop.is_set():
|
93 |
+
for f in futures:
|
94 |
+
f.cancel()
|
95 |
+
print("Batch processing was stopped by the user.")
|
96 |
+
break
|
97 |
+
try:
|
98 |
+
result = future.result()
|
99 |
+
except Exception as e:
|
100 |
+
result = (filename, f"An exception occurred: {e}")
|
101 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
102 |
+
results.append(result)
|
103 |
+
progress.update(1)
|
104 |
+
finally:
|
105 |
+
progress.close()
|
106 |
+
executor.shutdown(wait=False)
|
107 |
+
|
108 |
+
print(f"Processing complete. Total images processed: {len(results)}")
|
109 |
+
return results
|
110 |
+
|
111 |
+
def handle_file(image_path, target_path, file_handling_mode):
|
112 |
+
try:
|
113 |
+
if file_handling_mode[:4] == "copy":
|
114 |
+
shutil.copy(image_path, target_path)
|
115 |
+
elif file_handling_mode[:4] == "move":
|
116 |
+
shutil.move(image_path, target_path)
|
117 |
+
except Exception as e:
|
118 |
+
print(f"An exception occurred while handling the file {image_path}: {e}")
|
119 |
+
return f"Error handling file {image_path}: {e}"
|
120 |
+
return
|
121 |
+
|
122 |
+
def process_batch_watermark_detection(api_key, prompt, api_url, image_dir, detect_file_handling_mode, quality, timeout,
|
123 |
+
watermark_dir, model="gpt-4o"):
|
124 |
+
should_stop.clear()
|
125 |
+
save_api_details(api_key, api_url)
|
126 |
+
results = []
|
127 |
+
prompt = 'Is image have watermark'
|
128 |
+
|
129 |
+
image_files = []
|
130 |
+
for root, dirs, files in os.walk(image_dir):
|
131 |
+
for file in files:
|
132 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
133 |
+
image_files.append(os.path.join(root, file))
|
134 |
+
|
135 |
+
def process_image(filename, detect_file_handling_mode, watermark_dir):
|
136 |
+
image_path = os.path.join(image_dir, filename)
|
137 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
138 |
+
|
139 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
140 |
+
return "error"
|
141 |
+
|
142 |
+
# EOI是cog迷之误判?
|
143 |
+
if 'Yes,' in caption and '\'EOI\'' not in caption:
|
144 |
+
target_path = os.path.join(watermark_dir, filename)
|
145 |
+
handle_file(filename, watermark_dir, detect_file_handling_mode)
|
146 |
+
|
147 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
148 |
+
futures = {}
|
149 |
+
for filename in image_files:
|
150 |
+
future = executor.submit(process_image, filename, detect_file_handling_mode, watermark_dir)
|
151 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
152 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
153 |
+
|
154 |
+
try:
|
155 |
+
for future in concurrent.futures.as_completed(futures):
|
156 |
+
filename = futures[future] # 获取正在处理的文件名
|
157 |
+
if should_stop.is_set():
|
158 |
+
for f in futures:
|
159 |
+
f.cancel()
|
160 |
+
print("Batch processing was stopped by the user.")
|
161 |
+
break
|
162 |
+
try:
|
163 |
+
result = future.result()
|
164 |
+
except Exception as e:
|
165 |
+
result = (filename, f"An exception occurred: {e}")
|
166 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
167 |
+
results.append(result)
|
168 |
+
progress.update(1)
|
169 |
+
finally:
|
170 |
+
progress.close()
|
171 |
+
executor.shutdown(wait=False)
|
172 |
+
|
173 |
+
results = f"Total checked images: {len(results)}"
|
174 |
+
return results
|
175 |
+
|
176 |
+
def classify_images(api_key, api_url, quality, prompt, timeout, detect_file_handling_mode, image_dir, o_dir, *list_r):
|
177 |
+
|
178 |
+
# 初始化
|
179 |
+
should_stop.clear()
|
180 |
+
save_api_details(api_key, api_url)
|
181 |
+
results = []
|
182 |
+
|
183 |
+
# 检查输入
|
184 |
+
if not os.path.exists(image_dir):
|
185 |
+
return "Error: Image directory does not exist. / 错误:图片目录不存在"
|
186 |
+
if not o_dir:
|
187 |
+
o_dir = os.path.join(image_dir, "classify_output")
|
188 |
+
if not os.path.exists(o_dir):
|
189 |
+
os.makedirs(o_dir)
|
190 |
+
|
191 |
+
# 获取图像
|
192 |
+
image_files = []
|
193 |
+
for root, dirs, files in os.walk(image_dir):
|
194 |
+
for file in files:
|
195 |
+
if file.lower().endswith(SUPPORTED_IMAGE_FORMATS):
|
196 |
+
image_files.append(os.path.join(root, file))
|
197 |
+
|
198 |
+
# 转换列表
|
199 |
+
rules = []
|
200 |
+
for i in range(0, len(list_r), 2):
|
201 |
+
rule_type = list_r[i]
|
202 |
+
rule_input = list_r[i + 1]
|
203 |
+
if rule_type and rule_input:
|
204 |
+
rule_type_bool = rule_type == "Involve / 包含"
|
205 |
+
rules.append((rule_type_bool, rule_input))
|
206 |
+
if rules == []:
|
207 |
+
return "Error: All rules are empty. / 错误:未设置规则"
|
208 |
+
|
209 |
+
# 图像处理
|
210 |
+
def process_image(filename, rules, detect_file_handling_mode, image_dir, o_dir, model="gpt-4o"):
|
211 |
+
image_path = os.path.join(image_dir, filename)
|
212 |
+
caption = run_openai_api(image_path, prompt, api_key, api_url, quality, timeout, model)
|
213 |
+
|
214 |
+
if caption.startswith("Error:") or caption.startswith("API error:"):
|
215 |
+
return "error"
|
216 |
+
|
217 |
+
matching_rules = []
|
218 |
+
for rule_bool, rule_input in rules:
|
219 |
+
if (rule_bool and rule_input in caption) or (not rule_bool and rule_input not in caption):
|
220 |
+
matching_rules.append(rule_input)
|
221 |
+
|
222 |
+
if matching_rules:
|
223 |
+
folder_name = "-".join(matching_rules)
|
224 |
+
target_folder = os.path.join(o_dir, folder_name)
|
225 |
+
os.makedirs(target_folder, exist_ok=True)
|
226 |
+
handle_file(filename, target_folder, detect_file_handling_mode)
|
227 |
+
elif matching_rules == []:
|
228 |
+
no_match_folder = os.path.join(o_dir, "no_match")
|
229 |
+
os.makedirs(no_match_folder, exist_ok=True)
|
230 |
+
handle_file(filename, no_match_folder, detect_file_handling_mode)
|
231 |
+
|
232 |
+
# 批量处理
|
233 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
234 |
+
futures = {}
|
235 |
+
for filename in image_files:
|
236 |
+
future = executor.submit(process_image, filename, rules, detect_file_handling_mode, image_dir, o_dir)
|
237 |
+
futures[future] = filename # 将 future 和 filename 映射起来
|
238 |
+
progress = tqdm(total=len(futures), desc="Processing images")
|
239 |
+
|
240 |
+
try:
|
241 |
+
for future in concurrent.futures.as_completed(futures):
|
242 |
+
filename = futures[future] # 获取正在处理的文件名
|
243 |
+
|
244 |
+
if should_stop.is_set():
|
245 |
+
for f in futures:
|
246 |
+
f.cancel()
|
247 |
+
print("Batch processing was stopped by the user.")
|
248 |
+
break
|
249 |
+
|
250 |
+
try:
|
251 |
+
result = future.result()
|
252 |
+
except Exception as e:
|
253 |
+
result = (filename, f"An exception occurred: {e}")
|
254 |
+
print(f"An exception occurred while processing {filename}: {e}")
|
255 |
+
results.append(result)
|
256 |
+
progress.update(1)
|
257 |
+
|
258 |
+
|
259 |
+
finally:
|
260 |
+
progress.close()
|
261 |
+
executor.shutdown(wait=False)
|
262 |
+
|
263 |
+
results = f"Total checked images: {len(results)}"
|
264 |
+
return results
|
265 |
+
|
266 |
+
# api
|
267 |
+
def switch_API(api, state):
|
268 |
+
def is_connection():
|
269 |
+
try:
|
270 |
+
socket.create_connection(("127.0.0.1", 8000), timeout=1)
|
271 |
+
print("API has started.")
|
272 |
+
return True
|
273 |
+
except (socket.timeout, ConnectionRefusedError):
|
274 |
+
return False
|
275 |
+
if api[:3] == 'GPT' or api[:4] == "qwen":
|
276 |
+
if is_connection():
|
277 |
+
requests.post(f"http://127.0.0.1:8000/v1/close")
|
278 |
+
key = saved_api_key
|
279 |
+
url = saved_api_url
|
280 |
+
time_out = 100
|
281 |
+
if api[:4] == "qwen" and url.endswith("/v1/services/aigc/multimodal-generation/generation"):
|
282 |
+
mod = qwen_api_switch(api)
|
283 |
+
else:
|
284 |
+
mod = 'GPT4V'
|
285 |
+
s_state = mod
|
286 |
+
|
287 |
+
elif api[:3] == 'Cog' or api[:4] == "moon" or api[:7] == "MiniCPM":
|
288 |
+
if is_connection():
|
289 |
+
if state != api:
|
290 |
+
requests.post(f"http://127.0.0.1:8000/v1/{api}")
|
291 |
+
else:
|
292 |
+
API_command = f'python openai_api.py --mod {api}'
|
293 |
+
subprocess.Popen(API_command,shell=True)
|
294 |
+
while True:
|
295 |
+
if is_connection():
|
296 |
+
break
|
297 |
+
else:
|
298 |
+
print("Retrying...")
|
299 |
+
time.sleep(2)
|
300 |
+
|
301 |
+
key = ""
|
302 |
+
url = "http://127.0.0.1:8000/v1/chat/completions"
|
303 |
+
time_out = 300
|
304 |
+
s_state = api
|
305 |
+
|
306 |
+
return key, url, time_out, s_state
|
307 |
+
|
308 |
+
# UI界面
|
309 |
+
with gr.Blocks(title="GPT4V captioner") as demo:
|
310 |
+
gr.Markdown("### Image Captioning with GPT-4-Vision API / 使用 GPT-4-Vision API 进行图像打标")
|
311 |
+
|
312 |
+
with gr.Row():
|
313 |
+
api_key_input = gr.Textbox(label="API Key", placeholder="Enter your GPT-4-Vision API Key here", type="password",
|
314 |
+
value=saved_api_key)
|
315 |
+
api_url_input = gr.Textbox(label="API URL", value=saved_api_url or "https://api.openai.com/v1/chat/completions",
|
316 |
+
placeholder="Enter the GPT-4-Vision API URL here")
|
317 |
+
api_model_input = gr.Textbox(label="API Model", value="gpt-4o", placeholder="Enter the model name here")
|
318 |
+
quality_choices = ["auto", "high", "low"]
|
319 |
+
quality = gr.Dropdown(choices=quality_choices, label="Image Quality / 图片质量", value="auto")
|
320 |
+
timeout_input = gr.Number(label="Timeout (seconds) / 超时时间(秒)", value=10, step=1)
|
321 |
+
|
322 |
+
prompt_input = gr.Textbox(label="Prompt / 打标需求",
|
323 |
+
value="As an AI image tagging expert, please provide precise tags for these images to enhance CLIP model's understanding of the content. Employ succinct keywords or phrases, steering clear of elaborate sentences and extraneous conjunctions. Prioritize the tags by relevance. Your tags should capture key elements such as the main subject, setting, artistic style, composition, image quality, color tone, filter, and camera specifications, and any other tags crucial for the image. When tagging photos of people, include specific details like gender, nationality, attire, actions, pose, expressions, accessories, makeup, composition type, age, etc. For other image categories, apply appropriate and common descriptive tags as well. Recognize and tag any celebrities, well-known landmark or IPs if clearly featured in the image. Your tags should be accurate, non-duplicative, and within a 20-75 word count range. These tags will use for image re-creation, so the closer the resemblance to the original image, the better the tag quality. Tags should be comma-separated. Exceptional tagging will be rewarded with $10 per image.",
|
324 |
+
placeholder="Enter a descriptive prompt",
|
325 |
+
lines=5)
|
326 |
+
|
327 |
+
with gr.Accordion("Prompt Saving / 提示词存档", open=False):
|
328 |
+
def update_textbox(prompt):
|
329 |
+
return prompt
|
330 |
+
saved_pro = get_prompts_from_csv()
|
331 |
+
saved_prompts_dropdown = gr.Dropdown(label="Saved Prompts / 提示词存档", choices=saved_pro, type="value",interactive=True)
|
332 |
+
with gr.Row():
|
333 |
+
save_prompt_button = gr.Button("Save Prompt / 保存提示词")
|
334 |
+
delete_prompt_button = gr.Button("Delete Prompt / 删除提示词")
|
335 |
+
load_prompt_button = gr.Button("Load Prompt / 读取到输入框")
|
336 |
+
|
337 |
+
save_prompt_button.click(save_prompt, inputs=prompt_input,outputs=[saved_prompts_dropdown])
|
338 |
+
delete_prompt_button.click(delete_prompt, inputs=saved_prompts_dropdown, outputs=[saved_prompts_dropdown])
|
339 |
+
load_prompt_button.click(update_textbox, inputs=saved_prompts_dropdown, outputs=prompt_input)
|
340 |
+
|
341 |
+
with gr.Tab("Image Process / 图片处理"):
|
342 |
+
|
343 |
+
with gr.Tab("Image Zip / 图像预压缩"):
|
344 |
+
with gr.Row():
|
345 |
+
folder_path_input = gr.Textbox(
|
346 |
+
label="Image Folder Path / 图像文件夹路径",
|
347 |
+
placeholder="Enter the folder path containing images / 输入包含图像的文件夹路径"
|
348 |
+
)
|
349 |
+
process_images_button = gr.Button("Process Images / 压缩图像")
|
350 |
+
|
351 |
+
with gr.Row():
|
352 |
+
# Add a Markdown component to display the warning message
|
353 |
+
gr.Markdown("""
|
354 |
+
⚠ **Warning / 警告**: This preprocessing process will resize and compress all image files into jpg format with a total pixel count ≤ 1024×1024 while maintaining the original aspect ratio, ensuring that both dimensions are multiples of 32. **Please make sure to backup your original files before processing!** This procedure can reduce the size of the training set, help to speed up the labeling process, and decrease the time taken to cache latents to disk during training.
|
355 |
+
|
356 |
+
本预处理过程将会在保持原图长宽比情况下,把所有图像文件裁剪压缩为总像素≤1024×1024的jpg文件,并且长宽像素均为32的倍数。**请务必在处理前备份源文件!**该过程可以缩小训练集体积,有助于加快打标速度,并缩短训练过程中的Cache latents to disk时间。
|
357 |
+
""")
|
358 |
+
|
359 |
+
with gr.Row():
|
360 |
+
image_processing_output = gr.Textbox(
|
361 |
+
label="Image Processing Output / 图像处理输出",
|
362 |
+
lines=3
|
363 |
+
)
|
364 |
+
|
365 |
+
process_images_button.click(process_images_in_folder,
|
366 |
+
inputs=[folder_path_input],
|
367 |
+
outputs=[image_processing_output])
|
368 |
+
|
369 |
+
with gr.Tab("Single Image / 单图处理"):
|
370 |
+
with gr.Row():
|
371 |
+
image_input = gr.Image(type='filepath', label="Upload Image / 上传图片")
|
372 |
+
single_image_output = gr.Textbox(label="Caption Output / 标签输出")
|
373 |
+
with gr.Row():
|
374 |
+
single_image_submit = gr.Button("Caption Single Image / 图片打标", variant='primary')
|
375 |
+
|
376 |
+
with gr.Tab("Batch Image / 多图批处理"):
|
377 |
+
with gr.Row():
|
378 |
+
batch_dir_input = gr.Textbox(label="Batch Directory / 批量目录",
|
379 |
+
placeholder="Enter the directory path containing images for batch processing")
|
380 |
+
with gr.Row():
|
381 |
+
batch_process_submit = gr.Button("Batch Process Images / 批量处理图像", variant='primary')
|
382 |
+
with gr.Row():
|
383 |
+
batch_output = gr.Textbox(label="Batch Processing Output / 批量输出")
|
384 |
+
file_handling_mode = gr.Radio(
|
385 |
+
choices=["overwrite/覆盖", "prepend/前置插入", "append/末尾追加", "skip/跳过"],
|
386 |
+
value="overwrite/覆盖",
|
387 |
+
label="If a caption file exists: / 如果已经存在打标文件: "
|
388 |
+
)
|
389 |
+
with gr.Row():
|
390 |
+
stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
391 |
+
stop_button.click(stop_batch_processing, inputs=[], outputs=batch_output)
|
392 |
+
|
393 |
+
with gr.Tab("Failed File Screening / 打标失败文件筛查"):
|
394 |
+
folder_input = gr.Textbox(label="Folder Input / 文件夹输入", placeholder="Enter the directory path")
|
395 |
+
keywords_input = gr.Textbox(placeholder="Enter keywords, e.g., sorry,error / 请输入检索关键词,例如:sorry,error",
|
396 |
+
label="Keywords (optional) / 检索关键词(可选)")
|
397 |
+
run_button = gr.Button("Run Script / 运行脚本", variant='primary')
|
398 |
+
output_area = gr.Textbox(label="Script Output / 脚本输出")
|
399 |
+
|
400 |
+
run_button.click(fn=run_script, inputs=[folder_input, keywords_input], outputs=output_area)
|
401 |
+
|
402 |
+
with gr.Tab("Extra Function / 额外功能"):
|
403 |
+
|
404 |
+
gr.Markdown("""
|
405 |
+
以下功能基于CogVLM开发(GPT4未经测试),极力推荐使用CogVLM-vqa以达到最佳效果。\n
|
406 |
+
This function is developed based on CogVLM (GPT4 not tested), and it is strongly recommended to use CogVLM-vqa for optimal results.
|
407 |
+
""")
|
408 |
+
|
409 |
+
with gr.Tab("Watermark Detection / 批量水印检测"):
|
410 |
+
with gr.Row():
|
411 |
+
detect_batch_dir_input = gr.Textbox(label="Image Directory / 图片目录",
|
412 |
+
placeholder="Enter the directory path containing images for batch processing")
|
413 |
+
with gr.Row():
|
414 |
+
watermark_dir = gr.Textbox(label="Watermark Detected Image Directory / 检测到水印的图片目录",
|
415 |
+
placeholder="Enter the directory path to move/copy detected images")
|
416 |
+
detect_file_handling_mode = gr.Radio(choices=["move/移动", "copy/复制"], value="move/移动",
|
417 |
+
label="If watermark is detected / 如果图片检测到水印 ")
|
418 |
+
with gr.Row():
|
419 |
+
batch_detect_submit = gr.Button("Batch Detect Images / 批量检测图像", variant='primary')
|
420 |
+
with gr.Row():
|
421 |
+
detect_batch_output = gr.Textbox(label="Output / 结果")
|
422 |
+
with gr.Row():
|
423 |
+
detect_stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
424 |
+
detect_stop_button.click(stop_batch_processing, inputs=[], outputs=detect_batch_output)
|
425 |
+
with gr.Tab("Tag Polishing / 标签润色"):
|
426 |
+
gr.Markdown("""
|
427 |
+
使用其他打标器(如WD1.4)对图片进行打标后,在上方prompt中使用“Describe this image in a very detailed manner and refer these prompt tags:{大括号里替换为放置额外tags文件的目录,会自动读取和图片同名txt。比如 D:\ abc\}”\n
|
428 |
+
After marking the image using other captioner(such as WD1.4), enter the prompt in the “” marks in the prompt box.
|
429 |
+
“Describe this image in a very detailed manner and refer these prompt tags:
|
430 |
+
{This is the txt file path for captions, will automatically read the txt file with the same name as the image. For example, D: \ abc\}”
|
431 |
+
""")
|
432 |
+
with gr.Tab("Image filtering / 图片筛选"):
|
433 |
+
gr.Markdown("""
|
434 |
+
使用自定义规则筛选图片,将回答中包含或不包含对应词的图片放入对应规则的文件夹中。输出目录默认在源目录下的classify_output文件夹下。\n
|
435 |
+
Use custom rules to filter images. Place images containing or not containing corresponding words in the corresponding rule folder in the answer. Output Directory default in source directory \classify_output.
|
436 |
+
""")
|
437 |
+
with gr.Row():
|
438 |
+
classify_output = gr.Textbox(label="Output / 结果")
|
439 |
+
classify_button = gr.Button("Run / 开始", variant='primary')
|
440 |
+
classify_stop_button = gr.Button("Stop Batch Processing / 停止批量处理")
|
441 |
+
with gr.Row():
|
442 |
+
classify_dir = gr.Textbox(label="Input Image Directory / 输入图片目录",placeholder="Enter the directory path")
|
443 |
+
classify_output_dir = gr.Textbox(label="Output Directory / 输出目录", placeholder="Default source directory / 默认源目录")
|
444 |
+
classify_handling_mode = gr.Radio(label="If meets / 如果符合",choices=["move/移动", "copy/复制"], value="move/移动")
|
445 |
+
|
446 |
+
rule_inputs = []
|
447 |
+
for i in range(1,11):
|
448 |
+
with gr.Row():
|
449 |
+
rule_type = gr.Dropdown(label="Rule / 规则类型", choices=["","Involve / 包含", "Exclude / 不包含"], value="")
|
450 |
+
rule_input = gr.Textbox(label="Custom / 自定义", placeholder="Enter the words you need to filter / 输入你需要筛选的词")
|
451 |
+
rule_inputs.extend([rule_type, rule_input])
|
452 |
+
|
453 |
+
def caption_image(api_key, api_url, prompt, image, quality, timeout, model="gpt-4o"):
|
454 |
+
if image:
|
455 |
+
return process_single_image(api_key, prompt, api_url, image, quality, timeout, model)
|
456 |
+
|
457 |
+
def batch_process(api_key, api_url, prompt, batch_dir, file_handling_mode, quality, timeout, model="gpt-4o"):
|
458 |
+
process_batch_images(api_key, prompt, api_url, batch_dir, file_handling_mode, quality, timeout, model)
|
459 |
+
return "Batch processing complete. Captions saved or updated as '.txt' files next to images."
|
460 |
+
|
461 |
+
def batch_detect(api_key, api_url, prompt, batch_dir, detect_file_handling_mode, quality, timeout, watermark_dir, model="gpt-4o"):
|
462 |
+
results = process_batch_watermark_detection(api_key, prompt, api_url, batch_dir, detect_file_handling_mode,
|
463 |
+
quality, timeout,watermark_dir, model)
|
464 |
+
return results
|
465 |
+
|
466 |
+
single_image_submit.click(caption_image,
|
467 |
+
inputs=[api_key_input, api_url_input, prompt_input, image_input, quality, timeout_input, api_model_input],
|
468 |
+
outputs=single_image_output)
|
469 |
+
batch_process_submit.click(batch_process,
|
470 |
+
inputs=[api_key_input, api_url_input, prompt_input, batch_dir_input,
|
471 |
+
file_handling_mode, quality, timeout_input, api_model_input],
|
472 |
+
outputs=batch_output)
|
473 |
+
batch_detect_submit.click(batch_detect,
|
474 |
+
inputs=[api_key_input, api_url_input, prompt_input, detect_batch_dir_input,
|
475 |
+
detect_file_handling_mode, quality, timeout_input, watermark_dir, api_model_input],
|
476 |
+
outputs=detect_batch_output)
|
477 |
+
|
478 |
+
classify_button.click(classify_images,
|
479 |
+
inputs=[api_key_input, api_url_input, quality, prompt_input, timeout_input,
|
480 |
+
classify_handling_mode, classify_dir, classify_output_dir] + rule_inputs,
|
481 |
+
outputs=classify_output)
|
482 |
+
classify_stop_button.click(stop_batch_processing,inputs=[],outputs=classify_output)
|
483 |
+
|
484 |
+
with gr.Tab("Tag Manage / 标签处理"):
|
485 |
+
|
486 |
+
with gr.Row():
|
487 |
+
folder_path_input = gr.Textbox(label="Folder Path / 文件夹路径",
|
488 |
+
placeholder="Enter folder path / 在此输入文件夹路径")
|
489 |
+
top_n_input = gr.Number(label="Top N Tags / Top N 标签", value=100)
|
490 |
+
translate_tags_input = gr.Radio(label="Translate Tags to Chinese / 翻译标签",
|
491 |
+
choices=["GPT-3.5 translation / GPT3.5翻译",
|
492 |
+
"Free translation / 免费翻译",
|
493 |
+
"No translation / 不翻译"],
|
494 |
+
value="No translation / 不翻译")
|
495 |
+
process_tags_button = gr.Button("Process Tags / 处理标签", variant='primary')
|
496 |
+
output_message = gr.Textbox(label="Output Message / 输出信息", interactive=False)
|
497 |
+
|
498 |
+
with gr.Row():
|
499 |
+
tags_to_remove_input = gr.Textbox(label="Tags to Remove / 删除标签",
|
500 |
+
placeholder="Enter tags to remove, separated by commas / 输入要删除的标签,用逗号分隔",
|
501 |
+
lines=3)
|
502 |
+
tags_to_replace_input = gr.Textbox(label="Tags to Replace / 替换标签",
|
503 |
+
placeholder="Enter tags to replace in 'old_tag:new_tag' format, separated by commas / 输入要替换的标签,格式为 '旧标签:新标签',用逗号分隔",
|
504 |
+
lines=3)
|
505 |
+
new_tag_input = gr.Textbox(label="Add New Tag / 添加新标签",
|
506 |
+
placeholder="Enter a new tag to add / 输入一个新标签以添加", lines=3)
|
507 |
+
insert_position_input = gr.Radio(label="New Tag Insert Position / 新标签插入位置",
|
508 |
+
choices=["Start / 开始", "End / 结束", "Random / 随机"],
|
509 |
+
value="Start / 开始")
|
510 |
+
|
511 |
+
with gr.Row():
|
512 |
+
wordcloud_output = gr.Image(label="Word Cloud / 词云")
|
513 |
+
tag_counts_output = gr.Dataframe(label="Top Tags / 高频标签",
|
514 |
+
headers=["Tag Name", "Frequency", "Chinese Translation"],
|
515 |
+
interactive=True) # 修改 Dataframe 组件以显示三列
|
516 |
+
|
517 |
+
with gr.Row():
|
518 |
+
network_graph_output = gr.Image(label="Network Graph / 网络图")
|
519 |
+
|
520 |
+
process_tags_button.click(process_tags,
|
521 |
+
inputs=[folder_path_input, top_n_input, tags_to_remove_input,
|
522 |
+
tags_to_replace_input, new_tag_input, insert_position_input,
|
523 |
+
translate_tags_input, api_key_input, api_url_input], # 新增翻译复选框
|
524 |
+
outputs=[tag_counts_output, wordcloud_output, network_graph_output, output_message])
|
525 |
+
|
526 |
+
|
527 |
+
# API Config
|
528 |
+
with gr.Tab("API Config / API配置"):
|
529 |
+
# 本地模型配置
|
530 |
+
with gr.Accordion("Local Model / 使用本地模型", open=True):
|
531 |
+
with gr.Row():
|
532 |
+
gr.Markdown("""
|
533 |
+
⚠ **Warning / 警告**:
|
534 |
+
This is the API configuration page. To use local model, you need to configure environment and download it.
|
535 |
+
**Moondream** model **size is about 22g+**, and it takes a long time, Please confirm that the disk space is sufficient.Please confirm that your GPU has sufficient graphics memory ***(approximately 6g)***
|
536 |
+
**CogVLM**, you need to configure environment and download it, which is **approximately 35g+** in size and takes a long time ***(really, really long)***.
|
537 |
+
After installation and download, the total space occupied is about ***40g+***. Please confirm that the disk space is sufficient.
|
538 |
+
In addition, in terms of model selection, the vqa model performs better but slower, while the chat model is faster but slightly weaker.
|
539 |
+
Please confirm that your GPU has sufficient graphics memory ***(approximately 14g ±)*** when using CogVLM
|
540 |
+
|
541 |
+
此为API配置页面,使用本地模型需要配置相关环境并下载模型,
|
542 |
+
***moondream***模型大小约为**22g+**需要较长时间,请确认磁盘空间充足。显存需求约为6g,请确认自己的显卡有足够的显存。
|
543 |
+
***CogVLM***大小约为**35g+**,需要较长时间 **(真的很长)**。安装以及下载完成后,总占用空间约为40g+,请确认磁盘空间充足。
|
544 |
+
模型选择上,vqa模型效果更好但是更慢,chat模型更快但是效果略弱。使用CogVLM请确认自己的显卡有足够的显存 ***(约14g±)***
|
545 |
+
""")
|
546 |
+
with gr.Row():
|
547 |
+
detecter_output = gr.Textbox(label="Check Env / 环境检测", interactive=False)
|
548 |
+
detect_button = gr.Button("Check / 检查", variant='primary')
|
549 |
+
with gr.Row():
|
550 |
+
models_select = gr.Radio(label="Choose Models / 选择模型", choices=["moondream","vqa", "chat", "minicpm"], value="moondream")
|
551 |
+
acceleration_select = gr.Radio(label="Choose Default Plz / 选择是否国内加速(如果使用国内加速,请关闭魔法上网)", choices=["CN", "default"],
|
552 |
+
value="CN")
|
553 |
+
download_button = gr.Button("Download Models / 下载模型", variant='primary')
|
554 |
+
install_button = gr.Button("Install / 安装", variant='primary')
|
555 |
+
|
556 |
+
# API配置
|
557 |
+
mod_list = [
|
558 |
+
"GPT4V",
|
559 |
+
"qwen-vl-plus",
|
560 |
+
"qwen-vl-max",
|
561 |
+
"moondream",
|
562 |
+
"Cog-vqa",
|
563 |
+
"Cog-chat",
|
564 |
+
"MiniCPM"
|
565 |
+
]
|
566 |
+
with gr.Row():
|
567 |
+
switch_select = gr.Dropdown(label="Choose API / 选择API", choices=mod_list, value="GPT4V")
|
568 |
+
A_state = gr.Textbox(label="API State / API状态", interactive=False, value=mod_default)
|
569 |
+
switch_button = gr.Button("Switch / 切换", variant='primary')
|
570 |
+
set_default = gr.Button("Set as default / 设为默认", variant='primary')
|
571 |
+
|
572 |
+
|
573 |
+
detect_button.click(detecter, outputs=detecter_output)
|
574 |
+
download_button.click(downloader, inputs=[models_select, acceleration_select],
|
575 |
+
outputs=detecter_output)
|
576 |
+
install_button.click(installer, outputs=detecter_output)
|
577 |
+
switch_button.click(switch_API, inputs=[switch_select, A_state],
|
578 |
+
outputs=[api_key_input, api_url_input, timeout_input, A_state])
|
579 |
+
set_default.click(save_state, inputs=[switch_select, api_key_input, api_url_input], outputs=A_state)
|
580 |
+
|
581 |
+
|
582 |
+
gr.Markdown("""
|
583 |
+
### Developers: [Jiaye](https://civitai.com/user/jiayev1), [LEOSAM 是只兔狲](https://civitai.com/user/LEOSAM), [SleeeepyZhou](https://civitai.com/user/SleeeepyZhou), [Fok](https://civitai.com/user/fok3827), [gluttony-10](https://github.com/gluttony-10), [327](https://github.com/327), [十字鱼](https://space.bilibili.com/893892) | Welcome everyone to add more new features to this project.
|
584 |
+
""")
|
585 |
+
|
586 |
+
# 启动参数
|
587 |
+
def get_args():
|
588 |
+
parser = argparse.ArgumentParser(description='GPT4V-Image-Captioner启动参数')
|
589 |
+
parser.add_argument("--port", type=int, default="8848", help="占用端口,默认8848")
|
590 |
+
parser.add_argument("--listen", action='store_true', help="打开远程连接,默认关闭")
|
591 |
+
parser.add_argument("--share", action='store_true', help="打开gradio共享,默认关闭")
|
592 |
+
parser.add_argument("--no-browser", action='store_true', help="不要自动打开浏览器,默认关闭")
|
593 |
+
return parser.parse_args()
|
594 |
+
|
595 |
+
args = get_args()
|
596 |
+
|
597 |
+
if __name__ == "__main__":
|
598 |
+
threading.Thread(target=lambda: switch_API(mod_default, 'GPT')).start()
|
599 |
+
demo.launch(
|
600 |
+
server_name="0.0.0.0" if args.listen else None,
|
601 |
+
server_port=args.port,
|
602 |
+
share=args.share,
|
603 |
+
inbrowser=False if args.no_browser else True
|
604 |
+
)
|
install_linux_mac.sh
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Define the Python version
|
4 |
+
PYTHON_VERSION=3.10.
|
5 |
+
|
6 |
+
# Check if Python is installed and the version is as expected
|
7 |
+
if ! command -v python3 --version &>/dev/null || ! python3 --version | grep -q "$PYTHON_VERSION"; then
|
8 |
+
echo "Python is not installed or not the expected version. Please install Python $PYTHON_VERSION."
|
9 |
+
exit 1
|
10 |
+
fi
|
11 |
+
|
12 |
+
echo "Python is installed."
|
13 |
+
|
14 |
+
# Ping google to decide if use mirror
|
15 |
+
target_url="www.google.com"
|
16 |
+
timeout=3000
|
17 |
+
ping -c 1 -W $timeout $target_url -w 3 > /dev/null
|
18 |
+
|
19 |
+
if [ $? -ne 0 ]; then
|
20 |
+
echo "Use CN"
|
21 |
+
export PIP_DISABLE_PIP_VERSION_CHECK=1
|
22 |
+
export PIP_NO_CACHE_DIR=1
|
23 |
+
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
24 |
+
else
|
25 |
+
echo "Use default"
|
26 |
+
fi
|
27 |
+
|
28 |
+
# Upgrade pip to the latest version
|
29 |
+
pip install --upgrade pip
|
30 |
+
|
31 |
+
# Install necessary Python libraries
|
32 |
+
pip install -r ./install_script/requirements.txt
|
33 |
+
|
34 |
+
echo ""
|
35 |
+
echo "Install completed, please run Start to open the GUI"
|
36 |
+
echo "安装完毕,请运行Start打开GUI"
|
37 |
+
echo ""
|
38 |
+
read -p "press any key to continue...
|
39 |
+
按任意键继续..."
|
install_script/check.txt
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
torchvision
|
3 |
+
bitsandbytes
|
4 |
+
deepspeed
|
5 |
+
transformers
|
6 |
+
spacy
|
7 |
+
seaborn
|
8 |
+
loguru
|
9 |
+
streamlit
|
10 |
+
timm
|
11 |
+
accelerate
|
12 |
+
pydantic
|
13 |
+
xformers
|
14 |
+
requests
|
15 |
+
openai
|
16 |
+
fastapi
|
17 |
+
httpx
|
18 |
+
uvicorn
|
19 |
+
dashscope
|
install_script/check_open.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
import subprocess
|
3 |
+
|
4 |
+
def install_detection(requir_path):
|
5 |
+
# 读
|
6 |
+
file_path = requir_path
|
7 |
+
requirements = []
|
8 |
+
with open(file_path, 'r') as file:
|
9 |
+
for line in file:
|
10 |
+
requirements.append(line.strip())
|
11 |
+
|
12 |
+
# 查
|
13 |
+
missing_libs = []
|
14 |
+
for libs in requirements:
|
15 |
+
if libs.find("==") == -1: #only fix requirements which contain "==", because I don't know how to take "<=",">="... into account at the same time.
|
16 |
+
check_libs = libs
|
17 |
+
else:
|
18 |
+
check_libs = libs[:libs.index("==")]
|
19 |
+
if check_libs == "Pillow": #import PIL instead of import Pillow
|
20 |
+
check_libs = "PIL"
|
21 |
+
try:
|
22 |
+
importlib.import_module(check_libs)
|
23 |
+
except ImportError:
|
24 |
+
if check_libs == "PIL": #switch back
|
25 |
+
check_libs = "Pillow"
|
26 |
+
missing_libs.append(check_libs)
|
27 |
+
|
28 |
+
return missing_libs
|
29 |
+
|
30 |
+
def print_missing(missing_libs):
|
31 |
+
# 返
|
32 |
+
if missing_libs == []:
|
33 |
+
return ""
|
34 |
+
else:
|
35 |
+
return f"Not installed libraries: {', '.join(missing_libs)}"
|
36 |
+
|
37 |
+
# 启动检查
|
38 |
+
def check_open():
|
39 |
+
require_path = "./install_script/requirements.txt"
|
40 |
+
missings = install_detection(require_path)
|
41 |
+
installed = print_missing(missings)
|
42 |
+
if installed == "":
|
43 |
+
return
|
44 |
+
else:
|
45 |
+
print(installed)
|
46 |
+
for lib in missings:
|
47 |
+
subprocess.check_call(["pip", "install", lib])
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
check_open()
|
install_script/deepspeed-0.11.2+8ce7471-py3-none-any.whl
ADDED
Binary file (758 kB). View file
|
|
install_script/installcog.bat
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
|
3 |
+
call myenv\Scripts\activate
|
4 |
+
|
5 |
+
set HF_HOME=huggingface
|
6 |
+
REM ͨ���ٶȼ����������ʹ�þ���
|
7 |
+
set "target_url=www.google.com"
|
8 |
+
set "timeout=4000"
|
9 |
+
|
10 |
+
ping %target_url% -n 1 -w %timeout% >nul
|
11 |
+
if %ERRORLEVEL% neq 0 (
|
12 |
+
echo Use CN
|
13 |
+
echo ��װ����
|
14 |
+
set PIP_DISABLE_PIP_VERSION_CHECK=1
|
15 |
+
set PIP_NO_CACHE_DIR=1
|
16 |
+
set PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
17 |
+
|
18 |
+
echo ��װ torch...
|
19 |
+
pip install torch==2.2.1+cu121 torchvision==0.17.1+cu121 -f https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html -i https://pypi.tuna.tsinghua.edu.cn/simple
|
20 |
+
|
21 |
+
) else (
|
22 |
+
echo Use default
|
23 |
+
echo Installing deps...
|
24 |
+
pip install torch==2.2.1+cu121 torchvision==0.17.1+cu121 -i https://download.pytorch.org/whl/cu121
|
25 |
+
)
|
26 |
+
|
27 |
+
if %ERRORLEVEL% neq 0 (
|
28 |
+
echo torch install failed / torch ��װʧ�� > install_temp.txt
|
29 |
+
pause >nul
|
30 |
+
exit /b 1
|
31 |
+
)
|
32 |
+
|
33 |
+
|
34 |
+
pip install ./install_script/deepspeed-0.11.2+8ce7471-py3-none-any.whl
|
35 |
+
pip install -U -I --no-deps xformers==0.0.25
|
36 |
+
pip install -r ./install_script/require.txt
|
37 |
+
if %ERRORLEVEL% neq 0 (
|
38 |
+
echo Deps install failed / ������װʧ�� > install_temp.txt
|
39 |
+
pause >nul
|
40 |
+
exit /b 1
|
41 |
+
)
|
42 |
+
|
43 |
+
echo Install completed / ��װ��� > install_temp.txt
|
install_script/installcog.sh
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
source myenv/bin/activate
|
4 |
+
|
5 |
+
export HF_HOME="huggingface"
|
6 |
+
|
7 |
+
target_url="www.google.com"
|
8 |
+
timeout=4000
|
9 |
+
ping -c 1 -W $timeout $target_url -w 4 > /dev/null
|
10 |
+
|
11 |
+
if [ $? -ne 0 ]; then
|
12 |
+
echo "Use CN"
|
13 |
+
echo "安装依赖"
|
14 |
+
|
15 |
+
export PIP_DISABLE_PIP_VERSION_CHECK=1
|
16 |
+
export PIP_NO_CACHE_DIR=1
|
17 |
+
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
18 |
+
|
19 |
+
echo "安装 torch..."
|
20 |
+
pip install torch==2.2.1+cu121 torchvision==0.17.1+cu121 -f https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html -i https://pypi.tuna.tsinghua.edu.cn/simple
|
21 |
+
if [ $? -ne 0 ]; then
|
22 |
+
echo "torch 安装失败" > install_temp.txt
|
23 |
+
exit 1
|
24 |
+
fi
|
25 |
+
|
26 |
+
else
|
27 |
+
echo "Use default"
|
28 |
+
echo "Installing deps..."
|
29 |
+
pip install torch==2.2.1+cu121 torchvision==0.17.1+cu121 --extra-index-url https://download.pytorch.org/whl/cu121
|
30 |
+
fi
|
31 |
+
|
32 |
+
pip install deepspeed
|
33 |
+
pip install -U -I --no-deps xformers==0.0.25
|
34 |
+
pip install -r ./install_script/require.txt
|
35 |
+
if [ $? -ne 0 ]; then
|
36 |
+
echo "Deps install failed / 依赖安装失败" > install_temp.txt
|
37 |
+
exit 1
|
38 |
+
fi
|
39 |
+
|
40 |
+
echo "Install completed / 安装完毕" > install_temp.txt
|
install_script/require.txt
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
SwissArmyTransformer>=0.4.9
|
2 |
+
transformers==4.37.2
|
3 |
+
spacy>=3.6.0
|
4 |
+
seaborn>=0.13.0
|
5 |
+
loguru~=0.7.2
|
6 |
+
streamlit>=1.29.0
|
7 |
+
timm>=0.9.12
|
8 |
+
accelerate==0.26.1
|
9 |
+
pydantic>=2.5.2
|
10 |
+
|
11 |
+
requests
|
12 |
+
openai>=1.4.0
|
13 |
+
fastapi>=0.105.0
|
14 |
+
httpx>=0.25.2
|
15 |
+
uvicorn~=0.24.0
|
16 |
+
einops==0.7.0
|
17 |
+
protobuf==4.25.2
|
18 |
+
sentencepiece==0.1.99
|
19 |
+
bitsandbytes==0.43.0
|
install_script/requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
scipy==1.12.0
|
2 |
+
networkx
|
3 |
+
wordcloud
|
4 |
+
matplotlib
|
5 |
+
Pillow==10.2.0
|
6 |
+
tqdm
|
7 |
+
gradio==4.21.0
|
8 |
+
requests
|
9 |
+
huggingface_hub
|
10 |
+
GPUtil
|
11 |
+
dashscope
|
install_windows.bat
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
|
3 |
+
REM ���python��װ
|
4 |
+
SET PYTHON_VERSION=3.10.2
|
5 |
+
SET PYTHON_INSTALLER_URL=https://www.python.org/ftp/python/%PYTHON_VERSION%/python-%PYTHON_VERSION%-amd64.exe
|
6 |
+
|
7 |
+
python --version >NUL 2>&1
|
8 |
+
if %ERRORLEVEL% neq 0 (
|
9 |
+
echo Python is not installed. Attempting to install Python %PYTHON_VERSION%...
|
10 |
+
bitsadmin /transfer "PythonInstaller" %PYTHON_INSTALLER_URL% python-installer.exe
|
11 |
+
start /wait python-installer.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
|
12 |
+
del /f python-installer.exe
|
13 |
+
python --version >NUL 2>&1
|
14 |
+
if %ERRORLEVEL% neq 0 (
|
15 |
+
echo Failed to install Python.
|
16 |
+
pause >nul
|
17 |
+
exit /b 1
|
18 |
+
)
|
19 |
+
)
|
20 |
+
|
21 |
+
echo Python installed.
|
22 |
+
|
23 |
+
|
24 |
+
REM �������ⴴ��
|
25 |
+
if not exist "myenv" (
|
26 |
+
echo ���ڴ��������...
|
27 |
+
python -m venv myenv
|
28 |
+
if %ERRORLEVEL% neq 0 (
|
29 |
+
echo ���������ʧ�ܣ����� python �Ƿ�װ����Լ� python �汾�Ƿ�Ϊ64λ�汾��python 3.10����python��Ŀ¼�Ƿ��ڻ�������PATH�ڡ�
|
30 |
+
pause >nul
|
31 |
+
exit /b 1
|
32 |
+
)
|
33 |
+
)
|
34 |
+
|
35 |
+
call myenv\Scripts\activate
|
36 |
+
|
37 |
+
|
38 |
+
REM ͨ���ȸ�����������ʹ�þ���
|
39 |
+
set "target_url=www.google.com"
|
40 |
+
set "timeout=3000"
|
41 |
+
|
42 |
+
ping %target_url% -n 1 -w %timeout% >nul
|
43 |
+
if %errorlevel% neq 0 (
|
44 |
+
echo Use CN
|
45 |
+
set PIP_DISABLE_PIP_VERSION_CHECK=1
|
46 |
+
set PIP_NO_CACHE_DIR=1
|
47 |
+
set PIP_INDEX_URL=https://mirror.baidu.com/pypi/simple
|
48 |
+
) else (
|
49 |
+
echo Use default
|
50 |
+
)
|
51 |
+
|
52 |
+
set HF_HOME=huggingface
|
53 |
+
|
54 |
+
REM ��װ����
|
55 |
+
|
56 |
+
echo Installing deps...
|
57 |
+
echo ��װ����
|
58 |
+
python -m pip install --upgrade pip
|
59 |
+
pip install -r ./install_script/requirements.txt
|
60 |
+
if %ERRORLEVEL% neq 0 (
|
61 |
+
echo Deps install failed
|
62 |
+
echo ������װʧ�ܡ�
|
63 |
+
pause >nul
|
64 |
+
exit /b 1
|
65 |
+
)
|
66 |
+
|
67 |
+
echo.
|
68 |
+
echo Install completed, please run Start to open the GUI
|
69 |
+
echo ��װ��ϣ�������Start��GUI
|
70 |
+
echo.
|
71 |
+
|
72 |
+
pause
|
lib/Api_Utils.py
ADDED
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import os
|
3 |
+
import time
|
4 |
+
import json
|
5 |
+
import base64
|
6 |
+
import requests
|
7 |
+
import subprocess
|
8 |
+
import platform
|
9 |
+
from PIL import Image
|
10 |
+
from requests.adapters import HTTPAdapter
|
11 |
+
import re
|
12 |
+
from urllib3.util.retry import Retry
|
13 |
+
from huggingface_hub import snapshot_download
|
14 |
+
|
15 |
+
API_PATH = 'api_settings.json'
|
16 |
+
QWEN_MOD = 'qwen-vl-plus'
|
17 |
+
DEFAULT_GPT_MODEL = 'gpt-4o'
|
18 |
+
DEFAULT_CLAUDE_MODEL = 'claude-3-sonnet'
|
19 |
+
|
20 |
+
# 扩展prompt {} 标记功能,从文件读取额外内容
|
21 |
+
def addition_prompt_process(prompt, image_path):
|
22 |
+
# 从image_path分离文件名和扩展名,并更改扩展名为.txt
|
23 |
+
if '{' not in prompt and '}' not in prompt:
|
24 |
+
return prompt
|
25 |
+
file_root, _ = os.path.splitext(image_path)
|
26 |
+
new_file_name = os.path.basename(file_root) + ".txt"
|
27 |
+
# 从prompt中提取目录路径
|
28 |
+
directory_path = prompt[prompt.find('{') + 1: prompt.find('}')]
|
29 |
+
# 拼接新的文件路径
|
30 |
+
full_path = os.path.join(directory_path, new_file_name)
|
31 |
+
# 读取full_path指定的文件内容
|
32 |
+
try:
|
33 |
+
with open(full_path, 'r') as file:
|
34 |
+
file_content = file.read()
|
35 |
+
except Exception as e:
|
36 |
+
return f"Error reading file: {e}"
|
37 |
+
|
38 |
+
new_prompt = prompt.replace('{' + directory_path + '}', file_content)
|
39 |
+
return new_prompt
|
40 |
+
|
41 |
+
# 通义千问VL
|
42 |
+
def is_ali(api_url):
|
43 |
+
if api_url.endswith("/v1/services/aigc/multimodal-generation/generation"):
|
44 |
+
return True
|
45 |
+
else:
|
46 |
+
return False
|
47 |
+
|
48 |
+
def is_claude(api_url, model):
|
49 |
+
if api_url.endswith("v1/messages") or "claude" in model.lower():
|
50 |
+
return True
|
51 |
+
else:
|
52 |
+
return False
|
53 |
+
|
54 |
+
def qwen_api_switch(mod):
|
55 |
+
global QWEN_MOD
|
56 |
+
QWEN_MOD = mod
|
57 |
+
return QWEN_MOD
|
58 |
+
|
59 |
+
def qwen_api(image_path, prompt, api_key):
|
60 |
+
print(f"QWEN_MOD: {QWEN_MOD}")
|
61 |
+
|
62 |
+
os.environ['DASHSCOPE_API_KEY'] = api_key
|
63 |
+
from dashscope import MultiModalConversation
|
64 |
+
img = f"file://{image_path}"
|
65 |
+
messages = [{
|
66 |
+
'role': 'system',
|
67 |
+
'content': [
|
68 |
+
{'text': 'You are a helpful assistant.'}
|
69 |
+
]
|
70 |
+
}, {
|
71 |
+
'role':'user',
|
72 |
+
'content': [
|
73 |
+
{'image': img},
|
74 |
+
{'text': prompt},
|
75 |
+
]
|
76 |
+
}]
|
77 |
+
|
78 |
+
response = MultiModalConversation.call(model=QWEN_MOD, messages=messages, stream=False, max_length=300)
|
79 |
+
if '"status_code": 400' in response:
|
80 |
+
return f"API error: {response}"
|
81 |
+
if response.get("output") and response["output"].get("choices") and response["output"]["choices"][0].get("message") and response["output"]["choices"][0]["message"].get("content"):
|
82 |
+
if response["output"]["choices"][0]["message"]["content"][0].get("text", False):
|
83 |
+
caption = response["output"]["choices"][0]["message"]["content"][0]["text"]
|
84 |
+
else:
|
85 |
+
box_value = response["output"]["choices"][0]["message"]["content"][0]["box"]
|
86 |
+
text_value = response["output"]["choices"][0]["message"]["content"][1]["text"]
|
87 |
+
b_value = re.search(r'<ref>(.*?)</ref>', box_value).group(1)
|
88 |
+
caption = b_value + text_value
|
89 |
+
else:
|
90 |
+
caption = response
|
91 |
+
return caption
|
92 |
+
|
93 |
+
def claude_api(image_path, prompt, api_key, api_url, model, quality=None):
|
94 |
+
print(f"CLAUDE_MODEL: {model}")
|
95 |
+
|
96 |
+
with open(image_path, "rb") as image_file:
|
97 |
+
# Downscale the image
|
98 |
+
image = Image.open(image_file)
|
99 |
+
width, height = image.size
|
100 |
+
if quality:
|
101 |
+
if quality == "high":
|
102 |
+
target = 1024
|
103 |
+
elif quality == "low":
|
104 |
+
target = 512
|
105 |
+
elif quality == "auto":
|
106 |
+
if width >= 1024 or height >= 1024:
|
107 |
+
target = 1024
|
108 |
+
else:
|
109 |
+
target = 512
|
110 |
+
else:
|
111 |
+
target = 1024
|
112 |
+
|
113 |
+
aspect_ratio = width / height
|
114 |
+
|
115 |
+
# Determine the new dimensions while maintaining the aspect ratio
|
116 |
+
if width > target or height > target:
|
117 |
+
if width > height:
|
118 |
+
new_width = target
|
119 |
+
new_height = int(new_width / aspect_ratio)
|
120 |
+
else:
|
121 |
+
new_height = target
|
122 |
+
new_width = int(new_height * aspect_ratio)
|
123 |
+
else:
|
124 |
+
new_width, new_height = width, height
|
125 |
+
|
126 |
+
# Resize the image
|
127 |
+
resized_image = image.resize((new_width, new_height), Image.LANCZOS)
|
128 |
+
# Use buffer to store image
|
129 |
+
buffer = io.BytesIO()
|
130 |
+
resized_image.save(buffer, format="JPEG")
|
131 |
+
image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
132 |
+
|
133 |
+
# Claude API
|
134 |
+
data = {
|
135 |
+
"model": model,
|
136 |
+
"max_tokens": 300,
|
137 |
+
"messages": [
|
138 |
+
{"role": "user", "content": [
|
139 |
+
{"type": "image", "source": {
|
140 |
+
"type": "base64",
|
141 |
+
"media_type": "image/jpeg",
|
142 |
+
"data": image_base64
|
143 |
+
}
|
144 |
+
},
|
145 |
+
{"type": "text", "text": prompt}
|
146 |
+
]
|
147 |
+
}
|
148 |
+
]
|
149 |
+
}
|
150 |
+
|
151 |
+
# print(f"data: {data}\n")
|
152 |
+
|
153 |
+
headers = {
|
154 |
+
"Content-Type": "application/json",
|
155 |
+
"x-api-key:": api_key,
|
156 |
+
"anthropic-version": "2023-06-01"
|
157 |
+
}
|
158 |
+
|
159 |
+
# 配置重试策略
|
160 |
+
retries = Retry(total=5,
|
161 |
+
backoff_factor=1,
|
162 |
+
status_forcelist=[429, 500, 502, 503, 504],
|
163 |
+
allowed_methods=["HEAD", "GET", "OPTIONS", "POST"]) # 更新参数名
|
164 |
+
|
165 |
+
with requests.Session() as s:
|
166 |
+
s.mount('https://', HTTPAdapter(max_retries=retries))
|
167 |
+
|
168 |
+
try:
|
169 |
+
response = s.post(api_url, headers=headers, json=data)
|
170 |
+
response.raise_for_status()
|
171 |
+
# 连接错误回显
|
172 |
+
except requests.exceptions.HTTPError as errh:
|
173 |
+
return f"HTTP Error: {errh}"
|
174 |
+
except requests.exceptions.ConnectionError as errc:
|
175 |
+
return f"Error Connecting: {errc}"
|
176 |
+
except requests.exceptions.Timeout as errt:
|
177 |
+
return f"Timeout Error: {errt}"
|
178 |
+
except requests.exceptions.RequestException as err:
|
179 |
+
return f"OOps: Something Else: {err}"
|
180 |
+
|
181 |
+
try:
|
182 |
+
response_data = response.json()
|
183 |
+
if 'error' in response_data:
|
184 |
+
return f"API error: {response_data['error']['message']}"
|
185 |
+
caption = response_data['content'][0]['text']
|
186 |
+
return caption
|
187 |
+
except Exception as e:
|
188 |
+
return f"Failed to parse the API response: {e}\n{response.text}"
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
# API使用
|
193 |
+
def run_openai_api(image_path, prompt, api_key, api_url, quality=None, timeout=10, model=DEFAULT_GPT_MODEL):
|
194 |
+
prompt = addition_prompt_process(prompt, image_path)
|
195 |
+
# print("prompt{}:",prompt)
|
196 |
+
|
197 |
+
# Qwen-VL
|
198 |
+
if is_ali(api_url):
|
199 |
+
return qwen_api(image_path, prompt, api_key)
|
200 |
+
if is_claude(api_url, model):
|
201 |
+
return claude_api(image_path, prompt, api_key, api_url, model, quality)
|
202 |
+
with open(image_path, "rb") as image_file:
|
203 |
+
image_base64 = base64.b64encode(image_file.read()).decode('utf-8')
|
204 |
+
|
205 |
+
# GPT-4V
|
206 |
+
data = {
|
207 |
+
"model": model,
|
208 |
+
"messages": [
|
209 |
+
{
|
210 |
+
"role": "user",
|
211 |
+
"content":
|
212 |
+
[
|
213 |
+
{"type": "image_url", "image_url":
|
214 |
+
{"url": f"data:image/jpeg;base64,{image_base64}",
|
215 |
+
"detail": f"{quality}"}
|
216 |
+
},
|
217 |
+
{"type": "text", "text": prompt}
|
218 |
+
]
|
219 |
+
}
|
220 |
+
],
|
221 |
+
"max_tokens": 300
|
222 |
+
}
|
223 |
+
|
224 |
+
headers = {
|
225 |
+
"Content-Type": "application/json",
|
226 |
+
"Authorization": f"Bearer {api_key}"
|
227 |
+
}
|
228 |
+
|
229 |
+
# 配置重试策略
|
230 |
+
retries = Retry(total=5,
|
231 |
+
backoff_factor=1,
|
232 |
+
status_forcelist=[429, 500, 502, 503, 504],
|
233 |
+
allowed_methods=["HEAD", "GET", "OPTIONS", "POST"]) # 更新参数名
|
234 |
+
|
235 |
+
with requests.Session() as s:
|
236 |
+
s.mount('https://', HTTPAdapter(max_retries=retries))
|
237 |
+
|
238 |
+
try:
|
239 |
+
response = s.post(api_url, headers=headers, json=data, timeout=timeout)
|
240 |
+
response.raise_for_status()
|
241 |
+
# 连接错误回显
|
242 |
+
except requests.exceptions.HTTPError as errh:
|
243 |
+
return f"HTTP Error: {errh}"
|
244 |
+
except requests.exceptions.ConnectionError as errc:
|
245 |
+
return f"Error Connecting: {errc}"
|
246 |
+
except requests.exceptions.Timeout as errt:
|
247 |
+
return f"Timeout Error: {errt}"
|
248 |
+
except requests.exceptions.RequestException as err:
|
249 |
+
return f"OOps: Something Else: {err}"
|
250 |
+
|
251 |
+
try:
|
252 |
+
response_data = response.json()
|
253 |
+
|
254 |
+
if 'error' in response_data:
|
255 |
+
return f"API error: {response_data['error']['message']}"
|
256 |
+
|
257 |
+
caption = response_data["choices"][0]["message"]["content"]
|
258 |
+
return caption
|
259 |
+
except Exception as e:
|
260 |
+
return f"Failed to parse the API response: {e}\n{response.text}"
|
261 |
+
|
262 |
+
|
263 |
+
# API存档
|
264 |
+
def save_api_details(api_key, api_url):
|
265 |
+
if is_ali(api_url):
|
266 |
+
settings = {
|
267 |
+
'model' : QWEN_MOD,
|
268 |
+
'api_key': api_key,
|
269 |
+
'api_url': api_url
|
270 |
+
}
|
271 |
+
else:
|
272 |
+
settings = {
|
273 |
+
'model' : 'GPT',
|
274 |
+
'api_key': api_key,
|
275 |
+
'api_url': api_url
|
276 |
+
}
|
277 |
+
# 不记录空的apikey
|
278 |
+
if api_key != "":
|
279 |
+
with open(API_PATH, 'w', encoding='utf-8') as f:
|
280 |
+
json.dump(settings, f)
|
281 |
+
|
282 |
+
def save_state(llm, key, url):
|
283 |
+
if llm[:3] == "GPT" or llm[:4] == "qwen":
|
284 |
+
settings = {
|
285 |
+
'model': llm,
|
286 |
+
'api_key': key,
|
287 |
+
'api_url': url
|
288 |
+
}
|
289 |
+
|
290 |
+
elif llm[:3] == "Cog" or llm[:4] == "moon" or llm[:7] == "MiniCPM":
|
291 |
+
settings = {
|
292 |
+
'model' : llm,
|
293 |
+
'api_key': "",
|
294 |
+
'api_url': "http://127.0.0.1:8000/v1/chat/completions"
|
295 |
+
}
|
296 |
+
|
297 |
+
output = f"Set {llm} as default. / {llm}已设为默认"
|
298 |
+
with open(API_PATH, 'w', encoding='utf-8') as f:
|
299 |
+
json.dump(settings, f)
|
300 |
+
return output
|
301 |
+
|
302 |
+
# 读取API设置
|
303 |
+
def get_api_details():
|
304 |
+
settings_file = API_PATH
|
305 |
+
if os.path.exists(settings_file):
|
306 |
+
with open(settings_file, 'r') as f:
|
307 |
+
settings = json.load(f)
|
308 |
+
if settings.get('model', '') != '':
|
309 |
+
mod = settings.get('model', '')
|
310 |
+
url = settings.get('api_url', '')
|
311 |
+
if mod[:4] == "qwen":
|
312 |
+
global QWEN_MOD
|
313 |
+
QWEN_MOD = mod
|
314 |
+
else:
|
315 |
+
if is_ali(url):
|
316 |
+
mod = QWEN_MOD
|
317 |
+
return mod, settings.get('api_key', ''), url
|
318 |
+
else:
|
319 |
+
if settings.get('api_key', '') != '':
|
320 |
+
i_key = settings.get('api_key', '')
|
321 |
+
i_url = settings.get('api_url', '')
|
322 |
+
save_api_details(i_key,i_url)
|
323 |
+
with open(settings_file, 'r') as i:
|
324 |
+
settings = json.load(i)
|
325 |
+
return settings.get('model', ''), settings.get('api_key', ''), settings.get('api_url', '')
|
326 |
+
return 'GPT', '', ''
|
327 |
+
|
328 |
+
|
329 |
+
# 本地模型相关
|
330 |
+
def downloader(model_type, acceleration):
|
331 |
+
endpoint = 'https://hf-mirror.com' if acceleration == 'CN' else None
|
332 |
+
if model_type == 'vqa' or model_type == 'chat':
|
333 |
+
snapshot_download(
|
334 |
+
repo_id="lmsys/vicuna-7b-v1.5",
|
335 |
+
allow_patterns=["tokenizer*","special_tokens_map.json"],
|
336 |
+
endpoint=endpoint
|
337 |
+
)
|
338 |
+
if model_type == 'vqa':
|
339 |
+
snapshot_download(
|
340 |
+
repo_id="THUDM/cogagent-vqa-hf",
|
341 |
+
local_dir="./models/cogagent-vqa-hf",
|
342 |
+
max_workers=8,
|
343 |
+
endpoint=endpoint
|
344 |
+
)
|
345 |
+
elif model_type == 'chat':
|
346 |
+
snapshot_download(
|
347 |
+
repo_id="THUDM/cogagent-chat-hf",
|
348 |
+
local_dir="./models/cogagent-chat-hf",
|
349 |
+
max_workers=8,
|
350 |
+
endpoint=endpoint
|
351 |
+
)
|
352 |
+
elif model_type == 'moondream':
|
353 |
+
snapshot_download(
|
354 |
+
repo_id="vikhyatk/moondream1",
|
355 |
+
local_dir="./models/moondream",
|
356 |
+
max_workers=8,
|
357 |
+
endpoint=endpoint
|
358 |
+
)
|
359 |
+
elif model_type == 'minicpm':
|
360 |
+
snapshot_download(
|
361 |
+
repo_id="openbmb/MiniCPM-Llama3-V-2_5",
|
362 |
+
local_dir="./models/MiniCPM-Llama3-V-2_5",
|
363 |
+
max_workers=8,
|
364 |
+
endpoint=endpoint
|
365 |
+
)
|
366 |
+
return f"{model_type} Model download completed. / {model_type}模型下载完成"
|
367 |
+
|
368 |
+
def installer():
|
369 |
+
if platform.system() == "Windows":
|
370 |
+
install_command = f'.\install_script\installcog.bat'
|
371 |
+
else:
|
372 |
+
install_command = f'./install_script/installcog.sh'
|
373 |
+
subprocess.Popen(f'chmod +x {install_command}', shell=True)
|
374 |
+
subprocess.Popen('', shell=True) #Use an empty subprocess to refresh permission. If deleted, installcog.sh wouldn't launch properly, with Permission denied error
|
375 |
+
subprocess.Popen(install_command, shell=True)
|
376 |
+
|
377 |
+
while not os.path.exists('install_temp.txt'):
|
378 |
+
time.sleep(2)
|
379 |
+
with open('install_temp.txt', 'r') as file:
|
380 |
+
result_string = file.read()
|
381 |
+
os.remove('install_temp.txt')
|
382 |
+
return result_string
|
lib/Detecter.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
import GPUtil
|
3 |
+
|
4 |
+
def check_memory():
|
5 |
+
gpus = GPUtil.getGPUs()
|
6 |
+
for gpu in gpus:
|
7 |
+
if gpu.memoryTotal > 12000:
|
8 |
+
return ""
|
9 |
+
elif gpu.memoryTotal > 6000:
|
10 |
+
return "Only MoonDream can be used. / 仅可使用MoonDream"
|
11 |
+
return "Insufficient GPU graphics memory for use. / 显存过小"
|
12 |
+
|
13 |
+
def install_detection(requir_path):
|
14 |
+
# 读
|
15 |
+
file_path = requir_path
|
16 |
+
requirements = []
|
17 |
+
with open(file_path, 'r') as file:
|
18 |
+
for line in file:
|
19 |
+
requirements.append(line.strip())
|
20 |
+
|
21 |
+
# 查
|
22 |
+
missing_libs = []
|
23 |
+
for libs in requirements:
|
24 |
+
try:
|
25 |
+
importlib.import_module(libs)
|
26 |
+
except ImportError:
|
27 |
+
missing_libs.append(libs)
|
28 |
+
|
29 |
+
return missing_libs
|
30 |
+
|
31 |
+
def print_missing(missing_libs):
|
32 |
+
# 返
|
33 |
+
if missing_libs == []:
|
34 |
+
return ""
|
35 |
+
else:
|
36 |
+
return f"Not installed libraries: {', '.join(missing_libs)}"
|
37 |
+
|
38 |
+
def detecter():
|
39 |
+
gpu_check = check_memory()
|
40 |
+
cog_requir = "./install_script/check.txt"
|
41 |
+
installed = print_missing(install_detection(cog_requir))
|
42 |
+
|
43 |
+
if installed == "":
|
44 |
+
return gpu_check + "All listed libraries are installed. / 本地模型依赖安装无误"
|
45 |
+
else:
|
46 |
+
return gpu_check + installed
|
47 |
+
|
48 |
+
|
49 |
+
def is_installed(package):
|
50 |
+
try:
|
51 |
+
dist = importlib.metadata.distribution(package)
|
52 |
+
except importlib.metadata.PackageNotFoundError:
|
53 |
+
try:
|
54 |
+
spec = importlib.util.find_spec(package)
|
55 |
+
except ModuleNotFoundError:
|
56 |
+
return False
|
57 |
+
|
58 |
+
return spec is not None
|
59 |
+
|
60 |
+
return dist is not None
|
lib/Failed_Tagging_File_Screening.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import shutil
|
4 |
+
|
5 |
+
# List of supported image file extensions
|
6 |
+
IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.tif']
|
7 |
+
|
8 |
+
# Global variable to keep track of the number of moved images
|
9 |
+
moved_images_count = 0
|
10 |
+
|
11 |
+
# Check and move documents and their associated image files with the same name
|
12 |
+
def move_files_with_keywords(source_folder, target_folder, keywords):
|
13 |
+
global moved_images_count
|
14 |
+
# Create the target folder if it doesn't exist
|
15 |
+
if not os.path.exists(target_folder):
|
16 |
+
os.makedirs(target_folder)
|
17 |
+
|
18 |
+
# Iterate through all the files and folders within source_folder
|
19 |
+
for root, dirs, files in os.walk(source_folder):
|
20 |
+
for file in files:
|
21 |
+
if file.endswith('.txt'):
|
22 |
+
file_path = os.path.join(root, file)
|
23 |
+
# Check if the text file contains any of the keywords
|
24 |
+
if has_keywords(file_path, keywords):
|
25 |
+
# Move the text file
|
26 |
+
shutil.move(file_path, os.path.join(target_folder, file))
|
27 |
+
# Move the related image files with the same name
|
28 |
+
move_related_images(root, file, target_folder)
|
29 |
+
|
30 |
+
# Check if the text file contains any of the given keywords
|
31 |
+
def has_keywords(file_path, keywords):
|
32 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
33 |
+
content = file.read()
|
34 |
+
return any(keyword.lower() in content.lower() for keyword in keywords)
|
35 |
+
|
36 |
+
# Move the image files with the same name as the text file
|
37 |
+
def move_related_images(file_dir, text_file, target_folder):
|
38 |
+
global moved_images_count
|
39 |
+
base_name = os.path.splitext(text_file)[0]
|
40 |
+
for ext in IMAGE_EXTENSIONS:
|
41 |
+
image_file = base_name + ext
|
42 |
+
image_path = os.path.join(file_dir, image_file)
|
43 |
+
if os.path.exists(image_path):
|
44 |
+
# Check if the image already exists in the target folder
|
45 |
+
target_image_path = os.path.join(target_folder, image_file)
|
46 |
+
file_counter = 1
|
47 |
+
# Find a unique file name in the target folder
|
48 |
+
while os.path.exists(target_image_path):
|
49 |
+
# Generate a new file name with a counter
|
50 |
+
new_base_name = f"{base_name}_{file_counter}"
|
51 |
+
target_image_path = os.path.join(target_folder, new_base_name + ext)
|
52 |
+
file_counter += 1
|
53 |
+
# Move the image file to the target folder with the new unique name
|
54 |
+
shutil.move(image_path, target_image_path)
|
55 |
+
moved_images_count += 1 # Increment the count for each moved image
|
56 |
+
|
57 |
+
def main(image_path, keywords):
|
58 |
+
# The target folder will be created in the same directory as image_path
|
59 |
+
target_folder = os.path.join(os.path.dirname(image_path), 'moved_files')
|
60 |
+
move_files_with_keywords(image_path, target_folder, keywords)
|
61 |
+
# Display the message with the count of moved images and the target folder path
|
62 |
+
print(f"Operation complete / 操作完成. Total images moved: {moved_images_count}. Moved to folder: {target_folder}")
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
parser = argparse.ArgumentParser(description="Move documents containing keywords and their associated image files with the same name.")
|
66 |
+
parser.add_argument('--image_path', type=str, help='The path to the folder')
|
67 |
+
parser.add_argument('--keywords', type=str, help='List of keywords, separated by commas', default='error,sorry,content')
|
68 |
+
args = parser.parse_args()
|
69 |
+
|
70 |
+
# Split the received keyword string into a list
|
71 |
+
keywords = args.keywords.split(',')
|
72 |
+
|
73 |
+
main(args.image_path, keywords)
|
lib/GPT_Prompt.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import csv
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# GPT Prompt
|
6 |
+
PROMPTS_CSV_PATH = "saved_prompts.csv"
|
7 |
+
|
8 |
+
def get_prompts_from_csv():
|
9 |
+
if not os.path.exists(PROMPTS_CSV_PATH):
|
10 |
+
return []
|
11 |
+
with open(PROMPTS_CSV_PATH, 'r', newline='', encoding='utf-8') as file:
|
12 |
+
reader = csv.reader(file)
|
13 |
+
# remove empty rows
|
14 |
+
return [row[0] for row in reader if row]
|
15 |
+
|
16 |
+
def save_prompt(prompt):
|
17 |
+
# Append CSV
|
18 |
+
with open(PROMPTS_CSV_PATH, 'a+', newline='', encoding='utf-8') as file:
|
19 |
+
# Move to start
|
20 |
+
file.seek(0)
|
21 |
+
reader = csv.reader(file)
|
22 |
+
existing_prompts = [row[0] for row in reader]
|
23 |
+
if prompt not in existing_prompts:
|
24 |
+
writer = csv.writer(file)
|
25 |
+
writer.writerow([prompt])
|
26 |
+
# Move to end
|
27 |
+
file.seek(0, os.SEEK_END)
|
28 |
+
return gr.Dropdown(label="Saved Prompts", choices=get_prompts_from_csv(), type="value", interactive=True)
|
29 |
+
|
30 |
+
def delete_prompt(prompt):
|
31 |
+
lines = []
|
32 |
+
with open(PROMPTS_CSV_PATH, 'r', newline='', encoding='utf-8') as readFile:
|
33 |
+
reader = csv.reader(readFile)
|
34 |
+
lines = [row for row in reader if row and row[0] != prompt]
|
35 |
+
with open(PROMPTS_CSV_PATH, 'w', newline='', encoding='utf-8') as writeFile:
|
36 |
+
writer = csv.writer(writeFile)
|
37 |
+
writer.writerows(lines)
|
38 |
+
return gr.Dropdown(label="Saved Prompts", choices=get_prompts_from_csv(), type="value", interactive=True)
|
lib/Img_Processing.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import subprocess
|
3 |
+
import concurrent.futures
|
4 |
+
|
5 |
+
from PIL import Image
|
6 |
+
from tqdm import tqdm
|
7 |
+
from PIL import Image, ExifTags
|
8 |
+
|
9 |
+
target_resolutions = [
|
10 |
+
(640, 1632), # 640 * 1632 = 1044480
|
11 |
+
(704, 1472), # 704 * 1472 = 1036288
|
12 |
+
(768, 1360), # 768 * 1360 = 1044480
|
13 |
+
(832, 1248), # 832 * 1248 = 1038336
|
14 |
+
(896, 1152),
|
15 |
+
(960, 1088), # 960 * 1088 = 1044480
|
16 |
+
(992, 1056), # 992 * 1056 = 1047552
|
17 |
+
(1024, 1024), # 1024 * 1024 = 1048576
|
18 |
+
(1056, 992), # 1056 * 992 = 1047552
|
19 |
+
(1088, 960), # 1088 * 960 = 1044480
|
20 |
+
(1152, 896),
|
21 |
+
(1248, 832), # 1248 * 832 = 1038336
|
22 |
+
(1360, 768), # 1360 * 768 = 1044480
|
23 |
+
(1472, 704), # 1472 * 704 = 1036288
|
24 |
+
(1632, 640), # 1632 * 640 = 1044480
|
25 |
+
# (768, 1360), # 768 * 1360 = 1044480
|
26 |
+
# (1472, 704), # 1472 * 704 = 1036288
|
27 |
+
# (1024, 1024), # 1024 * 1024 = 1048576
|
28 |
+
]
|
29 |
+
|
30 |
+
# 图像预处理
|
31 |
+
def apply_exif_orientation(image):
|
32 |
+
try:
|
33 |
+
for orientation in ExifTags.TAGS.keys():
|
34 |
+
if ExifTags.TAGS[orientation] == 'Orientation':
|
35 |
+
break
|
36 |
+
exif = image._getexif()
|
37 |
+
|
38 |
+
if exif is not None:
|
39 |
+
exif = dict(exif.items())
|
40 |
+
orientation_value = exif.get(orientation)
|
41 |
+
|
42 |
+
if orientation_value == 3:
|
43 |
+
image = image.rotate(180, expand=True)
|
44 |
+
elif orientation_value == 6:
|
45 |
+
image = image.rotate(270, expand=True)
|
46 |
+
elif orientation_value == 8:
|
47 |
+
image = image.rotate(90, expand=True)
|
48 |
+
except (AttributeError, KeyError, IndexError, TypeError):
|
49 |
+
# cases: image don't have getexif
|
50 |
+
pass
|
51 |
+
|
52 |
+
return image
|
53 |
+
|
54 |
+
def convert_image_to_jpg(img, img_path):
|
55 |
+
"""Convert an Image object to JPG."""
|
56 |
+
# Remove extension from original filename and add .jpg
|
57 |
+
base_name = os.path.splitext(img_path)[0]
|
58 |
+
jpg_path = base_name + '.jpg'
|
59 |
+
|
60 |
+
# Convert image to RGB if it is RGBA (or any other mode)
|
61 |
+
if img.mode != 'RGB':
|
62 |
+
img = img.convert('RGB')
|
63 |
+
|
64 |
+
img.save(jpg_path, format='JPEG', quality=100)
|
65 |
+
|
66 |
+
def process_image(img_path):
|
67 |
+
try:
|
68 |
+
if img_path.lower().endswith((".jpg", ".png", ".bmp", ".gif", ".tif", ".tiff", ".jpeg", ".webp")):
|
69 |
+
img = Image.open(img_path)
|
70 |
+
img = apply_exif_orientation(img) # Apply the EXIF orientation
|
71 |
+
|
72 |
+
# Convert to 'RGB' if it is 'RGBA' or any other mode
|
73 |
+
img = img.convert('RGB')
|
74 |
+
|
75 |
+
# 计算原图像的宽高比
|
76 |
+
original_aspect_ratio = img.width / img.height
|
77 |
+
|
78 |
+
# 找到最接近原图像宽高比的目标分辨率
|
79 |
+
target_resolution = min(target_resolutions, key=lambda res: abs(original_aspect_ratio - res[0] / res[1]))
|
80 |
+
|
81 |
+
# 计算新的维度
|
82 |
+
if img.width / target_resolution[0] < img.height / target_resolution[1]:
|
83 |
+
new_width = target_resolution[0]
|
84 |
+
new_height = int(img.height * target_resolution[0] / img.width)
|
85 |
+
else:
|
86 |
+
new_height = target_resolution[1]
|
87 |
+
new_width = int(img.width * target_resolution[1] / img.height)
|
88 |
+
|
89 |
+
# 等比缩放图像
|
90 |
+
img = img.resize((new_width, new_height), Image.LANCZOS)
|
91 |
+
|
92 |
+
# 计算裁剪的区域
|
93 |
+
left = int((img.width - target_resolution[0]) / 2)
|
94 |
+
top = int((img.height - target_resolution[1]) / 2)
|
95 |
+
right = int((img.width + target_resolution[0]) / 2)
|
96 |
+
bottom = int((img.height + target_resolution[1]) / 2)
|
97 |
+
|
98 |
+
# 裁剪图像
|
99 |
+
img = img.crop((left, top, right, bottom))
|
100 |
+
|
101 |
+
# 转换并保存图像为JPG格式
|
102 |
+
convert_image_to_jpg(img, img_path)
|
103 |
+
|
104 |
+
except Exception as e:
|
105 |
+
print(f"Error processing image {img_path}: {e}")
|
106 |
+
return None
|
107 |
+
|
108 |
+
def delete_non_jpg_files(folder_path):
|
109 |
+
"""Delete all non-jpg image files in a directory, but keep txt files."""
|
110 |
+
for dirpath, dirnames, filenames in os.walk(folder_path):
|
111 |
+
for filename in filenames:
|
112 |
+
if not filename.lower().endswith((".jpg", ".txt")):
|
113 |
+
file_path = os.path.join(dirpath, filename)
|
114 |
+
try:
|
115 |
+
os.remove(file_path)
|
116 |
+
except Exception as e:
|
117 |
+
print(f"Error occurred while deleting file : {file_path}. Error : {str(e)}")
|
118 |
+
|
119 |
+
def process_images_in_folder(folder_path):
|
120 |
+
"""
|
121 |
+
Process all images in the given folder according to the target resolutions,
|
122 |
+
then delete all non-jpg files except for .txt files.
|
123 |
+
"""
|
124 |
+
processed_files = []
|
125 |
+
|
126 |
+
file_list = [os.path.join(dirpath, filename)
|
127 |
+
for dirpath, dirnames, filenames in os.walk(folder_path)
|
128 |
+
for filename in filenames]
|
129 |
+
|
130 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
131 |
+
list(tqdm(executor.map(process_image, file_list), total=len(file_list)))
|
132 |
+
|
133 |
+
delete_non_jpg_files(folder_path)
|
134 |
+
return f"Processed images in folder: {folder_path}"
|
135 |
+
|
136 |
+
# 失败检查
|
137 |
+
def run_script(folder_path, keywords):
|
138 |
+
keywords = keywords if keywords else "sorry,error"
|
139 |
+
result = subprocess.run(
|
140 |
+
[
|
141 |
+
'python', './lib/Failed_Tagging_File_Screening.py',
|
142 |
+
'--image_path', folder_path,
|
143 |
+
'--keywords', keywords
|
144 |
+
],
|
145 |
+
capture_output=True, text=True
|
146 |
+
)
|
147 |
+
return result.stdout if result.stdout else "No Output", result.stderr if result.stderr else "No Error"
|
lib/Tag_Processor.py
ADDED
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import collections
|
3 |
+
import random
|
4 |
+
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
import networkx as nx
|
7 |
+
|
8 |
+
from wordcloud import WordCloud
|
9 |
+
from itertools import combinations
|
10 |
+
from lib import Translator
|
11 |
+
|
12 |
+
|
13 |
+
def unique_elements(original, addition):
|
14 |
+
original_list = list(map(str.strip, original.split(',')))
|
15 |
+
addition_list = list(map(str.strip, addition.split(',')))
|
16 |
+
combined_list = []
|
17 |
+
seen = set()
|
18 |
+
for item in original_list + addition_list:
|
19 |
+
if item not in seen and item != '':
|
20 |
+
seen.add(item)
|
21 |
+
combined_list.append(item)
|
22 |
+
|
23 |
+
return ', '.join(combined_list)
|
24 |
+
|
25 |
+
def save_path(folder_path,file_name):
|
26 |
+
n_path = os.path.join(folder_path, "Tag_analysis")
|
27 |
+
if not os.path.exists(n_path):
|
28 |
+
try:
|
29 |
+
os.makedirs(n_path)
|
30 |
+
except Exception as e:
|
31 |
+
print(f"Error : {e}")
|
32 |
+
save_path = os.path.join(n_path, file_name)
|
33 |
+
return save_path
|
34 |
+
|
35 |
+
def modify_tags_in_folder(folder_path, tags_to_remove, tags_to_replace_dict, new_tag, insert_position):
|
36 |
+
for root, dirs, files in os.walk(folder_path):
|
37 |
+
for file in files:
|
38 |
+
if file.endswith('.txt'):
|
39 |
+
file_path = os.path.join(root, file)
|
40 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
41 |
+
content = f.read()
|
42 |
+
tags = [tag.strip() for tag in content.split(',')]
|
43 |
+
# 删除标签
|
44 |
+
tags = [tag for tag in tags if tag not in tags_to_remove]
|
45 |
+
# 替换标签
|
46 |
+
for old_tag, new_tag_replacement in tags_to_replace_dict.items():
|
47 |
+
tags = [new_tag_replacement if tag == old_tag else tag for tag in tags]
|
48 |
+
# 添加标签
|
49 |
+
if new_tag and new_tag.strip():
|
50 |
+
if insert_position == 'Start / 开始':
|
51 |
+
tags.insert(0, new_tag.strip())
|
52 |
+
elif insert_position == 'End / 结束':
|
53 |
+
tags.append(new_tag.strip())
|
54 |
+
elif insert_position == 'Random / 随机':
|
55 |
+
random_index = random.randrange(len(tags)+1)
|
56 |
+
tags.insert(random_index, new_tag.strip())
|
57 |
+
|
58 |
+
# 保存修改后的文件
|
59 |
+
with open(file_path, 'w', encoding='utf-8') as f:
|
60 |
+
updated_content = ', '.join(tags)
|
61 |
+
f.write(updated_content)
|
62 |
+
|
63 |
+
return "Tags modified successfully."
|
64 |
+
|
65 |
+
|
66 |
+
# 词云
|
67 |
+
def count_tags_in_folder(folder_path, top_n):
|
68 |
+
tags_counter = collections.Counter()
|
69 |
+
for root, dirs, files in os.walk(folder_path):
|
70 |
+
for file in files:
|
71 |
+
if file.endswith('.txt'):
|
72 |
+
file_path = os.path.join(root, file)
|
73 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
74 |
+
content = f.read()
|
75 |
+
tags = content.split(',')
|
76 |
+
tags = [tag.strip() for tag in tags]
|
77 |
+
tags_counter.update(tags)
|
78 |
+
|
79 |
+
sorted_tags = sorted(tags_counter.items(), key=lambda x: x[1], reverse=True)
|
80 |
+
return sorted_tags[:top_n]
|
81 |
+
|
82 |
+
def generate_network_graph(folder_path, top_n):
|
83 |
+
G = nx.Graph()
|
84 |
+
tags_cooccurrence = collections.defaultdict(int)
|
85 |
+
|
86 |
+
# 读取文件并计算标签的共现关系
|
87 |
+
for root, dirs, files in os.walk(folder_path):
|
88 |
+
for file in files:
|
89 |
+
if file.endswith('.txt'):
|
90 |
+
file_path = os.path.join(root, file)
|
91 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
92 |
+
content = f.read()
|
93 |
+
tags = list(set(content.split(','))) # 去重
|
94 |
+
for tag_pair in combinations(tags, 2):
|
95 |
+
if tag_pair[0].strip() and tag_pair[1].strip(): # 确保标签不是空的
|
96 |
+
tags_cooccurrence[tag_pair] += 1
|
97 |
+
|
98 |
+
# 只考虑top n个共现关系
|
99 |
+
top_cooccurrences = sorted(tags_cooccurrence.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
100 |
+
|
101 |
+
# 添加边到图中
|
102 |
+
for (tag1, tag2), weight in top_cooccurrences:
|
103 |
+
G.add_edge(tag1.strip(), tag2.strip(), weight=weight)
|
104 |
+
|
105 |
+
# 设置画布大小
|
106 |
+
plt.figure(figsize=(24, 12))
|
107 |
+
|
108 |
+
# 创建黑色背景
|
109 |
+
gradio_blue = '#0B0F19'
|
110 |
+
plt.gca().set_facecolor(gradio_blue)
|
111 |
+
|
112 |
+
# 为节点设置大小和颜色
|
113 |
+
degrees = dict(G.degree)
|
114 |
+
node_size = [v * 100 for v in degrees.values()]
|
115 |
+
# 使用更鲜亮的颜色映射
|
116 |
+
node_color = [degrees[n] for n in G.nodes]
|
117 |
+
|
118 |
+
# 为边设置宽度
|
119 |
+
edge_width = [G[u][v]['weight'] / 100 for u, v in G.edges] # 除以10是为了使边宽度合适
|
120 |
+
|
121 |
+
# 计算节点的布局
|
122 |
+
pos = nx.kamada_kawai_layout(G)
|
123 |
+
# pos = nx.spring_layout(G, k=0.5, iterations=50)
|
124 |
+
|
125 |
+
# 绘制节点,使用Plasma配色方案,以适配黑色背景
|
126 |
+
nx.draw_networkx_nodes(G, pos, node_size=node_size,
|
127 |
+
node_color=node_color, cmap=plt.cm.plasma, alpha=0.8)
|
128 |
+
|
129 |
+
# 绘制边,使用带有透明度的白色
|
130 |
+
nx.draw_networkx_edges(G, pos, width=edge_width, alpha=0.3, edge_color='w')
|
131 |
+
|
132 |
+
# 绘制标签,设置为白色以突出显示
|
133 |
+
nx.draw_networkx_labels(G, pos, font_size=12,
|
134 |
+
font_weight='bold', font_color='white',
|
135 |
+
font_family='sans-serif')
|
136 |
+
|
137 |
+
# 移除坐标轴
|
138 |
+
plt.axis('off')
|
139 |
+
|
140 |
+
# 保存图像
|
141 |
+
save_network = save_path(folder_path,'tag_network.png')
|
142 |
+
plt.savefig(save_network, format='png', dpi=300, bbox_inches='tight', facecolor=gradio_blue)
|
143 |
+
plt.close()
|
144 |
+
return save_network
|
145 |
+
|
146 |
+
def generate_wordcloud(folder_path, top):
|
147 |
+
tag_counts = count_tags_in_folder(folder_path, top)
|
148 |
+
wordcloud = WordCloud(width=1600, height=1200, background_color='white')
|
149 |
+
wordcloud.generate_from_frequencies(dict(tag_counts))
|
150 |
+
plt.figure(figsize=(20, 15))
|
151 |
+
plt.imshow(wordcloud, interpolation='bilinear')
|
152 |
+
plt.axis('off')
|
153 |
+
plt.tight_layout(pad=0)
|
154 |
+
save_wordcloud = save_path(folder_path,'tag_wordcloud.png')
|
155 |
+
plt.savefig(save_wordcloud, format='png')
|
156 |
+
plt.close()
|
157 |
+
return save_wordcloud
|
158 |
+
|
159 |
+
# Tag处理
|
160 |
+
def modify_file_content(file_path, new_content, mode):
|
161 |
+
if mode == "skip/跳过" and os.path.exists(file_path):
|
162 |
+
print(f"Skip writing, as the file {file_path} already exists.")
|
163 |
+
return
|
164 |
+
|
165 |
+
if mode == "overwrite/覆盖" or not os.path.exists(file_path):
|
166 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
167 |
+
file.write(new_content)
|
168 |
+
return
|
169 |
+
|
170 |
+
with open(file_path, 'r+', encoding='utf-8') as file:
|
171 |
+
existing_content = file.read()
|
172 |
+
file.seek(0)
|
173 |
+
if mode == "prepend/前置插入":
|
174 |
+
combined_content = unique_elements(new_content, existing_content)
|
175 |
+
file.write(combined_content)
|
176 |
+
file.truncate()
|
177 |
+
elif mode == "append/末尾追加":
|
178 |
+
combined_content = unique_elements(existing_content, new_content)
|
179 |
+
file.write(combined_content)
|
180 |
+
file.truncate()
|
181 |
+
else:
|
182 |
+
raise ValueError("Invalid mode. Must be 'overwrite/覆盖', 'prepend/前置插入', or 'append/末尾追加'.")
|
183 |
+
|
184 |
+
def process_tags(folder_path, top_n, tags_to_remove, tags_to_replace, new_tag, insert_position, translate, api_key,
|
185 |
+
api_url):
|
186 |
+
# 解析删除标签
|
187 |
+
tags_to_remove_list = tags_to_remove.split(',') if tags_to_remove else []
|
188 |
+
tags_to_remove_list = [tag.strip() for tag in tags_to_remove_list]
|
189 |
+
|
190 |
+
# 解析替换标签
|
191 |
+
tags_to_replace_dict = {}
|
192 |
+
if tags_to_replace:
|
193 |
+
try:
|
194 |
+
for pair in tags_to_replace.split(','):
|
195 |
+
old_tag, new_replacement_tag = pair.split(':')
|
196 |
+
tags_to_replace_dict[old_tag.strip()] = new_replacement_tag.strip()
|
197 |
+
except ValueError:
|
198 |
+
return "Error: Tags to replace must be in 'old_tag:new_tag' format separated by commas", None, None
|
199 |
+
|
200 |
+
# 修改文件夹中的标签
|
201 |
+
modify_tags_in_folder(folder_path, tags_to_remove_list, tags_to_replace_dict, new_tag, insert_position)
|
202 |
+
|
203 |
+
# 词云及网格图
|
204 |
+
top = int(top_n)
|
205 |
+
wordcloud_path = generate_wordcloud(folder_path, top)
|
206 |
+
networkgraph_path = generate_network_graph(folder_path, top)
|
207 |
+
|
208 |
+
# 翻译Tag功能
|
209 |
+
def truncate_tag(tag, max_length=30):
|
210 |
+
# 截断过长标签
|
211 |
+
return (tag[:max_length] + '...') if len(tag) > max_length else tag
|
212 |
+
|
213 |
+
tag_counts = count_tags_in_folder(folder_path, top)
|
214 |
+
|
215 |
+
if translate.startswith('GPT-3.5 translation / GPT3.5翻译'):
|
216 |
+
translator = Translator.GPTTranslator(api_key, api_url)
|
217 |
+
elif translate.startswith('Free translation / 免费翻译'):
|
218 |
+
translator = Translator.ChineseTranslator()
|
219 |
+
else:
|
220 |
+
translator = None
|
221 |
+
if translator:
|
222 |
+
tags_to_translate = [tag for tag, _ in tag_counts]
|
223 |
+
translations = Translator.translate_tags(translator, tags_to_translate)
|
224 |
+
# 确保 translations 列表长度与 tag_counts 一致
|
225 |
+
translations.extend(["" for _ in range(len(tag_counts) - len(translations))])
|
226 |
+
tag_counts_with_translation = [(truncate_tag(tag_counts[i][0]), tag_counts[i][1], translations[i]) for i in
|
227 |
+
range(len(tag_counts))]
|
228 |
+
else:
|
229 |
+
tag_counts_with_translation = [(truncate_tag(tag), count, "") for tag, count in tag_counts]
|
230 |
+
|
231 |
+
return tag_counts_with_translation, wordcloud_path, networkgraph_path, "Tags processed successfully."
|
lib/Translator.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from urllib3.util.retry import Retry
|
3 |
+
from requests.adapters import HTTPAdapter
|
4 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
5 |
+
|
6 |
+
class ChineseTranslator:
|
7 |
+
def __init__(self):
|
8 |
+
self.client = requests.Session()
|
9 |
+
|
10 |
+
def translate(self, text):
|
11 |
+
if not text:
|
12 |
+
return None
|
13 |
+
|
14 |
+
payload = {
|
15 |
+
"appid": "105",
|
16 |
+
"sgid": "en",
|
17 |
+
"sbid": "en",
|
18 |
+
"egid": "zh-CN",
|
19 |
+
"ebid": "zh-CN",
|
20 |
+
"content": text,
|
21 |
+
"type": "2",
|
22 |
+
}
|
23 |
+
|
24 |
+
response = self.client.post("https://translate-api-fykz.xiangtatech.com/translation/webs/index", data=payload)
|
25 |
+
if response.status_code == 200:
|
26 |
+
json_data = response.json()
|
27 |
+
by_value = json_data.get("by", "")
|
28 |
+
if not by_value:
|
29 |
+
return None
|
30 |
+
return by_value
|
31 |
+
|
32 |
+
return None
|
33 |
+
|
34 |
+
def close_session(self):
|
35 |
+
self.client.close()
|
36 |
+
|
37 |
+
class GPTTranslator:
|
38 |
+
def __init__(self, api_key, api_url):
|
39 |
+
self.headers = {
|
40 |
+
"Content-Type": "application/json",
|
41 |
+
"Authorization": f"Bearer {api_key}"
|
42 |
+
}
|
43 |
+
|
44 |
+
self.session = requests.Session()
|
45 |
+
retries = Retry(total=5, backoff_factor=0.1, status_forcelist=[429, 500, 502, 503, 504])
|
46 |
+
self.session.mount('https://', HTTPAdapter(max_retries=retries))
|
47 |
+
|
48 |
+
self.api_url = api_url
|
49 |
+
|
50 |
+
def translate(self, text):
|
51 |
+
data = {
|
52 |
+
"model": "gpt-3.5-turbo",
|
53 |
+
"messages": [
|
54 |
+
{"role": "user", "content": f"你是一个英译中专家,请直接返回'{text}'最有可能的三种中文翻译结果,彼此间语义有所区分,结果以逗号间隔."}
|
55 |
+
]
|
56 |
+
}
|
57 |
+
response = self.session.post(self.api_url, headers=self.headers, json=data)
|
58 |
+
response_data = response.json()
|
59 |
+
|
60 |
+
if response.status_code == 200 and 'choices' in response_data and 'content' in response_data['choices'][0]['message']:
|
61 |
+
return response_data['choices'][0]['message']['content']
|
62 |
+
else:
|
63 |
+
return f"Error or no translation for tag: {text}"
|
64 |
+
|
65 |
+
def close_session(self):
|
66 |
+
self.session.close()
|
67 |
+
|
68 |
+
def translate_tags(translator, tags):
|
69 |
+
translations = [None] * len(tags)
|
70 |
+
|
71 |
+
with ThreadPoolExecutor(max_workers=50) as executor:
|
72 |
+
future_to_index = {executor.submit(translator.translate, tag): i for i, tag in enumerate(tags)}
|
73 |
+
for future in as_completed(future_to_index):
|
74 |
+
index = future_to_index[future]
|
75 |
+
translations[index] = future.result()
|
76 |
+
|
77 |
+
translator.close_session()
|
78 |
+
|
79 |
+
return translations
|
moondream/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .util import detect_device
|
2 |
+
from .moondream import Moondream
|
moondream/configuration_moondream.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
from typing import Optional
|
4 |
+
import math
|
5 |
+
|
6 |
+
|
7 |
+
class PhiConfig(PretrainedConfig):
|
8 |
+
model_type = "phi-msft"
|
9 |
+
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
vocab_size: int = 51200,
|
13 |
+
n_positions: int = 2048,
|
14 |
+
n_embd: int = 2048,
|
15 |
+
n_layer: int = 24,
|
16 |
+
n_inner: Optional[int] = None,
|
17 |
+
n_head: int = 32,
|
18 |
+
n_head_kv: Optional[int] = None,
|
19 |
+
rotary_dim: Optional[int] = 32,
|
20 |
+
activation_function: Optional[str] = "gelu_new",
|
21 |
+
flash_attn: bool = False,
|
22 |
+
flash_rotary: bool = False,
|
23 |
+
fused_dense: bool = False,
|
24 |
+
attn_pdrop: float = 0.0,
|
25 |
+
embd_pdrop: float = 0.0,
|
26 |
+
resid_pdrop: float = 0.0,
|
27 |
+
layer_norm_epsilon: float = 1e-5,
|
28 |
+
initializer_range: float = 0.02,
|
29 |
+
tie_word_embeddings: bool = False,
|
30 |
+
pad_vocab_size_multiple: int = 64,
|
31 |
+
gradient_checkpointing: bool = False,
|
32 |
+
**kwargs
|
33 |
+
):
|
34 |
+
pad_vocab_size = (
|
35 |
+
math.ceil(vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple
|
36 |
+
)
|
37 |
+
super().__init__(
|
38 |
+
vocab_size=pad_vocab_size,
|
39 |
+
n_positions=n_positions,
|
40 |
+
n_embd=n_embd,
|
41 |
+
n_layer=n_layer,
|
42 |
+
n_inner=n_inner,
|
43 |
+
n_head=n_head,
|
44 |
+
n_head_kv=n_head_kv,
|
45 |
+
activation_function=activation_function,
|
46 |
+
attn_pdrop=attn_pdrop,
|
47 |
+
embd_pdrop=embd_pdrop,
|
48 |
+
resid_pdrop=resid_pdrop,
|
49 |
+
layer_norm_epsilon=layer_norm_epsilon,
|
50 |
+
initializer_range=initializer_range,
|
51 |
+
pad_vocab_size_multiple=pad_vocab_size_multiple,
|
52 |
+
tie_word_embeddings=tie_word_embeddings,
|
53 |
+
gradient_checkpointing=gradient_checkpointing,
|
54 |
+
**kwargs
|
55 |
+
)
|
56 |
+
self.rotary_dim = min(rotary_dim, n_embd // n_head)
|
57 |
+
self.flash_attn = flash_attn
|
58 |
+
self.flash_rotary = flash_rotary
|
59 |
+
self.fused_dense = fused_dense
|
60 |
+
|
61 |
+
attribute_map = {
|
62 |
+
"max_position_embeddings": "n_positions",
|
63 |
+
"hidden_size": "n_embd",
|
64 |
+
"num_attention_heads": "n_head",
|
65 |
+
"num_hidden_layers": "n_layer",
|
66 |
+
}
|
67 |
+
|
68 |
+
|
69 |
+
class MoondreamConfig(PretrainedConfig):
|
70 |
+
model_type = "moondream1"
|
71 |
+
|
72 |
+
def __init__(self, **kwargs):
|
73 |
+
self.phi_config = PhiConfig(**kwargs)
|
74 |
+
super().__init__(**kwargs)
|
moondream/modeling_phi.py
ADDED
@@ -0,0 +1,720 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Microsoft Corporation.
|
2 |
+
# Licensed under the MIT license.
|
3 |
+
#
|
4 |
+
# Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
|
5 |
+
# Licensed under the BSD 3-Clause License.
|
6 |
+
|
7 |
+
from dataclasses import dataclass, field
|
8 |
+
from typing import Any, Dict, Optional, Union, Tuple
|
9 |
+
|
10 |
+
import math
|
11 |
+
import torch
|
12 |
+
import torch.nn as nn
|
13 |
+
from einops import rearrange, repeat
|
14 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
15 |
+
from transformers.activations import ACT2FN
|
16 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
17 |
+
|
18 |
+
from .configuration_moondream import PhiConfig
|
19 |
+
|
20 |
+
FusedDense = None
|
21 |
+
|
22 |
+
|
23 |
+
@dataclass
|
24 |
+
class InferenceParams:
|
25 |
+
max_seqlen: int
|
26 |
+
max_batch_size: int
|
27 |
+
seqlen_offset: int = 0
|
28 |
+
batch_size_offset: int = 0
|
29 |
+
key_value_memory_dict: Dict[str, Any] = field(default_factory=dict)
|
30 |
+
lengths_per_sample: torch.Tensor = None
|
31 |
+
|
32 |
+
|
33 |
+
class Embedding(nn.Module):
|
34 |
+
def __init__(self, config: PretrainedConfig):
|
35 |
+
super().__init__()
|
36 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
37 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
38 |
+
|
39 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor:
|
40 |
+
return self.drop(self.wte(input_ids.view(-1, input_ids.size(-1))))
|
41 |
+
|
42 |
+
|
43 |
+
def _apply_rotary_emb(x, cos, sin):
|
44 |
+
seqlen, rotary_dim = x.size(1), cos.size(1) * 2
|
45 |
+
x_rot, x_pass = x[..., :rotary_dim], x[..., rotary_dim:]
|
46 |
+
x1, x2 = x_rot.chunk(2, dim=-1)
|
47 |
+
c, s = cos[:seqlen].unsqueeze(1), sin[:seqlen].unsqueeze(1)
|
48 |
+
x_rot = torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1)
|
49 |
+
return torch.cat([x_rot.to(x.dtype), x_pass], dim=-1)
|
50 |
+
|
51 |
+
|
52 |
+
def _apply_rotary_emb_kv(
|
53 |
+
kv: torch.FloatTensor, cos: torch.FloatTensor, sin: torch.FloatTensor
|
54 |
+
) -> torch.FloatTensor:
|
55 |
+
seqlen, rotary_dim = kv.shape[1], cos.shape[-1] * 2
|
56 |
+
k_rot = kv[:, :, 0, :, :rotary_dim].chunk(2, dim=-1)
|
57 |
+
k_pass = kv[:, :, 0, :, rotary_dim:]
|
58 |
+
c, s = cos[:seqlen].unsqueeze(1), sin[:seqlen].unsqueeze(1)
|
59 |
+
k_rot = torch.cat(
|
60 |
+
[k_rot[0] * c - k_rot[1] * s, k_rot[0] * s + k_rot[1] * c], dim=-1
|
61 |
+
)
|
62 |
+
return torch.cat(
|
63 |
+
[torch.cat([k_rot, k_pass], dim=-1).unsqueeze(2), kv[:, :, 1:2, :, :]], dim=2
|
64 |
+
)
|
65 |
+
|
66 |
+
|
67 |
+
def _apply_rotary_emb_qkv(
|
68 |
+
qkv: torch.FloatTensor, cos: torch.FloatTensor, sin: torch.FloatTensor
|
69 |
+
) -> torch.FloatTensor:
|
70 |
+
seqlen, rotary_dim = qkv.shape[1], cos.shape[1] * 2
|
71 |
+
|
72 |
+
c = cos[:seqlen].unsqueeze(1)
|
73 |
+
s = sin[:seqlen].unsqueeze(1)
|
74 |
+
|
75 |
+
qkv_rot = torch.stack(
|
76 |
+
[
|
77 |
+
torch.cat(
|
78 |
+
[
|
79 |
+
qkv[:, :, i, :, : rotary_dim // 2] * c
|
80 |
+
- qkv[:, :, i, :, rotary_dim // 2 : rotary_dim] * s,
|
81 |
+
qkv[:, :, i, :, : rotary_dim // 2] * s
|
82 |
+
+ qkv[:, :, i, :, rotary_dim // 2 : rotary_dim] * c,
|
83 |
+
],
|
84 |
+
dim=-1,
|
85 |
+
).to(qkv.dtype)
|
86 |
+
for i in range(2)
|
87 |
+
],
|
88 |
+
dim=2,
|
89 |
+
)
|
90 |
+
|
91 |
+
qkv_pass = qkv[:, :, :2, :, rotary_dim:].unsqueeze(2)
|
92 |
+
qkv_v = qkv[:, :, 2:3, :, :]
|
93 |
+
return torch.cat([qkv_rot, qkv_pass, qkv_v], dim=2)
|
94 |
+
|
95 |
+
|
96 |
+
class RotaryEmbedding(nn.Module):
|
97 |
+
# Enhanced Transformer with Rotary Position Embedding (https://arxiv.org/pdf/2104.09864.pdf)
|
98 |
+
def __init__(
|
99 |
+
self,
|
100 |
+
dim: int,
|
101 |
+
base: int = 10000,
|
102 |
+
scale_base: Optional[float] = None,
|
103 |
+
pos_idx_in_fp32: bool = True,
|
104 |
+
max_position_embeddings: int = 2048,
|
105 |
+
device: Optional[str] = None,
|
106 |
+
) -> None:
|
107 |
+
super().__init__()
|
108 |
+
# fp32 is preferred since the output of `torch.arange` can be quite large and bf16 would lose a lot of precision
|
109 |
+
self.dim, self.base, self.pos_idx_in_fp32, self.device = (
|
110 |
+
dim,
|
111 |
+
float(base),
|
112 |
+
pos_idx_in_fp32,
|
113 |
+
device,
|
114 |
+
)
|
115 |
+
self.max_position_embeddings = max_position_embeddings
|
116 |
+
if scale_base is not None:
|
117 |
+
raise NotImplementedError
|
118 |
+
|
119 |
+
# Generate and register the non-trainable buffers
|
120 |
+
self.register_buffer(
|
121 |
+
"inv_freq", self._compute_inv_freq(device), persistent=False
|
122 |
+
)
|
123 |
+
self.register_buffer(
|
124 |
+
"scale", self._calculate_scale(dim, scale_base, device), persistent=False
|
125 |
+
)
|
126 |
+
self._update_cos_sin_cache(
|
127 |
+
max_position_embeddings, device=device, dtype=torch.float32
|
128 |
+
)
|
129 |
+
|
130 |
+
def _calculate_scale(self, dim, scale_base, device):
|
131 |
+
return (
|
132 |
+
(
|
133 |
+
(
|
134 |
+
torch.arange(0, dim, 2, device=device, dtype=torch.float32)
|
135 |
+
+ 0.4 * dim
|
136 |
+
)
|
137 |
+
/ (1.4 * dim)
|
138 |
+
)
|
139 |
+
if scale_base is not None
|
140 |
+
else None
|
141 |
+
)
|
142 |
+
|
143 |
+
def _compute_inv_freq(self, device: Optional[str] = None) -> torch.FloatTensor:
|
144 |
+
return 1.0 / (
|
145 |
+
self.base
|
146 |
+
** (
|
147 |
+
torch.arange(0, self.dim, 2, device=device, dtype=torch.float32)
|
148 |
+
/ self.dim
|
149 |
+
)
|
150 |
+
)
|
151 |
+
|
152 |
+
def _update_cos_sin_cache(
|
153 |
+
self,
|
154 |
+
seqlen: int,
|
155 |
+
device: Optional[str] = None,
|
156 |
+
dtype: Optional[torch.dtype] = None,
|
157 |
+
) -> None:
|
158 |
+
self._seq_len_cached = seqlen
|
159 |
+
t = torch.arange(
|
160 |
+
seqlen,
|
161 |
+
device=device,
|
162 |
+
dtype=torch.float32 if self.pos_idx_in_fp32 else self.inv_freq.dtype,
|
163 |
+
)
|
164 |
+
inv_freq = (
|
165 |
+
self._compute_inv_freq(device=device)
|
166 |
+
if self.pos_idx_in_fp32 and self.inv_freq.dtype != torch.float32
|
167 |
+
else self.inv_freq
|
168 |
+
)
|
169 |
+
|
170 |
+
freqs = torch.outer(t, inv_freq)
|
171 |
+
|
172 |
+
def apply_scale(freqs, scale, operator, dtype):
|
173 |
+
result = operator(freqs)
|
174 |
+
return (result / scale).to(dtype) if scale is not None else result.to(dtype)
|
175 |
+
|
176 |
+
if scale := self.scale:
|
177 |
+
power = (
|
178 |
+
torch.arange(seqlen, dtype=scale.dtype, device=scale.device)
|
179 |
+
- seqlen // 2
|
180 |
+
) / self.scale_base
|
181 |
+
scale = scale.to(device=power.device) ** power.unsqueeze(1)
|
182 |
+
|
183 |
+
self._cos_cached = apply_scale(
|
184 |
+
freqs, 1 / scale if scale is not None else None, torch.cos, dtype
|
185 |
+
)
|
186 |
+
self._sin_cached = apply_scale(
|
187 |
+
freqs, 1 / scale if scale is not None else None, torch.sin, dtype
|
188 |
+
)
|
189 |
+
if scale is not None:
|
190 |
+
self._cos_k_cached = apply_scale(freqs, scale, torch.cos, dtype)
|
191 |
+
self._sin_k_cached = apply_scale(freqs, scale, torch.sin, dtype)
|
192 |
+
|
193 |
+
def forward(
|
194 |
+
self,
|
195 |
+
qkv: torch.Tensor,
|
196 |
+
kv: Optional[torch.Tensor] = None,
|
197 |
+
seqlen_offset: int = 0,
|
198 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
199 |
+
should_update = (
|
200 |
+
self._seq_len_cached < qkv.shape[1] + seqlen_offset
|
201 |
+
or self._cos_cached.device != qkv.device
|
202 |
+
or self._cos_cached.dtype != qkv.dtype
|
203 |
+
or (self.training and self._cos_cached.is_inference())
|
204 |
+
)
|
205 |
+
|
206 |
+
if should_update:
|
207 |
+
self._update_cos_sin_cache(
|
208 |
+
qkv.shape[1] + seqlen_offset, device=qkv.device, dtype=qkv.dtype
|
209 |
+
)
|
210 |
+
|
211 |
+
offset_cos = self._cos_cached[seqlen_offset:]
|
212 |
+
offset_sin = self._sin_cached[seqlen_offset:]
|
213 |
+
|
214 |
+
if kv is None:
|
215 |
+
return _apply_rotary_emb_qkv(qkv, offset_cos, offset_sin)
|
216 |
+
else:
|
217 |
+
return _apply_rotary_emb(qkv, offset_cos, offset_sin), _apply_rotary_emb_kv(
|
218 |
+
kv, offset_cos, offset_sin
|
219 |
+
)
|
220 |
+
|
221 |
+
|
222 |
+
class MLP(nn.Module):
|
223 |
+
def __init__(
|
224 |
+
self,
|
225 |
+
config: PretrainedConfig,
|
226 |
+
n_inner: Optional[int] = None,
|
227 |
+
act_fn: Optional[str] = None,
|
228 |
+
) -> None:
|
229 |
+
super().__init__()
|
230 |
+
n_inner = n_inner or getattr(config, "n_inner", None) or 4 * config.n_embd
|
231 |
+
act_fn = act_fn or config.activation_function
|
232 |
+
|
233 |
+
self.fc1 = nn.Linear(config.n_embd, n_inner)
|
234 |
+
self.fc2 = nn.Linear(n_inner, config.n_embd)
|
235 |
+
self.act = ACT2FN[act_fn]
|
236 |
+
|
237 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
238 |
+
return self.fc2(self.act(self.fc1(hidden_states)))
|
239 |
+
|
240 |
+
|
241 |
+
# Flash Attention (https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py)
|
242 |
+
class SelfAttention(nn.Module):
|
243 |
+
def __init__(
|
244 |
+
self,
|
245 |
+
causal: bool = True,
|
246 |
+
softmax_scale: Optional[float] = None,
|
247 |
+
attention_dropout: float = 0.0,
|
248 |
+
):
|
249 |
+
super().__init__()
|
250 |
+
self.causal = causal
|
251 |
+
self.softmax_scale = softmax_scale
|
252 |
+
self.drop = nn.Dropout(attention_dropout)
|
253 |
+
|
254 |
+
@torch.autocast("cpu", enabled=False)
|
255 |
+
@torch.autocast("cuda", enabled=False)
|
256 |
+
def forward(
|
257 |
+
self,
|
258 |
+
qkv: torch.FloatTensor,
|
259 |
+
causal: Optional[bool] = None,
|
260 |
+
key_padding_mask: Optional[torch.BoolTensor] = None,
|
261 |
+
):
|
262 |
+
q, k, v = qkv.chunk(3, dim=-1)
|
263 |
+
scale = self.softmax_scale or 1.0 / q.size(-1) ** 0.5
|
264 |
+
|
265 |
+
scores = (
|
266 |
+
torch.einsum("bthd,bshd->bhts", q.to(torch.float32), k.to(torch.float32))
|
267 |
+
* scale
|
268 |
+
)
|
269 |
+
if causal or self.causal:
|
270 |
+
scores.triu_(1).fill_(-10000.0)
|
271 |
+
if key_padding_mask is not None:
|
272 |
+
scores.masked_fill_(key_padding_mask[:, None, None, :], -10000.0)
|
273 |
+
|
274 |
+
attn = self.drop(torch.softmax(scores, dim=-1).to(v.dtype))
|
275 |
+
return torch.einsum("bhts,bshd->bthd", attn, v)
|
276 |
+
|
277 |
+
|
278 |
+
# Flash Attention (https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py)
|
279 |
+
class CrossAttention(nn.Module):
|
280 |
+
def __init__(self, causal=True, softmax_scale=None, attention_dropout=0.0):
|
281 |
+
super().__init__()
|
282 |
+
self.causal = causal
|
283 |
+
self.softmax_scale = softmax_scale
|
284 |
+
self.drop = nn.Dropout(attention_dropout)
|
285 |
+
|
286 |
+
@torch.autocast("cpu", enabled=False)
|
287 |
+
@torch.autocast("cuda", enabled=False)
|
288 |
+
def forward(
|
289 |
+
self,
|
290 |
+
q: torch.FloatTensor,
|
291 |
+
kv: torch.FloatTensor,
|
292 |
+
causal: bool = None,
|
293 |
+
key_padding_mask: Optional[torch.BoolTensor] = None,
|
294 |
+
) -> torch.FloatTensor:
|
295 |
+
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
296 |
+
seqlen_k = kv.shape[1]
|
297 |
+
|
298 |
+
if kv.shape[3] != q.shape[2]:
|
299 |
+
kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3])
|
300 |
+
k, v = kv.unbind(dim=2)
|
301 |
+
|
302 |
+
q = q.to(torch.float32)
|
303 |
+
k = k.to(torch.float32)
|
304 |
+
|
305 |
+
causal = self.causal if causal is None else causal
|
306 |
+
softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
|
307 |
+
|
308 |
+
# Autocast is manually disabled to avoid `torch.einsum` performing the operation using float16, which might lead to overflow
|
309 |
+
scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
|
310 |
+
|
311 |
+
if key_padding_mask is not None:
|
312 |
+
padding_mask = torch.full(
|
313 |
+
(batch_size, seqlen_k),
|
314 |
+
-10000.0,
|
315 |
+
dtype=scores.dtype,
|
316 |
+
device=scores.device,
|
317 |
+
)
|
318 |
+
padding_mask.masked_fill_(key_padding_mask, 0.0)
|
319 |
+
scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
|
320 |
+
|
321 |
+
if causal:
|
322 |
+
rows = rearrange(
|
323 |
+
torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1"
|
324 |
+
)
|
325 |
+
cols = torch.arange(seqlen_k, device=k.device, dtype=torch.long)
|
326 |
+
causal_mask = cols > rows + seqlen_k - seqlen_q
|
327 |
+
scores = scores.masked_fill(causal_mask, -10000.0)
|
328 |
+
|
329 |
+
attention = torch.softmax(scores, dim=-1).to(v.dtype)
|
330 |
+
attention = self.drop(attention)
|
331 |
+
output = torch.einsum("bhts,bshd->bthd", attention, v)
|
332 |
+
|
333 |
+
return output
|
334 |
+
|
335 |
+
|
336 |
+
def _find_mha_dims(
|
337 |
+
config: PretrainedConfig,
|
338 |
+
n_head: Optional[int] = None,
|
339 |
+
n_head_kv: Optional[int] = None,
|
340 |
+
head_dim: Optional[int] = None,
|
341 |
+
) -> Tuple[int, int]:
|
342 |
+
if n_head is None and head_dim is None:
|
343 |
+
head_dim = config.n_embd // config.n_head
|
344 |
+
n_head = config.n_head
|
345 |
+
elif n_head is None or head_dim is None:
|
346 |
+
raise ValueError("`n_head` and `head_dim` must be both specified or `None`.")
|
347 |
+
if n_head_kv is None:
|
348 |
+
n_head_kv = getattr(config, "n_head_kv", None) or n_head
|
349 |
+
return n_head, n_head_kv, head_dim
|
350 |
+
|
351 |
+
|
352 |
+
def _update_kv_cache(
|
353 |
+
kv: torch.FloatTensor, inference_params: InferenceParams, layer_idx: int
|
354 |
+
) -> torch.FloatTensor:
|
355 |
+
num_heads, head_dim = kv.shape[-2:]
|
356 |
+
layer_memory = inference_params.key_value_memory_dict.setdefault(
|
357 |
+
layer_idx,
|
358 |
+
torch.empty(
|
359 |
+
inference_params.max_batch_size,
|
360 |
+
inference_params.max_seqlen,
|
361 |
+
2,
|
362 |
+
num_heads,
|
363 |
+
head_dim,
|
364 |
+
dtype=kv.dtype,
|
365 |
+
device=kv.device,
|
366 |
+
),
|
367 |
+
)
|
368 |
+
|
369 |
+
batch_slice = slice(
|
370 |
+
inference_params.batch_size_offset,
|
371 |
+
inference_params.batch_size_offset + kv.shape[0],
|
372 |
+
)
|
373 |
+
seqlen_slice = slice(
|
374 |
+
inference_params.seqlen_offset, inference_params.seqlen_offset + kv.shape[1]
|
375 |
+
)
|
376 |
+
|
377 |
+
if seqlen_slice.stop >= inference_params.max_seqlen:
|
378 |
+
layer_memory = torch.cat((layer_memory, kv), dim=1)
|
379 |
+
inference_params.key_value_memory_dict[layer_idx] = layer_memory
|
380 |
+
|
381 |
+
layer_memory[batch_slice, seqlen_slice, ...] = kv
|
382 |
+
return layer_memory[batch_slice, : seqlen_slice.stop, ...]
|
383 |
+
|
384 |
+
|
385 |
+
# Multi-head attention layer with rotary embeddings
|
386 |
+
class MHA(nn.Module):
|
387 |
+
def __init__(
|
388 |
+
self,
|
389 |
+
config,
|
390 |
+
dtype=None,
|
391 |
+
device=None,
|
392 |
+
rotary_dim=None,
|
393 |
+
rotary_base=10000.0,
|
394 |
+
rotary_scale_base=None,
|
395 |
+
n_head=None,
|
396 |
+
n_head_kv=None,
|
397 |
+
head_dim=None,
|
398 |
+
bias=True,
|
399 |
+
causal=True,
|
400 |
+
softmax_scale=None,
|
401 |
+
layer_idx=None,
|
402 |
+
return_residual=False,
|
403 |
+
checkpointing=False,
|
404 |
+
):
|
405 |
+
super().__init__()
|
406 |
+
|
407 |
+
# Set rotary embedding if specified
|
408 |
+
self.rotary_dim = rotary_dim or getattr(config, "rotary_dim", 0)
|
409 |
+
if self.rotary_dim:
|
410 |
+
self.rotary_emb = RotaryEmbedding(
|
411 |
+
self.rotary_dim,
|
412 |
+
base=rotary_base,
|
413 |
+
scale_base=rotary_scale_base,
|
414 |
+
device=device,
|
415 |
+
max_position_embeddings=config.n_positions,
|
416 |
+
)
|
417 |
+
|
418 |
+
# Determine MHA dims from arguments or config
|
419 |
+
self.n_head, self.n_head_kv, self.head_dim = _find_mha_dims(
|
420 |
+
config, n_head, n_head_kv, head_dim
|
421 |
+
)
|
422 |
+
op_size = self.head_dim * (self.n_head + 2 * self.n_head_kv)
|
423 |
+
hidden_size = config.n_embd
|
424 |
+
|
425 |
+
# Choose Linear class based on config, FusedDense is optional
|
426 |
+
LinearClass = (
|
427 |
+
FusedDense if config.fused_dense and FusedDense is not None else nn.Linear
|
428 |
+
)
|
429 |
+
self.Wqkv = LinearClass(
|
430 |
+
hidden_size, op_size, bias=bias, device=device, dtype=dtype
|
431 |
+
)
|
432 |
+
self.out_proj = LinearClass(
|
433 |
+
hidden_size, hidden_size, bias=bias, device=device, dtype=dtype
|
434 |
+
)
|
435 |
+
|
436 |
+
# Initialize attention mechanisms
|
437 |
+
attn_kwargs = {
|
438 |
+
"causal": causal,
|
439 |
+
"softmax_scale": softmax_scale,
|
440 |
+
"attention_dropout": config.attn_pdrop,
|
441 |
+
}
|
442 |
+
self.inner_attn = SelfAttention(**attn_kwargs)
|
443 |
+
self.inner_cross_attn = CrossAttention(**attn_kwargs)
|
444 |
+
|
445 |
+
self.layer_idx = layer_idx
|
446 |
+
self.return_residual = return_residual
|
447 |
+
self.checkpointing = checkpointing
|
448 |
+
|
449 |
+
def _forward_self_attn(
|
450 |
+
self, x: torch.FloatTensor, key_padding_mask: Optional[torch.BoolTensor]
|
451 |
+
) -> torch.FloatTensor:
|
452 |
+
qkv = rearrange(
|
453 |
+
self.Wqkv(x), "... (three h d) -> ... three h d", three=3, d=self.head_dim
|
454 |
+
)
|
455 |
+
if self.rotary_dim > 0:
|
456 |
+
qkv = self.rotary_emb(qkv)
|
457 |
+
attn_func = (
|
458 |
+
torch.utils.checkpoint.checkpoint
|
459 |
+
if self.checkpointing
|
460 |
+
else lambda f, *args, **kwargs: f(*args, **kwargs)
|
461 |
+
)
|
462 |
+
return attn_func(self.inner_attn, qkv, key_padding_mask=key_padding_mask)
|
463 |
+
|
464 |
+
def _forward_cross_attn(
|
465 |
+
self,
|
466 |
+
x: torch.FloatTensor,
|
467 |
+
past_key_values: Optional[InferenceParams],
|
468 |
+
key_padding_mask: Optional[torch.BoolTensor],
|
469 |
+
) -> torch.FloatTensor:
|
470 |
+
qkv = self.Wqkv(x)
|
471 |
+
q, kv = (
|
472 |
+
qkv[..., : self.n_head * self.head_dim],
|
473 |
+
qkv[..., self.n_head * self.head_dim :],
|
474 |
+
)
|
475 |
+
q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim)
|
476 |
+
kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim)
|
477 |
+
|
478 |
+
seqlen_offset = (
|
479 |
+
past_key_values.seqlen_offset if past_key_values is not None else 0
|
480 |
+
)
|
481 |
+
causal = None if seqlen_offset == 0 else False
|
482 |
+
if self.rotary_dim > 0:
|
483 |
+
q, kv = self.rotary_emb(q, kv=kv, seqlen_offset=seqlen_offset)
|
484 |
+
|
485 |
+
if past_key_values is not None:
|
486 |
+
kv = _update_kv_cache(kv, past_key_values, self.layer_idx)
|
487 |
+
|
488 |
+
attn_func = (
|
489 |
+
torch.utils.checkpoint.checkpoint
|
490 |
+
if self.checkpointing
|
491 |
+
else lambda fn, *args, **kwargs: fn(*args, **kwargs)
|
492 |
+
)
|
493 |
+
|
494 |
+
return attn_func(
|
495 |
+
self.inner_cross_attn,
|
496 |
+
q,
|
497 |
+
kv,
|
498 |
+
key_padding_mask=key_padding_mask,
|
499 |
+
causal=causal,
|
500 |
+
)
|
501 |
+
|
502 |
+
def forward(
|
503 |
+
self,
|
504 |
+
x: torch.FloatTensor,
|
505 |
+
past_key_values: Optional[InferenceParams] = None,
|
506 |
+
attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
|
507 |
+
) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
|
508 |
+
attention_mask = attention_mask.bool() if attention_mask is not None else None
|
509 |
+
use_cross_attn = self.n_head != self.n_head_kv or past_key_values is not None
|
510 |
+
attn_output_function = (
|
511 |
+
self._forward_cross_attn if use_cross_attn else self._forward_self_attn
|
512 |
+
)
|
513 |
+
attn_output = (
|
514 |
+
attn_output_function(x, past_key_values, attention_mask)
|
515 |
+
if use_cross_attn
|
516 |
+
else attn_output_function(x, attention_mask)
|
517 |
+
)
|
518 |
+
output = self.out_proj(rearrange(attn_output, "... h d -> ... (h d)"))
|
519 |
+
return (output, x) if self.return_residual else output
|
520 |
+
|
521 |
+
|
522 |
+
# Parallel block. This block applies parallel mixer and MLP layers to the input (used in GPT-J and CodeGen).
|
523 |
+
class ParallelBlock(nn.Module):
|
524 |
+
def __init__(self, config: PretrainedConfig, block_idx: Optional[int] = None):
|
525 |
+
super().__init__()
|
526 |
+
self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
527 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
528 |
+
self.block_idx = block_idx
|
529 |
+
self.mixer = MHA(config, layer_idx=block_idx)
|
530 |
+
self.mlp = MLP(config)
|
531 |
+
|
532 |
+
def forward(
|
533 |
+
self,
|
534 |
+
hidden_states: torch.FloatTensor,
|
535 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
536 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
537 |
+
) -> torch.FloatTensor:
|
538 |
+
residual = hidden_states
|
539 |
+
hidden_states = self.ln(hidden_states)
|
540 |
+
|
541 |
+
attn_outputs = self.mixer(
|
542 |
+
hidden_states,
|
543 |
+
past_key_values=past_key_values,
|
544 |
+
attention_mask=attention_mask,
|
545 |
+
)
|
546 |
+
if isinstance(attn_outputs, tuple):
|
547 |
+
attn_outputs = attn_outputs[0]
|
548 |
+
|
549 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
550 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
551 |
+
return attn_outputs + feed_forward_hidden_states + residual
|
552 |
+
|
553 |
+
|
554 |
+
class CausalLMHead(nn.Module):
|
555 |
+
"""Causal Language Modeling head. Simplified version."""
|
556 |
+
|
557 |
+
def __init__(self, config):
|
558 |
+
super().__init__()
|
559 |
+
self.ln = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
560 |
+
self.linear = nn.Linear(config.n_embd, config.vocab_size)
|
561 |
+
|
562 |
+
def forward(self, hidden_states):
|
563 |
+
return self.linear(self.ln(hidden_states)).to(torch.float32)
|
564 |
+
|
565 |
+
|
566 |
+
# Improving Language Understanding by Generative Pre-Training
|
567 |
+
# (https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf)
|
568 |
+
class CausalLMLoss(nn.Module):
|
569 |
+
def __init__(self, shift_labels: bool = True) -> None:
|
570 |
+
super().__init__()
|
571 |
+
self.shift_labels = shift_labels
|
572 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
573 |
+
|
574 |
+
def forward(
|
575 |
+
self, logits: torch.FloatTensor, labels: torch.LongTensor
|
576 |
+
) -> torch.FloatTensor:
|
577 |
+
if self.shift_labels:
|
578 |
+
logits, labels = logits[..., :-1, :], labels[..., 1:]
|
579 |
+
return self.loss_fct(logits.reshape(-1, logits.size(-1)), labels.reshape(-1))
|
580 |
+
|
581 |
+
|
582 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
583 |
+
config_class = PhiConfig
|
584 |
+
base_model_prefix = "transformer"
|
585 |
+
supports_gradient_checkpointing = False
|
586 |
+
_no_split_modules = ["ParallelBlock"]
|
587 |
+
|
588 |
+
def __init__(self, *inputs, **kwargs) -> None:
|
589 |
+
super().__init__(*inputs, **kwargs)
|
590 |
+
|
591 |
+
def prepare_inputs_for_generation(
|
592 |
+
self,
|
593 |
+
input_ids: torch.LongTensor = None,
|
594 |
+
inputs_embeds: torch.FloatTensor = None,
|
595 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
596 |
+
attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
|
597 |
+
**kwargs,
|
598 |
+
) -> Dict[str, Any]:
|
599 |
+
if input_ids is None and inputs_embeds is None:
|
600 |
+
raise ValueError(
|
601 |
+
"You have to specify either `input_ids` or `inputs_embeds`."
|
602 |
+
)
|
603 |
+
|
604 |
+
max_batch_size = (
|
605 |
+
inputs_embeds.shape[0] if inputs_embeds is not None else input_ids.shape[0]
|
606 |
+
)
|
607 |
+
seqlen_offset = (
|
608 |
+
inputs_embeds.shape[1] + input_ids.shape[1] - 2
|
609 |
+
if inputs_embeds is not None
|
610 |
+
else input_ids.shape[1] - 1
|
611 |
+
)
|
612 |
+
|
613 |
+
args = (
|
614 |
+
{"inputs_embeds": inputs_embeds}
|
615 |
+
if inputs_embeds is not None
|
616 |
+
else {"input_ids": input_ids}
|
617 |
+
)
|
618 |
+
|
619 |
+
if not isinstance(past_key_values, InferenceParams):
|
620 |
+
past_key_values = InferenceParams(
|
621 |
+
max_seqlen=self.config.n_positions,
|
622 |
+
max_batch_size=max_batch_size,
|
623 |
+
seqlen_offset=0,
|
624 |
+
batch_size_offset=0,
|
625 |
+
key_value_memory_dict={},
|
626 |
+
lengths_per_sample=None,
|
627 |
+
)
|
628 |
+
else:
|
629 |
+
past_key_values.seqlen_offset = seqlen_offset
|
630 |
+
args = {"input_ids": input_ids[:, -1].unsqueeze(-1)}
|
631 |
+
|
632 |
+
return {
|
633 |
+
**args,
|
634 |
+
"past_key_values": past_key_values,
|
635 |
+
"attention_mask": attention_mask,
|
636 |
+
}
|
637 |
+
|
638 |
+
|
639 |
+
class PhiModel(PhiPreTrainedModel):
|
640 |
+
_keys_to_ignore_on_load_missing = [""]
|
641 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
|
642 |
+
|
643 |
+
def __init__(self, config: PhiConfig) -> None:
|
644 |
+
super().__init__(config)
|
645 |
+
self.embd = Embedding(config)
|
646 |
+
self.h = nn.ModuleList(
|
647 |
+
[ParallelBlock(config, block_idx=i) for i in range(config.n_layer)]
|
648 |
+
)
|
649 |
+
self.gradient_checkpointing = config.gradient_checkpointing
|
650 |
+
self.post_init()
|
651 |
+
|
652 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
653 |
+
return self.embd.wte
|
654 |
+
|
655 |
+
def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
|
656 |
+
self.embd.wte = new_embeddings
|
657 |
+
|
658 |
+
def forward(
|
659 |
+
self,
|
660 |
+
input_ids: torch.LongTensor = None,
|
661 |
+
inputs_embeds: torch.FloatTensor = None,
|
662 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
663 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
664 |
+
) -> torch.FloatTensor:
|
665 |
+
if (input_ids is None) == (inputs_embeds is None):
|
666 |
+
raise ValueError("Specify exactly one of `input_ids` or `inputs_embeds`.")
|
667 |
+
hidden_states = self.embd(input_ids) if input_ids is not None else inputs_embeds
|
668 |
+
|
669 |
+
for layer in self.h:
|
670 |
+
func = layer.__call__ if self.gradient_checkpointing else layer
|
671 |
+
args = (hidden_states, past_key_values, attention_mask)
|
672 |
+
hidden_states = (
|
673 |
+
torch.utils.checkpoint.checkpoint(func, *args, use_reentrant=True)
|
674 |
+
if self.gradient_checkpointing
|
675 |
+
else func(*args)
|
676 |
+
)
|
677 |
+
|
678 |
+
return hidden_states
|
679 |
+
|
680 |
+
|
681 |
+
class PhiForCausalLM(PhiPreTrainedModel):
|
682 |
+
_keys_to_ignore_on_load_missing, _keys_to_ignore_on_load_unexpected = (
|
683 |
+
[""],
|
684 |
+
[r"transformer\.h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"],
|
685 |
+
)
|
686 |
+
|
687 |
+
def __init__(self, config: PhiConfig) -> None:
|
688 |
+
super().__init__(config)
|
689 |
+
self.transformer = PhiModel(config)
|
690 |
+
self.lm_head = CausalLMHead(config)
|
691 |
+
self.loss = CausalLMLoss()
|
692 |
+
self.post_init()
|
693 |
+
|
694 |
+
def get_output_embeddings(self) -> nn.Linear:
|
695 |
+
return self.lm_head.linear
|
696 |
+
|
697 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
698 |
+
self.lm_head.linear = new_embeddings
|
699 |
+
|
700 |
+
def forward(
|
701 |
+
self,
|
702 |
+
input_ids: torch.LongTensor = None,
|
703 |
+
inputs_embeds: torch.FloatTensor = None,
|
704 |
+
past_key_values: Optional[Union[torch.FloatTensor, InferenceParams]] = None,
|
705 |
+
attention_mask: Optional[torch.BoolTensor] = None,
|
706 |
+
labels: Optional[torch.LongTensor] = None,
|
707 |
+
**kwargs,
|
708 |
+
) -> CausalLMOutputWithPast:
|
709 |
+
hidden_states = self.transformer(
|
710 |
+
input_ids=input_ids,
|
711 |
+
inputs_embeds=inputs_embeds,
|
712 |
+
past_key_values=past_key_values,
|
713 |
+
attention_mask=attention_mask,
|
714 |
+
)
|
715 |
+
lm_logits = self.lm_head(hidden_states)
|
716 |
+
loss = self.loss(lm_logits, labels) if labels is not None else None
|
717 |
+
|
718 |
+
return CausalLMOutputWithPast(
|
719 |
+
loss=loss, logits=lm_logits, past_key_values=past_key_values
|
720 |
+
)
|
moondream/moondream.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from .vision_encoder import VisionEncoder
|
4 |
+
from .configuration_moondream import MoondreamConfig
|
5 |
+
from transformers import PreTrainedModel
|
6 |
+
import re
|
7 |
+
|
8 |
+
from .modeling_phi import PhiForCausalLM
|
9 |
+
from .configuration_moondream import PhiConfig
|
10 |
+
|
11 |
+
class Moondream(PreTrainedModel):
|
12 |
+
config_class = MoondreamConfig
|
13 |
+
|
14 |
+
def __init__(self, config):
|
15 |
+
super().__init__(config)
|
16 |
+
self.vision_encoder = VisionEncoder()
|
17 |
+
|
18 |
+
if type(config.phi_config) == dict:
|
19 |
+
phi_config = PhiConfig(**config.phi_config)
|
20 |
+
else:
|
21 |
+
phi_config = config.phi_config
|
22 |
+
self.text_model = PhiForCausalLM(phi_config)
|
23 |
+
|
24 |
+
@property
|
25 |
+
def device(self):
|
26 |
+
return self.text_model.device
|
27 |
+
|
28 |
+
def encode_image(self, image):
|
29 |
+
return self.vision_encoder(image)
|
30 |
+
|
31 |
+
def input_embeds(self, prompt, image_embeds, tokenizer):
|
32 |
+
def _tokenize(txt):
|
33 |
+
return tokenizer(
|
34 |
+
txt, return_tensors="pt", add_special_tokens=False
|
35 |
+
).input_ids.to(self.device)
|
36 |
+
|
37 |
+
text_emb = self.text_model.get_input_embeddings()
|
38 |
+
|
39 |
+
# Add BOS token
|
40 |
+
embeds = []
|
41 |
+
embeds.append(
|
42 |
+
text_emb((torch.tensor([[tokenizer.bos_token_id]], device=self.device)))
|
43 |
+
)
|
44 |
+
|
45 |
+
if "<image>" not in prompt:
|
46 |
+
embeds.append(text_emb(_tokenize(prompt)))
|
47 |
+
else:
|
48 |
+
assert prompt.count("<image>") == 1
|
49 |
+
before, after = prompt.split("<image>")
|
50 |
+
embeds.append(text_emb(_tokenize(f"{before}<image>")))
|
51 |
+
embeds.append(image_embeds.to(self.device))
|
52 |
+
embeds.append(text_emb(_tokenize(f"</image>{after}")))
|
53 |
+
|
54 |
+
return torch.cat(embeds, dim=1)
|
55 |
+
|
56 |
+
def generate(
|
57 |
+
self,
|
58 |
+
image_embeds,
|
59 |
+
prompt,
|
60 |
+
tokenizer,
|
61 |
+
eos_text="<END>",
|
62 |
+
max_new_tokens=128,
|
63 |
+
**kwargs,
|
64 |
+
):
|
65 |
+
eos_tokens = tokenizer(eos_text, add_special_tokens=False)[0].ids
|
66 |
+
|
67 |
+
generate_config = {
|
68 |
+
"eos_token_id": eos_tokens,
|
69 |
+
"bos_token_id": tokenizer.bos_token_id,
|
70 |
+
"pad_token_id": tokenizer.eos_token_id,
|
71 |
+
"max_new_tokens": max_new_tokens,
|
72 |
+
**kwargs,
|
73 |
+
}
|
74 |
+
|
75 |
+
with torch.no_grad():
|
76 |
+
inputs_embeds = self.input_embeds(prompt, image_embeds, tokenizer)
|
77 |
+
output_ids = self.text_model.generate(
|
78 |
+
inputs_embeds=inputs_embeds, **generate_config
|
79 |
+
)
|
80 |
+
|
81 |
+
return tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
82 |
+
|
83 |
+
def answer_question(
|
84 |
+
self,
|
85 |
+
image_embeds,
|
86 |
+
question,
|
87 |
+
tokenizer,
|
88 |
+
chat_history="",
|
89 |
+
result_queue=None,
|
90 |
+
**kwargs,
|
91 |
+
):
|
92 |
+
prompt = f"<image>\n\n{chat_history}Question: {question}\n\nAnswer: "
|
93 |
+
answer = self.generate(
|
94 |
+
image_embeds,
|
95 |
+
prompt,
|
96 |
+
eos_text="<END>",
|
97 |
+
tokenizer=tokenizer,
|
98 |
+
max_new_tokens=256,
|
99 |
+
**kwargs,
|
100 |
+
)[0]
|
101 |
+
cleaned_answer = re.sub("<$", "", re.sub("END$", "", answer)).strip()
|
102 |
+
|
103 |
+
# Use the result_queue to pass the result if it is provided
|
104 |
+
if result_queue:
|
105 |
+
result_queue.put(cleaned_answer)
|
106 |
+
else:
|
107 |
+
return cleaned_answer
|
moondream/util.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
|
4 |
+
def detect_device():
|
5 |
+
"""
|
6 |
+
Detects the appropriate device to run on, and return the device and dtype.
|
7 |
+
"""
|
8 |
+
if torch.cuda.is_available():
|
9 |
+
return torch.device("cuda"), torch.float16
|
10 |
+
elif torch.backends.mps.is_available():
|
11 |
+
return torch.device("mps"), torch.float16
|
12 |
+
else:
|
13 |
+
return torch.device("cpu"), torch.float32
|
moondream/vision_encoder.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
from PIL import Image
|
4 |
+
from einops import rearrange
|
5 |
+
from torchvision.transforms.v2 import (
|
6 |
+
Compose,
|
7 |
+
Resize,
|
8 |
+
InterpolationMode,
|
9 |
+
ToImage,
|
10 |
+
ToDtype,
|
11 |
+
Normalize,
|
12 |
+
)
|
13 |
+
import timm
|
14 |
+
|
15 |
+
|
16 |
+
class VisualHolder(nn.Module):
|
17 |
+
def __init__(self, model):
|
18 |
+
super().__init__()
|
19 |
+
self.visual = model
|
20 |
+
|
21 |
+
def forward(self, x):
|
22 |
+
return self.visual(x)
|
23 |
+
|
24 |
+
|
25 |
+
class ModelHolder(nn.Module):
|
26 |
+
def __init__(self, model):
|
27 |
+
super().__init__()
|
28 |
+
self.model = model
|
29 |
+
|
30 |
+
def forward(self, x):
|
31 |
+
return self.model(x)
|
32 |
+
|
33 |
+
|
34 |
+
class LinearPatchEmbedding(nn.Module):
|
35 |
+
def __init__(self, conv):
|
36 |
+
super().__init__()
|
37 |
+
self.linear = nn.Linear(588, 1152)
|
38 |
+
self.linear.weight.data = conv.weight.data.view(1152, -1)
|
39 |
+
if conv.bias is not None:
|
40 |
+
self.linear.bias.data = conv.bias.data
|
41 |
+
|
42 |
+
def forward(self, x):
|
43 |
+
return self.linear(x)
|
44 |
+
|
45 |
+
|
46 |
+
class MLP(nn.Module):
|
47 |
+
def __init__(
|
48 |
+
self,
|
49 |
+
in_features: int,
|
50 |
+
hidden_features: int = None,
|
51 |
+
out_features: int = None,
|
52 |
+
act_layer: nn.Module = nn.GELU,
|
53 |
+
) -> None:
|
54 |
+
super().__init__()
|
55 |
+
out_features = out_features or in_features
|
56 |
+
hidden_features = hidden_features or in_features
|
57 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
58 |
+
self.act = act_layer()
|
59 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
60 |
+
|
61 |
+
torch.nn.init.kaiming_normal_(
|
62 |
+
self.fc1.weight, mode="fan_in", nonlinearity="relu"
|
63 |
+
)
|
64 |
+
torch.nn.init.kaiming_normal_(
|
65 |
+
self.fc2.weight, mode="fan_in", nonlinearity="relu"
|
66 |
+
)
|
67 |
+
|
68 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
69 |
+
x = self.fc1(x)
|
70 |
+
x = self.act(x)
|
71 |
+
x = self.fc2(x)
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
class VisionProjection(nn.Module):
|
76 |
+
def __init__(self):
|
77 |
+
super().__init__()
|
78 |
+
|
79 |
+
image_embedding_dim = 1152
|
80 |
+
model_dim = 2048
|
81 |
+
hidden_dim = model_dim * 4
|
82 |
+
|
83 |
+
self.mlp = MLP(image_embedding_dim, hidden_dim, model_dim)
|
84 |
+
|
85 |
+
@property
|
86 |
+
def device(self):
|
87 |
+
return self.mlp.fc1.weight.device
|
88 |
+
|
89 |
+
def forward(self, x):
|
90 |
+
return self.mlp(x)
|
91 |
+
|
92 |
+
|
93 |
+
class VisionEncoder(nn.Module):
|
94 |
+
def __init__(self) -> None:
|
95 |
+
super().__init__()
|
96 |
+
|
97 |
+
self.encoder = ModelHolder(
|
98 |
+
VisualHolder(timm.create_model("vit_so400m_patch14_siglip_384"))
|
99 |
+
)
|
100 |
+
self.encoder.model.visual.patch_embed = LinearPatchEmbedding(
|
101 |
+
self.encoder.model.visual.patch_embed.proj
|
102 |
+
)
|
103 |
+
self.encoder.model.visual.attn_pool = nn.Identity()
|
104 |
+
|
105 |
+
self.projection = VisionProjection()
|
106 |
+
|
107 |
+
self.preprocess = Compose(
|
108 |
+
[
|
109 |
+
Resize(size=(378, 378), interpolation=InterpolationMode.BICUBIC),
|
110 |
+
ToImage(),
|
111 |
+
ToDtype(torch.float32, scale=True),
|
112 |
+
Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
113 |
+
]
|
114 |
+
)
|
115 |
+
|
116 |
+
@property
|
117 |
+
def device(self):
|
118 |
+
return self.projection.mlp.fc1.weight.device
|
119 |
+
|
120 |
+
@property
|
121 |
+
def dtype(self):
|
122 |
+
return self.projection.mlp.fc1.weight.dtype
|
123 |
+
|
124 |
+
def __call__(self, image: Image) -> torch.Tensor:
|
125 |
+
with torch.no_grad():
|
126 |
+
x = (
|
127 |
+
self.preprocess(image.convert("RGB"))
|
128 |
+
.unsqueeze(0)
|
129 |
+
.to(self.device, dtype=self.dtype)
|
130 |
+
)
|
131 |
+
x = rearrange(x, "b c (h p1) (w p2) -> b (h w) (c p1 p2)", p1=14, p2=14)
|
132 |
+
|
133 |
+
x = self.encoder(x)
|
134 |
+
x = self.projection(x)
|
135 |
+
|
136 |
+
return x
|
omnichat.py
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import json
|
4 |
+
from PIL import Image
|
5 |
+
import base64
|
6 |
+
import io
|
7 |
+
from accelerate import load_checkpoint_and_dispatch, init_empty_weights
|
8 |
+
from transformers import AutoTokenizer, AutoModel
|
9 |
+
|
10 |
+
from omnilmm.utils import disable_torch_init
|
11 |
+
from omnilmm.model.omnilmm import OmniLMMForCausalLM
|
12 |
+
from omnilmm.model.utils import build_transform
|
13 |
+
from omnilmm.train.train_utils import omni_preprocess
|
14 |
+
|
15 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
16 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
17 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
18 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
def init_omni_lmm(model_path):
|
23 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
24 |
+
disable_torch_init()
|
25 |
+
model_name = os.path.expanduser(model_path)
|
26 |
+
print(f'Load omni_lmm model and tokenizer from {model_name}')
|
27 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
28 |
+
model_name, model_max_length=2048)
|
29 |
+
|
30 |
+
if False:
|
31 |
+
# model on multiple devices for small size gpu memory (Nvidia 3090 24G x2)
|
32 |
+
with init_empty_weights():
|
33 |
+
model = OmniLMMForCausalLM.from_pretrained(model_name, tune_clip=True, torch_dtype=torch.bfloat16)
|
34 |
+
model = load_checkpoint_and_dispatch(model, model_name, dtype=torch.bfloat16,
|
35 |
+
device_map="auto", no_split_module_classes=['Eva','MistralDecoderLayer', 'ModuleList', 'Resampler']
|
36 |
+
)
|
37 |
+
else:
|
38 |
+
model = OmniLMMForCausalLM.from_pretrained(
|
39 |
+
model_name, tune_clip=True, torch_dtype=torch.bfloat16
|
40 |
+
).to(device='cuda', dtype=torch.bfloat16)
|
41 |
+
|
42 |
+
image_processor = build_transform(
|
43 |
+
is_train=False, input_size=model.model.config.image_size, std_mode='OPENAI_CLIP')
|
44 |
+
|
45 |
+
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
|
46 |
+
assert mm_use_im_start_end
|
47 |
+
|
48 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN,
|
49 |
+
DEFAULT_IM_END_TOKEN], special_tokens=True)
|
50 |
+
|
51 |
+
|
52 |
+
vision_config = model.model.vision_config
|
53 |
+
vision_config.im_patch_token = tokenizer.convert_tokens_to_ids(
|
54 |
+
[DEFAULT_IMAGE_PATCH_TOKEN])[0]
|
55 |
+
vision_config.use_im_start_end = mm_use_im_start_end
|
56 |
+
vision_config.im_start_token, vision_config.im_end_token = tokenizer.convert_tokens_to_ids(
|
57 |
+
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN])
|
58 |
+
image_token_len = model.model.config.num_query
|
59 |
+
|
60 |
+
return model, image_processor, image_token_len, tokenizer
|
61 |
+
|
62 |
+
def expand_question_into_multimodal(question_text, image_token_len, im_st_token, im_ed_token, im_patch_token):
|
63 |
+
if '<image>' in question_text[0]['content']:
|
64 |
+
question_text[0]['content'] = question_text[0]['content'].replace(
|
65 |
+
'<image>', im_st_token + im_patch_token * image_token_len + im_ed_token)
|
66 |
+
else:
|
67 |
+
question_text[0]['content'] = im_st_token + im_patch_token * \
|
68 |
+
image_token_len + im_ed_token + '\n' + question_text[0]['content']
|
69 |
+
return question_text
|
70 |
+
|
71 |
+
def wrap_question_for_omni_lmm(question, image_token_len, tokenizer):
|
72 |
+
question = expand_question_into_multimodal(
|
73 |
+
question, image_token_len, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_PATCH_TOKEN)
|
74 |
+
|
75 |
+
conversation = question
|
76 |
+
data_dict = omni_preprocess(sources=[conversation],
|
77 |
+
tokenizer=tokenizer,
|
78 |
+
generation=True)
|
79 |
+
|
80 |
+
data_dict = dict(input_ids=data_dict["input_ids"][0],
|
81 |
+
labels=data_dict["labels"][0])
|
82 |
+
return data_dict
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
class OmniLMM12B:
|
87 |
+
def __init__(self, model_path) -> None:
|
88 |
+
model, img_processor, image_token_len, tokenizer = init_omni_lmm(model_path)
|
89 |
+
self.model = model
|
90 |
+
self.image_token_len = image_token_len
|
91 |
+
self.image_transform = img_processor
|
92 |
+
self.tokenizer = tokenizer
|
93 |
+
self.model.eval()
|
94 |
+
|
95 |
+
def decode(self, image, input_ids):
|
96 |
+
with torch.inference_mode():
|
97 |
+
output = self.model.generate_vllm(
|
98 |
+
input_ids=input_ids.unsqueeze(0).cuda(),
|
99 |
+
images=image.unsqueeze(0).half().cuda(),
|
100 |
+
temperature=0.6,
|
101 |
+
max_new_tokens=1024,
|
102 |
+
# num_beams=num_beams,
|
103 |
+
do_sample=True,
|
104 |
+
output_scores=True,
|
105 |
+
return_dict_in_generate=True,
|
106 |
+
repetition_penalty=1.1,
|
107 |
+
top_k=30,
|
108 |
+
top_p=0.9,
|
109 |
+
)
|
110 |
+
|
111 |
+
response = self.tokenizer.decode(
|
112 |
+
output.sequences[0], skip_special_tokens=True)
|
113 |
+
response = response.strip()
|
114 |
+
return response
|
115 |
+
|
116 |
+
def chat(self, input):
|
117 |
+
try:
|
118 |
+
image = Image.open(io.BytesIO(base64.b64decode(input['image']))).convert('RGB')
|
119 |
+
except Exception as e:
|
120 |
+
return "Image decode error"
|
121 |
+
|
122 |
+
msgs = json.loads(input['question'])
|
123 |
+
input_ids = wrap_question_for_omni_lmm(
|
124 |
+
msgs, self.image_token_len, self.tokenizer)['input_ids']
|
125 |
+
input_ids = torch.as_tensor(input_ids)
|
126 |
+
#print('input_ids', input_ids)
|
127 |
+
image = self.image_transform(image)
|
128 |
+
|
129 |
+
out = self.decode(image, input_ids)
|
130 |
+
|
131 |
+
return out
|
132 |
+
|
133 |
+
|
134 |
+
def img2base64(file_name):
|
135 |
+
with open(file_name, 'rb') as f:
|
136 |
+
encoded_string = base64.b64encode(f.read())
|
137 |
+
return encoded_string
|
138 |
+
|
139 |
+
class OmniLMM3B:
|
140 |
+
def __init__(self, model_path) -> None:
|
141 |
+
self.model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(dtype=torch.bfloat16)
|
142 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
143 |
+
self.model.eval().cuda()
|
144 |
+
|
145 |
+
def chat(self, input):
|
146 |
+
try:
|
147 |
+
image = Image.open(io.BytesIO(base64.b64decode(input['image']))).convert('RGB')
|
148 |
+
except Exception as e:
|
149 |
+
return "Image decode error"
|
150 |
+
|
151 |
+
msgs = json.loads(input['question'])
|
152 |
+
|
153 |
+
answer, context, _ = self.model.chat(
|
154 |
+
image=image,
|
155 |
+
msgs=msgs,
|
156 |
+
context=None,
|
157 |
+
tokenizer=self.tokenizer,
|
158 |
+
sampling=True,
|
159 |
+
temperature=0.7
|
160 |
+
)
|
161 |
+
return answer
|
162 |
+
|
163 |
+
class MiniCPMV2_5:
|
164 |
+
def __init__(self, model_path) -> None:
|
165 |
+
self.model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(dtype=torch.float16)
|
166 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
167 |
+
self.model.eval().cuda()
|
168 |
+
|
169 |
+
def chat(self, input):
|
170 |
+
try:
|
171 |
+
image = Image.open(io.BytesIO(base64.b64decode(input['image']))).convert('RGB')
|
172 |
+
except Exception as e:
|
173 |
+
return "Image decode error"
|
174 |
+
|
175 |
+
msgs = json.loads(input['question'])
|
176 |
+
|
177 |
+
answer = self.model.chat(
|
178 |
+
image=image,
|
179 |
+
msgs=msgs,
|
180 |
+
tokenizer=self.tokenizer,
|
181 |
+
sampling=True,
|
182 |
+
temperature=0.7
|
183 |
+
)
|
184 |
+
return answer
|
185 |
+
|
186 |
+
|
187 |
+
class OmniLMMChat:
|
188 |
+
def __init__(self, model_path) -> None:
|
189 |
+
if '12B' in model_path:
|
190 |
+
self.model = OmniLMM12B(model_path)
|
191 |
+
elif 'MiniCPM-Llama3-V' in model_path:
|
192 |
+
self.model = MiniCPMV2_5(model_path)
|
193 |
+
else:
|
194 |
+
self.model = OmniLMM3B(model_path)
|
195 |
+
|
196 |
+
def chat(self, input):
|
197 |
+
return self.model.chat(input)
|
198 |
+
|
199 |
+
|
200 |
+
if __name__ == '__main__':
|
201 |
+
|
202 |
+
model_path = 'openbmb/OmniLMM-12B'
|
203 |
+
chat_model = OmniLMMChat(model_path)
|
204 |
+
|
205 |
+
im_64 = img2base64('./assets/worldmap_ck.jpg')
|
206 |
+
|
207 |
+
# first round chat
|
208 |
+
msgs = [{"role": "user", "content": "What is interesting about this image?"}]
|
209 |
+
input = {"image": im_64, "question": json.dumps(msgs, ensure_ascii=True)}
|
210 |
+
answer = chat_model.chat(input)
|
211 |
+
print(msgs[-1]["content"]+'\n', answer)
|
212 |
+
|
213 |
+
# second round chat
|
214 |
+
msgs.append({"role": "assistant", "content": answer})
|
215 |
+
msgs.append({"role": "user", "content": "Where is China in the image"})
|
216 |
+
input = {"image": im_64,"question": json.dumps(msgs, ensure_ascii=True)}
|
217 |
+
answer = chat_model.chat(input)
|
218 |
+
print(msgs[-1]["content"]+'\n', answer)
|
219 |
+
|
omnilmm/__init__.py
ADDED
File without changes
|
omnilmm/constants.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
omnilmm/conversation.py
ADDED
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import auto, Enum
|
3 |
+
from typing import List, Tuple
|
4 |
+
|
5 |
+
|
6 |
+
class SeparatorStyle(Enum):
|
7 |
+
"""Different separator style."""
|
8 |
+
SINGLE = auto()
|
9 |
+
TWO = auto()
|
10 |
+
|
11 |
+
|
12 |
+
@dataclasses.dataclass
|
13 |
+
class Conversation:
|
14 |
+
"""A class that keeps all conversation history."""
|
15 |
+
system: str
|
16 |
+
roles: List[str]
|
17 |
+
messages: List[List[str]]
|
18 |
+
offset: int
|
19 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
20 |
+
sep: str = "###"
|
21 |
+
sep2: str = None
|
22 |
+
version: str = "Unknown"
|
23 |
+
|
24 |
+
skip_next: bool = False
|
25 |
+
|
26 |
+
def get_prompt(self):
|
27 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
28 |
+
ret = self.system + self.sep
|
29 |
+
for role, message in self.messages:
|
30 |
+
if message:
|
31 |
+
if type(message) is tuple:
|
32 |
+
message, _, _ = message
|
33 |
+
ret += role + ": " + message + self.sep
|
34 |
+
else:
|
35 |
+
ret += role + ":"
|
36 |
+
return ret
|
37 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
38 |
+
seps = [self.sep, self.sep2]
|
39 |
+
ret = self.system + seps[0]
|
40 |
+
for i, (role, message) in enumerate(self.messages):
|
41 |
+
if message:
|
42 |
+
if type(message) is tuple:
|
43 |
+
message, _, _ = message
|
44 |
+
ret += role + ": " + message + seps[i % 2]
|
45 |
+
else:
|
46 |
+
ret += role + ":"
|
47 |
+
return ret
|
48 |
+
else:
|
49 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
50 |
+
|
51 |
+
def append_message(self, role, message):
|
52 |
+
self.messages.append([role, message])
|
53 |
+
|
54 |
+
def get_images(self, return_pil=False):
|
55 |
+
images = []
|
56 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
57 |
+
if i % 2 == 0:
|
58 |
+
if type(msg) is tuple:
|
59 |
+
import base64
|
60 |
+
from io import BytesIO
|
61 |
+
from PIL import Image
|
62 |
+
msg, image, image_process_mode = msg
|
63 |
+
if image_process_mode == "Pad":
|
64 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
65 |
+
width, height = pil_img.size
|
66 |
+
if width == height:
|
67 |
+
return pil_img
|
68 |
+
elif width > height:
|
69 |
+
result = Image.new(
|
70 |
+
pil_img.mode, (width, width), background_color)
|
71 |
+
result.paste(
|
72 |
+
pil_img, (0, (width - height) // 2))
|
73 |
+
return result
|
74 |
+
else:
|
75 |
+
result = Image.new(
|
76 |
+
pil_img.mode, (height, height), background_color)
|
77 |
+
result.paste(
|
78 |
+
pil_img, ((height - width) // 2, 0))
|
79 |
+
return result
|
80 |
+
image = expand2square(image)
|
81 |
+
elif image_process_mode == "Crop":
|
82 |
+
pass
|
83 |
+
elif image_process_mode == "Resize":
|
84 |
+
image = image.resize((224, 224))
|
85 |
+
else:
|
86 |
+
raise ValueError(
|
87 |
+
f"Invalid image_process_mode: {image_process_mode}")
|
88 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
89 |
+
aspect_ratio = max_hw / min_hw
|
90 |
+
max_len, min_len = 800, 400
|
91 |
+
shortest_edge = int(
|
92 |
+
min(max_len / aspect_ratio, min_len, min_hw))
|
93 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
94 |
+
W, H = image.size
|
95 |
+
if H > W:
|
96 |
+
H, W = longest_edge, shortest_edge
|
97 |
+
else:
|
98 |
+
H, W = shortest_edge, longest_edge
|
99 |
+
image = image.resize((W, H))
|
100 |
+
if return_pil:
|
101 |
+
images.append(image)
|
102 |
+
else:
|
103 |
+
buffered = BytesIO()
|
104 |
+
image.save(buffered, format="JPEG")
|
105 |
+
img_b64_str = base64.b64encode(
|
106 |
+
buffered.getvalue()).decode()
|
107 |
+
images.append(img_b64_str)
|
108 |
+
return images
|
109 |
+
|
110 |
+
def to_gradio_chatbot(self):
|
111 |
+
ret = []
|
112 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
113 |
+
if i % 2 == 0:
|
114 |
+
if type(msg) is tuple:
|
115 |
+
import base64
|
116 |
+
from io import BytesIO
|
117 |
+
msg, image, image_process_mode = msg
|
118 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
119 |
+
aspect_ratio = max_hw / min_hw
|
120 |
+
max_len, min_len = 800, 400
|
121 |
+
shortest_edge = int(
|
122 |
+
min(max_len / aspect_ratio, min_len, min_hw))
|
123 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
124 |
+
W, H = image.size
|
125 |
+
if H > W:
|
126 |
+
H, W = longest_edge, shortest_edge
|
127 |
+
else:
|
128 |
+
H, W = shortest_edge, longest_edge
|
129 |
+
image = image.resize((W, H))
|
130 |
+
# image = image.resize((224, 224))
|
131 |
+
buffered = BytesIO()
|
132 |
+
image.save(buffered, format="JPEG")
|
133 |
+
img_b64_str = base64.b64encode(
|
134 |
+
buffered.getvalue()).decode()
|
135 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
136 |
+
msg = msg.replace('<image>', img_str)
|
137 |
+
ret.append([msg, None])
|
138 |
+
else:
|
139 |
+
ret[-1][-1] = msg
|
140 |
+
return ret
|
141 |
+
|
142 |
+
def copy(self):
|
143 |
+
return Conversation(
|
144 |
+
system=self.system,
|
145 |
+
roles=self.roles,
|
146 |
+
messages=[[x, y] for x, y in self.messages],
|
147 |
+
offset=self.offset,
|
148 |
+
sep_style=self.sep_style,
|
149 |
+
sep=self.sep,
|
150 |
+
sep2=self.sep2)
|
151 |
+
|
152 |
+
def dict(self):
|
153 |
+
if len(self.get_images()) > 0:
|
154 |
+
return {
|
155 |
+
"system": self.system,
|
156 |
+
"roles": self.roles,
|
157 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
158 |
+
"offset": self.offset,
|
159 |
+
"sep": self.sep,
|
160 |
+
"sep2": self.sep2,
|
161 |
+
}
|
162 |
+
return {
|
163 |
+
"system": self.system,
|
164 |
+
"roles": self.roles,
|
165 |
+
"messages": self.messages,
|
166 |
+
"offset": self.offset,
|
167 |
+
"sep": self.sep,
|
168 |
+
"sep2": self.sep2,
|
169 |
+
}
|
170 |
+
|
171 |
+
|
172 |
+
conv_v1 = Conversation(
|
173 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
174 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
175 |
+
roles=("Human", "Assistant"),
|
176 |
+
messages=(
|
177 |
+
("Human", "Give three tips for staying healthy."),
|
178 |
+
("Assistant",
|
179 |
+
"Sure, here are three tips for staying healthy:\n"
|
180 |
+
"1. Exercise regularly: Regular physical activity can help improve your overall health and wellbeing. "
|
181 |
+
"It can also help reduce your risk of chronic conditions such as obesity, diabetes, heart disease, "
|
182 |
+
"and certain cancers. Aim for at least 150 minutes of moderate-intensity aerobic exercise or "
|
183 |
+
"75 minutes of vigorous-intensity aerobic exercise per week, along with muscle-strengthening "
|
184 |
+
"activities at least two days per week.\n"
|
185 |
+
"2. Eat a balanced diet: Eating a balanced diet that is rich in fruits, "
|
186 |
+
"vegetables, whole grains, lean proteins, and healthy fats can help support "
|
187 |
+
"your overall health. Try to limit your intake of processed and high-sugar foods, "
|
188 |
+
"and aim to drink plenty of water throughout the day.\n"
|
189 |
+
"3. Get enough sleep: Getting enough quality sleep is essential for your physical "
|
190 |
+
"and mental health. Adults should aim for seven to nine hours of sleep per night. "
|
191 |
+
"Establish a regular sleep schedule and try to create a relaxing bedtime routine to "
|
192 |
+
"help improve the quality of your sleep.")
|
193 |
+
),
|
194 |
+
offset=2,
|
195 |
+
sep_style=SeparatorStyle.SINGLE,
|
196 |
+
sep="###",
|
197 |
+
)
|
198 |
+
|
199 |
+
conv_v1_2 = Conversation(
|
200 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
201 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
202 |
+
roles=("Human", "Assistant"),
|
203 |
+
messages=(
|
204 |
+
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
205 |
+
("Assistant",
|
206 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
207 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
208 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
209 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
210 |
+
"renewable and non-renewable energy sources:\n"
|
211 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
212 |
+
"energy sources are finite and will eventually run out.\n"
|
213 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
214 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
215 |
+
"and other negative effects.\n"
|
216 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
217 |
+
"have lower operational costs than non-renewable sources.\n"
|
218 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
219 |
+
"locations than non-renewable sources.\n"
|
220 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
221 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
222 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
223 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
224 |
+
),
|
225 |
+
offset=2,
|
226 |
+
sep_style=SeparatorStyle.SINGLE,
|
227 |
+
sep="###",
|
228 |
+
)
|
229 |
+
|
230 |
+
conv_vicuna_v1_1 = Conversation(
|
231 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
232 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
233 |
+
roles=("USER", "ASSISTANT"),
|
234 |
+
version="v1",
|
235 |
+
messages=(),
|
236 |
+
offset=0,
|
237 |
+
sep_style=SeparatorStyle.TWO,
|
238 |
+
sep=" ",
|
239 |
+
sep2="</s>",
|
240 |
+
)
|
241 |
+
|
242 |
+
conv_bair_v1 = Conversation(
|
243 |
+
system="BEGINNING OF CONVERSATION:",
|
244 |
+
roles=("USER", "GPT"),
|
245 |
+
messages=(),
|
246 |
+
offset=0,
|
247 |
+
sep_style=SeparatorStyle.TWO,
|
248 |
+
sep=" ",
|
249 |
+
sep2="</s>",
|
250 |
+
)
|
251 |
+
|
252 |
+
simple_conv = Conversation(
|
253 |
+
system="You are LLaVA, a large language model trained by UW Madison WAIV Lab, based on LLaMA architecture."
|
254 |
+
"You are designed to assist human with a variety of tasks using natural language."
|
255 |
+
"Follow the instructions carefully.",
|
256 |
+
roles=("Human", "Assistant"),
|
257 |
+
messages=(
|
258 |
+
("Human", "Hi!"),
|
259 |
+
("Assistant", "Hi there! How can I help you today?\n")
|
260 |
+
),
|
261 |
+
offset=2,
|
262 |
+
sep_style=SeparatorStyle.SINGLE,
|
263 |
+
sep="###",
|
264 |
+
)
|
265 |
+
|
266 |
+
simple_conv_multimodal = Conversation(
|
267 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
268 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
269 |
+
roles=("Human", "Assistant"),
|
270 |
+
messages=(
|
271 |
+
),
|
272 |
+
offset=0,
|
273 |
+
sep_style=SeparatorStyle.SINGLE,
|
274 |
+
sep="###",
|
275 |
+
)
|
276 |
+
|
277 |
+
simple_conv_legacy = Conversation(
|
278 |
+
system="You are LLaVA, a large language model trained by UW Madison WAIV Lab."
|
279 |
+
"You are designed to assist human with a variety of tasks using natural language."
|
280 |
+
"Follow the instructions carefully.",
|
281 |
+
roles=("Human", "Assistant"),
|
282 |
+
messages=(
|
283 |
+
("Human", "Hi!\n\n### Response:"),
|
284 |
+
("Assistant", "Hi there! How can I help you today?\n")
|
285 |
+
),
|
286 |
+
offset=2,
|
287 |
+
sep_style=SeparatorStyle.SINGLE,
|
288 |
+
sep="###",
|
289 |
+
)
|
290 |
+
|
291 |
+
conv_llava_v1 = Conversation(
|
292 |
+
system="You are LLaVA, a large language and vision assistant trained by UW Madison WAIV Lab."
|
293 |
+
"You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
294 |
+
"Follow the instructions carefully and explain your answers in detail.",
|
295 |
+
roles=("USER", "ASSISTANT"),
|
296 |
+
version="v1",
|
297 |
+
messages=(),
|
298 |
+
offset=0,
|
299 |
+
sep_style=SeparatorStyle.TWO,
|
300 |
+
sep=" ",
|
301 |
+
sep2="</s>",
|
302 |
+
)
|
303 |
+
|
304 |
+
default_conversation = conv_v1_2
|
305 |
+
conv_templates = {
|
306 |
+
"default": conv_v1_2,
|
307 |
+
"simple": simple_conv,
|
308 |
+
"simple_legacy": simple_conv_legacy,
|
309 |
+
"multimodal": simple_conv_multimodal,
|
310 |
+
"llava_v1": conv_llava_v1,
|
311 |
+
|
312 |
+
# fastchat
|
313 |
+
"v1": conv_v1_2,
|
314 |
+
"bair_v1": conv_bair_v1,
|
315 |
+
"vicuna_v1_1": conv_vicuna_v1_1,
|
316 |
+
}
|
317 |
+
|
318 |
+
|
319 |
+
if __name__ == "__main__":
|
320 |
+
print(default_conversation.get_prompt())
|
omnilmm/model/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .omnilmm import OmniLMMForCausalLM
|
omnilmm/model/omnilmm.py
ADDED
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import gc
|
3 |
+
import math
|
4 |
+
import timm
|
5 |
+
import torch
|
6 |
+
from torch import Tensor
|
7 |
+
import torch.nn as nn
|
8 |
+
from torch.nn import CrossEntropyLoss
|
9 |
+
from typing import List, Optional, Tuple, Union
|
10 |
+
|
11 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
12 |
+
from transformers import MistralForCausalLM, MistralModel, MistralConfig
|
13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
14 |
+
|
15 |
+
from omnilmm.model.utils import build_transform
|
16 |
+
from omnilmm.model.resampler import Resampler
|
17 |
+
|
18 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
19 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
20 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
21 |
+
|
22 |
+
|
23 |
+
class OmniLMMConfig(MistralConfig):
|
24 |
+
model_type = "omnilmm"
|
25 |
+
|
26 |
+
|
27 |
+
class Identity(torch.nn.Identity):
|
28 |
+
def forward(self, input: Tensor, **kwargs) -> Tensor:
|
29 |
+
return super().forward(input)
|
30 |
+
|
31 |
+
|
32 |
+
def create_vision_module(config):
|
33 |
+
vision_tower = timm.create_model('eva02_enormous_patch14_clip_224.laion2b_plus',
|
34 |
+
pretrained=False,
|
35 |
+
num_classes=0,
|
36 |
+
dynamic_img_size=True,
|
37 |
+
dynamic_img_pad=True)
|
38 |
+
|
39 |
+
if isinstance(vision_tower, timm.models.VisionTransformer):
|
40 |
+
if vision_tower.attn_pool is not None:
|
41 |
+
vision_tower.attn_pool = Identity()
|
42 |
+
|
43 |
+
# use 2nd last layer's output
|
44 |
+
vision_tower.blocks[-1] = Identity()
|
45 |
+
|
46 |
+
embed_dim = config.hidden_size
|
47 |
+
resampler = Resampler(
|
48 |
+
grid_size=int(math.sqrt(config.num_query)),
|
49 |
+
embed_dim=embed_dim,
|
50 |
+
num_heads=embed_dim // 128,
|
51 |
+
kv_dim=vision_tower.embed_dim,
|
52 |
+
)
|
53 |
+
return vision_tower, resampler
|
54 |
+
|
55 |
+
|
56 |
+
class OmniLMMModel(MistralModel):
|
57 |
+
config_class = OmniLMMConfig
|
58 |
+
|
59 |
+
def __init__(self, config: OmniLMMConfig, mm_vision_tower=None, mm_hidden_size=None, tune_clip=True):
|
60 |
+
super(OmniLMMModel, self).__init__(config)
|
61 |
+
|
62 |
+
if hasattr(config, "mm_vision_tower"):
|
63 |
+
vision_tower, resampler = create_vision_module(config)
|
64 |
+
|
65 |
+
# print(__file__, 'skip loading vision tower weights')
|
66 |
+
|
67 |
+
# HACK: for FSDP
|
68 |
+
self.vision_tower = [vision_tower]
|
69 |
+
self.resampler = resampler
|
70 |
+
if tune_clip:
|
71 |
+
self.vision_tower = self.vision_tower[0]
|
72 |
+
|
73 |
+
self.vision_config = lambda x: None
|
74 |
+
|
75 |
+
def initialize_vision_modules(self, vision_tower, no_randaug, num_query, image_size, tune_clip=False):
|
76 |
+
self.config.mm_vision_tower = vision_tower
|
77 |
+
self.config.use_mm_proj = True
|
78 |
+
self.config.num_query = num_query
|
79 |
+
self.config.image_size = image_size
|
80 |
+
|
81 |
+
if not hasattr(self, 'vision_tower'):
|
82 |
+
vision_tower, resampler = create_vision_module(self.config)
|
83 |
+
state_dict = torch.load(
|
84 |
+
'/tt/data/public/multimodal/multimodal_model_ckpts/timm/eva02_enormous_patch14_clip_224.laion2b_plus.pt')
|
85 |
+
vision_tower.load_state_dict(state_dict, strict=False)
|
86 |
+
del state_dict
|
87 |
+
gc.collect()
|
88 |
+
else:
|
89 |
+
if isinstance(self.vision_tower, list):
|
90 |
+
vision_tower = self.vision_tower[0]
|
91 |
+
else:
|
92 |
+
vision_tower = self.vision_tower
|
93 |
+
resampler = self.resampler
|
94 |
+
self.vision_tower = vision_tower if tune_clip else [vision_tower]
|
95 |
+
self.resampler = resampler
|
96 |
+
|
97 |
+
train_img_transform = build_transform(
|
98 |
+
is_train=True, randaug=not no_randaug, input_size=self.config.image_size, std_mode='OPENAI_CLIP')
|
99 |
+
eval_img_transform = build_transform(
|
100 |
+
is_train=False, input_size=self.config.image_size, std_mode='OPENAI_CLIP')
|
101 |
+
|
102 |
+
return dict(
|
103 |
+
image_processor=(train_img_transform, eval_img_transform),
|
104 |
+
image_token_len=num_query,
|
105 |
+
vision_config=self.vision_config
|
106 |
+
)
|
107 |
+
|
108 |
+
def get_vision_embedding(self, pixel_values):
|
109 |
+
if isinstance(self.vision_tower, list):
|
110 |
+
vision_tower = self.vision_tower[0] # HACK: for FSDP
|
111 |
+
else:
|
112 |
+
vision_tower = self.vision_tower
|
113 |
+
|
114 |
+
dtype = vision_tower.pos_embed.data.dtype
|
115 |
+
vision_embedding = vision_tower.forward_features(
|
116 |
+
pixel_values.type(dtype))
|
117 |
+
if hasattr(vision_tower, 'num_prefix_tokens') and vision_tower.num_prefix_tokens > 0:
|
118 |
+
vision_embedding = vision_embedding[:,
|
119 |
+
vision_tower.num_prefix_tokens:]
|
120 |
+
res = self.resampler(vision_embedding)
|
121 |
+
return res
|
122 |
+
|
123 |
+
def get_vllm_embedding(self, data):
|
124 |
+
|
125 |
+
if 'vision_hidden_states' not in data:
|
126 |
+
pixel_values_list = data['pixel_values']
|
127 |
+
vision_hidden_states = []
|
128 |
+
for pixel_values in pixel_values_list:
|
129 |
+
if len(pixel_values) > 0:
|
130 |
+
vision_hidden_states.append(self.get_vision_embedding(pixel_values.unsqueeze(0))[0])
|
131 |
+
else:
|
132 |
+
vision_hidden_states.append([])
|
133 |
+
else:
|
134 |
+
vision_hidden_states = data['vision_hidden_states']
|
135 |
+
|
136 |
+
#vllm_embedding = self.llm.model.embed_tokens(data['input_ids']) * self.llm.config.scale_emb
|
137 |
+
inputs_embeds = self.embed_tokens(data['input_ids'])
|
138 |
+
vision_hidden_states = [i.type(inputs_embeds.dtype)
|
139 |
+
if isinstance(i, torch.Tensor) else i for i in vision_hidden_states
|
140 |
+
]
|
141 |
+
|
142 |
+
|
143 |
+
# HACK: replace back original embeddings for LLaVA pretraining
|
144 |
+
orig_embeds_params = getattr(self, 'orig_embeds_params', None)
|
145 |
+
|
146 |
+
new_input_embeds = []
|
147 |
+
cur_image_idx = 0
|
148 |
+
for cur_input_ids, cur_input_embeds in zip(data['input_ids'], inputs_embeds):
|
149 |
+
if (cur_input_ids == self.vision_config.im_patch_token).sum() == 0:
|
150 |
+
# multimodal LLM, but the current sample is not multimodal
|
151 |
+
cur_input_embeds = cur_input_embeds + (0. * dummy_image_features).sum()
|
152 |
+
new_input_embeds.append(cur_input_embeds)
|
153 |
+
continue
|
154 |
+
|
155 |
+
if self.vision_config.use_im_start_end:
|
156 |
+
cur_image_features = vision_hidden_states[cur_image_idx]
|
157 |
+
num_patches = cur_image_features.shape[0]
|
158 |
+
if (cur_input_ids == self.vision_config.im_start_token).sum() != (cur_input_ids == self.vision_config.im_end_token).sum():
|
159 |
+
raise ValueError(
|
160 |
+
"The number of image start tokens and image end tokens should be the same.")
|
161 |
+
image_start_tokens = torch.where(
|
162 |
+
cur_input_ids == self.vision_config.im_start_token)[0]
|
163 |
+
for image_start_token_pos in image_start_tokens:
|
164 |
+
cur_image_features = vision_hidden_states[cur_image_idx].to(
|
165 |
+
device=cur_input_embeds.device)
|
166 |
+
num_patches = cur_image_features.shape[0]
|
167 |
+
if cur_input_ids[image_start_token_pos + num_patches + 1] != self.vision_config.im_end_token:
|
168 |
+
raise ValueError(
|
169 |
+
"The image end token should follow the image start token.")
|
170 |
+
if orig_embeds_params is not None:
|
171 |
+
cur_new_input_embeds = torch.cat((cur_input_embeds[:image_start_token_pos].detach(), cur_input_embeds[image_start_token_pos:image_start_token_pos+1], cur_image_features,
|
172 |
+
cur_input_embeds[image_start_token_pos + num_patches + 1:image_start_token_pos + num_patches + 2], cur_input_embeds[image_start_token_pos + num_patches + 2:].detach()), dim=0)
|
173 |
+
else:
|
174 |
+
cur_new_input_embeds = torch.cat(
|
175 |
+
(cur_input_embeds[:image_start_token_pos+1], cur_image_features, cur_input_embeds[image_start_token_pos + num_patches + 1:]), dim=0)
|
176 |
+
cur_image_idx += 1
|
177 |
+
new_input_embeds.append(cur_new_input_embeds)
|
178 |
+
else:
|
179 |
+
raise NotImplementedError
|
180 |
+
inputs_embeds = torch.stack(new_input_embeds, dim=0)
|
181 |
+
|
182 |
+
return inputs_embeds, vision_hidden_states
|
183 |
+
|
184 |
+
def forward(
|
185 |
+
self,
|
186 |
+
input_ids: torch.LongTensor = None,
|
187 |
+
attention_mask: Optional[torch.Tensor] = None,
|
188 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
189 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
190 |
+
use_cache: Optional[bool] = None,
|
191 |
+
output_attentions: Optional[bool] = None,
|
192 |
+
output_hidden_states: Optional[bool] = None,
|
193 |
+
images: Optional[torch.FloatTensor] = None,
|
194 |
+
return_dict: Optional[bool] = None,
|
195 |
+
**kwargs
|
196 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
197 |
+
|
198 |
+
# HACK: replace back original embeddings for LLaVA pretraining
|
199 |
+
orig_embeds_params = getattr(self, 'orig_embeds_params', None)
|
200 |
+
|
201 |
+
if inputs_embeds is None and past_key_values is None:
|
202 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
203 |
+
|
204 |
+
vision_tower = getattr(self, 'vision_tower', None)
|
205 |
+
if vision_tower is not None and (input_ids.shape[1] != 1 or self.training) and images is not None:
|
206 |
+
|
207 |
+
if type(images) is list:
|
208 |
+
image_features = []
|
209 |
+
for image in images:
|
210 |
+
image_forward_out = self.get_vision_embedding(image.unsqueeze(0))[
|
211 |
+
0]
|
212 |
+
image_features.append(image_forward_out)
|
213 |
+
else:
|
214 |
+
image_features = self.get_vision_embedding(images)
|
215 |
+
|
216 |
+
dummy_image_features = torch.zeros(
|
217 |
+
self.config.num_query,
|
218 |
+
self.config.hidden_size,
|
219 |
+
device=inputs_embeds.device,
|
220 |
+
dtype=inputs_embeds.dtype)
|
221 |
+
|
222 |
+
new_input_embeds = []
|
223 |
+
cur_image_idx = 0
|
224 |
+
for cur_input_ids, cur_input_embeds in zip(input_ids, inputs_embeds):
|
225 |
+
if (cur_input_ids == self.vision_config.im_patch_token).sum() == 0:
|
226 |
+
# multimodal LLM, but the current sample is not multimodal
|
227 |
+
cur_input_embeds = cur_input_embeds + \
|
228 |
+
(0. * dummy_image_features).sum()
|
229 |
+
new_input_embeds.append(cur_input_embeds)
|
230 |
+
continue
|
231 |
+
|
232 |
+
if self.vision_config.use_im_start_end:
|
233 |
+
cur_image_features = image_features[cur_image_idx]
|
234 |
+
num_patches = cur_image_features.shape[0]
|
235 |
+
if (cur_input_ids == self.vision_config.im_start_token).sum() != (cur_input_ids == self.vision_config.im_end_token).sum():
|
236 |
+
raise ValueError(
|
237 |
+
"The number of image start tokens and image end tokens should be the same.")
|
238 |
+
image_start_tokens = torch.where(
|
239 |
+
cur_input_ids == self.vision_config.im_start_token)[0]
|
240 |
+
for image_start_token_pos in image_start_tokens:
|
241 |
+
cur_image_features = image_features[cur_image_idx].to(
|
242 |
+
device=cur_input_embeds.device)
|
243 |
+
num_patches = cur_image_features.shape[0]
|
244 |
+
if cur_input_ids[image_start_token_pos + num_patches + 1] != self.vision_config.im_end_token:
|
245 |
+
raise ValueError(
|
246 |
+
"The image end token should follow the image start token.")
|
247 |
+
if orig_embeds_params is not None:
|
248 |
+
cur_new_input_embeds = torch.cat((cur_input_embeds[:image_start_token_pos].detach(), cur_input_embeds[image_start_token_pos:image_start_token_pos+1], cur_image_features,
|
249 |
+
cur_input_embeds[image_start_token_pos + num_patches + 1:image_start_token_pos + num_patches + 2], cur_input_embeds[image_start_token_pos + num_patches + 2:].detach()), dim=0)
|
250 |
+
else:
|
251 |
+
cur_new_input_embeds = torch.cat(
|
252 |
+
(cur_input_embeds[:image_start_token_pos+1], cur_image_features, cur_input_embeds[image_start_token_pos + num_patches + 1:]), dim=0)
|
253 |
+
cur_image_idx += 1
|
254 |
+
new_input_embeds.append(cur_new_input_embeds)
|
255 |
+
else:
|
256 |
+
raise NotImplementedError
|
257 |
+
inputs_embeds = torch.stack(new_input_embeds, dim=0)
|
258 |
+
input_ids = None
|
259 |
+
|
260 |
+
return super(OmniLMMModel, self).forward(
|
261 |
+
input_ids=input_ids, attention_mask=attention_mask, past_key_values=past_key_values,
|
262 |
+
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
263 |
+
output_attentions=output_attentions, output_hidden_states=output_hidden_states,
|
264 |
+
return_dict=return_dict,
|
265 |
+
**kwargs
|
266 |
+
)
|
267 |
+
|
268 |
+
|
269 |
+
class OmniLMMForCausalLM(MistralForCausalLM):
|
270 |
+
config_class = OmniLMMConfig
|
271 |
+
|
272 |
+
def __init__(self, config, mm_vision_tower=None, tune_clip=True):
|
273 |
+
super(MistralForCausalLM, self).__init__(config)
|
274 |
+
self.model = OmniLMMModel(
|
275 |
+
config, mm_vision_tower=mm_vision_tower, tune_clip=tune_clip)
|
276 |
+
|
277 |
+
self.lm_head = nn.Linear(
|
278 |
+
config.hidden_size, config.vocab_size, bias=False)
|
279 |
+
|
280 |
+
# Initialize weights and apply final processing
|
281 |
+
self.post_init()
|
282 |
+
|
283 |
+
def forward(
|
284 |
+
self,
|
285 |
+
input_ids: torch.LongTensor = None,
|
286 |
+
attention_mask: Optional[torch.Tensor] = None,
|
287 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
288 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
289 |
+
labels: Optional[torch.LongTensor] = None,
|
290 |
+
use_cache: Optional[bool] = None,
|
291 |
+
output_attentions: Optional[bool] = None,
|
292 |
+
output_hidden_states: Optional[bool] = None,
|
293 |
+
images: Optional[torch.FloatTensor] = None,
|
294 |
+
return_dict: Optional[bool] = None,
|
295 |
+
**kwargs
|
296 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
297 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
298 |
+
output_hidden_states = (
|
299 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
300 |
+
)
|
301 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
302 |
+
|
303 |
+
# print(f'@@@ At forward, labels: {labels.shape}-{labels}', flush=True)
|
304 |
+
# print(f'@@@ At forward, input_ids: {input_ids.shape}-{input_ids}', flush=True)
|
305 |
+
# print(f'@@@ At forward, input_ids: {attention_mask.shape}-{attention_mask}', flush=True)
|
306 |
+
|
307 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
308 |
+
outputs = self.model(
|
309 |
+
input_ids=input_ids,
|
310 |
+
attention_mask=attention_mask,
|
311 |
+
past_key_values=past_key_values,
|
312 |
+
inputs_embeds=inputs_embeds,
|
313 |
+
use_cache=use_cache,
|
314 |
+
output_attentions=output_attentions,
|
315 |
+
output_hidden_states=output_hidden_states,
|
316 |
+
return_dict=return_dict,
|
317 |
+
images=images,
|
318 |
+
**kwargs
|
319 |
+
)
|
320 |
+
|
321 |
+
hidden_states = outputs[0]
|
322 |
+
logits = self.lm_head(hidden_states)
|
323 |
+
|
324 |
+
loss = None
|
325 |
+
if labels is not None:
|
326 |
+
# Shift so that tokens < n predict n
|
327 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
328 |
+
shift_labels = labels[..., 1:].contiguous()
|
329 |
+
# Flatten the tokens
|
330 |
+
loss_fct = CrossEntropyLoss()
|
331 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
332 |
+
shift_labels = shift_labels.view(-1)
|
333 |
+
# Enable model/pipeline parallelism
|
334 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
335 |
+
loss = loss_fct(shift_logits, shift_labels)
|
336 |
+
|
337 |
+
if not return_dict:
|
338 |
+
output = (logits,) + outputs[1:]
|
339 |
+
return (loss,) + output if loss is not None else output
|
340 |
+
|
341 |
+
return CausalLMOutputWithPast(
|
342 |
+
loss=loss,
|
343 |
+
logits=logits,
|
344 |
+
past_key_values=outputs.past_key_values,
|
345 |
+
hidden_states=outputs.hidden_states,
|
346 |
+
attentions=outputs.attentions,
|
347 |
+
)
|
348 |
+
|
349 |
+
# TODO could be removed for generate_vllm()
|
350 |
+
def prepare_inputs_for_generation(
|
351 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
352 |
+
):
|
353 |
+
if past_key_values:
|
354 |
+
input_ids = input_ids[:, -1:]
|
355 |
+
|
356 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
357 |
+
if inputs_embeds is not None and past_key_values is None:
|
358 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
359 |
+
else:
|
360 |
+
model_inputs = {"input_ids": input_ids}
|
361 |
+
|
362 |
+
model_inputs.update(
|
363 |
+
{
|
364 |
+
"past_key_values": past_key_values,
|
365 |
+
"use_cache": kwargs.get("use_cache"),
|
366 |
+
"attention_mask": attention_mask,
|
367 |
+
"images": kwargs.get("images", None),
|
368 |
+
}
|
369 |
+
)
|
370 |
+
return model_inputs
|
371 |
+
|
372 |
+
def generate_vllm(
|
373 |
+
self,
|
374 |
+
input_ids: torch.LongTensor = None,
|
375 |
+
images: Optional[torch.FloatTensor] = None,
|
376 |
+
vision_hidden_states=None,
|
377 |
+
return_vision_hidden_states=False,
|
378 |
+
**kwargs
|
379 |
+
):
|
380 |
+
model_inputs = {'input_ids': input_ids}
|
381 |
+
if vision_hidden_states is None:
|
382 |
+
model_inputs['pixel_values'] = images
|
383 |
+
else:
|
384 |
+
model_inputs['vision_hidden_states'] = vision_hidden_states
|
385 |
+
|
386 |
+
with torch.inference_mode():
|
387 |
+
inputs_embeds, vision_hidden_states = self.model.get_vllm_embedding(model_inputs)
|
388 |
+
|
389 |
+
result = self.generate(
|
390 |
+
inputs_embeds=inputs_embeds,
|
391 |
+
**kwargs
|
392 |
+
)
|
393 |
+
|
394 |
+
if return_vision_hidden_states:
|
395 |
+
return result, vision_hidden_states
|
396 |
+
|
397 |
+
return result
|
398 |
+
|
399 |
+
|
400 |
+
def initialize_vision_tokenizer(self, mm_use_im_start_end, tokenizer, device,
|
401 |
+
tune_mm_mlp_adapter=False):
|
402 |
+
self.model.vision_config.use_im_start_end = mm_use_im_start_end
|
403 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
404 |
+
self.resize_token_embeddings(len(tokenizer))
|
405 |
+
|
406 |
+
if mm_use_im_start_end:
|
407 |
+
num_new_tokens = tokenizer.add_tokens(
|
408 |
+
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
409 |
+
self.resize_token_embeddings(len(tokenizer))
|
410 |
+
self.model.vision_config.im_start_token, self.model.vision_config.im_end_token = tokenizer.convert_tokens_to_ids(
|
411 |
+
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN])
|
412 |
+
|
413 |
+
if num_new_tokens > 0:
|
414 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
415 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
416 |
+
|
417 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
418 |
+
dim=0, keepdim=True)
|
419 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
420 |
+
dim=0, keepdim=True)
|
421 |
+
|
422 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
423 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
424 |
+
|
425 |
+
# for new sft data
|
426 |
+
num_new_tokens = tokenizer.add_tokens(
|
427 |
+
['<box>', '</box>', '<ref>', '</ref>', '<quad>', '</quad>'], special_tokens=True)
|
428 |
+
self.resize_token_embeddings(len(tokenizer))
|
429 |
+
|
430 |
+
if num_new_tokens > 0:
|
431 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
432 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
433 |
+
|
434 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
435 |
+
dim=0, keepdim=True)
|
436 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
437 |
+
dim=0, keepdim=True)
|
438 |
+
|
439 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
440 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
441 |
+
|
442 |
+
if tune_mm_mlp_adapter:
|
443 |
+
self.model.orig_embeds_params = [
|
444 |
+
self.get_input_embeddings().weight.data.clone().to(device=device)]
|
445 |
+
for p in self.get_input_embeddings().parameters():
|
446 |
+
p.requires_grad = True
|
447 |
+
for p in self.get_output_embeddings().parameters():
|
448 |
+
p.requires_grad = False
|
449 |
+
|
450 |
+
self.model.vision_config.im_patch_token = tokenizer.convert_tokens_to_ids(
|
451 |
+
[DEFAULT_IMAGE_PATCH_TOKEN])[0]
|
452 |
+
print(f'Tokenizer: {tokenizer}\n patch_token_id: {self.model.vision_config.im_patch_token}, visoin_config: {self.model.vision_config}', flush=True)
|
453 |
+
# exit()
|
454 |
+
|
455 |
+
|
456 |
+
AutoConfig.register("omnilmm", OmniLMMConfig)
|
457 |
+
AutoModelForCausalLM.register(OmniLMMConfig, OmniLMMForCausalLM)
|
omnilmm/model/resampler.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
from collections import OrderedDict
|
7 |
+
import math
|
8 |
+
import requests
|
9 |
+
from io import BytesIO
|
10 |
+
from functools import partial
|
11 |
+
from PIL import Image
|
12 |
+
from typing import Callable, Optional, Sequence, Tuple, List, Union
|
13 |
+
import numpy as np
|
14 |
+
|
15 |
+
import torch
|
16 |
+
from torch import nn
|
17 |
+
from torch.nn import functional as F
|
18 |
+
from torch.nn.init import trunc_normal_
|
19 |
+
from torchvision import transforms
|
20 |
+
from torchvision.transforms import InterpolationMode
|
21 |
+
|
22 |
+
|
23 |
+
def get_abs_pos(abs_pos, tgt_size):
|
24 |
+
# abs_pos: L, C
|
25 |
+
# tgt_size: M
|
26 |
+
# return: M, C
|
27 |
+
src_size = int(math.sqrt(abs_pos.size(0)))
|
28 |
+
tgt_size = int(math.sqrt(tgt_size))
|
29 |
+
dtype = abs_pos.dtype
|
30 |
+
|
31 |
+
if src_size != tgt_size:
|
32 |
+
return F.interpolate(
|
33 |
+
abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
|
34 |
+
size=(tgt_size, tgt_size),
|
35 |
+
mode="bicubic",
|
36 |
+
align_corners=False,
|
37 |
+
).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
|
38 |
+
else:
|
39 |
+
return abs_pos
|
40 |
+
|
41 |
+
|
42 |
+
# https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
|
43 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
|
44 |
+
"""
|
45 |
+
grid_size: int of the grid height and width
|
46 |
+
return:
|
47 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
48 |
+
"""
|
49 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
50 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
51 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
52 |
+
grid = np.stack(grid, axis=0)
|
53 |
+
|
54 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
55 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
56 |
+
if cls_token:
|
57 |
+
pos_embed = np.concatenate(
|
58 |
+
[np.zeros([1, embed_dim]), pos_embed], axis=0)
|
59 |
+
return pos_embed
|
60 |
+
|
61 |
+
|
62 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
63 |
+
assert embed_dim % 2 == 0
|
64 |
+
|
65 |
+
# use half of dimensions to encode grid_h
|
66 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(
|
67 |
+
embed_dim // 2, grid[0]) # (H*W, D/2)
|
68 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(
|
69 |
+
embed_dim // 2, grid[1]) # (H*W, D/2)
|
70 |
+
|
71 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
72 |
+
return emb
|
73 |
+
|
74 |
+
|
75 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
76 |
+
"""
|
77 |
+
embed_dim: output dimension for each position
|
78 |
+
pos: a list of positions to be encoded: size (M,)
|
79 |
+
out: (M, D)
|
80 |
+
"""
|
81 |
+
assert embed_dim % 2 == 0
|
82 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
83 |
+
omega /= embed_dim / 2.
|
84 |
+
omega = 1. / 10000 ** omega # (D/2,)
|
85 |
+
|
86 |
+
pos = pos.reshape(-1) # (M,)
|
87 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
88 |
+
|
89 |
+
emb_sin = np.sin(out) # (M, D/2)
|
90 |
+
emb_cos = np.cos(out) # (M, D/2)
|
91 |
+
|
92 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
93 |
+
return emb
|
94 |
+
|
95 |
+
|
96 |
+
class Resampler(nn.Module):
|
97 |
+
"""
|
98 |
+
A 2D perceiver-resampler network with one cross attention layers by
|
99 |
+
(grid_size**2) learnable queries and 2d sincos pos_emb
|
100 |
+
Outputs:
|
101 |
+
A tensor with the shape of (grid_size**2, embed_dim)
|
102 |
+
"""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
grid_size,
|
107 |
+
embed_dim,
|
108 |
+
num_heads,
|
109 |
+
kv_dim=None,
|
110 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6)
|
111 |
+
):
|
112 |
+
super().__init__()
|
113 |
+
self.num_queries = grid_size ** 2
|
114 |
+
self.embed_dim = embed_dim
|
115 |
+
self.num_heads = num_heads
|
116 |
+
|
117 |
+
self.pos_embed = nn.Parameter(
|
118 |
+
torch.from_numpy(get_2d_sincos_pos_embed(
|
119 |
+
embed_dim, grid_size)).float()
|
120 |
+
).requires_grad_(False)
|
121 |
+
|
122 |
+
self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
|
123 |
+
trunc_normal_(self.query, std=.02)
|
124 |
+
|
125 |
+
if kv_dim is not None and kv_dim != embed_dim:
|
126 |
+
self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
|
127 |
+
else:
|
128 |
+
self.kv_proj = nn.Identity()
|
129 |
+
|
130 |
+
self.attn = nn.MultiheadAttention(embed_dim, num_heads)
|
131 |
+
self.ln_q = norm_layer(embed_dim)
|
132 |
+
self.ln_kv = norm_layer(embed_dim)
|
133 |
+
|
134 |
+
self.ln_post = norm_layer(embed_dim)
|
135 |
+
self.proj = nn.Parameter(
|
136 |
+
(embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
|
137 |
+
|
138 |
+
self.apply(self._init_weights)
|
139 |
+
|
140 |
+
def _init_weights(self, m):
|
141 |
+
if isinstance(m, nn.Linear):
|
142 |
+
trunc_normal_(m.weight, std=.02)
|
143 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
144 |
+
nn.init.constant_(m.bias, 0)
|
145 |
+
elif isinstance(m, nn.LayerNorm):
|
146 |
+
nn.init.constant_(m.bias, 0)
|
147 |
+
nn.init.constant_(m.weight, 1.0)
|
148 |
+
|
149 |
+
def forward(self, x, attn_mask=None):
|
150 |
+
|
151 |
+
pos_embed = get_abs_pos(self.pos_embed, x.size(1))
|
152 |
+
|
153 |
+
x = self.kv_proj(x)
|
154 |
+
x = self.ln_kv(x).permute(1, 0, 2)
|
155 |
+
|
156 |
+
N = x.shape[1]
|
157 |
+
q = self.ln_q(self.query)
|
158 |
+
# print((self._repeat(q, N) + self.pos_embed.unsqueeze(1)).dtype, (x + pos_embed.unsqueeze(1)).dtype, x.dtype)
|
159 |
+
out = self.attn(
|
160 |
+
self._repeat(q, N) + self.pos_embed.unsqueeze(1),
|
161 |
+
x + pos_embed.unsqueeze(1),
|
162 |
+
x,
|
163 |
+
attn_mask=attn_mask)[0]
|
164 |
+
x = out.permute(1, 0, 2)
|
165 |
+
|
166 |
+
x = self.ln_post(x)
|
167 |
+
x = x @ self.proj
|
168 |
+
return x
|
169 |
+
|
170 |
+
def _repeat(self, query, N: int):
|
171 |
+
return query.unsqueeze(1).repeat(1, N, 1)
|
omnilmm/model/utils.py
ADDED
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torchvision import transforms
|
2 |
+
from timm.data.transforms import RandomResizedCropAndInterpolation
|
3 |
+
from timm.data.constants import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD
|
4 |
+
from transformers import AutoConfig
|
5 |
+
from PIL import Image
|
6 |
+
from io import BytesIO
|
7 |
+
import torch.distributed as dist
|
8 |
+
import numpy as np
|
9 |
+
import pickle
|
10 |
+
import base64
|
11 |
+
import cv2
|
12 |
+
import os
|
13 |
+
import torch
|
14 |
+
from transformers import AutoConfig, StoppingCriteria
|
15 |
+
|
16 |
+
try:
|
17 |
+
from timm.data.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
|
18 |
+
except ImportError:
|
19 |
+
OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
20 |
+
OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
|
21 |
+
|
22 |
+
|
23 |
+
def auto_upgrade(config):
|
24 |
+
cfg = AutoConfig.from_pretrained(config)
|
25 |
+
if 'llava' in config and cfg.model_type != 'llava':
|
26 |
+
print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
|
27 |
+
print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
|
28 |
+
confirm = input(
|
29 |
+
"Please confirm that you want to upgrade the checkpoint. [Y/N]")
|
30 |
+
if confirm.lower() in ["y", "yes"]:
|
31 |
+
print("Upgrading checkpoint...")
|
32 |
+
assert len(cfg.architectures) == 1
|
33 |
+
setattr(cfg.__class__, "model_type", "llava")
|
34 |
+
cfg.architectures[0] = 'LlavaLlamaForCausalLM'
|
35 |
+
cfg.save_pretrained(config)
|
36 |
+
print("Checkpoint upgraded.")
|
37 |
+
else:
|
38 |
+
print("Checkpoint upgrade aborted.")
|
39 |
+
exit(1)
|
40 |
+
|
41 |
+
|
42 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
43 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
44 |
+
self.keywords = keywords
|
45 |
+
self.tokenizer = tokenizer
|
46 |
+
self.start_len = None
|
47 |
+
self.input_ids = input_ids
|
48 |
+
|
49 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
50 |
+
if self.start_len is None:
|
51 |
+
self.start_len = self.input_ids.shape[1]
|
52 |
+
else:
|
53 |
+
outputs = self.tokenizer.batch_decode(
|
54 |
+
output_ids[:, self.start_len:], skip_special_tokens=True)[0]
|
55 |
+
for keyword in self.keywords:
|
56 |
+
if keyword in outputs:
|
57 |
+
return True
|
58 |
+
return False
|
59 |
+
|
60 |
+
|
61 |
+
def auto_upgrade(config):
|
62 |
+
cfg = AutoConfig.from_pretrained(config)
|
63 |
+
if 'llava' in config and cfg.model_type != 'llava':
|
64 |
+
print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
|
65 |
+
print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
|
66 |
+
confirm = input(
|
67 |
+
"Please confirm that you want to upgrade the checkpoint. [Y/N]")
|
68 |
+
if confirm.lower() in ["y", "yes"]:
|
69 |
+
print("Upgrading checkpoint...")
|
70 |
+
assert len(cfg.architectures) == 1
|
71 |
+
setattr(cfg.__class__, "model_type", "llava")
|
72 |
+
cfg.architectures[0] = 'LlavaLlamaForCausalLM'
|
73 |
+
cfg.save_pretrained(config)
|
74 |
+
print("Checkpoint upgraded.")
|
75 |
+
else:
|
76 |
+
print("Checkpoint upgrade aborted.")
|
77 |
+
exit(1)
|
78 |
+
|
79 |
+
# aug functions
|
80 |
+
|
81 |
+
|
82 |
+
def identity_func(img):
|
83 |
+
return img
|
84 |
+
|
85 |
+
|
86 |
+
def autocontrast_func(img, cutoff=0):
|
87 |
+
'''
|
88 |
+
same output as PIL.ImageOps.autocontrast
|
89 |
+
'''
|
90 |
+
n_bins = 256
|
91 |
+
|
92 |
+
def tune_channel(ch):
|
93 |
+
n = ch.size
|
94 |
+
cut = cutoff * n // 100
|
95 |
+
if cut == 0:
|
96 |
+
high, low = ch.max(), ch.min()
|
97 |
+
else:
|
98 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
99 |
+
low = np.argwhere(np.cumsum(hist) > cut)
|
100 |
+
low = 0 if low.shape[0] == 0 else low[0]
|
101 |
+
high = np.argwhere(np.cumsum(hist[::-1]) > cut)
|
102 |
+
high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0]
|
103 |
+
if high <= low:
|
104 |
+
table = np.arange(n_bins)
|
105 |
+
else:
|
106 |
+
scale = (n_bins - 1) / (high - low)
|
107 |
+
table = np.arange(n_bins) * scale - low * scale
|
108 |
+
table[table < 0] = 0
|
109 |
+
table[table > n_bins - 1] = n_bins - 1
|
110 |
+
table = table.clip(0, 255).astype(np.uint8)
|
111 |
+
return table[ch]
|
112 |
+
|
113 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
114 |
+
out = cv2.merge(channels)
|
115 |
+
return out
|
116 |
+
|
117 |
+
|
118 |
+
def equalize_func(img):
|
119 |
+
'''
|
120 |
+
same output as PIL.ImageOps.equalize
|
121 |
+
PIL's implementation is different from cv2.equalize
|
122 |
+
'''
|
123 |
+
n_bins = 256
|
124 |
+
|
125 |
+
def tune_channel(ch):
|
126 |
+
hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
|
127 |
+
non_zero_hist = hist[hist != 0].reshape(-1)
|
128 |
+
step = np.sum(non_zero_hist[:-1]) // (n_bins - 1)
|
129 |
+
if step == 0:
|
130 |
+
return ch
|
131 |
+
n = np.empty_like(hist)
|
132 |
+
n[0] = step // 2
|
133 |
+
n[1:] = hist[:-1]
|
134 |
+
table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8)
|
135 |
+
return table[ch]
|
136 |
+
|
137 |
+
channels = [tune_channel(ch) for ch in cv2.split(img)]
|
138 |
+
out = cv2.merge(channels)
|
139 |
+
return out
|
140 |
+
|
141 |
+
|
142 |
+
def rotate_func(img, degree, fill=(0, 0, 0)):
|
143 |
+
'''
|
144 |
+
like PIL, rotate by degree, not radians
|
145 |
+
'''
|
146 |
+
H, W = img.shape[0], img.shape[1]
|
147 |
+
center = W / 2, H / 2
|
148 |
+
M = cv2.getRotationMatrix2D(center, degree, 1)
|
149 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill)
|
150 |
+
return out
|
151 |
+
|
152 |
+
|
153 |
+
def solarize_func(img, thresh=128):
|
154 |
+
'''
|
155 |
+
same output as PIL.ImageOps.posterize
|
156 |
+
'''
|
157 |
+
table = np.array([el if el < thresh else 255 - el for el in range(256)])
|
158 |
+
table = table.clip(0, 255).astype(np.uint8)
|
159 |
+
out = table[img]
|
160 |
+
return out
|
161 |
+
|
162 |
+
|
163 |
+
def color_func(img, factor):
|
164 |
+
'''
|
165 |
+
same output as PIL.ImageEnhance.Color
|
166 |
+
'''
|
167 |
+
# implementation according to PIL definition, quite slow
|
168 |
+
# degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis]
|
169 |
+
# out = blend(degenerate, img, factor)
|
170 |
+
# M = (
|
171 |
+
# np.eye(3) * factor
|
172 |
+
# + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor)
|
173 |
+
# )[np.newaxis, np.newaxis, :]
|
174 |
+
M = (
|
175 |
+
np.float32([
|
176 |
+
[0.886, -0.114, -0.114],
|
177 |
+
[-0.587, 0.413, -0.587],
|
178 |
+
[-0.299, -0.299, 0.701]]) * factor
|
179 |
+
+ np.float32([[0.114], [0.587], [0.299]])
|
180 |
+
)
|
181 |
+
out = np.matmul(img, M).clip(0, 255).astype(np.uint8)
|
182 |
+
return out
|
183 |
+
|
184 |
+
|
185 |
+
def contrast_func(img, factor):
|
186 |
+
"""
|
187 |
+
same output as PIL.ImageEnhance.Contrast
|
188 |
+
"""
|
189 |
+
mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299]))
|
190 |
+
table = np.array([(
|
191 |
+
el - mean) * factor + mean
|
192 |
+
for el in range(256)
|
193 |
+
]).clip(0, 255).astype(np.uint8)
|
194 |
+
out = table[img]
|
195 |
+
return out
|
196 |
+
|
197 |
+
|
198 |
+
def brightness_func(img, factor):
|
199 |
+
'''
|
200 |
+
same output as PIL.ImageEnhance.Contrast
|
201 |
+
'''
|
202 |
+
table = (np.arange(256, dtype=np.float32) *
|
203 |
+
factor).clip(0, 255).astype(np.uint8)
|
204 |
+
out = table[img]
|
205 |
+
return out
|
206 |
+
|
207 |
+
|
208 |
+
def sharpness_func(img, factor):
|
209 |
+
'''
|
210 |
+
The differences the this result and PIL are all on the 4 boundaries, the center
|
211 |
+
areas are same
|
212 |
+
'''
|
213 |
+
kernel = np.ones((3, 3), dtype=np.float32)
|
214 |
+
kernel[1][1] = 5
|
215 |
+
kernel /= 13
|
216 |
+
degenerate = cv2.filter2D(img, -1, kernel)
|
217 |
+
if factor == 0.0:
|
218 |
+
out = degenerate
|
219 |
+
elif factor == 1.0:
|
220 |
+
out = img
|
221 |
+
else:
|
222 |
+
out = img.astype(np.float32)
|
223 |
+
degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :]
|
224 |
+
out[1:-1, 1:-1, :] = degenerate + factor * \
|
225 |
+
(out[1:-1, 1:-1, :] - degenerate)
|
226 |
+
out = out.astype(np.uint8)
|
227 |
+
return out
|
228 |
+
|
229 |
+
|
230 |
+
def shear_x_func(img, factor, fill=(0, 0, 0)):
|
231 |
+
H, W = img.shape[0], img.shape[1]
|
232 |
+
M = np.float32([[1, factor, 0], [0, 1, 0]])
|
233 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill,
|
234 |
+
flags=cv2.INTER_LINEAR).astype(np.uint8)
|
235 |
+
return out
|
236 |
+
|
237 |
+
|
238 |
+
def translate_x_func(img, offset, fill=(0, 0, 0)):
|
239 |
+
'''
|
240 |
+
same output as PIL.Image.transform
|
241 |
+
'''
|
242 |
+
H, W = img.shape[0], img.shape[1]
|
243 |
+
M = np.float32([[1, 0, -offset], [0, 1, 0]])
|
244 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill,
|
245 |
+
flags=cv2.INTER_LINEAR).astype(np.uint8)
|
246 |
+
return out
|
247 |
+
|
248 |
+
|
249 |
+
def translate_y_func(img, offset, fill=(0, 0, 0)):
|
250 |
+
'''
|
251 |
+
same output as PIL.Image.transform
|
252 |
+
'''
|
253 |
+
H, W = img.shape[0], img.shape[1]
|
254 |
+
M = np.float32([[1, 0, 0], [0, 1, -offset]])
|
255 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill,
|
256 |
+
flags=cv2.INTER_LINEAR).astype(np.uint8)
|
257 |
+
return out
|
258 |
+
|
259 |
+
|
260 |
+
def posterize_func(img, bits):
|
261 |
+
'''
|
262 |
+
same output as PIL.ImageOps.posterize
|
263 |
+
'''
|
264 |
+
out = np.bitwise_and(img, np.uint8(255 << (8 - bits)))
|
265 |
+
return out
|
266 |
+
|
267 |
+
|
268 |
+
def shear_y_func(img, factor, fill=(0, 0, 0)):
|
269 |
+
H, W = img.shape[0], img.shape[1]
|
270 |
+
M = np.float32([[1, 0, 0], [factor, 1, 0]])
|
271 |
+
out = cv2.warpAffine(img, M, (W, H), borderValue=fill,
|
272 |
+
flags=cv2.INTER_LINEAR).astype(np.uint8)
|
273 |
+
return out
|
274 |
+
|
275 |
+
|
276 |
+
def cutout_func(img, pad_size, replace=(0, 0, 0)):
|
277 |
+
replace = np.array(replace, dtype=np.uint8)
|
278 |
+
H, W = img.shape[0], img.shape[1]
|
279 |
+
rh, rw = np.random.random(2)
|
280 |
+
pad_size = pad_size // 2
|
281 |
+
ch, cw = int(rh * H), int(rw * W)
|
282 |
+
x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H)
|
283 |
+
y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W)
|
284 |
+
out = img.copy()
|
285 |
+
out[x1:x2, y1:y2, :] = replace
|
286 |
+
return out
|
287 |
+
|
288 |
+
|
289 |
+
# level to args
|
290 |
+
def enhance_level_to_args(MAX_LEVEL):
|
291 |
+
def level_to_args(level):
|
292 |
+
return ((level / MAX_LEVEL) * 1.8 + 0.1,)
|
293 |
+
return level_to_args
|
294 |
+
|
295 |
+
|
296 |
+
def shear_level_to_args(MAX_LEVEL, replace_value):
|
297 |
+
def level_to_args(level):
|
298 |
+
level = (level / MAX_LEVEL) * 0.3
|
299 |
+
if np.random.random() > 0.5:
|
300 |
+
level = -level
|
301 |
+
return (level, replace_value)
|
302 |
+
|
303 |
+
return level_to_args
|
304 |
+
|
305 |
+
|
306 |
+
def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
|
307 |
+
def level_to_args(level):
|
308 |
+
level = (level / MAX_LEVEL) * float(translate_const)
|
309 |
+
if np.random.random() > 0.5:
|
310 |
+
level = -level
|
311 |
+
return (level, replace_value)
|
312 |
+
|
313 |
+
return level_to_args
|
314 |
+
|
315 |
+
|
316 |
+
def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
|
317 |
+
def level_to_args(level):
|
318 |
+
level = int((level / MAX_LEVEL) * cutout_const)
|
319 |
+
return (level, replace_value)
|
320 |
+
|
321 |
+
return level_to_args
|
322 |
+
|
323 |
+
|
324 |
+
def solarize_level_to_args(MAX_LEVEL):
|
325 |
+
def level_to_args(level):
|
326 |
+
level = int((level / MAX_LEVEL) * 256)
|
327 |
+
return (level, )
|
328 |
+
return level_to_args
|
329 |
+
|
330 |
+
|
331 |
+
def none_level_to_args(level):
|
332 |
+
return ()
|
333 |
+
|
334 |
+
|
335 |
+
def posterize_level_to_args(MAX_LEVEL):
|
336 |
+
def level_to_args(level):
|
337 |
+
level = int((level / MAX_LEVEL) * 4)
|
338 |
+
return (level, )
|
339 |
+
return level_to_args
|
340 |
+
|
341 |
+
|
342 |
+
def rotate_level_to_args(MAX_LEVEL, replace_value):
|
343 |
+
def level_to_args(level):
|
344 |
+
level = (level / MAX_LEVEL) * 30
|
345 |
+
if np.random.random() < 0.5:
|
346 |
+
level = -level
|
347 |
+
return (level, replace_value)
|
348 |
+
|
349 |
+
return level_to_args
|
350 |
+
|
351 |
+
|
352 |
+
func_dict = {
|
353 |
+
'Identity': identity_func,
|
354 |
+
'AutoContrast': autocontrast_func,
|
355 |
+
'Equalize': equalize_func,
|
356 |
+
'Rotate': rotate_func,
|
357 |
+
'Solarize': solarize_func,
|
358 |
+
'Color': color_func,
|
359 |
+
'Contrast': contrast_func,
|
360 |
+
'Brightness': brightness_func,
|
361 |
+
'Sharpness': sharpness_func,
|
362 |
+
'ShearX': shear_x_func,
|
363 |
+
'TranslateX': translate_x_func,
|
364 |
+
'TranslateY': translate_y_func,
|
365 |
+
'Posterize': posterize_func,
|
366 |
+
'ShearY': shear_y_func,
|
367 |
+
}
|
368 |
+
|
369 |
+
translate_const = 10
|
370 |
+
MAX_LEVEL = 10
|
371 |
+
replace_value = (128, 128, 128)
|
372 |
+
arg_dict = {
|
373 |
+
'Identity': none_level_to_args,
|
374 |
+
'AutoContrast': none_level_to_args,
|
375 |
+
'Equalize': none_level_to_args,
|
376 |
+
'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value),
|
377 |
+
'Solarize': solarize_level_to_args(MAX_LEVEL),
|
378 |
+
'Color': enhance_level_to_args(MAX_LEVEL),
|
379 |
+
'Contrast': enhance_level_to_args(MAX_LEVEL),
|
380 |
+
'Brightness': enhance_level_to_args(MAX_LEVEL),
|
381 |
+
'Sharpness': enhance_level_to_args(MAX_LEVEL),
|
382 |
+
'ShearX': shear_level_to_args(MAX_LEVEL, replace_value),
|
383 |
+
'TranslateX': translate_level_to_args(
|
384 |
+
translate_const, MAX_LEVEL, replace_value
|
385 |
+
),
|
386 |
+
'TranslateY': translate_level_to_args(
|
387 |
+
translate_const, MAX_LEVEL, replace_value
|
388 |
+
),
|
389 |
+
'Posterize': posterize_level_to_args(MAX_LEVEL),
|
390 |
+
'ShearY': shear_level_to_args(MAX_LEVEL, replace_value),
|
391 |
+
}
|
392 |
+
|
393 |
+
|
394 |
+
class RandomAugment(object):
|
395 |
+
|
396 |
+
def __init__(self, N=2, M=10, isPIL=False, augs=[]):
|
397 |
+
self.N = N
|
398 |
+
self.M = M
|
399 |
+
self.isPIL = isPIL
|
400 |
+
if augs:
|
401 |
+
self.augs = augs
|
402 |
+
else:
|
403 |
+
self.augs = list(arg_dict.keys())
|
404 |
+
|
405 |
+
def get_random_ops(self):
|
406 |
+
sampled_ops = np.random.choice(self.augs, self.N)
|
407 |
+
return [(op, 0.5, self.M) for op in sampled_ops]
|
408 |
+
|
409 |
+
def __call__(self, img):
|
410 |
+
if self.isPIL:
|
411 |
+
img = np.array(img)
|
412 |
+
ops = self.get_random_ops()
|
413 |
+
for name, prob, level in ops:
|
414 |
+
if np.random.random() > prob:
|
415 |
+
continue
|
416 |
+
args = arg_dict[name](level)
|
417 |
+
img = func_dict[name](img, *args)
|
418 |
+
return img
|
419 |
+
|
420 |
+
|
421 |
+
def build_transform(is_train, randaug=True, input_size=224, interpolation='bicubic', std_mode='IMAGENET_INCEPTION'):
|
422 |
+
if std_mode == 'IMAGENET_INCEPTION':
|
423 |
+
mean = IMAGENET_INCEPTION_MEAN
|
424 |
+
std = IMAGENET_INCEPTION_STD
|
425 |
+
elif std_mode == 'OPENAI_CLIP':
|
426 |
+
mean = OPENAI_CLIP_MEAN
|
427 |
+
std = OPENAI_CLIP_STD
|
428 |
+
else:
|
429 |
+
raise NotImplementedError
|
430 |
+
|
431 |
+
if is_train:
|
432 |
+
crop_scale = float(os.environ.get('TRAIN_CROP_SCALE', 0.9999))
|
433 |
+
t = [
|
434 |
+
RandomResizedCropAndInterpolation(
|
435 |
+
input_size, scale=(crop_scale, 1.0), interpolation='bicubic'),
|
436 |
+
# transforms.RandomHorizontalFlip(),
|
437 |
+
]
|
438 |
+
if randaug and os.environ.get('TRAIN_DO_AUG', 'False') == 'True':
|
439 |
+
print(f'@@@@@ Do random aug during training', flush=True)
|
440 |
+
t.append(
|
441 |
+
RandomAugment(
|
442 |
+
2, 7, isPIL=True,
|
443 |
+
augs=[
|
444 |
+
'Identity', 'AutoContrast', 'Equalize', 'Brightness', 'Sharpness',
|
445 |
+
'ShearX', 'ShearY', 'TranslateX', 'TranslateY', 'Rotate',
|
446 |
+
]))
|
447 |
+
else:
|
448 |
+
print(f'@@@@@ Skip random aug during training', flush=True)
|
449 |
+
t += [
|
450 |
+
transforms.ToTensor(),
|
451 |
+
transforms.Normalize(mean=mean, std=std),
|
452 |
+
]
|
453 |
+
t = transforms.Compose(t)
|
454 |
+
else:
|
455 |
+
t = transforms.Compose([
|
456 |
+
transforms.Resize((input_size, input_size),
|
457 |
+
interpolation=transforms.InterpolationMode.BICUBIC),
|
458 |
+
transforms.ToTensor(),
|
459 |
+
transforms.Normalize(mean=mean, std=std)
|
460 |
+
])
|
461 |
+
|
462 |
+
return t
|
463 |
+
|
464 |
+
|
465 |
+
def img2b64(img_path):
|
466 |
+
img = Image.open(img_path) # path to file
|
467 |
+
img_buffer = BytesIO()
|
468 |
+
img.save(img_buffer, format=img.format)
|
469 |
+
byte_data = img_buffer.getvalue()
|
470 |
+
base64_str = base64.b64encode(byte_data) # bytes
|
471 |
+
base64_str = base64_str.decode("utf-8") # str
|
472 |
+
return base64_str
|
473 |
+
|
474 |
+
|
475 |
+
def str2b64(str):
|
476 |
+
return base64.b64encode(str.encode('utf-8')).decode('utf-8')
|
477 |
+
|
478 |
+
|
479 |
+
def b642str(b64):
|
480 |
+
return base64.b64decode(b64).decode('utf-8')
|
481 |
+
|
482 |
+
|
483 |
+
def is_dist_avail_and_initialized():
|
484 |
+
if not dist.is_available():
|
485 |
+
return False
|
486 |
+
if not dist.is_initialized():
|
487 |
+
return False
|
488 |
+
return True
|
489 |
+
|
490 |
+
|
491 |
+
def get_world_size():
|
492 |
+
if not is_dist_avail_and_initialized():
|
493 |
+
return 1
|
494 |
+
return dist.get_world_size()
|
495 |
+
|
496 |
+
|
497 |
+
def get_rank():
|
498 |
+
if not is_dist_avail_and_initialized():
|
499 |
+
return 0
|
500 |
+
return dist.get_rank()
|
501 |
+
|
502 |
+
|
503 |
+
def all_gather(data):
|
504 |
+
"""
|
505 |
+
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
506 |
+
Args:
|
507 |
+
data: any picklable object
|
508 |
+
Returns:
|
509 |
+
list[data]: list of data gathered from each rank
|
510 |
+
"""
|
511 |
+
world_size = get_world_size()
|
512 |
+
if world_size == 1:
|
513 |
+
return [data]
|
514 |
+
|
515 |
+
# serialized to a Tensor
|
516 |
+
buffer = pickle.dumps(data)
|
517 |
+
storage = torch.ByteStorage.from_buffer(buffer)
|
518 |
+
tensor = torch.ByteTensor(storage).to("cuda")
|
519 |
+
|
520 |
+
# obtain Tensor size of each rank
|
521 |
+
local_size = torch.LongTensor([tensor.numel()]).to("cuda")
|
522 |
+
size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
|
523 |
+
dist.all_gather(size_list, local_size)
|
524 |
+
size_list = [int(size.item()) for size in size_list]
|
525 |
+
max_size = max(size_list)
|
526 |
+
|
527 |
+
# receiving Tensor from all ranks
|
528 |
+
# we pad the tensor because torch all_gather does not support
|
529 |
+
# gathering tensors of different shapes
|
530 |
+
tensor_list = []
|
531 |
+
for _ in size_list:
|
532 |
+
tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda"))
|
533 |
+
if local_size != max_size:
|
534 |
+
padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda")
|
535 |
+
tensor = torch.cat((tensor, padding), dim=0)
|
536 |
+
dist.all_gather(tensor_list, tensor)
|
537 |
+
|
538 |
+
data_list = []
|
539 |
+
for size, tensor in zip(size_list, tensor_list):
|
540 |
+
buffer = tensor.cpu().numpy().tobytes()[:size]
|
541 |
+
data_list.append(pickle.loads(buffer))
|
542 |
+
|
543 |
+
return data_list
|
544 |
+
|
545 |
+
|
546 |
+
def mean(lst):
|
547 |
+
return sum(lst) / len(lst)
|
548 |
+
|
549 |
+
|
550 |
+
def stop_gradient_by_name(name: str):
|
551 |
+
def apply_fn(module):
|
552 |
+
if hasattr(module, name):
|
553 |
+
getattr(module, name).requires_grad_(False)
|
554 |
+
|
555 |
+
return apply_fn
|
omnilmm/train/train_utils.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gc
|
3 |
+
import copy
|
4 |
+
import time
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import warnings
|
8 |
+
import transformers
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
from typing import Dict, Optional, Sequence
|
13 |
+
from omnilmm import conversation as conversation_lib
|
14 |
+
|
15 |
+
IGNORE_INDEX = -100
|
16 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
17 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
18 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
19 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
20 |
+
|
21 |
+
|
22 |
+
def _tokenize_fn(strings: Sequence[str],
|
23 |
+
tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
24 |
+
"""Tokenize a list of strings."""
|
25 |
+
tokenized_list = [
|
26 |
+
tokenizer(
|
27 |
+
text,
|
28 |
+
return_tensors="pt",
|
29 |
+
padding="longest",
|
30 |
+
max_length=tokenizer.model_max_length,
|
31 |
+
truncation=True,
|
32 |
+
) for text in strings
|
33 |
+
]
|
34 |
+
input_ids = labels = [
|
35 |
+
tokenized.input_ids[0] for tokenized in tokenized_list
|
36 |
+
]
|
37 |
+
input_ids_lens = labels_lens = [
|
38 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
|
39 |
+
for tokenized in tokenized_list
|
40 |
+
]
|
41 |
+
return dict(
|
42 |
+
input_ids=input_ids,
|
43 |
+
labels=labels,
|
44 |
+
input_ids_lens=input_ids_lens,
|
45 |
+
labels_lens=labels_lens,
|
46 |
+
)
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
def omni_preprocess(sources,
|
51 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
52 |
+
generation=False):
|
53 |
+
system_content = 'You are an artificial intelligence assistant, which gives helpful, detailed, and polite answers to the human\'s questions.'
|
54 |
+
ignore_index = -100
|
55 |
+
|
56 |
+
response_template = '\n<|assistant|>\n'
|
57 |
+
instruction_template = '\n<|user|>\n'
|
58 |
+
response_token_ids = tokenizer.encode(
|
59 |
+
response_template, add_special_tokens=False)
|
60 |
+
instruction_token_ids = tokenizer.encode(
|
61 |
+
instruction_template, add_special_tokens=False)
|
62 |
+
|
63 |
+
batch_input_ids = []
|
64 |
+
batch_labels = []
|
65 |
+
for i in range(len(sources)):
|
66 |
+
new_source = []
|
67 |
+
prev_role = 'unexpect'
|
68 |
+
for conv_turn in sources[i]:
|
69 |
+
role = conv_turn['from'] if 'from' in conv_turn else conv_turn['role']
|
70 |
+
content = conv_turn['value'] if 'value' in conv_turn else conv_turn['content']
|
71 |
+
|
72 |
+
role = 'user' if role == 'human' else role
|
73 |
+
role = 'assistant' if role == 'gpt' else role
|
74 |
+
|
75 |
+
assert role in ['user', 'assistant']
|
76 |
+
assert role != prev_role, f'role={role}, prev_role={prev_role}'
|
77 |
+
prev_role = role
|
78 |
+
|
79 |
+
new_turn = {
|
80 |
+
'role': role,
|
81 |
+
'content': content
|
82 |
+
}
|
83 |
+
new_source.append(new_turn)
|
84 |
+
if new_source[0]['role'] != 'system':
|
85 |
+
new_source.insert(0, {'role': 'system', 'content': system_content})
|
86 |
+
|
87 |
+
# TODO: this automatically add '\n' to the end
|
88 |
+
res_text = tokenizer.apply_chat_template(
|
89 |
+
new_source, tokenize=False, add_generation_prompt=generation)
|
90 |
+
if not generation:
|
91 |
+
res_text = res_text.strip()
|
92 |
+
|
93 |
+
conversations_tokenized = _tokenize_fn([res_text], tokenizer)
|
94 |
+
res_input_ids = conversations_tokenized["input_ids"][0]
|
95 |
+
|
96 |
+
# since labels and input_ids are reference towards the same object
|
97 |
+
res_labels = copy.deepcopy(conversations_tokenized["labels"][0])
|
98 |
+
|
99 |
+
response_token_ids_idxs = []
|
100 |
+
human_token_ids_idxs = []
|
101 |
+
|
102 |
+
for assistant_idx in np.where(res_labels == response_token_ids[0])[0]:
|
103 |
+
# find the indexes of the start of a response.
|
104 |
+
if (response_token_ids == res_labels[assistant_idx: assistant_idx + len(
|
105 |
+
response_token_ids)].tolist()
|
106 |
+
):
|
107 |
+
response_token_ids_idxs.append(
|
108 |
+
assistant_idx + len(response_token_ids))
|
109 |
+
|
110 |
+
if len(response_token_ids_idxs) == 0:
|
111 |
+
warnings.warn(
|
112 |
+
f"Could not find response key `{response_template}` in the "
|
113 |
+
f'following instance: @===>{tokenizer.decode(res_input_ids)}<===@ '
|
114 |
+
f'Raw text is @===>{res_text}<===@'
|
115 |
+
f'Raw source is @===>{new_source}<===@'
|
116 |
+
f"This instance will be ignored in loss calculation. "
|
117 |
+
f"Note, if this happens often, consider increasing the `max_seq_length`."
|
118 |
+
)
|
119 |
+
res_labels[:] = ignore_index
|
120 |
+
|
121 |
+
human_token_ids = instruction_token_ids
|
122 |
+
for human_idx in np.where(res_labels == human_token_ids[0])[0]:
|
123 |
+
# find the indexes of the start of a human answer.
|
124 |
+
if human_token_ids == res_labels[human_idx: human_idx + len(human_token_ids)].tolist():
|
125 |
+
human_token_ids_idxs.append(human_idx)
|
126 |
+
|
127 |
+
if len(human_token_ids_idxs) == 0:
|
128 |
+
warnings.warn(
|
129 |
+
f"Could not find instruction key `{instruction_template}` in the "
|
130 |
+
f'following instance: @===>{tokenizer.decode(res_input_ids)}<===@ '
|
131 |
+
f'Raw text is @===>{res_text}<===@'
|
132 |
+
f'Raw source is @===>{new_source}<===@'
|
133 |
+
f"This instance will be ignored in loss calculation. "
|
134 |
+
f"Note, if this happens often, consider increasing the `max_seq_length`."
|
135 |
+
)
|
136 |
+
res_labels[:] = ignore_index
|
137 |
+
|
138 |
+
for idx, (start, end) in enumerate(zip(human_token_ids_idxs, response_token_ids_idxs)):
|
139 |
+
# Make pytorch loss function ignore all non response tokens
|
140 |
+
if idx != 0:
|
141 |
+
res_labels[start:end] = ignore_index
|
142 |
+
else:
|
143 |
+
res_labels[:end] = ignore_index
|
144 |
+
|
145 |
+
if len(response_token_ids_idxs) < len(human_token_ids_idxs):
|
146 |
+
res_labels[human_token_ids_idxs[-1]:] = ignore_index
|
147 |
+
|
148 |
+
batch_input_ids.append(res_input_ids)
|
149 |
+
batch_labels.append(res_labels)
|
150 |
+
|
151 |
+
return dict(input_ids=batch_input_ids, labels=batch_labels)
|
152 |
+
|
153 |
+
|
omnilmm/utils.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import logging
|
3 |
+
import logging.handlers
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
|
7 |
+
import requests
|
8 |
+
|
9 |
+
from omnilmm.constants import LOGDIR
|
10 |
+
|
11 |
+
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
12 |
+
moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
|
13 |
+
|
14 |
+
handler = None
|
15 |
+
|
16 |
+
|
17 |
+
def build_logger(logger_name, logger_filename):
|
18 |
+
global handler
|
19 |
+
|
20 |
+
formatter = logging.Formatter(
|
21 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
22 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
23 |
+
)
|
24 |
+
|
25 |
+
# Set the format of root handlers
|
26 |
+
if not logging.getLogger().handlers:
|
27 |
+
logging.basicConfig(level=logging.INFO)
|
28 |
+
logging.getLogger().handlers[0].setFormatter(formatter)
|
29 |
+
|
30 |
+
# Redirect stdout and stderr to loggers
|
31 |
+
stdout_logger = logging.getLogger("stdout")
|
32 |
+
stdout_logger.setLevel(logging.INFO)
|
33 |
+
sl = StreamToLogger(stdout_logger, logging.INFO)
|
34 |
+
sys.stdout = sl
|
35 |
+
|
36 |
+
stderr_logger = logging.getLogger("stderr")
|
37 |
+
stderr_logger.setLevel(logging.ERROR)
|
38 |
+
sl = StreamToLogger(stderr_logger, logging.ERROR)
|
39 |
+
sys.stderr = sl
|
40 |
+
|
41 |
+
# Get logger
|
42 |
+
logger = logging.getLogger(logger_name)
|
43 |
+
logger.setLevel(logging.INFO)
|
44 |
+
|
45 |
+
# Add a file handler for all loggers
|
46 |
+
if handler is None:
|
47 |
+
os.makedirs(LOGDIR, exist_ok=True)
|
48 |
+
filename = os.path.join(LOGDIR, logger_filename)
|
49 |
+
handler = logging.handlers.TimedRotatingFileHandler(
|
50 |
+
filename, when='D', utc=True)
|
51 |
+
handler.setFormatter(formatter)
|
52 |
+
|
53 |
+
for name, item in logging.root.manager.loggerDict.items():
|
54 |
+
if isinstance(item, logging.Logger):
|
55 |
+
item.addHandler(handler)
|
56 |
+
|
57 |
+
return logger
|
58 |
+
|
59 |
+
|
60 |
+
class StreamToLogger(object):
|
61 |
+
"""
|
62 |
+
Fake file-like stream object that redirects writes to a logger instance.
|
63 |
+
"""
|
64 |
+
|
65 |
+
def __init__(self, logger, log_level=logging.INFO):
|
66 |
+
self.terminal = sys.stdout
|
67 |
+
self.logger = logger
|
68 |
+
self.log_level = log_level
|
69 |
+
self.linebuf = ''
|
70 |
+
|
71 |
+
def __getattr__(self, attr):
|
72 |
+
return getattr(self.terminal, attr)
|
73 |
+
|
74 |
+
def write(self, buf):
|
75 |
+
temp_linebuf = self.linebuf + buf
|
76 |
+
self.linebuf = ''
|
77 |
+
for line in temp_linebuf.splitlines(True):
|
78 |
+
# From the io.TextIOWrapper docs:
|
79 |
+
# On output, if newline is None, any '\n' characters written
|
80 |
+
# are translated to the system default line separator.
|
81 |
+
# By default sys.stdout.write() expects '\n' newlines and then
|
82 |
+
# translates them so this is still cross platform.
|
83 |
+
if line[-1] == '\n':
|
84 |
+
self.logger.log(self.log_level, line.rstrip())
|
85 |
+
else:
|
86 |
+
self.linebuf += line
|
87 |
+
|
88 |
+
def flush(self):
|
89 |
+
if self.linebuf != '':
|
90 |
+
self.logger.log(self.log_level, self.linebuf.rstrip())
|
91 |
+
self.linebuf = ''
|
92 |
+
|
93 |
+
|
94 |
+
def disable_torch_init():
|
95 |
+
"""
|
96 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
97 |
+
"""
|
98 |
+
import torch
|
99 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
100 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
101 |
+
|
102 |
+
|
103 |
+
def violates_moderation(text):
|
104 |
+
"""
|
105 |
+
Check whether the text violates OpenAI moderation API.
|
106 |
+
"""
|
107 |
+
url = "https://api.openai.com/v1/moderations"
|
108 |
+
headers = {"Content-Type": "application/json",
|
109 |
+
"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
|
110 |
+
text = text.replace("\n", "")
|
111 |
+
data = "{" + '"input": ' + f'"{text}"' + "}"
|
112 |
+
data = data.encode("utf-8")
|
113 |
+
try:
|
114 |
+
ret = requests.post(url, headers=headers, data=data, timeout=5)
|
115 |
+
flagged = ret.json()["results"][0]["flagged"]
|
116 |
+
except requests.exceptions.RequestException as e:
|
117 |
+
flagged = False
|
118 |
+
except KeyError as e:
|
119 |
+
flagged = False
|
120 |
+
|
121 |
+
return flagged
|
122 |
+
|
123 |
+
|
124 |
+
def pretty_print_semaphore(semaphore):
|
125 |
+
if semaphore is None:
|
126 |
+
return "None"
|
127 |
+
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
|
openai_api.py
ADDED
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gc
|
2 |
+
import json
|
3 |
+
import time
|
4 |
+
import requests
|
5 |
+
import base64
|
6 |
+
import uvicorn
|
7 |
+
import argparse
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from transformers import AutoModelForCausalLM, LlamaTokenizer, PreTrainedModel, PreTrainedTokenizer, \
|
11 |
+
TextIteratorStreamer, CodeGenTokenizerFast as Tokenizer
|
12 |
+
|
13 |
+
from contextlib import asynccontextmanager
|
14 |
+
from loguru import logger
|
15 |
+
from typing import List, Literal, Union, Tuple, Optional
|
16 |
+
|
17 |
+
from fastapi import FastAPI, HTTPException
|
18 |
+
from fastapi.middleware.cors import CORSMiddleware
|
19 |
+
from pydantic import BaseModel, Field
|
20 |
+
|
21 |
+
from PIL import Image
|
22 |
+
from io import BytesIO
|
23 |
+
|
24 |
+
import os
|
25 |
+
import re
|
26 |
+
from threading import Thread
|
27 |
+
from moondream import Moondream, detect_device
|
28 |
+
|
29 |
+
import omnichat
|
30 |
+
|
31 |
+
# 请求
|
32 |
+
class TextContent(BaseModel):
|
33 |
+
type: Literal["text"]
|
34 |
+
text: str
|
35 |
+
class ImageUrl(BaseModel):
|
36 |
+
url: str
|
37 |
+
class ImageUrlContent(BaseModel):
|
38 |
+
type: Literal["image_url"]
|
39 |
+
image_url: ImageUrl
|
40 |
+
ContentItem = Union[TextContent, ImageUrlContent]
|
41 |
+
class ChatMessageInput(BaseModel):
|
42 |
+
role: Literal["user", "assistant", "system"]
|
43 |
+
content: Union[str, List[ContentItem]]
|
44 |
+
name: Optional[str] = None
|
45 |
+
class ChatCompletionRequest(BaseModel):
|
46 |
+
model: str
|
47 |
+
messages: List[ChatMessageInput]
|
48 |
+
temperature: Optional[float] = 0.8
|
49 |
+
top_p: Optional[float] = 0.8
|
50 |
+
max_tokens: Optional[int] = None
|
51 |
+
stream: Optional[bool] = False
|
52 |
+
# Additional parameters
|
53 |
+
repetition_penalty: Optional[float] = 1.0
|
54 |
+
|
55 |
+
# 响应
|
56 |
+
class ChatMessageResponse(BaseModel):
|
57 |
+
role: Literal["assistant"]
|
58 |
+
content: str = None
|
59 |
+
name: Optional[str] = None
|
60 |
+
class ChatCompletionResponseChoice(BaseModel):
|
61 |
+
index: int
|
62 |
+
message: ChatMessageResponse
|
63 |
+
class DeltaMessage(BaseModel):
|
64 |
+
role: Optional[Literal["user", "assistant", "system"]] = None
|
65 |
+
content: Optional[str] = None
|
66 |
+
class ChatCompletionResponseStreamChoice(BaseModel):
|
67 |
+
index: int
|
68 |
+
delta: DeltaMessage
|
69 |
+
class UsageInfo(BaseModel):
|
70 |
+
prompt_tokens: int = 0
|
71 |
+
total_tokens: int = 0
|
72 |
+
completion_tokens: Optional[int] = 0
|
73 |
+
class ChatCompletionResponse(BaseModel):
|
74 |
+
model: str
|
75 |
+
object: Literal["chat.completion", "chat.completion.chunk"]
|
76 |
+
choices: List[Union[ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice]]
|
77 |
+
created: Optional[int] = Field(default_factory=lambda: int(time.time()))
|
78 |
+
usage: Optional[UsageInfo] = None
|
79 |
+
|
80 |
+
# 图片输入处理
|
81 |
+
def process_img(input_data):
|
82 |
+
if isinstance(input_data, str):
|
83 |
+
# URL
|
84 |
+
if input_data.startswith("http://") or input_data.startswith("https://"):
|
85 |
+
response = requests.get(input_data)
|
86 |
+
image_data = response.content
|
87 |
+
pil_image = Image.open(BytesIO(image_data)).convert('RGB')
|
88 |
+
# base64
|
89 |
+
elif input_data.startswith("data:image/"):
|
90 |
+
base64_data = input_data.split(",")[1]
|
91 |
+
image_data = base64.b64decode(base64_data)
|
92 |
+
pil_image = Image.open(BytesIO(image_data)).convert('RGB')
|
93 |
+
# img_path
|
94 |
+
else:
|
95 |
+
pil_image = Image.open(input_data)
|
96 |
+
# PIL
|
97 |
+
elif isinstance(input_data, Image.Image):
|
98 |
+
pil_image = input_data
|
99 |
+
else:
|
100 |
+
raise ValueError("data type error")
|
101 |
+
|
102 |
+
return pil_image
|
103 |
+
|
104 |
+
# 历史消息处理
|
105 |
+
def process_history_and_images(messages: List[ChatMessageInput]) -> Tuple[
|
106 |
+
Optional[str], Optional[List[Tuple[str, str]]], Optional[List[Image.Image]]]:
|
107 |
+
formatted_history = []
|
108 |
+
image_list = []
|
109 |
+
last_user_query = ''
|
110 |
+
|
111 |
+
for i, message in enumerate(messages):
|
112 |
+
role = message.role
|
113 |
+
content = message.content
|
114 |
+
|
115 |
+
if isinstance(content, list): # text
|
116 |
+
text_content = ' '.join(item.text for item in content if isinstance(item, TextContent))
|
117 |
+
else:
|
118 |
+
text_content = content
|
119 |
+
|
120 |
+
if isinstance(content, list): # image
|
121 |
+
for item in content:
|
122 |
+
if isinstance(item, ImageUrlContent):
|
123 |
+
image_url = item.image_url.url
|
124 |
+
image = process_img(image_url)
|
125 |
+
image_list.append(image)
|
126 |
+
|
127 |
+
if role == 'user':
|
128 |
+
if i == len(messages) - 1: # last message
|
129 |
+
last_user_query = text_content
|
130 |
+
else:
|
131 |
+
formatted_history.append((text_content, ''))
|
132 |
+
elif role == 'assistant':
|
133 |
+
if formatted_history:
|
134 |
+
if formatted_history[-1][1] != '':
|
135 |
+
assert False, f"the last query is answered. answer again. {formatted_history[-1][0]}, {formatted_history[-1][1]}, {text_content}"
|
136 |
+
formatted_history[-1] = (formatted_history[-1][0], text_content)
|
137 |
+
else:
|
138 |
+
assert False, f"assistant reply before user"
|
139 |
+
else:
|
140 |
+
assert False, f"unrecognized role: {role}"
|
141 |
+
|
142 |
+
return last_user_query, formatted_history, image_list
|
143 |
+
|
144 |
+
@torch.inference_mode()
|
145 |
+
# Moondrean推理
|
146 |
+
def generate_stream_moondream(params: dict):
|
147 |
+
global model, tokenizer
|
148 |
+
|
149 |
+
# 输入处理
|
150 |
+
def chat_history_to_prompt(history):
|
151 |
+
prompt = ""
|
152 |
+
for i, (old_query, response) in enumerate(history):
|
153 |
+
prompt += f"Question: {old_query}\n\nAnswer: {response}\n\n"
|
154 |
+
return prompt
|
155 |
+
|
156 |
+
messages = params["messages"]
|
157 |
+
prompt, formatted_history, image_list = process_history_and_images(messages)
|
158 |
+
history = chat_history_to_prompt(formatted_history)
|
159 |
+
# 只处理最后一张图
|
160 |
+
img = image_list[-1]
|
161 |
+
|
162 |
+
# 构建输入
|
163 |
+
'''
|
164 |
+
answer_question(
|
165 |
+
self,
|
166 |
+
image_embeds,
|
167 |
+
question,
|
168 |
+
tokenizer,
|
169 |
+
chat_history="",
|
170 |
+
result_queue=None,
|
171 |
+
**kwargs,
|
172 |
+
)
|
173 |
+
'''
|
174 |
+
image_embeds = model.encode_image(img)
|
175 |
+
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
|
176 |
+
gen_kwargs = {
|
177 |
+
"image_embeds": image_embeds,
|
178 |
+
"question": prompt,
|
179 |
+
"tokenizer": tokenizer,
|
180 |
+
"chat_history": history,
|
181 |
+
"result_queue": None,
|
182 |
+
"streamer": streamer,
|
183 |
+
}
|
184 |
+
|
185 |
+
thread = Thread(
|
186 |
+
target=model.answer_question,
|
187 |
+
kwargs=gen_kwargs,
|
188 |
+
)
|
189 |
+
|
190 |
+
input_echo_len = 0
|
191 |
+
total_len = 0
|
192 |
+
# 启动推理
|
193 |
+
thread.start()
|
194 |
+
buffer = ""
|
195 |
+
for new_text in streamer:
|
196 |
+
clean_text = re.sub("<$|END$", "", new_text)
|
197 |
+
buffer += clean_text
|
198 |
+
yield {
|
199 |
+
"text": buffer.strip("<END"),
|
200 |
+
"usage": {
|
201 |
+
"prompt_tokens": input_echo_len,
|
202 |
+
"completion_tokens": total_len - input_echo_len,
|
203 |
+
"total_tokens": total_len,
|
204 |
+
},
|
205 |
+
}
|
206 |
+
generated_ret ={
|
207 |
+
"text": buffer.strip("<END"),
|
208 |
+
"usage": {
|
209 |
+
"prompt_tokens": input_echo_len,
|
210 |
+
"completion_tokens": total_len - input_echo_len,
|
211 |
+
"total_tokens": total_len,
|
212 |
+
},
|
213 |
+
}
|
214 |
+
yield generated_ret
|
215 |
+
|
216 |
+
# Moondrean单次响应
|
217 |
+
def generate_moondream(params: dict):
|
218 |
+
for response in generate_stream_moondream(params):
|
219 |
+
pass
|
220 |
+
return response
|
221 |
+
|
222 |
+
|
223 |
+
@torch.inference_mode()
|
224 |
+
# CogVLM推理
|
225 |
+
def generate_stream_cogvlm(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, params: dict):
|
226 |
+
"""
|
227 |
+
Generates a stream of responses using the CogVLM model in inference mode.
|
228 |
+
It's optimized to handle continuous input-output interactions with the model in a streaming manner.
|
229 |
+
"""
|
230 |
+
messages = params["messages"]
|
231 |
+
temperature = float(params.get("temperature", 1.0))
|
232 |
+
repetition_penalty = float(params.get("repetition_penalty", 1.0))
|
233 |
+
top_p = float(params.get("top_p", 1.0))
|
234 |
+
max_new_tokens = int(params.get("max_tokens", 256))
|
235 |
+
query, history, image_list = process_history_and_images(messages)
|
236 |
+
|
237 |
+
logger.debug(f"==== request ====\n{query}")
|
238 |
+
|
239 |
+
# only can slove the latest picture
|
240 |
+
input_by_model = model.build_conversation_input_ids(tokenizer, query=query, history=history,
|
241 |
+
images=[image_list[-1]])
|
242 |
+
inputs = {
|
243 |
+
'input_ids': input_by_model['input_ids'].unsqueeze(0).to(DEVICE),
|
244 |
+
'token_type_ids': input_by_model['token_type_ids'].unsqueeze(0).to(DEVICE),
|
245 |
+
'attention_mask': input_by_model['attention_mask'].unsqueeze(0).to(DEVICE),
|
246 |
+
'images': [[input_by_model['images'][0].to(DEVICE).to(torch_type)]],
|
247 |
+
}
|
248 |
+
if 'cross_images' in input_by_model and input_by_model['cross_images']:
|
249 |
+
inputs['cross_images'] = [[input_by_model['cross_images'][0].to(DEVICE).to(torch_type)]]
|
250 |
+
|
251 |
+
input_echo_len = len(inputs["input_ids"][0])
|
252 |
+
streamer = TextIteratorStreamer(tokenizer=tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
253 |
+
gen_kwargs = {
|
254 |
+
"repetition_penalty": repetition_penalty,
|
255 |
+
"max_new_tokens": max_new_tokens,
|
256 |
+
"do_sample": False,
|
257 |
+
"top_p": top_p,
|
258 |
+
'streamer': streamer,
|
259 |
+
}
|
260 |
+
if temperature > 1e-5:
|
261 |
+
gen_kwargs["temperature"] = temperature
|
262 |
+
|
263 |
+
total_len = 0
|
264 |
+
generated_text = ""
|
265 |
+
with torch.no_grad():
|
266 |
+
model.generate(**inputs, **gen_kwargs)
|
267 |
+
for next_text in streamer:
|
268 |
+
generated_text += next_text
|
269 |
+
yield {
|
270 |
+
"text": generated_text,
|
271 |
+
"usage": {
|
272 |
+
"prompt_tokens": input_echo_len,
|
273 |
+
"completion_tokens": total_len - input_echo_len,
|
274 |
+
"total_tokens": total_len,
|
275 |
+
},
|
276 |
+
}
|
277 |
+
ret = {
|
278 |
+
"text": generated_text,
|
279 |
+
"usage": {
|
280 |
+
"prompt_tokens": input_echo_len,
|
281 |
+
"completion_tokens": total_len - input_echo_len,
|
282 |
+
"total_tokens": total_len,
|
283 |
+
},
|
284 |
+
}
|
285 |
+
yield ret
|
286 |
+
|
287 |
+
# CogVLM单次响应
|
288 |
+
def generate_cogvlm(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, params: dict):
|
289 |
+
|
290 |
+
for response in generate_stream_cogvlm(model, tokenizer, params):
|
291 |
+
pass
|
292 |
+
return response
|
293 |
+
|
294 |
+
def generate_minicpm(model, params):
|
295 |
+
messages = params["messages"]
|
296 |
+
query, history, image_list = process_history_and_images(messages)
|
297 |
+
msgs = history
|
298 |
+
msgs.append({'role': 'user', 'content': query})
|
299 |
+
image = image_list[-1]
|
300 |
+
# image is a PIL image
|
301 |
+
buffer = BytesIO()
|
302 |
+
image.save(buffer, format="JPEG") # You can adjust the format as needed
|
303 |
+
buffer.seek(0)
|
304 |
+
image_base64 = base64.b64encode(buffer.read())
|
305 |
+
image_base64_str = image_base64.decode("utf-8")
|
306 |
+
input = {'image': image_base64_str, 'question': json.dumps(msgs)}
|
307 |
+
generation = model.chat(input)
|
308 |
+
response = {"text": generation, "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}}
|
309 |
+
print(response)
|
310 |
+
return response
|
311 |
+
|
312 |
+
# 流式响应
|
313 |
+
async def predict(model_id: str, params: dict):
|
314 |
+
return "no stream"
|
315 |
+
|
316 |
+
torch.set_grad_enabled(False)
|
317 |
+
# 生命周期管理器,结束清显存
|
318 |
+
@asynccontextmanager
|
319 |
+
async def lifespan(app: FastAPI):
|
320 |
+
yield
|
321 |
+
if torch.cuda.is_available():
|
322 |
+
torch.cuda.empty_cache()
|
323 |
+
torch.cuda.ipc_collect()
|
324 |
+
app = FastAPI(lifespan=lifespan)
|
325 |
+
# 允许跨域
|
326 |
+
app.add_middleware(
|
327 |
+
CORSMiddleware,
|
328 |
+
allow_origins=["*"],
|
329 |
+
allow_credentials=True,
|
330 |
+
allow_methods=["*"],
|
331 |
+
allow_headers=["*"],
|
332 |
+
)
|
333 |
+
|
334 |
+
# 对话路由
|
335 |
+
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
|
336 |
+
async def create_chat_completion(request: ChatCompletionRequest):
|
337 |
+
global model, tokenizer
|
338 |
+
|
339 |
+
# 检查请求
|
340 |
+
if len(request.messages) < 1 or request.messages[-1].role == "assistant":
|
341 |
+
raise HTTPException(status_code=400, detail="Invalid request")
|
342 |
+
|
343 |
+
gen_params = dict(
|
344 |
+
messages=request.messages,
|
345 |
+
temperature=request.temperature,
|
346 |
+
top_p=request.top_p,
|
347 |
+
max_tokens=request.max_tokens or 1024,
|
348 |
+
echo=False,
|
349 |
+
stream=request.stream,
|
350 |
+
)
|
351 |
+
|
352 |
+
# 流式响应
|
353 |
+
if request.stream:
|
354 |
+
generate = predict(request.model, gen_params)
|
355 |
+
return
|
356 |
+
|
357 |
+
# 单次响应
|
358 |
+
if STATE_MOD == "cog":
|
359 |
+
response = generate_cogvlm(model, tokenizer, gen_params)
|
360 |
+
elif STATE_MOD == "moon":
|
361 |
+
response = generate_moondream(gen_params)
|
362 |
+
elif STATE_MOD == "mini":
|
363 |
+
response = generate_minicpm(model, gen_params)
|
364 |
+
usage = UsageInfo()
|
365 |
+
message = ChatMessageResponse(
|
366 |
+
role="assistant",
|
367 |
+
content=response["text"],
|
368 |
+
)
|
369 |
+
logger.debug(f"==== message ====\n{message}")
|
370 |
+
choice_data = ChatCompletionResponseChoice(
|
371 |
+
index=0,
|
372 |
+
message=message,
|
373 |
+
)
|
374 |
+
task_usage = UsageInfo.model_validate(response["usage"])
|
375 |
+
for usage_key, usage_value in task_usage.model_dump().items():
|
376 |
+
setattr(usage, usage_key, getattr(usage, usage_key) + usage_value)
|
377 |
+
return ChatCompletionResponse(model=request.model, choices=[choice_data], object="chat.completion", usage=usage)
|
378 |
+
|
379 |
+
# 模型切换路由配置
|
380 |
+
STATE_MOD = "moon"
|
381 |
+
MODEL_PATH = ""
|
382 |
+
|
383 |
+
# 模型加载
|
384 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
385 |
+
def load_mod(model_input, mod_type):
|
386 |
+
global model, tokenizer, language_processor_version
|
387 |
+
if mod_type == "cog":
|
388 |
+
tokenizer_path = os.environ.get("TOKENIZER_PATH", 'lmsys/vicuna-7b-v1.5')
|
389 |
+
tokenizer = LlamaTokenizer.from_pretrained(
|
390 |
+
tokenizer_path,
|
391 |
+
trust_remote_code=True,
|
392 |
+
signal_type=language_processor_version
|
393 |
+
)
|
394 |
+
if 'cuda' in DEVICE:
|
395 |
+
model = AutoModelForCausalLM.from_pretrained(
|
396 |
+
model_input,
|
397 |
+
trust_remote_code=True,
|
398 |
+
load_in_4bit=True,
|
399 |
+
torch_dtype=torch_type,
|
400 |
+
low_cpu_mem_usage=True
|
401 |
+
).eval()
|
402 |
+
else:
|
403 |
+
model = AutoModelForCausalLM.from_pretrained(
|
404 |
+
model_input,
|
405 |
+
trust_remote_code=True
|
406 |
+
).float().to(DEVICE).eval()
|
407 |
+
elif mod_type == "moon":
|
408 |
+
device, dtype = detect_device()
|
409 |
+
model = Moondream.from_pretrained(model_input).to(device=device, dtype=dtype).eval()
|
410 |
+
tokenizer = Tokenizer.from_pretrained(model_input)
|
411 |
+
elif mod_type == "mini":
|
412 |
+
model, tokenizer = omnichat.OmniLMMChat(model_input), None
|
413 |
+
|
414 |
+
@app.post("/v1/Cog-vqa")
|
415 |
+
async def switch_vqa():
|
416 |
+
global model, STATE_MOD, mod_vqa, language_processor_version
|
417 |
+
STATE_MOD = "cog"
|
418 |
+
del model
|
419 |
+
model = None
|
420 |
+
language_processor_version = "chat_old"
|
421 |
+
load_mod(mod_vqa, STATE_MOD)
|
422 |
+
|
423 |
+
@app.post("/v1/Cog-chat")
|
424 |
+
async def switch_chat():
|
425 |
+
global model, STATE_MOD, mod_chat, language_processor_version
|
426 |
+
STATE_MOD = "cog"
|
427 |
+
del model
|
428 |
+
model = None
|
429 |
+
language_processor_version = "chat"
|
430 |
+
load_mod(mod_chat, STATE_MOD)
|
431 |
+
|
432 |
+
@app.post("/v1/moondream")
|
433 |
+
async def switch_moon():
|
434 |
+
global model, STATE_MOD, mod_moon
|
435 |
+
STATE_MOD = "moon"
|
436 |
+
del model
|
437 |
+
model = None
|
438 |
+
load_mod(mod_moon, STATE_MOD)
|
439 |
+
|
440 |
+
@app.post("/v1/MiniCPM")
|
441 |
+
async def switch_mini():
|
442 |
+
global model, STATE_MOD, mod_mini
|
443 |
+
STATE_MOD = "mini"
|
444 |
+
del model
|
445 |
+
model = None
|
446 |
+
load_mod(mod_mini, STATE_MOD)
|
447 |
+
|
448 |
+
# 关闭
|
449 |
+
@app.post("/v1/close")
|
450 |
+
async def close():
|
451 |
+
global model
|
452 |
+
del model
|
453 |
+
model = None
|
454 |
+
|
455 |
+
gc.collect()
|
456 |
+
|
457 |
+
parser = argparse.ArgumentParser()
|
458 |
+
parser.add_argument("--mod", type=str, default="moondrean")
|
459 |
+
args = parser.parse_args()
|
460 |
+
mod = args.mod
|
461 |
+
|
462 |
+
mod_vqa = './models/cogagent-vqa-hf'
|
463 |
+
mod_chat = './models/cogagent-chat-hf'
|
464 |
+
mod_moon = './models/moondream'
|
465 |
+
mod_mini = './models/MiniCPM-Llama3-V-2_5'
|
466 |
+
|
467 |
+
'''
|
468 |
+
mod_list = [
|
469 |
+
"moondrean",
|
470 |
+
"Cog-vqa",
|
471 |
+
"Cog-chat"
|
472 |
+
"MiniCPM"
|
473 |
+
]
|
474 |
+
'''
|
475 |
+
|
476 |
+
if mod == "Cog-vqa":
|
477 |
+
STATE_MOD = "cog"
|
478 |
+
MODEL_PATH = mod_vqa
|
479 |
+
language_processor_version = "chat_old"
|
480 |
+
elif mod == "Cog-chat":
|
481 |
+
STATE_MOD = "cog"
|
482 |
+
MODEL_PATH = mod_chat
|
483 |
+
language_processor_version = "chat"
|
484 |
+
elif mod == "moondream":
|
485 |
+
STATE_MOD = "moon"
|
486 |
+
MODEL_PATH = mod_moon
|
487 |
+
elif mod == "MiniCPM":
|
488 |
+
STATE_MOD = "mini"
|
489 |
+
MODEL_PATH = mod_mini
|
490 |
+
|
491 |
+
if __name__ == "__main__":
|
492 |
+
if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8:
|
493 |
+
torch_type = torch.bfloat16
|
494 |
+
else:
|
495 |
+
torch_type = torch.float16
|
496 |
+
|
497 |
+
print("========Use torch type as:{} with device:{}========\n\n".format(torch_type, DEVICE))
|
498 |
+
|
499 |
+
load_mod(MODEL_PATH, STATE_MOD)
|
500 |
+
|
501 |
+
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
|
start_linux_mac.sh
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
export HF_HOME="huggingface"
|
3 |
+
|
4 |
+
python ./install_script/check_open.py
|
5 |
+
|
6 |
+
python gpt-caption.py --share "$@"
|
7 |
+
|
8 |
+
read -p "Press any key to continue . . . "
|
start_windows.bat
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
set HF_HOME=huggingface
|
3 |
+
|
4 |
+
call myenv\Scripts\activate
|
5 |
+
python ./install_script/check_open.py
|
6 |
+
|
7 |
+
python gpt-caption.py %*
|
8 |
+
|
9 |
+
pause
|
utils/__init__.py
ADDED
File without changes
|
utils/merge_model.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- encoding: utf-8 -*-
|
2 |
+
import os, sys
|
3 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import argparse
|
7 |
+
from models.cogvlm_model import FineTuneTestCogVLMModel
|
8 |
+
from sat.training.model_io import save_checkpoint
|
9 |
+
|
10 |
+
def main():
|
11 |
+
parser = argparse.ArgumentParser()
|
12 |
+
parser.add_argument("--version", type=str, default="base", help='version to interact with')
|
13 |
+
parser.add_argument("--from_pretrained", type=str, default="checkpoints/merged_lora", help='pretrained ckpt')
|
14 |
+
parser.add_argument("--fp16", action="store_true")
|
15 |
+
parser.add_argument("--bf16", action="store_true")
|
16 |
+
args = parser.parse_args()
|
17 |
+
rank = int(os.environ.get('RANK', 0))
|
18 |
+
world_size = int(os.environ.get('WORLD_SIZE', 1))
|
19 |
+
parser = FineTuneTestCogVLMModel.add_model_specific_args(parser)
|
20 |
+
args = parser.parse_args()
|
21 |
+
|
22 |
+
# load model
|
23 |
+
model, model_args = FineTuneTestCogVLMModel.from_pretrained(
|
24 |
+
args.from_pretrained,
|
25 |
+
args=argparse.Namespace(
|
26 |
+
deepspeed=None,
|
27 |
+
local_rank=rank,
|
28 |
+
rank=rank,
|
29 |
+
world_size=world_size,
|
30 |
+
model_parallel_size=world_size,
|
31 |
+
mode='inference',
|
32 |
+
skip_init=True,
|
33 |
+
use_gpu_initialization=True if torch.cuda.is_available() else False,
|
34 |
+
device='cuda',
|
35 |
+
**vars(args)
|
36 |
+
), url='local', overwrite_args={'model_parallel_size': 1})
|
37 |
+
model = model.eval()
|
38 |
+
model_args.save = './checkpoints/merged_model_{}'.format(model_args.eva_args["image_size"][0])
|
39 |
+
save_checkpoint(1, model, None, None, model_args)
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
main()
|
utils/split_dataset.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
|
4 |
+
def find_all_files(path, suffix=".jpg"):
|
5 |
+
target_files = []
|
6 |
+
for cur_dir, _, files in os.walk(path, followlinks=True):
|
7 |
+
for f in files:
|
8 |
+
if f.endswith(suffix):
|
9 |
+
target_files.append(os.path.join(cur_dir, f))
|
10 |
+
print(f'find {len(target_files)} files...')
|
11 |
+
return target_files
|
12 |
+
|
13 |
+
all_files = find_all_files('archive')
|
14 |
+
os.makedirs("archive_split", exist_ok=True)
|
15 |
+
os.makedirs("archive_split/train", exist_ok=True)
|
16 |
+
os.makedirs("archive_split/valid", exist_ok=True)
|
17 |
+
os.makedirs("archive_split/test", exist_ok=True)
|
18 |
+
|
19 |
+
import random
|
20 |
+
random.seed(2023)
|
21 |
+
random.shuffle(all_files)
|
22 |
+
train = all_files[:8000]
|
23 |
+
valid = all_files[8000:8000+500]
|
24 |
+
test = all_files[8000+500:8000+500+1500]
|
25 |
+
|
26 |
+
print("building train")
|
27 |
+
for file in train:
|
28 |
+
shutil.move(file, os.path.join("archive_split/train", file.split("/")[-1]))
|
29 |
+
print("building valid")
|
30 |
+
for file in valid:
|
31 |
+
shutil.move(file, os.path.join("archive_split/valid", file.split("/")[-1]))
|
32 |
+
print("building test")
|
33 |
+
for file in test:
|
34 |
+
shutil.move(file, os.path.join("archive_split/test", file.split("/")[-1]))
|
35 |
+
print("done")
|
utils/utils/__init__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .chat import chat
|
2 |
+
from .language import llama2_tokenizer, llama2_text_processor, llama2_text_processor_inference
|
3 |
+
from .vision import get_image_processor
|
4 |
+
from .grounding_parser import parse_response
|
5 |
+
from .dataset import ItemDataset
|
utils/utils/chat.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- encoding: utf-8 -*-
|
2 |
+
'''
|
3 |
+
@File : chat.py
|
4 |
+
@Time : 2023/05/08 19:10:08
|
5 |
+
@Author : Ming Ding
|
6 |
+
@Contact : dm18@mails.tsinghua.edu.cn
|
7 |
+
'''
|
8 |
+
|
9 |
+
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
10 |
+
import requests
|
11 |
+
from PIL import Image
|
12 |
+
from io import BytesIO
|
13 |
+
|
14 |
+
import torch
|
15 |
+
from sat.generation.autoregressive_sampling import filling_sequence, stream_filling_sequence, get_masks_and_position_ids_default
|
16 |
+
from sat.generation.sampling_strategies import BaseStrategy, BeamSearchStrategy
|
17 |
+
from sat.mpu import get_model_parallel_rank
|
18 |
+
|
19 |
+
def process_image(image_path, img_processor, cross_img_processor, image):
|
20 |
+
if image is None:
|
21 |
+
if image_path.startswith("http"):
|
22 |
+
response = requests.get(image_path, timeout=10)
|
23 |
+
image = Image.open(BytesIO(response.content))
|
24 |
+
else:
|
25 |
+
image = Image.open(image_path)
|
26 |
+
|
27 |
+
if image is not None and isinstance(image, Image.Image):
|
28 |
+
pil_img = image.convert('RGB')
|
29 |
+
img_dict = img_processor(pil_img)
|
30 |
+
cross_img_dict = cross_img_processor(pil_img) if cross_img_processor is not None else {}
|
31 |
+
ret = (img_dict, pil_img, cross_img_dict)
|
32 |
+
else:
|
33 |
+
ret = image
|
34 |
+
return ret
|
35 |
+
|
36 |
+
def chat(image_path, model, text_processor, img_processor,
|
37 |
+
query: str, history: List[Tuple[str, str]] = None, cross_img_processor=None, image: Image = None,
|
38 |
+
max_length: int = 4096, top_p=0.95, top_k=5, temperature=0.95, repetition_penalty=1.0,
|
39 |
+
invalid_slices=[], no_prompt=False, args=None
|
40 |
+
):
|
41 |
+
if image is None:
|
42 |
+
assert image_path is not None
|
43 |
+
if not history:
|
44 |
+
history = []
|
45 |
+
|
46 |
+
if no_prompt:
|
47 |
+
query = ''
|
48 |
+
prompt = text_processor.history_to_prompt(query, history)
|
49 |
+
|
50 |
+
(torch_image, pil_img, cross_image) = process_image(image_path, img_processor, cross_img_processor, image)
|
51 |
+
|
52 |
+
if torch_image is not None:
|
53 |
+
for k in torch_image:
|
54 |
+
if type(torch_image[k]) is torch.Tensor and torch_image[k].dtype is not torch.int and torch_image[k].dtype is not torch.long:
|
55 |
+
torch_image[k] = torch_image[k].to(torch.bfloat16 if args.bf16 else torch.float16)
|
56 |
+
if type(torch_image[k]) is torch.Tensor:
|
57 |
+
torch_image[k] = torch_image[k].to(next(model.parameters()).device)
|
58 |
+
|
59 |
+
if cross_image is not None:
|
60 |
+
for k in cross_image:
|
61 |
+
if type(cross_image[k]) is torch.Tensor and cross_image[k].dtype is not torch.int and cross_image[k].dtype is not torch.long:
|
62 |
+
cross_image[k] = cross_image[k].to(torch.bfloat16 if args.bf16 else torch.float16)
|
63 |
+
if type(cross_image[k]) is torch.Tensor:
|
64 |
+
cross_image[k] = cross_image[k].to(next(model.parameters()).device)
|
65 |
+
|
66 |
+
inputs_dic = text_processor(prompt)
|
67 |
+
for k in inputs_dic:
|
68 |
+
if type(inputs_dic[k]) is torch.Tensor and inputs_dic[k].dtype is not torch.int and inputs_dic[k].dtype is not torch.long:
|
69 |
+
inputs_dic[k] = inputs_dic[k].to(torch.bfloat16 if args.bf16 else torch.float16)
|
70 |
+
if type(inputs_dic[k]) is torch.Tensor:
|
71 |
+
inputs_dic[k] = inputs_dic[k].to(next(model.parameters()).device)
|
72 |
+
input_ids = inputs_dic['input_ids'].to(model.parameters().__next__().device)[0]
|
73 |
+
|
74 |
+
if max_length-len(input_ids) <= 1:
|
75 |
+
response = "The prompt exceeds the context length limit, please try again."
|
76 |
+
return response, history, (torch_image, pil_img)
|
77 |
+
|
78 |
+
seq = torch.cat(
|
79 |
+
[input_ids, torch.tensor([-1]*(max_length-len(input_ids)), device=input_ids.device)], dim=0
|
80 |
+
)
|
81 |
+
strategy = BaseStrategy(temperature=temperature, top_p=top_p, top_k=top_k, end_tokens=[text_processor.tokenizer.eos_token_id],
|
82 |
+
invalid_slices=invalid_slices, repetition_penalty=repetition_penalty)
|
83 |
+
# use beam search to get a better result
|
84 |
+
# strategy = BeamSearchStrategy(temperature=temperature, top_p=top_p, top_k=top_k, end_tokens=[text_processor.tokenizer.eos_token_id],
|
85 |
+
# num_beams=5, consider_end=True, repetition_penalty=repetition_penalty)
|
86 |
+
get_func = text_processor.get_func(input_ids, **inputs_dic) if hasattr(text_processor, 'get_func') else get_masks_and_position_ids_default
|
87 |
+
|
88 |
+
img_inputs = {'vision_'+k: v for k, v in torch_image.items()}
|
89 |
+
if cross_image is not None:
|
90 |
+
img_inputs = {**img_inputs, **{'cross_'+k:v for k,v in cross_image.items()}}
|
91 |
+
inputs_dic.pop('input_ids')
|
92 |
+
inputs = {**img_inputs, **inputs_dic}
|
93 |
+
|
94 |
+
if args.stream_chat:
|
95 |
+
filling_stream = stream_filling_sequence(
|
96 |
+
model, seq,
|
97 |
+
batch_size=1,
|
98 |
+
get_masks_and_position_ids=get_func,
|
99 |
+
strategy=strategy,
|
100 |
+
**inputs
|
101 |
+
)
|
102 |
+
if get_model_parallel_rank() == 0:
|
103 |
+
if 'chinese' in args and not args.chinese:
|
104 |
+
print("Model: ", end='')
|
105 |
+
else:
|
106 |
+
print("模型��", end='')
|
107 |
+
offset = len(text_processor.tokenizer.decode(input_ids))
|
108 |
+
for tokens, mems in filling_stream:
|
109 |
+
torch.cuda.empty_cache()
|
110 |
+
tmp_response = text_processor.tokenizer.decode(tokens[0])
|
111 |
+
if tmp_response[-1] != "�":
|
112 |
+
if get_model_parallel_rank() == 0:
|
113 |
+
tmp_response_offseted = tmp_response[offset:]
|
114 |
+
if hasattr(text_processor, 'process_response'):
|
115 |
+
tmp_response_offseted = text_processor.process_response(tmp_response_offseted)
|
116 |
+
print(tmp_response_offseted, end='', flush=True)
|
117 |
+
offset = len(tmp_response)
|
118 |
+
if get_model_parallel_rank() == 0:
|
119 |
+
print()
|
120 |
+
output = strategy.finalize(tokens, mems)[0]
|
121 |
+
|
122 |
+
response = text_processor.tokenizer.decode(output[0])
|
123 |
+
else:
|
124 |
+
output = filling_sequence(
|
125 |
+
model, seq,
|
126 |
+
batch_size=1,
|
127 |
+
get_masks_and_position_ids=get_func,
|
128 |
+
strategy=strategy,
|
129 |
+
**inputs
|
130 |
+
)[0] # drop memory
|
131 |
+
|
132 |
+
# ---------------
|
133 |
+
# port from inference_glm.py, more general than chat mode
|
134 |
+
# clip -1s and fill back generated things into seq
|
135 |
+
if type(output) is not list:
|
136 |
+
output_list = output.tolist()
|
137 |
+
else:
|
138 |
+
output_list = output
|
139 |
+
|
140 |
+
response = text_processor.tokenizer.decode(output_list[0])
|
141 |
+
# print('original:', response)
|
142 |
+
if hasattr(text_processor, 'process_response'):
|
143 |
+
response = text_processor.process_response(response)
|
144 |
+
response = response.split(text_processor.sep)[-1].strip()
|
145 |
+
if get_model_parallel_rank() == 0:
|
146 |
+
from utils.utils.grounding_parser import parse_response
|
147 |
+
parse_response(pil_img, response)
|
148 |
+
history = history + [(query, response)]
|
149 |
+
return response, history, (torch_image, pil_img, cross_image)
|
utils/utils/dataset.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
import random
|
4 |
+
import logging
|
5 |
+
import jsonlines
|
6 |
+
from io import BytesIO
|
7 |
+
from PIL import Image
|
8 |
+
from torch.utils.data import Dataset
|
9 |
+
from sat.helpers import print_rank0
|
10 |
+
|
11 |
+
def find_all_files(path, suffix=".jpg"):
|
12 |
+
target_files = []
|
13 |
+
for cur_dir, _, files in os.walk(path, followlinks=True):
|
14 |
+
for f in files:
|
15 |
+
if f.endswith(suffix):
|
16 |
+
target_files.append(os.path.join(cur_dir, f))
|
17 |
+
print_rank0(f'find {len(target_files)} files...')
|
18 |
+
return target_files
|
19 |
+
|
20 |
+
class ItemDataset(Dataset):
|
21 |
+
def __init__(self, image_processor, text_processor, args, data_dirs, cross_image_processor=None, **kwargs):
|
22 |
+
super().__init__()
|
23 |
+
self.data = self.load_data(data_dirs)
|
24 |
+
self.image_processor, self.text_processor, self.cross_image_processor = image_processor, text_processor, cross_image_processor
|
25 |
+
|
26 |
+
def process_img(self, img):
|
27 |
+
img_dict = {'vision': self.image_processor(img)}
|
28 |
+
if self.cross_image_processor:
|
29 |
+
img_dict.update({'cross': self.cross_image_processor(img)})
|
30 |
+
return img_dict
|
31 |
+
|
32 |
+
def process_text(self, answer, prompt):
|
33 |
+
return self.text_processor(answer, prompt)
|
34 |
+
|
35 |
+
def load_data(self, data_dir):
|
36 |
+
all_files = find_all_files(data_dir, suffix=".jpg")
|
37 |
+
print_rank0(f"find {len(all_files)} samples in all...")
|
38 |
+
return all_files
|
39 |
+
|
40 |
+
def __len__(self):
|
41 |
+
return len(self.data)
|
42 |
+
|
43 |
+
def __getitem__(self, index):
|
44 |
+
data = self.data[index]
|
45 |
+
# img
|
46 |
+
try:
|
47 |
+
img = Image.open(data).convert('RGB')
|
48 |
+
except Exception as e:
|
49 |
+
print_rank0(e, level=logging.WARNING)
|
50 |
+
return {}
|
51 |
+
img_dict = self.process_img(img)
|
52 |
+
# text
|
53 |
+
label = data.split('/')[-1].split('.')[0]
|
54 |
+
uni_key = label
|
55 |
+
text_dict = self.process_text(label, "CAPTCHA:")
|
56 |
+
if text_dict is None:
|
57 |
+
print_rank0(f"Process text failed. Please check the max_target_length & max_source_length.\n The data is {data}", level=logging.WARNING)
|
58 |
+
return {}
|
59 |
+
# other attr
|
60 |
+
ret = {**img_dict, **text_dict, "question_id": uni_key}
|
61 |
+
return ret
|
utils/utils/grounding_parser.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import seaborn as sns
|
2 |
+
from PIL import Image, ImageDraw, ImageFont
|
3 |
+
import matplotlib.font_manager
|
4 |
+
import spacy
|
5 |
+
import re
|
6 |
+
|
7 |
+
nlp = spacy.load("en_core_web_sm")
|
8 |
+
|
9 |
+
def draw_boxes(image, boxes, texts, output_fn='output.png'):
|
10 |
+
box_width = 5
|
11 |
+
color_palette = sns.color_palette("husl", len(boxes))
|
12 |
+
colors = [(int(r*255), int(g*255), int(b*255)) for r, g, b in color_palette]
|
13 |
+
|
14 |
+
width, height = image.size
|
15 |
+
absolute_boxes = [[(int(box[0] * width), int(box[1] * height), int(box[2] * width), int(box[3] * height)) for box in b] for b in boxes]
|
16 |
+
|
17 |
+
overlay = Image.new('RGBA', image.size, (255, 255, 255, 0))
|
18 |
+
draw = ImageDraw.Draw(overlay)
|
19 |
+
font_path = sorted(matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf'))[0]
|
20 |
+
font = ImageFont.truetype(font_path, size=26)
|
21 |
+
|
22 |
+
for box, text, color in zip(absolute_boxes, texts, colors):
|
23 |
+
for b in box:
|
24 |
+
draw.rectangle(b, outline=color, width=box_width)
|
25 |
+
if not text:
|
26 |
+
continue
|
27 |
+
splited_text = text.split('\n')
|
28 |
+
num_lines = len(splited_text)
|
29 |
+
text_width, text_height = font.getbbox(splited_text[0])[-2:]
|
30 |
+
y_start = b[3] - text_height * num_lines - box_width
|
31 |
+
if b[2] - b[0] < 100 or b[3] - b[1] < 100:
|
32 |
+
y_start = b[3]
|
33 |
+
for i, line in enumerate(splited_text):
|
34 |
+
text_width, text_height = font.getbbox(line)[-2:]
|
35 |
+
x = b[0] + box_width
|
36 |
+
y = y_start + text_height * i
|
37 |
+
draw.rectangle([x, y, x+text_width, y+text_height], fill=(128, 128, 128, 160))
|
38 |
+
draw.text((x, y), line, font=font, fill=(255, 255, 255))
|
39 |
+
img_with_overlay = Image.alpha_composite(image.convert('RGBA'), overlay).convert('RGB')
|
40 |
+
img_with_overlay.save(output_fn)
|
41 |
+
|
42 |
+
def boxstr_to_boxes(box_str):
|
43 |
+
boxes = [[int(y)/1000 for y in x.split(',')] for x in box_str.split(';') if x.replace(',', '').isdigit()]
|
44 |
+
return boxes
|
45 |
+
|
46 |
+
def text_to_dict(text):
|
47 |
+
doc = nlp(text)
|
48 |
+
|
49 |
+
box_matches = list(re.finditer(r'\[\[([^\]]+)\]\]', text))
|
50 |
+
box_positions = [match.start() for match in box_matches]
|
51 |
+
|
52 |
+
noun_phrases = []
|
53 |
+
boxes = []
|
54 |
+
|
55 |
+
for match, box_position in zip(box_matches, box_positions):
|
56 |
+
nearest_np_start = max([0] + [chunk.start_char for chunk in doc.noun_chunks if chunk.end_char <= box_position])
|
57 |
+
noun_phrase = text[nearest_np_start:box_position].strip()
|
58 |
+
if noun_phrase and noun_phrase[-1] == '?':
|
59 |
+
noun_phrase = text[:box_position].strip()
|
60 |
+
box_string = match.group(1)
|
61 |
+
|
62 |
+
noun_phrases.append(noun_phrase)
|
63 |
+
boxes.append(boxstr_to_boxes(box_string))
|
64 |
+
|
65 |
+
pairs = []
|
66 |
+
for noun_phrase, box_string in zip(noun_phrases, boxes):
|
67 |
+
pairs.append((noun_phrase.lower(), box_string))
|
68 |
+
return dict(pairs)
|
69 |
+
|
70 |
+
def parse_response(img, response, output_fn='output.png'):
|
71 |
+
img = img.convert('RGB')
|
72 |
+
width, height = img.size
|
73 |
+
ratio = min(1920 / width, 1080 / height)
|
74 |
+
new_width = int(width * ratio)
|
75 |
+
new_height = int(height * ratio)
|
76 |
+
new_img = img.resize((new_width, new_height), Image.LANCZOS)
|
77 |
+
pattern = r"\[\[(.*?)\]\]"
|
78 |
+
positions = re.findall(pattern, response)
|
79 |
+
boxes = [[[int(y) for y in x.split(',')] for x in pos.split(';') if x.replace(',', '').isdigit()] for pos in positions]
|
80 |
+
dic = text_to_dict(response)
|
81 |
+
if not dic:
|
82 |
+
texts = []
|
83 |
+
boxes = []
|
84 |
+
else:
|
85 |
+
texts, boxes = zip(*dic.items())
|
86 |
+
draw_boxes(new_img, boxes, texts, output_fn=output_fn)
|