import os import json from datetime import datetime from utils import divide_prompt import argparse from flask import Flask, render_template, request, send_from_directory, jsonify app = Flask(__name__) FILE_PATH = os.path.dirname(os.path.abspath(__file__)) # 设置图像目录路径 IMAGE_DIR = os.path.join(FILE_PATH, "../images_divided") ITEMS_PER_PAGE = 1 # 每页显示的 data 项目数 # PROMPT_DATA_FILE = os.path.join(FILE_PATH, 'data/extended_data_summary_v2.jsonl') PROMPT_DATA_FILE = os.path.join(FILE_PATH, 'data/2by2_data_summary.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} def load_metadata(): """加载用户的元数据""" if not os.path.exists(METADATA_FILE): return {"last_page": None, "last_updated": None} try: with open(METADATA_FILE, 'r', encoding='utf-8') as f: return json.load(f) except: return {"last_page": None, "last_updated": None} def save_metadata(page): """保存当前页码到元数据文件""" metadata = { "last_page": page, "last_updated": datetime.now().isoformat() } os.makedirs(os.path.dirname(METADATA_FILE), exist_ok=True) with open(METADATA_FILE, 'w', encoding='utf-8') as f: json.dump(metadata, f, ensure_ascii=False, indent=2) @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('.') # ]) folders = sorted([ idx for idx in PROMPT_DATA.keys() if os.path.isdir(os.path.join(IMAGE_DIR, idx)) ]) 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] = record 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 = [] for y, cand in zip([y for y in second_indices if y != j], candidates): item = { '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, 'stared': False, 'discarded': False, 'grid_issue': False } 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(item['existing_rank_images']) > 0 item['stared'] = existing_data.get('stared', False) item['discarded'] = existing_data.get('discarded', False) item['grid_issue'] = existing_data.get('grid_issue', False) items.append(item) data.extend(items) # 获取页码参数,优先级:URL参数 > 元数据文件 > start_idx配置 > 默认1 url_page = request.args.get('page') if url_page: # 如果URL明确指定了页码,使用URL的页码 page = int(url_page) else: metadata = load_metadata() last_page = metadata.get('last_page', None) if last_page: # 如果元数据文件中有记录,使用元数据中的页码 page = last_page elif not app.config.get('START_IDX_USED', False): # 如果start_idx还没被使用过,使用start_idx page = app.config.get('START_IDX', 1) app.config['START_IDX_USED'] = True else: # 否则使用默认页码1 page = 1 # 保存当前页码到元数据 save_metadata(page) 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('/update_page', methods=['POST']) def update_page(): """更新当前页码到元数据文件""" try: data = request.get_json() page = data.get('page') if page: save_metadata(int(page)) return jsonify({'status': 'success'}) return jsonify({'status': 'error', 'message': '无效的页码'}), 400 except Exception as e: return jsonify({'status': 'error', 'message': str(e)}), 500 @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 = [item['image_path'].split('/')[-1] for item in ranking] 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): if (existing.get('folder') == folder and existing.get('ref_image') == ref_filename and tuple(sorted(existing.get('compare_images', []))) == tuple(sorted(all_compare_images))): record['stared'] = existing.get('stared', False) record['discarded'] = existing.get('discarded', False) record['grid_issue'] = existing.get('grid_issue', False) existing_records[i] = record updated = True break if not updated: record['stared'] = False record['discarded'] = False record['grid_issue'] = False existing_records.append(record) save_records(existing_records) return jsonify({'status': 'success','message': f"排序已{'更新' if updated else '保存'}!",'record': record}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}), 500 @app.route('/star', methods=['POST']) def star_image(): try: data = request.get_json() folder = data.get("folder") ref_image = data.get("ref_image") stared = data.get("stared", False) compare_images = data.get("compare_images", []) rank_images = data.get("rank_images", []) existing_records = load_existing_records() updated = False for record in existing_records: if (record.get("folder") == folder and record.get("ref_image") == ref_image and tuple(sorted(record.get("compare_images", []))) == tuple(sorted(compare_images))): record["stared"] = stared if rank_images: record["rank_images"] = rank_images record["timestamp"] = datetime.now().isoformat() updated = True break if not updated: new_record = { "folder": folder, "ref_image": ref_image, "compare_images": compare_images, "rank_images": rank_images, "stared": stared, "timestamp": datetime.now().isoformat() } existing_records.append(new_record) save_records(existing_records) return jsonify({"status": "success", "message": f"{'已收藏' if stared else '已取消收藏'}"}) except Exception as e: print(f"Error in star_image: {str(e)}") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/discard', methods=['POST']) def discard_image(): try: data = request.get_json() folder = data.get("folder") ref_image = data.get("ref_image") discarded = data.get("discarded", False) compare_images = data.get("compare_images", []) rank_images = data.get("rank_images", []) existing_records = load_existing_records() updated = False for record in existing_records: if (record.get("folder") == folder and record.get("ref_image") == ref_image and tuple(sorted(record.get("compare_images", []))) == tuple(sorted(compare_images))): record["discarded"] = discarded if rank_images: record["rank_images"] = rank_images record["timestamp"] = datetime.now().isoformat() updated = True break if not updated: new_record = { "folder": folder, "ref_image": ref_image, "compare_images": compare_images, "rank_images": rank_images, "discarded": discarded, "timestamp": datetime.now().isoformat() } existing_records.append(new_record) save_records(existing_records) return jsonify({"status": "success", "message": f"{'已丢弃' if discarded else '已取消丢弃'}"}) except Exception as e: print(f"Error in discard_image: {str(e)}") 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: try: records.append(json.loads(line)) except json.JSONDecodeError: continue return records def save_records(records): 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('/grid_issue', methods=['POST']) def grid_issue_image(): try: data = request.get_json() folder = data.get("folder") ref_image = data.get("ref_image") grid_issue = data.get("grid_issue", False) compare_images = data.get("compare_images", []) rank_images = data.get("rank_images", []) existing_records = load_existing_records() updated = False for record in existing_records: if (record.get("folder") == folder and record.get("ref_image") == ref_image and tuple(sorted(record.get("compare_images", []))) == tuple(sorted(compare_images))): record["grid_issue"] = grid_issue if rank_images: record["rank_images"] = rank_images record["timestamp"] = datetime.now().isoformat() updated = True break if not updated: new_record = { "folder": folder, "ref_image": ref_image, "compare_images": compare_images, "rank_images": rank_images, "grid_issue": grid_issue, "timestamp": datetime.now().isoformat() } existing_records.append(new_record) save_records(existing_records) return jsonify({"status": "success", "message": f"{'已标记网格问题' if grid_issue else '已取消网格问题标记'}"}) except Exception as e: print(f"Error in grid_issue_image: {str(e)}") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/images/') def images(filename): return send_from_directory(IMAGE_DIR, filename) @app.route('/view_data') def view_data(): existing_records = load_existing_records() return jsonify(existing_records) def parse_args(): parser = argparse.ArgumentParser(description="Run the annotation server.") parser.add_argument('--port', type=str, default='5000', help='Host address to run the server on') parser.add_argument('--user', type=str, default='user', help='User name for the session') parser.add_argument('--start_idx', type=int, default=1, help='Starting page index for initialization') return parser.parse_args() if __name__ == '__main__': args = parse_args() user = args.user port = int(args.port) start_idx = args.start_idx global DATA_FILE, METADATA_FILE DATA_FILE = os.path.join(FILE_PATH, "data", f"annotation_{user}.jsonl") METADATA_FILE = os.path.join(FILE_PATH, "data", f"metadata_{user}.json") # 将start_idx存储到app配置中 app.config['START_IDX'] = start_idx print(f"启动服务器:") print(f" 用户: {user}") print(f" 端口: {port}") print(f" 起始页码: {start_idx}") print(f" 数据文件: {DATA_FILE}") print(f" 元数据文件: {METADATA_FILE}") app.run(debug=True, port=port)