| 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_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) |
| ] |
| |
| |
| for item in items: |
| |
| current_compare_images = [img.split('/')[-1] for img in item['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['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] |
| |
| |
| ref_image = request.form.get('ref_image', '') |
| |
| |
| ref_filename = ref_image.split('/')[-1] |
| |
| |
| 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() |
| |
| |
| 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) |