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