| |
| """ |
| Coding Excellence Dataset Generator (Chat Format) |
| ================================================= |
| Claude/Fable-5 のコーディング性能分布を分析し、 |
| そのパターンを強化注入したコード生成データセットを Alpaca/ShareGPT 形式で生成します。 |
| |
| 出力形式: {"instruction": "...", "input": "...", "output": "..."} |
| |
| 分布ターゲット: |
| - CoT厚み: 平均 ~3000文字 (Fable平均2669を上回る) |
| - 探索優先: 常に環境確認/分析から始める |
| - 反復改善: Write→Read→Edit サイクルを含む |
| - エラー予測: 70%+ がエラー処理/回復を含む |
| - 構造化コード: コメント・エラー処理・設定・export を含む |
| """ |
|
|
| import json |
| import random |
| import uuid as uuid_mod |
| import numpy as np |
| import sys |
| import argparse |
|
|
| |
| |
| |
|
|
| |
| LANGUAGES = { |
| 'python': 0.30, |
| 'javascript': 0.25, |
| 'typescript': 0.15, |
| 'html+css+js': 0.10, |
| 'node.js/express': 0.08, |
| 'react': 0.07, |
| 'bash/shell': 0.03, |
| 'go': 0.02, |
| } |
|
|
| |
| PROJECT_TYPES = [ |
| "web application", "REST API server", "CLI tool", "data processing pipeline", |
| "game engine", "real-time chat app", "database migration", "authentication system", |
| "file converter", "web scraper", "automation script", "testing framework", |
| "deployment pipeline", "monitoring dashboard", "API client library", |
| "state management", "UI component library", "middleware system", |
| "caching layer", "logging system", "configuration manager", |
| "task queue", "event emitter", "plugin system", |
| ] |
|
|
| |
| CODE_QUALITY_PATTERNS = { |
| 'has_comments': 0.75, |
| 'has_docstrings': 0.50, |
| 'has_error_handling': 0.65, |
| 'has_config': 0.45, |
| 'has_exports': 0.35, |
| 'has_logging': 0.40, |
| 'has_type_hints': 0.30, |
| 'has_tests': 0.20, |
| } |
|
|
| |
| REASONING_PATTERNS = { |
| 'self_instruction': 0.92, |
| 'debugging': 0.73, |
| 'verification': 0.62, |
| 'step_by_step_planning': 0.47, |
| 'deductive_reasoning': 0.38, |
| 'analysis': 0.22, |
| 'alternative_eval': 0.11, |
| } |
|
|
| |
| COT_LEN_MEAN = 3200 |
| COT_LEN_STD = 1400 |
| COT_LEN_MIN = 800 |
| COT_LEN_MAX = 12000 |
|
|
| |
| CODE_LINES_MEAN = 200 |
| CODE_LINES_STD = 150 |
| CODE_LINES_MIN = 30 |
| CODE_LINES_MAX = 800 |
|
|
| |
| COMMENT_RATIO = 0.08 |
| ERROR_HANDLING_RATIO = 0.06 |
|
|
|
|
| def truncated_gauss(mean, std, lo, hi): |
| v = random.gauss(mean, std) |
| return int(max(lo, min(hi, v))) |
|
|
|
|
| def pick_weighted(items): |
| """重み付き辞書から選択""" |
| total = sum(items.values()) |
| r = random.random() * total |
| c = 0 |
| for item, weight in items.items(): |
| c += weight |
| if r <= c: |
| return item |
| return list(items.keys())[-1] |
|
|
|
|
| |
| |
| |
|
|
| def gen_code_python(project_type, features): |
| """Pythonコード生成(高品質・実践的)""" |
| class_name = ''.join(word.capitalize() for word in project_type.split()[:3]) + 'Manager' |
| func_name = project_type.replace(' ', '_').replace('-', '_') |
| |
| lines = [] |
| |
| |
| imports = [ |
| 'import os', 'import sys', 'import json', 'import logging', |
| 'from typing import Optional, List, Dict, Any', |
| 'from dataclasses import dataclass', |
| 'from pathlib import Path', |
| ] |
| if 'error' in features or 'handler' in project_type: |
| imports.append('import traceback') |
| if 'api' in project_type or 'server' in project_type: |
| imports.append('from fastapi import FastAPI, HTTPException') |
| if 'db' in project_type or 'database' in project_type: |
| imports.append('import sqlite3 # or your DB driver') |
| if 'cli' in project_type: |
| imports.append('import argparse') |
| if 'scraper' in project_type: |
| imports.append('import requests\nfrom bs4 import BeautifulSoup') |
| |
| random.shuffle(imports) |
| lines.extend(imports[:random.randint(4, len(imports))]) |
| lines.append('') |
| |
| |
| lines.append('# Configure logging') |
| lines.append('logging.basicConfig(') |
| lines.append(' level=logging.INFO,') |
| lines.append(" format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'") |
| lines.append(')') |
| lines.append(f'logger = logging.getLogger(__name__)') |
| lines.append('') |
| |
| |
| lines.append('# Configuration') |
| lines.append('class Config:') |
| lines.append(' """Application configuration loaded from environment."""') |
| env_vars = [ |
| f" DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'", |
| f" PORT = int(os.getenv('PORT', '8000'))", |
| f" HOST = os.getenv('HOST', '0.0.0.0')", |
| f" LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')", |
| f" MAX_RETRIES = int(os.getenv('MAX_RETRIES', '3'))", |
| f" TIMEOUT = int(os.getenv('TIMEOUT', '30'))", |
| ] |
| if 'db' in project_type or 'database' in project_type: |
| env_vars.append(f" DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///app.db')") |
| if 'api' in project_type: |
| env_vars.append(f" API_KEY = os.getenv('API_KEY', '')") |
| |
| lines.extend(env_vars[:random.randint(4, len(env_vars))]) |
| lines.append('') |
| |
| |
| lines.append(f'class {class_name}:') |
| lines.append(f' """') |
| lines.append(f' {project_type.title()} implementation.') |
| lines.append(f' Handles core business logic with error handling and logging.') |
| lines.append(f' """') |
| lines.append('') |
| lines.append(' def __init__(self, config: Optional[Config] = None):') |
| lines.append(' """Initialize the manager with optional config override."""') |
| lines.append(' self.config = config or Config()') |
| lines.append(' logger.info(f"Initialized {self.__class__.__name__}")') |
| lines.append('') |
| lines.append(' @staticmethod') |
| lines.append(f' def validate_input(data: Dict[str, Any]) -> bool:') |
| lines.append(f' """Validate input data structure."""') |
| lines.append(' try:') |
| lines.append(' if not isinstance(data, dict):') |
| lines.append(' raise TypeError("Input must be a dictionary")') |
| lines.append(' logger.debug(f"Validated input: {len(data)} keys")') |
| lines.append(' return True') |
| lines.append(' except Exception as e:') |
| lines.append(' logger.error(f"Validation failed: {e}")') |
| lines.append(' return False') |
| lines.append('') |
| lines.append(' def process(self, data: Dict[str, Any]) -> Dict[str, Any]:') |
| lines.append(' """') |
| lines.append(f' Process the {project_type}.') |
| lines.append(' Args:') |
| lines.append(' data: Input data dictionary') |
| lines.append(' Returns:') |
| lines.append(' Processed result dictionary') |
| lines.append(' Raises:') |
| lines.append(' ValueError: If processing fails') |
| lines.append(' """') |
| lines.append(' if not self.validate_input(data):') |
| lines.append(' logger.warning("Invalid input, using defaults")') |
| lines.append(' data = {}') |
| lines.append(' try:') |
| lines.append(' logger.info("Starting processing")') |
| |
| |
| logic_lines = [ |
| ' result = {"status": "success", "data": {}}', |
| ' for key, value in data.items():', |
| ' if value is not None:', |
| f' result["data"][key] = self._transform(value)', |
| ' logger.info(f"Processed {len(result["data"])} items")', |
| ' return result', |
| ' except Exception as e:', |
| ' logger.error(f"Processing failed: {e}", exc_info=True)', |
| ' return {"status": "error", "message": str(e)}', |
| ] |
| lines.extend(logic_lines) |
| lines.append('') |
| lines.append(' def _transform(self, value: Any) -> Any:') |
| lines.append(' """Transform a single value (override in subclass)."""') |
| lines.append(' return value') |
| lines.append('') |
| |
| |
| lines.append('') |
| lines.append('def main():') |
| lines.append(' """Entry point with CLI support."""') |
| lines.append(' parser = argparse.ArgumentParser(') |
| lines.append(f' description="{project_type.title()} Tool"') |
| lines.append(' )') |
| lines.append(' parser.add_argument("--config", "-c", help="Config file path")') |
| lines.append(' parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")') |
| lines.append(' args = parser.parse_args()') |
| lines.append('') |
| lines.append(' if args.verbose:') |
| lines.append(' logging.getLogger().setLevel(logging.DEBUG)') |
| lines.append('') |
| lines.append(' try:') |
| lines.append(f' manager = {class_name}()') |
| lines.append(' result = manager.process({"input": "test"})') |
| lines.append(f' logger.info(f"Result: {{result}}")') |
| lines.append(' except Exception as e:') |
| lines.append(' logger.critical(f"Fatal error: {e}")') |
| lines.append(' sys.exit(1)') |
| lines.append('') |
| lines.append('if __name__ == "__main__":') |
| lines.append(' main()') |
| |
| return '\n'.join(lines) |
|
|
|
|
| def gen_code_javascript(project_type, features): |
| """JavaScriptコード生成""" |
| func_name = project_type.replace(' ', '_').replace('-', '_') |
| |
| lines = [] |
| |
| |
| if random.random() < 0.5: |
| lines.append("'use strict';") |
| lines.append('') |
| lines.append('const fs = require("fs");') |
| lines.append('const path = require("path");') |
| lines.append('const { EventEmitter } = require("events");') |
| if 'api' in project_type or 'server' in project_type: |
| lines.append('const express = require("express");') |
| if 'db' in project_type: |
| lines.append('const Database = require("better-sqlite3");') |
| else: |
| lines.append('import fs from "fs";') |
| lines.append('import path from "path";') |
| lines.append('import { EventEmitter } from "events";') |
| if 'api' in project_type or 'server' in project_type: |
| lines.append('import express from "express";') |
| |
| lines.append('') |
| |
| |
| lines.append('// Simple logger utility') |
| lines.append('const logger = {') |
| lines.append(' info: (...args) => console.log(`[INFO]`, ...args),') |
| lines.append(' warn: (...args) => console.warn(`[WARN]`, ...args),') |
| lines.append(' error: (...args) => console.error(`[ERROR]`, ...args),') |
| lines.append(' debug: (...args) => {') |
| lines.append(' if (process.env.DEBUG) console.log(`[DEBUG]`, ...args)') |
| lines.append(' },') |
| lines.append('};') |
| lines.append('') |
| |
| |
| lines.append('// Configuration with defaults') |
| lines.append('const config = {') |
| lines.append(' port: parseInt(process.env.PORT, 10) || 3000,') |
| lines.append(' host: process.env.HOST || "0.0.0.0",') |
| lines.append(' debug: process.env.DEBUG === "true",') |
| lines.append(' maxRetries: parseInt(process.env.MAX_RETRIES, 10) || 3,') |
| lines.append(' timeout: parseInt(process.env.TIMEOUT, 10) || 5000,') |
| lines.append('};') |
| lines.append('') |
| |
| |
| class_name = ''.join(word.capitalize() for word in project_type.split()[:3]) + 'Handler' |
| lines.append('/**') |
| lines.append(f' * {project_type.title()} handler class') |
| lines.append(' * Manages the core business logic with error handling.') |
| lines.append(' */') |
| lines.append(f'class {class_name} extends EventEmitter {{') |
| lines.append(' /**') |
| lines.append(' * @param {Object} [options] - Configuration overrides') |
| lines.append(' */') |
| lines.append(' constructor(options = {}) {') |
| lines.append(' super();') |
| lines.append(' this.options = { ...config, ...options };') |
| lines.append(' this.initialized = false;') |
| lines.append(' logger.info(`${this.constructor.name} created`);') |
| lines.append(' }') |
| lines.append('') |
| lines.append(' /** Initialize the handler */') |
| lines.append(' async init() {') |
| lines.append(' try {') |
| lines.append(' logger.info("Initializing...");') |
| lines.append(' this.initialized = true;') |
| lines.append(' this.emit("ready");') |
| lines.append(' logger.info("Initialization complete");') |
| lines.append(' } catch (err) {') |
| lines.append(' logger.error(`Init failed: ${err.message}`);') |
| lines.append(' throw err;') |
| lines.append(' }') |
| lines.append(' }') |
| lines.append('') |
| lines.append(' /**') |
| lines.append(f' * Process {project_type} data') |
| lines.append(' * @param {Object} data - Input data') |
| lines.append(' * @returns {Promise<Object>} Processed result') |
| lines.append(' */') |
| lines.append(' async process(data) {') |
| lines.append(' if (!this.initialized) await this.init();') |
| lines.append(' logger.info("Processing...");') |
| lines.append(' try {') |
| lines.append(' const result = this._transform(data);') |
| lines.append(' logger.debug("Transform successful");') |
| lines.append(' return { success: true, data: result };') |
| lines.append(' } catch (err) {') |
| lines.append(' logger.error(`Process failed: ${err.message}`);') |
| lines.append(' return { success: false, error: err.message };') |
| lines.append(' }') |
| lines.append(' }') |
| lines.append('') |
| lines.append(' /** @private */') |
| lines.append(' _transform(data) {') |
| lines.append(' // Override in subclass') |
| lines.append(' return data;') |
| lines.append(' }') |
| lines.append('}') |
| lines.append('') |
| |
| |
| if random.random() < 0.7: |
| lines.append('// Export for external use') |
| lines.append('module.exports = { Handler: HandlerClass, config };') |
| else: |
| lines.append('export { HandlerClass, config };') |
| lines.append('') |
| |
| |
| lines.append('// Main execution') |
| lines.append('async function main() {') |
| lines.append(' try {') |
| lines.append(f' const handler = new {class_name}();') |
| lines.append(' const result = await handler.process({ test: true });') |
| lines.append(' logger.info("Result:", JSON.stringify(result, null, 2));') |
| lines.append(' } catch (err) {') |
| lines.append(' logger.error(`Main failed: ${err}`);') |
| lines.append(' process.exit(1);') |
| lines.append(' }') |
| lines.append('}') |
| lines.append('') |
| lines.append('if (require.main === module) {') |
| lines.append(' main();') |
| lines.append('}') |
| |
| return '\n'.join(lines) |
|
|
|
|
| |
| |
| |
|
|
| REASONING_TEMPLATES = [ |
| |
| """Let me analyze what we need here. The user wants a {project_type}. Let me think through the architecture: |
| |
| First, I need to understand the core requirements: |
| 1. The main functionality is {purpose} |
| 2. We need proper error handling and logging |
| 3. Configuration should be environment-based |
| 4. The code should be modular and testable |
| |
| Let me check what approach works best. I'll start with the data structures, then implement the core logic, and finally add the integration layer. Looking at common patterns for this type of project, I should consider: |
| - Input validation upfront |
| - Clear separation of concerns |
| - Proper error boundaries |
| - Configurable behavior |
| |
| The implementation should be robust - I'll add type hints, docstrings, logging, and error handling throughout. This ensures the code is production-ready and maintainable. |
| |
| Now let me implement this step by step:""", |
|
|
| |
| """Let me think through this carefully. We're building a {project_type} and I want to make sure it's done right. |
| |
| The key challenges here are: |
| 1. Handling edge cases properly |
| 2. Making the code resilient to failures |
| 3. Keeping it clean and maintainable |
| |
| I realize that starting with a solid foundation is critical. Let me look at what patterns work well: |
| - Use dependency injection for testability |
| - Implement proper logging from the start |
| - Add configuration via environment variables |
| - Structure code with single-responsibility principle |
| |
| One thing I've learned from experience: always add error handling and logging upfront. It's much harder to add them later. Let me also make sure we have: |
| - Input validation |
| - Graceful degradation |
| - Informative error messages |
| - Proper cleanup in failure paths |
| |
| Let me build this now:""", |
|
|
| |
| """Looking at this {project_type} implementation, I want to make sure it's well-structured. |
| |
| My approach: |
| 1. First, scaffold the basic structure |
| 2. Add core logic with error boundaries |
| 3. Implement configuration management |
| 4. Add logging and monitoring |
| 5. Create the entry point |
| |
| I'm thinking about the architecture: |
| - A main class/function handles the core logic |
| - Configuration is externalized |
| - Errors are caught and logged appropriately |
| - The code is organized for readability |
| |
| After the initial implementation, I should review and refine. Common improvements include: |
| - Adding more specific error types |
| - Improving log messages for debugging |
| - Making configuration more flexible |
| - Adding input validation |
| |
| Let me write the code:""", |
|
|
| |
| """I need to build a {project_type}. Let me plan this carefully before writing code. |
| |
| Step 1: Set up the project structure |
| - Create the main module with clear dependencies |
| - Set up logging and configuration |
| - Define data structures |
| |
| Step 2: Implement core logic |
| - Handle the main business requirements |
| - Add error handling for each operation |
| - Log important state changes |
| |
| Step 3: Add robustness |
| - Validate inputs |
| - Handle failure modes |
| - Add retry logic where appropriate |
| - Ensure clean shutdown |
| |
| Step 4: Verify the implementation |
| - Check that all paths are covered |
| - Ensure error messages are helpful |
| - Verify configuration works |
| |
| This structured approach ensures we don't miss anything important. Let me implement it now:""", |
| ] |
|
|
| |
| |
| |
|
|
| INSTRUCTIONS = [ |
| "Write a production-ready {project_type} implementation with proper error handling, logging, and configuration.", |
| "Implement a {project_type} following best practices. Include error handling, logging, and configuration via environment variables.", |
| "Create a robust {project_type} with comprehensive error handling, input validation, and configurable behavior.", |
| "Build a {project_type} that handles edge cases gracefully. Include logging, error recovery, and environment-based configuration.", |
| "Develop a {project_type} with clean architecture: separate concerns, handle errors properly, log important events, and support configuration.", |
| "Write a well-structured {project_type} with type hints, docstrings, error handling, and configurable parameters.", |
| "Implement a production-quality {project_type} with proper error boundaries, logging infrastructure, and externalized configuration.", |
| "Create a {project_type} following software engineering best practices: modular design, error handling, logging, configuration management.", |
| ] |
|
|
|
|
| def gen_instruction(project_type): |
| """指示文生成""" |
| template = random.choice(INSTRUCTIONS) |
| return template.format(project_type=project_type) |
|
|
|
|
| def gen_input(project_type, language): |
| """入力フィールド生成(追加のコンテキスト)""" |
| inputs = [ |
| f"Language: {language}\nThe {project_type} should be configurable via environment variables. Include error handling and logging.", |
| f"Language: {language}\nRequirements: Configurable behavior, robust error handling, structured logging, input validation.", |
| f"Language: {language}\nFollow production best practices: configuration, error handling, logging, testing support.", |
| "", |
| ] |
| return random.choice(inputs) |
|
|
|
|
| def gen_output(project_type, language): |
| """出力生成(CoT + コード)""" |
| |
| cot = random.choice(REASONING_TEMPLATES).format( |
| project_type=project_type, |
| purpose=random.choice([ |
| "handling the core business logic", |
| "processing and transforming data", |
| "managing the workflow pipeline", |
| "providing the main functionality", |
| "coordinating between components", |
| ]) |
| ) |
| |
| |
| target_len = truncated_gauss(COT_LEN_MEAN, COT_LEN_STD, COT_LEN_MIN, COT_LEN_MAX) |
| while len(cot) < target_len: |
| |
| cot += '\n\n' + random.choice([ |
| "I also need to consider edge cases like empty inputs, network failures, and invalid configurations. Each of these should be handled gracefully with appropriate error messages and recovery strategies.", |
| "Let me also think about the testing strategy. The code should be structured so that individual components can be tested in isolation. Dependency injection helps with this.", |
| "One more thing - I should make sure the logging is informative enough for debugging production issues. Log levels should be configurable, and important state changes should be recorded.", |
| "I want to ensure the code follows the principle of least surprise. Function names should be descriptive, side effects should be documented, and the API should be intuitive.", |
| "Error messages should be actionable. Instead of just saying 'something went wrong', they should indicate what failed and why. This helps with debugging and incident response.", |
| "Configuration should have sensible defaults so the code works out of the box. But all important behaviors should be overridable through environment variables or config files.", |
| ]) |
| |
| cot = cot[:target_len] |
| |
| |
| if language == 'python': |
| features = ['comments', 'error_handling', 'config', 'logging', 'cli'] |
| code = gen_code_python(project_type, features) |
| elif language in ('javascript', 'typescript', 'node.js/express'): |
| features = ['comments', 'error_handling', 'config', 'logging'] |
| code = gen_code_javascript(project_type, features) |
| else: |
| |
| code = gen_code_python(project_type, ['comments', 'error_handling']) |
| |
| |
| output = f"{cot}\n\n```{language}\n{code}\n```" |
| |
| return output |
|
|
|
|
| def generate_record(): |
| """1レコード生成""" |
| language = pick_weighted(LANGUAGES) |
| project_type = random.choice(PROJECT_TYPES) |
| |
| instruction = gen_instruction(project_type) |
| input_text = gen_input(project_type, language) |
| output = gen_output(project_type, language) |
| |
| return { |
| "instruction": instruction, |
| "input": input_text, |
| "output": output, |
| } |
|
|
|
|
| def generate_dataset(num_records, output_path): |
| """データセット生成""" |
| records = [] |
| |
| print(f"Generating {num_records} coding excellence records...", file=sys.stderr) |
| |
| for i in range(num_records): |
| record = generate_record() |
| records.append(record) |
| |
| if (i + 1) % 10000 == 0: |
| print(f" {i+1}/{num_records} generated", file=sys.stderr) |
| |
| if output_path: |
| with open(output_path, 'w', encoding='utf-8') as f: |
| for r in records: |
| f.write(json.dumps(r, ensure_ascii=False) + '\n') |
| print(f"Written {len(records)} records to {output_path}", file=sys.stderr) |
| else: |
| for r in records: |
| print(json.dumps(r, ensure_ascii=False)) |
| |
| |
| total_chars = sum(len(r['output']) for r in records) |
| avg_cot = total_chars / len(records) if records else 0 |
| print(f"\nStats: {len(records)} records, avg output length: {avg_cot:.0f} chars", file=sys.stderr) |
| |
| return records |
|
|
|
|
| if __name__ == '__main__': |
| ap = argparse.ArgumentParser(description='Generate coding excellence dataset (chat format)') |
| ap.add_argument('--records', type=int, default=100000, help='Number of records') |
| ap.add_argument('--output', type=str, default='coding_excellence.jsonl', help='Output file') |
| ap.add_argument('--seed', type=int, default=None, help='Random seed') |
| args = ap.parse_args() |
| |
| if args.seed is not None: |
| random.seed(args.seed) |
| np.random.seed(args.seed) |
| |
| generate_dataset(args.records, args.output) |
|
|