Jayce-Ping's picture
Add files using upload-large-folder tool
436c9ff verified
raw
history blame
9.18 kB
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)