| import os |
| import json |
| import base64 |
| from io import BytesIO |
| from openai import OpenAI |
| from typing import List, Dict |
| from datasets import load_from_disk |
| from PIL import Image |
| import random |
| from tqdm import tqdm |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| import threading |
| from filelock import FileLock |
| import time |
|
|
| |
| api_key = "sk-lGBrn5aWRZBPIEtNiUpIblgqBRdLfvephIJ71LBZWQEIp3kc" |
| base_url = "https://openai.app.msh.team/v1" |
|
|
| client = OpenAI( |
| api_key=api_key, |
| base_url=base_url |
| ) |
|
|
| def encode_image_to_base64(image: Image.Image) -> str: |
| """ |
| 将PIL Image编码为base64字符串 |
| |
| Args: |
| image: PIL Image对象 |
| |
| Returns: |
| base64编码的图片字符串 |
| """ |
| buffer = BytesIO() |
| |
| if image.mode != 'RGB': |
| image = image.convert('RGB') |
| image.save(buffer, format='JPEG', quality=95) |
| image_bytes = buffer.getvalue() |
| return base64.b64encode(image_bytes).decode('utf-8') |
|
|
| def save_image_file(image: Image.Image, sample_index: int, output_dir: str = "images/coldstart") -> str: |
| """ |
| 保存图片到文件 |
| |
| Args: |
| image: PIL Image对象 |
| sample_index: 样本索引 |
| output_dir: 输出目录 |
| |
| Returns: |
| 保存的文件路径 |
| """ |
| try: |
| |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| filename = f"sample_{sample_index}.jpg" |
| filepath = os.path.join(output_dir, filename) |
| |
| |
| if image.mode != 'RGB': |
| image = image.convert('RGB') |
| image.save(filepath, format='JPEG', quality=95) |
| |
| return filepath |
| |
| except Exception as e: |
| print(f"保存图片时出错: {e}") |
| return "" |
|
|
| def get_gemini_response(image: Image.Image, question: str, sample_index: int) -> Dict[str, str]: |
| """ |
| 使用Gemini模型对OCR-VQA问题进行回答 |
| |
| Args: |
| image: PIL Image对象 |
| question: 问题文本 |
| sample_index: 样本索引(用于保存图片) |
| |
| Returns: |
| 包含对话格式数据的字典 |
| """ |
| try: |
| |
| image_path = save_image_file(image, sample_index) |
| |
| |
| base64_image = encode_image_to_base64(image) |
| |
| |
| prompt_text = f"Please carefully observe the image and answer the question: {question}. Put your final answer in \\boxed{{}}." |
|
|
| |
| messages = [ |
| { |
| "role": "user", |
| "content": [ |
| { |
| "type": "text", |
| "text": prompt_text |
| }, |
| { |
| "type": "image_url", |
| "image_url": { |
| "url": f"data:image/jpeg;base64,{base64_image}" |
| } |
| } |
| ] |
| } |
| ] |
| |
| |
| response = client.chat.completions.create( |
| model="gemini-2.5-pro-preview-05-06", |
| messages=messages, |
| max_completion_tokens=300 |
| ) |
| |
| |
| choice = response.choices[0] |
| message = choice.message |
| content = message.content.strip() if message.content else "" |
| reasoning = getattr(message, 'reasoning', '') or "" |
| |
| |
| full_response = "" |
| if reasoning: |
| full_response += f"<think>{reasoning}</think>" |
| full_response += content |
| |
| return { |
| "full_response": full_response, |
| "image_path": image_path |
| } |
| |
| except Exception as e: |
| error_msg = f"ERROR: 调用Gemini模型时出错: {e}" |
| print(error_msg) |
| return { |
| "full_response": error_msg, |
| "image_path": save_image_file(image, sample_index) if image else "" |
| } |
|
|
| def load_ocr_vqa_dataset(dataset_path: str, split: str = "validation", num_samples: int = 100): |
| """ |
| 加载OCR-VQA数据集 |
| |
| Args: |
| dataset_path: 数据集路径 |
| split: 数据集分割(train/validation/test) |
| num_samples: 要处理的样本数量 |
| |
| Returns: |
| 选定的数据样本列表 |
| """ |
| print(f"加载OCR-VQA数据集: {dataset_path}") |
| |
| try: |
| |
| dataset = load_from_disk(dataset_path) |
| split_data = dataset[split] |
| |
| print(f"数据集加载成功!") |
| print(f"- {split} 集总样本数: {len(split_data):,}") |
| print(f"- 将随机选择 {num_samples} 个样本进行处理") |
| |
| |
| random.seed(42) |
| indices = random.sample(range(len(split_data)), min(num_samples, len(split_data))) |
| selected_data = split_data.select(indices) |
| |
| |
| samples = [] |
| for i, item in enumerate(selected_data): |
| |
| problem = item['problem'] |
| question = problem.replace('<image>', '').strip() |
| |
| samples.append({ |
| 'index': indices[i], |
| 'image': item['images'][0], |
| 'question': question, |
| 'ground_truth': item['answer'] |
| }) |
| |
| print(f"成功选择了 {len(samples)} 个样本") |
| return samples |
| |
| except Exception as e: |
| print(f"加载数据集时出错: {e}") |
| return [] |
|
|
| def append_to_jsonl_file(data: Dict, filename: str, max_retries: int = 3): |
| """ |
| 使用filelock安全地追加数据到JSONL文件(每行一个JSON对象) |
| |
| Args: |
| data: 要追加的数据 |
| filename: 文件名 |
| max_retries: 最大重试次数 |
| """ |
| lock_file = filename + ".lock" |
| |
| for attempt in range(max_retries): |
| try: |
| |
| with FileLock(lock_file, timeout=10): |
| |
| with open(filename, 'a', encoding='utf-8') as f: |
| json.dump(data, f, ensure_ascii=False, separators=(',', ':')) |
| f.write('\n') |
| |
| return True |
| |
| except Exception as e: |
| print(f"写入文件时出错 (尝试 {attempt + 1}/{max_retries}): {e}") |
| if attempt < max_retries - 1: |
| time.sleep(0.1 * (attempt + 1)) |
| continue |
| |
| print(f"写入文件失败,已重试 {max_retries} 次") |
| return False |
|
|
| def convert_jsonl_to_json(jsonl_file: str, json_file: str): |
| """ |
| 将JSONL文件转换为标准JSON数组格式 |
| |
| Args: |
| jsonl_file: JSONL文件路径 |
| json_file: 输出JSON文件路径 |
| """ |
| try: |
| data_list = [] |
| with open(jsonl_file, 'r', encoding='utf-8') as f: |
| for line in f: |
| line = line.strip() |
| if line: |
| try: |
| data_list.append(json.loads(line)) |
| except json.JSONDecodeError as e: |
| print(f"解析JSON行时出错: {e}, 行内容: {line[:100]}") |
| |
| |
| with open(json_file, 'w', encoding='utf-8') as f: |
| json.dump(data_list, f, ensure_ascii=False, indent=2) |
| |
| print(f"成功转换 {len(data_list)} 条数据从 {jsonl_file} 到 {json_file}") |
| return len(data_list) |
| |
| except Exception as e: |
| print(f"转换文件时出错: {e}") |
| return 0 |
|
|
| def process_single_sample(sample: Dict, thread_id: int, output_file: str) -> Dict: |
| """ |
| 处理单个样本并直接写入文件(线程安全) |
| |
| Args: |
| sample: 单个样本数据 |
| thread_id: 线程ID |
| output_file: 输出文件名 |
| |
| Returns: |
| 处理结果字典 |
| """ |
| try: |
| |
| gemini_result = get_gemini_response(sample['image'], sample['question'], sample['index']) |
| |
| |
| conversation_data = { |
| "messages": [ |
| { |
| "content": f"<image>{sample['question']}", |
| "role": "user" |
| }, |
| { |
| "content": gemini_result['full_response'], |
| "role": "assistant" |
| } |
| ], |
| "images": [ |
| gemini_result['image_path'] |
| ] |
| } |
| |
| |
| write_success = append_to_jsonl_file(conversation_data, output_file) |
| |
| return { |
| 'success': True, |
| 'write_success': write_success, |
| 'sample_index': sample['index'] |
| } |
| |
| except Exception as e: |
| print(f"线程{thread_id}处理样本 {sample['index']} 时出错: {e}") |
| |
| |
| error_data = { |
| "messages": [ |
| { |
| "content": f"<image>{sample['question']}", |
| "role": "user" |
| }, |
| { |
| "content": f"ERROR: {str(e)}", |
| "role": "assistant" |
| } |
| ], |
| "images": [ |
| save_image_file(sample['image'], sample['index']) if sample.get('image') else "" |
| ] |
| } |
| |
| write_success = append_to_jsonl_file(error_data, output_file) |
| |
| return { |
| 'success': False, |
| 'write_success': write_success, |
| 'sample_index': sample['index'], |
| 'error': str(e) |
| } |
|
|
| def process_samples_with_gemini_multithread(samples: List[Dict], output_file: str, max_workers: int = 8): |
| """ |
| 使用多线程和Gemini模型处理样本并直接写入文件 |
| |
| Args: |
| samples: 样本列表 |
| output_file: 输出文件名 |
| max_workers: 最大线程数 |
| |
| Returns: |
| 处理统计信息 |
| """ |
| success_count = 0 |
| error_count = 0 |
| write_error_count = 0 |
| failed_samples = [] |
| count_lock = threading.Lock() |
| |
| print(f"开始使用{max_workers}个线程处理 {len(samples)} 个样本...") |
| |
| |
| jsonl_file = output_file.replace('.json', '.jsonl') |
| print(f"结果将写入JSONL临时文件: {jsonl_file}") |
| |
| |
| with open(jsonl_file, 'w', encoding='utf-8') as f: |
| pass |
| |
| |
| with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| |
| future_to_sample = { |
| executor.submit(process_single_sample, sample, i % max_workers, jsonl_file): sample |
| for i, sample in enumerate(samples) |
| } |
| |
| |
| with tqdm(total=len(samples), desc="多线程处理中") as pbar: |
| |
| for future in as_completed(future_to_sample): |
| try: |
| result = future.result() |
| |
| |
| with count_lock: |
| if result['success']: |
| success_count += 1 |
| else: |
| error_count += 1 |
| |
| if not result['write_success']: |
| write_error_count += 1 |
| failed_samples.append(result['sample_index']) |
| |
| except Exception as e: |
| sample = future_to_sample[future] |
| print(f"获取结果时出错,样本 {sample['index']}: {e}") |
| with count_lock: |
| error_count += 1 |
| failed_samples.append(sample['index']) |
| finally: |
| pbar.update(1) |
| |
| |
| print(f"\n转换JSONL为标准JSON格式...") |
| actual_count = convert_jsonl_to_json(jsonl_file, output_file) |
| |
| |
| try: |
| os.remove(jsonl_file) |
| print(f"已清理临时文件: {jsonl_file}") |
| except Exception as e: |
| print(f"清理临时文件时出错: {e}") |
| |
| return { |
| 'total_samples': len(samples), |
| 'success_samples': success_count, |
| 'error_samples': error_count, |
| 'write_error_count': write_error_count, |
| 'actual_saved_count': actual_count, |
| 'failed_samples': failed_samples, |
| 'success_rate': success_count / len(samples) if len(samples) > 0 else 0, |
| 'save_rate': actual_count / len(samples) if len(samples) > 0 else 0 |
| } |
|
|
| def save_stats(stats: Dict, output_file: str): |
| """ |
| 保存统计信息 |
| |
| Args: |
| stats: 统计信息字典 |
| output_file: 输出文件名 |
| """ |
| try: |
| stats_file = output_file.replace('.json', '_stats.json') |
| with open(stats_file, 'w', encoding='utf-8') as f: |
| json.dump(stats, f, ensure_ascii=False, indent=2) |
| |
| print(f"统计信息已保存: {stats_file}") |
| print(f"处理统计: {stats['success_samples']}/{stats['total_samples']} 成功,成功率: {stats['success_rate']:.2%}") |
| |
| except Exception as e: |
| print(f"保存统计信息时出错: {e}") |
|
|
| def preview_results(output_file: str, num_examples: int = 3): |
| """ |
| 预览结果文件(标准JSON格式) |
| |
| Args: |
| output_file: 结果文件名 |
| num_examples: 要显示的示例数量 |
| """ |
| try: |
| if not os.path.exists(output_file): |
| print(f"文件不存在: {output_file}") |
| return |
| |
| with open(output_file, 'r', encoding='utf-8') as f: |
| data = json.load(f) |
| |
| print(f"\n=== 结果预览 (前{min(num_examples, len(data))}个示例) ===") |
| print(f"总共 {len(data)} 个对话") |
| |
| for i, conversation in enumerate(data[:num_examples]): |
| print(f"\n--- 对话 {i+1} ---") |
| print(f"用户问题: {conversation['messages'][0]['content']}") |
| print(f"助手回答: {conversation['messages'][1]['content'][:200]}{'...' if len(conversation['messages'][1]['content']) > 200 else ''}") |
| print(f"图片路径: {conversation['images'][0]}") |
| |
| except Exception as e: |
| print(f"预览结果时出错: {e}") |
|
|
| def main(): |
| """主函数""" |
| print("=== OCR-VQA + Gemini模型 Cold Start数据生成 ===") |
| |
| |
| dataset_path = "/mnt/moonfs/kimiv-ksyun/xulin/datasets/OCR-VQA/ocr_vqa_clean_dataset" |
| split = "validation" |
| num_samples = 1000 |
| max_workers = 20 |
| output_file = "ocr_vqa_coldstart_data.json" |
| |
| print(f"配置:") |
| print(f"- 数据集路径: {dataset_path}") |
| print(f"- 数据集分割: {split}") |
| print(f"- 处理样本数: {num_samples}") |
| print(f"- 最大线程数: {max_workers}") |
| print(f"- 使用模型: gemini-2.5-pro-preview-05-06") |
| print(f"- 输出文件: {output_file}") |
| print(f"- 图片保存目录: images/coldstart/") |
| |
| |
| samples = load_ocr_vqa_dataset(dataset_path, split, num_samples) |
| if not samples: |
| print("❌ 数据集加载失败,程序退出") |
| return |
| |
| |
| stats = process_samples_with_gemini_multithread(samples, output_file, max_workers) |
| |
| |
| save_stats(stats, output_file) |
| |
| |
| preview_results(output_file) |
| |
| print(f"\n🎉 Cold Start数据生成完成!") |
| print(f"📁 对话数据文件: {output_file}") |
| print(f"📊 统计文件: {output_file.replace('.json', '_stats.json')}") |
| print(f"🧠 自动提取推理过程: ✅") |
| print(f"🖼️ 图片保存到images/coldstart/目录: ✅") |
| print(f"⚡ 多线程+filelock+JSONL追加: ✅") |
| print(f"💬 对话格式数据: ✅") |
| print(f"📈 实际保存: {stats['actual_saved_count']}/{stats['total_samples']} 条数据") |
| print(f"\n💡 生成的数据可以直接用于多模态模型的冷启动训练!") |
|
|
| if __name__ == "__main__": |
| main() |
|
|