Spaces:
Sleeping
Sleeping
Download core/data_generator.py from UTKojima/1stPaper_v1: direct link, hf CLI and curl.
- Browser
- Download file 36.2 kB
-
https://huggingface.co/spaces/UTKojima/1stPaper_v1/resolve/main/core/data_generator.py
- Command line
-
hf download hf://spaces/UTKojima/1stPaper_v1/core/data_generator.py
-
curl -L -o data_generator.py https://huggingface.co/spaces/UTKojima/1stPaper_v1/resolve/main/core/data_generator.py
36.2 kB
| """ | |
| Data Generation and Corpus Expansion for Enhanced Symplectic LLM Experiment | |
| データ生成・コーパス拡張機能 | |
| Author: Kazuhiro Kojima | |
| Version: 1.0.0 | |
| """ | |
| import random | |
| import json | |
| import logging | |
| from typing import List, Dict, Any, Optional, Tuple | |
| from dataclasses import dataclass | |
| import numpy as np | |
| from datetime import datetime | |
| # 内部モジュール | |
| from cats_corpus_100 import get_corpus | |
| from config import EXPERIMENT_DEFAULTS | |
| # ログ設定 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class DatasetMetadata: | |
| """データセットメタデータ""" | |
| original_size: int | |
| expanded_size: int | |
| expansion_methods: List[str] | |
| creation_timestamp: str | |
| source_corpus: str | |
| quality_score: float | |
| class CorpusExpander: | |
| """コーパス拡張クラス""" | |
| def __init__(self, random_seed: int = 42): | |
| """初期化""" | |
| self.random_seed = random_seed | |
| random.seed(random_seed) | |
| np.random.seed(random_seed) | |
| # 拡張用リソース | |
| self.conjunctions = [ | |
| "また、", "さらに、", "ところで、", "ちなみに、", "一方、", | |
| "つまり、", "例えば、", "特に、", "実際、", "確かに、", | |
| "しかし、", "それでも、", "だから、", "そのため、", "このように、", | |
| "同時に、", "その結果、", "要するに、", "ただし、", "なお、" | |
| ] | |
| self.sentence_endings = [ | |
| "のである。", "のだ。", "ものだ。", "ことだ。", "のです。", | |
| "と思う。", "と言える。", "に違いない。", "であろう。", "かもしれない。", | |
| "と考えられる。", "ということだ。", "のではないか。", "と思われる。", "らしい。" | |
| ] | |
| self.intensifiers = [ | |
| "とても", "非常に", "かなり", "相当", "極めて", | |
| "たいへん", "すごく", "ものすごく", "大変", "実に" | |
| ] | |
| self.time_expressions = [ | |
| "朝", "昼", "夕方", "夜", "深夜", | |
| "春", "夏", "秋", "冬", | |
| "晴れた日", "雨の日", "雪の日", "曇りの日" | |
| ] | |
| logger.info(f"🔧 CorpusExpander initialized with seed {random_seed}") | |
| def expand_corpus(self, target_size: int) -> List[str]: | |
| """コーパスを指定サイズまで拡張""" | |
| base_corpus = get_corpus() | |
| logger.info(f"📚 Base corpus loaded: {len(base_corpus)} sentences") | |
| if target_size <= len(base_corpus): | |
| return base_corpus[:target_size] | |
| expanded_corpus = base_corpus.copy() | |
| expansion_methods = [] | |
| # 拡張戦略 | |
| strategies = [ | |
| (self._add_conjunctions, "conjunction_addition"), | |
| (self._modify_endings, "ending_modification"), | |
| (self._add_intensifiers, "intensifier_addition"), | |
| (self._add_time_context, "temporal_context"), | |
| (self._synonym_replacement, "synonym_replacement"), | |
| (self._structural_variation, "structural_variation") | |
| ] | |
| while len(expanded_corpus) < target_size: | |
| # 元のコーパスから文を選択 | |
| source_sentence = random.choice(base_corpus) | |
| # ランダムに拡張戦略を選択 | |
| strategy_func, method_name = random.choice(strategies) | |
| try: | |
| new_sentence = strategy_func(source_sentence) | |
| # 重複チェック | |
| if new_sentence not in expanded_corpus: | |
| expanded_corpus.append(new_sentence) | |
| expansion_methods.append(method_name) | |
| except Exception as e: | |
| logger.warning(f"Failed to apply {method_name} to '{source_sentence[:30]}...': {e}") | |
| continue | |
| final_corpus = expanded_corpus[:target_size] | |
| logger.info(f"📈 Corpus expanded: {len(base_corpus)} → {len(final_corpus)} sentences") | |
| logger.info(f"🛠️ Expansion methods used: {set(expansion_methods)}") | |
| return final_corpus | |
| def _add_conjunctions(self, sentence: str) -> str: | |
| """接続詞追加""" | |
| conjunction = random.choice(self.conjunctions) | |
| return conjunction + sentence | |
| def _modify_endings(self, sentence: str) -> str: | |
| """文末変更""" | |
| # 既存の句点を除去 | |
| base_sentence = sentence.rstrip("。") | |
| new_ending = random.choice(self.sentence_endings) | |
| return base_sentence + new_ending | |
| def _add_intensifiers(self, sentence: str) -> str: | |
| """強調語追加""" | |
| intensifier = random.choice(self.intensifiers) | |
| # 形容詞を探して強調語を挿入 | |
| adjective_patterns = ["美しい", "可愛い", "小さい", "大きい", "静か", "活発", "元気"] | |
| for adj in adjective_patterns: | |
| if adj in sentence: | |
| return sentence.replace(adj, intensifier + adj, 1) | |
| # 形容詞が見つからない場合は文頭に追加 | |
| return intensifier + "、" + sentence | |
| def _add_time_context(self, sentence: str) -> str: | |
| """時間的文脈追加""" | |
| time_expr = random.choice(self.time_expressions) | |
| return f"{time_expr}、{sentence}" | |
| def _synonym_replacement(self, sentence: str) -> str: | |
| """同義語置換""" | |
| # 猫関連の同義語辞書 | |
| cat_synonyms = { | |
| "猫": ["ネコ", "にゃんこ", "ねこちゃん", "キャット"], | |
| "子猫": ["こねこ", "仔猫", "kitten", "子ネコ"], | |
| "飼い猫": ["ペット", "愛猫", "家猫"], | |
| "野良猫": ["のら猫", "野良ネコ", "street cat"], | |
| "鳴く": ["泣く", "ニャーニャー鳴く", "声を出す"], | |
| "眠る": ["寝る", "居眠りする", "うとうとする"], | |
| "遊ぶ": ["じゃれる", "戯れる", "楽しむ"] | |
| } | |
| modified_sentence = sentence | |
| for original, synonyms in cat_synonyms.items(): | |
| if original in modified_sentence: | |
| synonym = random.choice(synonyms) | |
| modified_sentence = modified_sentence.replace(original, synonym, 1) | |
| break | |
| return modified_sentence | |
| def _structural_variation(self, sentence: str) -> str: | |
| """構造的バリエーション""" | |
| # 語順変更や受動態化など | |
| structural_patterns = [ | |
| lambda s: s.replace("は", "が", 1) if "は" in s else s, | |
| lambda s: s.replace("を", "に", 1) if "を" in s else s, | |
| lambda s: s.replace("で", "において", 1) if "で" in s else s, | |
| lambda s: s.replace("と", "そして", 1) if "と" in s else s | |
| ] | |
| pattern = random.choice(structural_patterns) | |
| return pattern(sentence) | |
| def generate_validation_set(self, size: int = 100) -> List[str]: | |
| """検証用データセット生成""" | |
| base_corpus = get_corpus() | |
| # 元のコーパスから重複しない文を生成 | |
| validation_sentences = [] | |
| for i in range(size): | |
| source_sentence = base_corpus[i % len(base_corpus)] | |
| # 複数の変換を適用 | |
| modified = source_sentence | |
| num_modifications = random.randint(1, 3) | |
| for _ in range(num_modifications): | |
| strategies = [ | |
| self._add_conjunctions, | |
| self._modify_endings, | |
| self._add_intensifiers, | |
| self._add_time_context | |
| ] | |
| strategy = random.choice(strategies) | |
| try: | |
| modified = strategy(modified) | |
| except: | |
| continue | |
| validation_sentences.append(modified) | |
| logger.info(f"✅ Validation set generated: {len(validation_sentences)} sentences") | |
| return validation_sentences | |
| def analyze_corpus_diversity(self, corpus: List[str]) -> Dict[str, Any]: | |
| """コーパス多様性分析""" | |
| analysis = { | |
| 'total_sentences': len(corpus), | |
| 'average_length': np.mean([len(s) for s in corpus]), | |
| 'length_std': np.std([len(s) for s in corpus]), | |
| 'unique_words': len(set(''.join(corpus).split())), | |
| 'vocabulary_diversity': 0, | |
| 'sentence_length_distribution': {}, | |
| 'word_frequency': {} | |
| } | |
| # 語彙多様性計算 (Type-Token Ratio) | |
| all_words = ''.join(corpus).split() | |
| analysis['vocabulary_diversity'] = len(set(all_words)) / len(all_words) if all_words else 0 | |
| # 文長分布 | |
| lengths = [len(s) for s in corpus] | |
| analysis['sentence_length_distribution'] = { | |
| 'min': min(lengths), | |
| 'max': max(lengths), | |
| 'median': np.median(lengths), | |
| 'q25': np.percentile(lengths, 25), | |
| 'q75': np.percentile(lengths, 75) | |
| } | |
| # 頻出語分析 | |
| from collections import Counter | |
| word_counts = Counter(all_words) | |
| analysis['word_frequency'] = dict(word_counts.most_common(10)) | |
| return analysis | |
| class DatasetGenerator: | |
| """データセット生成メインクラス""" | |
| def __init__(self, corpus_expander: CorpusExpander = None): | |
| self.corpus_expander = corpus_expander or CorpusExpander() | |
| def create_experimental_dataset(self, | |
| sample_size: int, | |
| validation_size: int = 100, | |
| test_size: int = 50) -> Dict[str, Any]: | |
| """実験用データセット作成""" | |
| logger.info(f"🔨 Creating experimental dataset: {sample_size} samples") | |
| # メインデータセット | |
| main_corpus = self.corpus_expander.expand_corpus(sample_size) | |
| # 検証データセット | |
| validation_corpus = self.corpus_expander.generate_validation_set(validation_size) | |
| # テストデータセット(元のコーパスから) | |
| base_corpus = get_corpus() | |
| test_corpus = base_corpus[:test_size] | |
| # 多様性分析 | |
| main_diversity = self.corpus_expander.analyze_corpus_diversity(main_corpus) | |
| # メタデータ作成 | |
| metadata = DatasetMetadata( | |
| original_size=len(base_corpus), | |
| expanded_size=len(main_corpus), | |
| expansion_methods=["conjunction", "ending", "intensifier", "temporal", "synonym", "structural"], | |
| creation_timestamp=datetime.now().isoformat(), | |
| source_corpus="cats_corpus_100", | |
| quality_score=main_diversity['vocabulary_diversity'] | |
| ) | |
| dataset = { | |
| 'main_corpus': main_corpus, | |
| 'validation_corpus': validation_corpus, | |
| 'test_corpus': test_corpus, | |
| 'metadata': metadata.__dict__, | |
| 'diversity_analysis': main_diversity, | |
| 'statistics': { | |
| 'total_sentences': len(main_corpus) + len(validation_corpus) + len(test_corpus), | |
| 'main_size': len(main_corpus), | |
| 'validation_size': len(validation_corpus), | |
| 'test_size': len(test_corpus), | |
| 'expansion_ratio': len(main_corpus) / len(base_corpus) | |
| } | |
| } | |
| logger.info(f"✅ Experimental dataset created successfully") | |
| logger.info(f"📊 Main: {len(main_corpus)}, Validation: {len(validation_corpus)}, Test: {len(test_corpus)}") | |
| return dataset | |
| def save_dataset(self, dataset: Dict[str, Any], filepath: str = None) -> str: | |
| """データセット保存""" | |
| if not filepath: | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| filepath = f"experimental_dataset_{timestamp}.json" | |
| # DatasetMetadataオブジェクトを辞書に変換 | |
| dataset_copy = dataset.copy() | |
| if 'metadata' in dataset_copy and hasattr(dataset_copy['metadata'], '__dict__'): | |
| dataset_copy['metadata'] = dataset_copy['metadata'].__dict__ | |
| with open(filepath, 'w', encoding='utf-8') as f: | |
| json.dump(dataset_copy, f, indent=2, ensure_ascii=False) | |
| logger.info(f"💾 Dataset saved to: {filepath}") | |
| return filepath | |
| def load_dataset(self, filepath: str) -> Dict[str, Any]: | |
| """データセット読み込み""" | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| dataset = json.load(f) | |
| logger.info(f"📂 Dataset loaded from: {filepath}") | |
| return dataset | |
| class ValidationDataGenerator: | |
| """検証データ生成クラス""" | |
| def __init__(self): | |
| pass | |
| def generate_stress_test_data(self, size: int = 50) -> List[str]: | |
| """ストレステスト用データ生成""" | |
| stress_patterns = [ | |
| # 極端に短い文 | |
| "猫。", "ねこ。", "にゃん。", | |
| # 極端に長い文 | |
| "我が家で飼っている三毛猫のタマちゃんは、毎朝早起きして庭の花壇で日向ぼっこをしながら、通りかかる鳥たちを興味深そうに眺めているのですが、時々突然立ち上がって獲物を追いかけるような仕草を見せることがあり、その姿がとても愛らしくて家族全員が癒されています。", | |
| # 記号を含む文 | |
| "猫の名前は「ミケ」です。", "猫が「にゃーん♪」と鳴いた。", | |
| # 数字を含む文 | |
| "我が家には3匹の猫がいます。", "猫の寿命は約15年です。", | |
| # 英語を含む文 | |
| "This cat is very cute.", "猫はcatと言います。" | |
| ] | |
| stress_data = [] | |
| for i in range(size): | |
| pattern = stress_patterns[i % len(stress_patterns)] | |
| stress_data.append(pattern) | |
| logger.info(f"🧪 Stress test data generated: {len(stress_data)} sentences") | |
| return stress_data | |
| def generate_edge_cases(self) -> List[str]: | |
| """エッジケース生成""" | |
| edge_cases = [ | |
| "", # 空文字 | |
| " ", # 空白のみ | |
| "。", # 句点のみ | |
| "猫" * 100, # 同じ文字の繰り返し | |
| "?!?!?!", # 記号の連続 | |
| "123456789", # 数字のみ | |
| "ABCDEFGHIJ", # 英語のみ | |
| "\n\t\r", # 制御文字 | |
| ] | |
| logger.info(f"⚠️ Edge cases generated: {len(edge_cases)} cases") | |
| return edge_cases | |
| # ユーティリティ関数 | |
| def quick_corpus_expansion(target_size: int = 1000, seed: int = 42) -> List[str]: | |
| """クイックコーパス拡張""" | |
| expander = CorpusExpander(random_seed=seed) | |
| return expander.expand_corpus(target_size) | |
| def analyze_expansion_quality(original_corpus: List[str], | |
| expanded_corpus: List[str]) -> Dict[str, Any]: | |
| """拡張品質分析""" | |
| original_analysis = CorpusExpander().analyze_corpus_diversity(original_corpus) | |
| expanded_analysis = CorpusExpander().analyze_corpus_diversity(expanded_corpus) | |
| quality_metrics = { | |
| 'vocabulary_growth': expanded_analysis['vocabulary_diversity'] / original_analysis['vocabulary_diversity'], | |
| 'length_variation_increase': expanded_analysis['length_std'] / original_analysis['length_std'], | |
| 'size_expansion_ratio': len(expanded_corpus) / len(original_corpus), | |
| 'uniqueness_ratio': len(set(expanded_corpus)) / len(expanded_corpus), | |
| 'original_retention': len(set(original_corpus).intersection(set(expanded_corpus))) / len(original_corpus) | |
| } | |
| return { | |
| 'original_analysis': original_analysis, | |
| 'expanded_analysis': expanded_analysis, | |
| 'quality_metrics': quality_metrics | |
| } | |
| # エクスポート | |
| __all__ = [ | |
| 'CorpusExpander', | |
| 'DatasetGenerator', | |
| 'ValidationDataGenerator', | |
| 'DatasetMetadata', | |
| 'quick_corpus_expansion', | |
| 'analyze_expansion_quality' | |
| ] | |
| if __name__ == "__main__": | |
| # テスト実行 | |
| print("🧪 Data Generator Test") | |
| # コーパス拡張テスト | |
| expander = CorpusExpander(random_seed=42) | |
| expanded = expander.expand_corpus(200) | |
| print(f"📚 Expanded corpus: {len(expanded)} sentences") | |
| # 多様性分析テスト | |
| diversity = expander.analyze_corpus_diversity(expanded) | |
| print(f"📊 Diversity analysis: {diversity['vocabulary_diversity']:.3f}") | |
| # データセット生成テスト | |
| generator = DatasetGenerator(expander) | |
| dataset = generator.create_experimental_dataset( | |
| sample_size=150, | |
| validation_size=30, | |
| test_size=20 | |
| ) | |
| print(f"🔨 Dataset created: {dataset['statistics']}") | |
| # 品質分析テスト | |
| base_corpus = get_corpus() | |
| quality = analyze_expansion_quality(base_corpus, expanded) | |
| print(f"📈 Quality metrics: {quality['quality_metrics']}") | |
| # ストレステストデータ生成 | |
| validator = ValidationDataGenerator() | |
| stress_data = validator.generate_stress_test_data(10) | |
| print(f"🧪 Stress test data: {len(stress_data)} samples") | |
| # エッジケース生成 | |
| edge_cases = validator.generate_edge_cases() | |
| print(f"⚠️ Edge cases: {len(edge_cases)} cases") | |
| print("✅ All tests completed successfully") | |
| class AdvancedCorpusAnalyzer: | |
| """高度なコーパス分析クラス""" | |
| def __init__(self): | |
| self.morphological_patterns = { | |
| 'particles': ['は', 'が', 'を', 'に', 'で', 'と', 'から', 'まで', 'より'], | |
| 'auxiliary_verbs': ['だ', 'である', 'です', 'ます', 'た', 'ている', 'てある'], | |
| 'conjunctions': ['そして', 'しかし', 'だから', 'また', 'さらに', 'ところで'], | |
| 'question_markers': ['か', 'かな', 'だろう', 'でしょう'] | |
| } | |
| def analyze_linguistic_features(self, corpus: List[str]) -> Dict[str, Any]: | |
| """言語的特徴分析""" | |
| features = { | |
| 'morphological_distribution': {}, | |
| 'sentence_types': {}, | |
| 'complexity_metrics': {}, | |
| 'stylistic_features': {} | |
| } | |
| # 形態素分布分析 | |
| for category, patterns in self.morphological_patterns.items(): | |
| category_count = 0 | |
| for sentence in corpus: | |
| for pattern in patterns: | |
| category_count += sentence.count(pattern) | |
| features['morphological_distribution'][category] = category_count / len(corpus) | |
| # 文タイプ分析 | |
| question_count = sum(1 for s in corpus if '?' in s or 'か。' in s) | |
| exclamation_count = sum(1 for s in corpus if '!' in s) | |
| declarative_count = len(corpus) - question_count - exclamation_count | |
| features['sentence_types'] = { | |
| 'declarative': declarative_count / len(corpus), | |
| 'interrogative': question_count / len(corpus), | |
| 'exclamatory': exclamation_count / len(corpus) | |
| } | |
| # 複雑度メトリクス | |
| punctuation_density = sum(s.count('、') + s.count('。') for s in corpus) / len(corpus) | |
| avg_clauses = sum(s.count('、') + 1 for s in corpus) / len(corpus) | |
| features['complexity_metrics'] = { | |
| 'average_punctuation_density': punctuation_density, | |
| 'average_clauses_per_sentence': avg_clauses, | |
| 'sentence_length_variance': np.var([len(s) for s in corpus]) | |
| } | |
| # 文体特徴 | |
| formal_markers = ['である', 'ではない', 'について', 'に関して'] | |
| informal_markers = ['だ', 'じゃない', 'ちゃう', 'やつ'] | |
| formal_count = sum(sum(sentence.count(marker) for marker in formal_markers) for sentence in corpus) | |
| informal_count = sum(sum(sentence.count(marker) for marker in informal_markers) for sentence in corpus) | |
| features['stylistic_features'] = { | |
| 'formality_ratio': formal_count / max(informal_count, 1), | |
| 'average_formal_markers': formal_count / len(corpus), | |
| 'average_informal_markers': informal_count / len(corpus) | |
| } | |
| return features | |
| def compare_corpus_similarity(self, corpus1: List[str], corpus2: List[str]) -> Dict[str, float]: | |
| """コーパス間類似度比較""" | |
| # 語彙重複度 | |
| words1 = set(''.join(corpus1).split()) | |
| words2 = set(''.join(corpus2).split()) | |
| jaccard_similarity = len(words1.intersection(words2)) / len(words1.union(words2)) | |
| # 文長分布類似度 | |
| lengths1 = [len(s) for s in corpus1] | |
| lengths2 = [len(s) for s in corpus2] | |
| # コルモゴロフ・スミルノフ検定による分布比較 | |
| from scipy.stats import ks_2samp | |
| ks_stat, ks_p = ks_2samp(lengths1, lengths2) | |
| # 平均文長差 | |
| mean_length_diff = abs(np.mean(lengths1) - np.mean(lengths2)) | |
| return { | |
| 'vocabulary_jaccard_similarity': jaccard_similarity, | |
| 'length_distribution_ks_statistic': ks_stat, | |
| 'length_distribution_p_value': ks_p, | |
| 'mean_length_difference': mean_length_diff, | |
| 'size_ratio': len(corpus2) / len(corpus1) | |
| } | |
| class SemanticCorpusEnhancer: | |
| """意味的コーパス強化クラス""" | |
| def __init__(self): | |
| # 意味的関連語グループ | |
| self.semantic_groups = { | |
| 'cat_family': ['猫', 'ネコ', '猫ちゃん', 'にゃんこ', 'キャット'], | |
| 'cat_actions': ['鳴く', '眠る', '遊ぶ', '歩く', '走る', '跳ぶ', '登る'], | |
| 'cat_attributes': ['可愛い', '美しい', '柔らかい', '暖かい', '小さい'], | |
| 'cat_colors': ['黒', '白', '茶色', '三毛', 'グレー', '縞模様'], | |
| 'cat_body_parts': ['尻尾', '耳', '目', '鼻', '肉球', '爪', 'ひげ'], | |
| 'emotions': ['嬉しい', '悲しい', '楽しい', '驚く', '怒る', '安心'], | |
| 'times': ['朝', '昼', '夕方', '夜', '深夜', '明け方'], | |
| 'places': ['家', '庭', '部屋', '外', '屋根', '木', 'ソファ'] | |
| } | |
| # 感情の強度レベル | |
| self.emotion_intensities = { | |
| 'mild': ['少し', 'やや', 'ちょっと'], | |
| 'moderate': ['とても', 'かなり', 'すごく'], | |
| 'strong': ['非常に', '極めて', 'ものすごく'] | |
| } | |
| def enhance_with_semantic_variation(self, sentence: str, variation_type: str = 'random') -> str: | |
| """意味的バリエーション付与""" | |
| enhanced = sentence | |
| if variation_type == 'emotional': | |
| enhanced = self._add_emotional_context(enhanced) | |
| elif variation_type == 'descriptive': | |
| enhanced = self._add_descriptive_elements(enhanced) | |
| elif variation_type == 'temporal': | |
| enhanced = self._add_temporal_specificity(enhanced) | |
| elif variation_type == 'spatial': | |
| enhanced = self._add_spatial_context(enhanced) | |
| else: # random | |
| methods = [ | |
| self._add_emotional_context, | |
| self._add_descriptive_elements, | |
| self._add_temporal_specificity, | |
| self._add_spatial_context | |
| ] | |
| method = random.choice(methods) | |
| enhanced = method(enhanced) | |
| return enhanced | |
| def _add_emotional_context(self, sentence: str) -> str: | |
| """感情的文脈追加""" | |
| emotions = self.semantic_groups['emotions'] | |
| intensities = random.choice(list(self.emotion_intensities.values())) | |
| emotion = random.choice(emotions) | |
| intensity = random.choice(intensities) | |
| if '。' in sentence: | |
| base = sentence.rstrip('。') | |
| return f"{base}、{intensity}{emotion}そうだ。" | |
| return f"{intensity}{emotion}そうに、{sentence}" | |
| def _add_descriptive_elements(self, sentence: str) -> str: | |
| """記述的要素追加""" | |
| # 猫の身体部位や属性を強調 | |
| for body_part in self.semantic_groups['cat_body_parts']: | |
| if body_part in sentence: | |
| attributes = self.semantic_groups['cat_attributes'] | |
| attribute = random.choice(attributes) | |
| enhanced = sentence.replace(body_part, f"{attribute}{body_part}") | |
| return enhanced | |
| # 色の追加 | |
| if '猫' in sentence: | |
| colors = self.semantic_groups['cat_colors'] | |
| color = random.choice(colors) | |
| return sentence.replace('猫', f'{color}い猫', 1) | |
| return sentence | |
| def _add_temporal_specificity(self, sentence: str) -> str: | |
| """時間的特定性追加""" | |
| times = self.semantic_groups['times'] | |
| time_context = random.choice(times) | |
| seasonal_context = random.choice(['春の', '夏の', '秋の', '冬の']) | |
| weather_context = random.choice(['晴れた', '雨の', '曇りの', '雪の']) | |
| full_context = f"{seasonal_context}{weather_context}{time_context}" | |
| return f"{full_context}、{sentence}" | |
| def _add_spatial_context(self, sentence: str) -> str: | |
| """空間的文脈追加""" | |
| places = self.semantic_groups['places'] | |
| place = random.choice(places) | |
| spatial_markers = ['の中で', 'の近くで', 'の上で', 'の下で', 'の隣で'] | |
| marker = random.choice(spatial_markers) | |
| return f"{place}{marker}、{sentence}" | |
| def create_semantic_variations(self, base_sentence: str, num_variations: int = 5) -> List[str]: | |
| """意味的バリエーション作成""" | |
| variations = [base_sentence] # 元の文も含める | |
| variation_types = ['emotional', 'descriptive', 'temporal', 'spatial'] | |
| for i in range(num_variations): | |
| variation_type = variation_types[i % len(variation_types)] | |
| try: | |
| varied_sentence = self.enhance_with_semantic_variation(base_sentence, variation_type) | |
| if varied_sentence not in variations: | |
| variations.append(varied_sentence) | |
| except Exception as e: | |
| logger.warning(f"Failed to create variation: {e}") | |
| continue | |
| return variations | |
| class DatasetQualityAssurance: | |
| """データセット品質保証クラス""" | |
| def __init__(self): | |
| self.quality_criteria = { | |
| 'min_length': 5, | |
| 'max_length': 200, | |
| 'min_diversity_score': 0.1, | |
| 'max_repetition_ratio': 0.3, | |
| 'required_punctuation': ['。'], | |
| 'forbidden_patterns': ['', ' ', '\n', '\t'] | |
| } | |
| def validate_dataset(self, corpus: List[str]) -> Dict[str, Any]: | |
| """データセット検証""" | |
| validation_results = { | |
| 'total_sentences': len(corpus), | |
| 'passed_sentences': 0, | |
| 'failed_sentences': 0, | |
| 'failure_reasons': {}, | |
| 'quality_score': 0.0, | |
| 'recommendations': [] | |
| } | |
| for sentence in corpus: | |
| is_valid, failure_reason = self._validate_single_sentence(sentence) | |
| if is_valid: | |
| validation_results['passed_sentences'] += 1 | |
| else: | |
| validation_results['failed_sentences'] += 1 | |
| if failure_reason not in validation_results['failure_reasons']: | |
| validation_results['failure_reasons'][failure_reason] = 0 | |
| validation_results['failure_reasons'][failure_reason] += 1 | |
| # 品質スコア計算 | |
| validation_results['quality_score'] = validation_results['passed_sentences'] / len(corpus) | |
| # 推奨事項生成 | |
| validation_results['recommendations'] = self._generate_quality_recommendations(validation_results) | |
| return validation_results | |
| def _validate_single_sentence(self, sentence: str) -> Tuple[bool, Optional[str]]: | |
| """単一文の検証""" | |
| # 長さチェック | |
| if len(sentence) < self.quality_criteria['min_length']: | |
| return False, 'too_short' | |
| if len(sentence) > self.quality_criteria['max_length']: | |
| return False, 'too_long' | |
| # 禁止パターンチェック | |
| if sentence in self.quality_criteria['forbidden_patterns']: | |
| return False, 'forbidden_pattern' | |
| # 句読点チェック | |
| has_required_punctuation = any(punct in sentence for punct in self.quality_criteria['required_punctuation']) | |
| if not has_required_punctuation: | |
| return False, 'missing_punctuation' | |
| # 繰り返しチェック | |
| words = sentence.split() | |
| if len(words) > 0: | |
| unique_words = len(set(words)) | |
| repetition_ratio = 1 - (unique_words / len(words)) | |
| if repetition_ratio > self.quality_criteria['max_repetition_ratio']: | |
| return False, 'high_repetition' | |
| return True, None | |
| def _generate_quality_recommendations(self, validation_results: Dict[str, Any]) -> List[str]: | |
| """品質改善推奨事項生成""" | |
| recommendations = [] | |
| failure_reasons = validation_results['failure_reasons'] | |
| if 'too_short' in failure_reasons: | |
| recommendations.append(f"{failure_reasons['too_short']}文が短すぎます。最低{self.quality_criteria['min_length']}文字必要です。") | |
| if 'too_long' in failure_reasons: | |
| recommendations.append(f"{failure_reasons['too_long']}文が長すぎます。最大{self.quality_criteria['max_length']}文字以下にしてください。") | |
| if 'missing_punctuation' in failure_reasons: | |
| recommendations.append(f"{failure_reasons['missing_punctuation']}文に適切な句読点が不足しています。") | |
| if 'high_repetition' in failure_reasons: | |
| recommendations.append(f"{failure_reasons['high_repetition']}文で語彙の繰り返しが多すぎます。多様性を向上させてください。") | |
| quality_score = validation_results['quality_score'] | |
| if quality_score < 0.8: | |
| recommendations.append("全体的な品質スコアが低いです。データ生成プロセスの見直しを推奨します。") | |
| elif quality_score < 0.9: | |
| recommendations.append("品質スコアが良好ですが、さらなる改善の余地があります。") | |
| return recommendations | |
| def cleanup_dataset(self, corpus: List[str]) -> Tuple[List[str], Dict[str, Any]]: | |
| """データセットクリーンアップ""" | |
| cleaned_corpus = [] | |
| cleanup_stats = { | |
| 'original_size': len(corpus), | |
| 'removed_count': 0, | |
| 'removal_reasons': {} | |
| } | |
| for sentence in corpus: | |
| is_valid, failure_reason = self._validate_single_sentence(sentence) | |
| if is_valid: | |
| cleaned_corpus.append(sentence) | |
| else: | |
| cleanup_stats['removed_count'] += 1 | |
| if failure_reason not in cleanup_stats['removal_reasons']: | |
| cleanup_stats['removal_reasons'][failure_reason] = 0 | |
| cleanup_stats['removal_reasons'][failure_reason] += 1 | |
| cleanup_stats['final_size'] = len(cleaned_corpus) | |
| cleanup_stats['retention_rate'] = len(cleaned_corpus) / len(corpus) | |
| logger.info(f"🧹 Dataset cleaned: {len(corpus)} → {len(cleaned_corpus)} sentences") | |
| logger.info(f"📊 Retention rate: {cleanup_stats['retention_rate']:.2%}") | |
| return cleaned_corpus, cleanup_stats | |
| # 追加のユーティリティ関数 | |
| def create_balanced_dataset(corpus: List[str], | |
| target_size: int, | |
| balance_criteria: str = 'length') -> List[str]: | |
| """バランス調整されたデータセット作成""" | |
| if balance_criteria == 'length': | |
| # 文長によるバランス調整 | |
| lengths = [len(s) for s in corpus] | |
| length_percentiles = [np.percentile(lengths, p) for p in [25, 50, 75]] | |
| categories = [] | |
| for sentence in corpus: | |
| length = len(sentence) | |
| if length <= length_percentiles[0]: | |
| categories.append('short') | |
| elif length <= length_percentiles[1]: | |
| categories.append('medium') | |
| elif length <= length_percentiles[2]: | |
| categories.append('long') | |
| else: | |
| categories.append('very_long') | |
| # 各カテゴリから均等に選択 | |
| category_counts = {cat: categories.count(cat) for cat in set(categories)} | |
| samples_per_category = target_size // len(category_counts) | |
| balanced_corpus = [] | |
| for category in category_counts.keys(): | |
| category_sentences = [corpus[i] for i, cat in enumerate(categories) if cat == category] | |
| sampled = random.sample(category_sentences, min(samples_per_category, len(category_sentences))) | |
| balanced_corpus.extend(sampled) | |
| # 残りをランダムサンプリング | |
| while len(balanced_corpus) < target_size: | |
| remaining = [s for s in corpus if s not in balanced_corpus] | |
| if remaining: | |
| balanced_corpus.append(random.choice(remaining)) | |
| else: | |
| break | |
| return balanced_corpus[:target_size] | |
| def export_dataset_report(dataset: Dict[str, Any], | |
| analysis_results: Dict[str, Any], | |
| filepath: str = None) -> str: | |
| """データセットレポート出力""" | |
| if not filepath: | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| filepath = f"dataset_report_{timestamp}.json" | |
| report = { | |
| 'report_metadata': { | |
| 'generation_timestamp': datetime.now().isoformat(), | |
| 'report_version': '1.0.0' | |
| }, | |
| 'dataset_summary': dataset.get('statistics', {}), | |
| 'quality_analysis': analysis_results, | |
| 'corpus_samples': { | |
| 'main_corpus_sample': dataset['main_corpus'][:5], | |
| 'validation_corpus_sample': dataset['validation_corpus'][:3], | |
| 'test_corpus_sample': dataset['test_corpus'][:3] | |
| }, | |
| 'recommendations': [] | |
| } | |
| # 推奨事項生成 | |
| quality_score = analysis_results.get('quality_score', 0) | |
| if quality_score < 0.8: | |
| report['recommendations'].append("品質改善のためのデータクリーンアップが必要です") | |
| with open(filepath, 'w', encoding='utf-8') as f: | |
| json.dump(report, f, indent=2, ensure_ascii=False) | |
| logger.info(f"📋 Dataset report exported to: {filepath}") | |
| return filepath | |
| # 更新されたエクスポート | |
| __all__ = [ | |
| 'CorpusExpander', | |
| 'DatasetGenerator', | |
| 'ValidationDataGenerator', | |
| 'DatasetMetadata', | |
| 'AdvancedCorpusAnalyzer', | |
| 'SemanticCorpusEnhancer', | |
| 'DatasetQualityAssurance', | |
| 'quick_corpus_expansion', | |
| 'analyze_expansion_quality', | |
| 'create_balanced_dataset', | |
| 'export_dataset_report' | |
| ] | |