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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from utils import divide_prompt
|
| 5 |
+
from flask import Flask, render_template, request, send_from_directory, jsonify
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# 设置图像目录路径
|
| 10 |
+
IMAGE_DIR = "../images_divided"
|
| 11 |
+
ITEMS_PER_PAGE = 1 # 每页显示的 data 项目数
|
| 12 |
+
DATA_FILE = "data/annotation.jsonl" # 保存排序结果的文件
|
| 13 |
+
PROMPT_DATA_FILE = 'data/extended_data_summary_v2.jsonl'
|
| 14 |
+
|
| 15 |
+
with open(PROMPT_DATA_FILE, 'r', encoding='utf-8') as f:
|
| 16 |
+
PROMPT_DATA = [json.loads(line) for line in f if line.strip()]
|
| 17 |
+
PROMPT_DATA = {item['idx']: item for item in PROMPT_DATA}
|
| 18 |
+
|
| 19 |
+
@app.route('/')
|
| 20 |
+
def index():
|
| 21 |
+
# 读取所有文件夹
|
| 22 |
+
folders = sorted([
|
| 23 |
+
f for f in os.listdir(IMAGE_DIR)
|
| 24 |
+
if os.path.isdir(os.path.join(IMAGE_DIR, f)) and not f.startswith('.')
|
| 25 |
+
])
|
| 26 |
+
data = []
|
| 27 |
+
|
| 28 |
+
# 加载已有的标注记录
|
| 29 |
+
existing_records = load_existing_records()
|
| 30 |
+
existing_dict = {}
|
| 31 |
+
for record in existing_records:
|
| 32 |
+
folder = record.get('folder')
|
| 33 |
+
ref_image = record.get('ref_image')
|
| 34 |
+
compare_images = tuple(sorted(record.get('compare_images', []))) # 使用排序后的元组作为键的一部分
|
| 35 |
+
key = (folder, ref_image, compare_images)
|
| 36 |
+
existing_dict[key] = {
|
| 37 |
+
'compare_images': record.get('compare_images', []),
|
| 38 |
+
'rank_images': record.get('rank_images', [])
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
for cnt, idx in enumerate(folders):
|
| 42 |
+
folder_path = os.path.join(IMAGE_DIR, idx)
|
| 43 |
+
images = sorted([img for img in os.listdir(folder_path) if img.endswith('.png')])
|
| 44 |
+
first_indices, second_indices = zip(*[
|
| 45 |
+
list(map(int, img.split('.')[0].split('_')))
|
| 46 |
+
for img in images
|
| 47 |
+
])
|
| 48 |
+
first_indices = sorted(set(first_indices))
|
| 49 |
+
second_indices = sorted(set(second_indices))
|
| 50 |
+
|
| 51 |
+
for i in first_indices:
|
| 52 |
+
for j in second_indices:
|
| 53 |
+
ref_img = f"{i}_{j}.png"
|
| 54 |
+
candidates = [
|
| 55 |
+
[
|
| 56 |
+
f"{x}_{y}.png"
|
| 57 |
+
for x in first_indices
|
| 58 |
+
]
|
| 59 |
+
for y in second_indices if y != j
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
items = [
|
| 63 |
+
{
|
| 64 |
+
'ref_image': f"/images/{idx}/{ref_img}",
|
| 65 |
+
'compare_images': [f"/images/{idx}/{cand_img}" for cand_img in cand], # 待比较的图像列表
|
| 66 |
+
'folder': idx,
|
| 67 |
+
'ref_index': (i, j),
|
| 68 |
+
'candidate_column': y,
|
| 69 |
+
'prompt': divide_prompt(PROMPT_DATA[idx]['prompt'])[0] if idx in PROMPT_DATA and 'prompt' in PROMPT_DATA[idx] else '',
|
| 70 |
+
'existing_compare_images': [], # 临时占位,后面会更新
|
| 71 |
+
'existing_rank_images': [], # 临时占位,后面会更新
|
| 72 |
+
'is_annotated': False, # 临时占位,后面会更新
|
| 73 |
+
} for y, cand in zip([y for y in second_indices if y != j], candidates)
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
# 对每个 item 检查是否已有标注
|
| 77 |
+
for item in items:
|
| 78 |
+
# 从完整路径中提取文件名
|
| 79 |
+
current_compare_images = [img.split('/')[-1] for img in item['compare_images']]
|
| 80 |
+
|
| 81 |
+
# 检查是否已有标注(使用 ref_image 和 compare_images 一起判定)
|
| 82 |
+
ref_filename = item['ref_image'].split('/')[-1]
|
| 83 |
+
lookup_key = (idx, ref_filename, tuple(sorted(current_compare_images)))
|
| 84 |
+
existing_data = existing_dict.get(lookup_key, {})
|
| 85 |
+
|
| 86 |
+
# 更新 item 的标注信息
|
| 87 |
+
item['existing_compare_images'] = existing_data.get('compare_images', [])
|
| 88 |
+
item['existing_rank_images'] = existing_data.get('rank_images', [])
|
| 89 |
+
item['is_annotated'] = len(existing_data.get('rank_images', [])) > 0
|
| 90 |
+
|
| 91 |
+
data.extend(items)
|
| 92 |
+
|
| 93 |
+
# 分页逻辑
|
| 94 |
+
page = int(request.args.get('page', 1))
|
| 95 |
+
start = (page - 1) * ITEMS_PER_PAGE
|
| 96 |
+
end = start + ITEMS_PER_PAGE
|
| 97 |
+
paginated_data = data[start:end]
|
| 98 |
+
|
| 99 |
+
return render_template(
|
| 100 |
+
'index.html',
|
| 101 |
+
data=paginated_data,
|
| 102 |
+
page=page,
|
| 103 |
+
total_pages=(len(data) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
@app.route('/sort', methods=['POST'])
|
| 107 |
+
def sort_images():
|
| 108 |
+
try:
|
| 109 |
+
# 获取排序后的数据
|
| 110 |
+
sorted_images = request.form.getlist('sorted_images')
|
| 111 |
+
|
| 112 |
+
if not sorted_images:
|
| 113 |
+
return jsonify({'status': 'error', 'message': '没有排序数据'}), 400
|
| 114 |
+
|
| 115 |
+
# 解析排序数据
|
| 116 |
+
ranking = []
|
| 117 |
+
for item in sorted_images:
|
| 118 |
+
rank, image_path = item.split(':', 1)
|
| 119 |
+
ranking.append({
|
| 120 |
+
'rank': int(rank),
|
| 121 |
+
'image_path': image_path
|
| 122 |
+
})
|
| 123 |
+
|
| 124 |
+
# 排序以确保顺序正确
|
| 125 |
+
ranking.sort(key=lambda x: x['rank'])
|
| 126 |
+
|
| 127 |
+
# 提取有用信息
|
| 128 |
+
if ranking:
|
| 129 |
+
first_image = ranking[0]['image_path']
|
| 130 |
+
parts = first_image.split('/')
|
| 131 |
+
folder = parts[2] # folder_name
|
| 132 |
+
|
| 133 |
+
# 获取参考图像信息(从表单中)
|
| 134 |
+
ref_image = request.form.get('ref_image', '')
|
| 135 |
+
|
| 136 |
+
# 解析参考图像文件名
|
| 137 |
+
ref_filename = ref_image.split('/')[-1] # x_y.png
|
| 138 |
+
|
| 139 |
+
# 获取原始的 compare_images(所有候选图像的原始顺序)
|
| 140 |
+
all_compare_images = request.form.get('all_compare_images', '')
|
| 141 |
+
if all_compare_images:
|
| 142 |
+
all_compare_images = json.loads(all_compare_images)
|
| 143 |
+
else:
|
| 144 |
+
all_compare_images = []
|
| 145 |
+
|
| 146 |
+
# 解析排序图像的文件名 - 这是用户的排序结果
|
| 147 |
+
ranked_filenames = []
|
| 148 |
+
for item in ranking:
|
| 149 |
+
filename = item['image_path'].split('/')[-1]
|
| 150 |
+
ranked_filenames.append(filename)
|
| 151 |
+
|
| 152 |
+
# 创建唯一的数据记录
|
| 153 |
+
record = {
|
| 154 |
+
'folder': folder,
|
| 155 |
+
'ref_image': ref_filename,
|
| 156 |
+
'compare_images': all_compare_images, # 原始顺序的所有候选图像
|
| 157 |
+
'rank_images': ranked_filenames, # 用户的排序结果
|
| 158 |
+
'timestamp': datetime.now().isoformat()
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
# 读取现有数据以检查唯一性
|
| 162 |
+
existing_records = load_existing_records()
|
| 163 |
+
|
| 164 |
+
# 检查是否已存在相同的记录(基于 folder, ref_image 和 compare_images)
|
| 165 |
+
updated = False
|
| 166 |
+
for i, existing in enumerate(existing_records):
|
| 167 |
+
existing_compare_sorted = tuple(sorted(existing.get('compare_images', [])))
|
| 168 |
+
current_compare_sorted = tuple(sorted(all_compare_images))
|
| 169 |
+
|
| 170 |
+
if (existing.get('folder') == folder and
|
| 171 |
+
existing.get('ref_image') == ref_filename and
|
| 172 |
+
existing_compare_sorted == current_compare_sorted):
|
| 173 |
+
# 更新现有记录
|
| 174 |
+
existing_records[i] = record
|
| 175 |
+
updated = True
|
| 176 |
+
break
|
| 177 |
+
|
| 178 |
+
if not updated:
|
| 179 |
+
# 添加新记录
|
| 180 |
+
existing_records.append(record)
|
| 181 |
+
|
| 182 |
+
# 保存到文件
|
| 183 |
+
save_records(existing_records)
|
| 184 |
+
|
| 185 |
+
print(f"{'更新' if updated else '添加'}排序记录:", record)
|
| 186 |
+
|
| 187 |
+
return jsonify({
|
| 188 |
+
'status': 'success',
|
| 189 |
+
'message': f"排序已{'更新' if updated else '保存'}!",
|
| 190 |
+
'record': record
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
except Exception as e:
|
| 194 |
+
print(f"错误: {str(e)}")
|
| 195 |
+
import traceback
|
| 196 |
+
traceback.print_exc()
|
| 197 |
+
return jsonify({'status': 'error', 'message': str(e)}), 500
|
| 198 |
+
|
| 199 |
+
def load_existing_records():
|
| 200 |
+
"""加载现有的记录"""
|
| 201 |
+
if not os.path.exists(DATA_FILE):
|
| 202 |
+
return []
|
| 203 |
+
|
| 204 |
+
records = []
|
| 205 |
+
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
| 206 |
+
for line in f:
|
| 207 |
+
line = line.strip()
|
| 208 |
+
if line:
|
| 209 |
+
records.append(json.loads(line))
|
| 210 |
+
return records
|
| 211 |
+
|
| 212 |
+
def save_records(records):
|
| 213 |
+
"""保存记录到JSONL文件"""
|
| 214 |
+
# 确保目录存在
|
| 215 |
+
os.makedirs(os.path.dirname(DATA_FILE), exist_ok=True)
|
| 216 |
+
|
| 217 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 218 |
+
for record in records:
|
| 219 |
+
f.write(json.dumps(record, ensure_ascii=False) + '\n')
|
| 220 |
+
|
| 221 |
+
# 添加一个路由来提供图片文件
|
| 222 |
+
@app.route('/images/<path:filename>')
|
| 223 |
+
def serve_images(filename):
|
| 224 |
+
return send_from_directory(IMAGE_DIR, filename)
|
| 225 |
+
|
| 226 |
+
# 添加一个查看已保存数据的路由
|
| 227 |
+
@app.route('/view_data')
|
| 228 |
+
def view_data():
|
| 229 |
+
"""查看已保存的排序数据"""
|
| 230 |
+
records = load_existing_records()
|
| 231 |
+
return jsonify({
|
| 232 |
+
'total': len(records),
|
| 233 |
+
'records': records
|
| 234 |
+
})
|
| 235 |
+
|
| 236 |
+
if __name__ == '__main__':
|
| 237 |
+
app.run(debug=True)
|