#!/usr/bin/env python3 from __future__ import annotations import json import re import shutil import statistics from collections import Counter, defaultdict from pathlib import Path from typing import Any import pandas as pd ROOT = Path("life_streaming_cot_dataset") DATA_DIR = ROOT / "data" VERSION = "v0.4.1" GENERATION_METHOD = "source_grounded_rule_based_v0.4.1_quality_patch" REFINEMENT_METHOD = "rule_based_quality_patch_v0.4.1" REPO_ID = "skyzhou06/LifeStreamingCoT" EXCLUDED_HQ_FLAGS = { "copied_source_response", "awkward_answer", "keyword_stitching", "repeated_context_chunks", "weak_high_quality_candidate", "generic_reasoning", "closing_mishandled", "possible_slot_error", "excessive_chunking", "fragment_chunk", "low_specificity", } SEVERE_FLAGS = { "generic_reasoning", "closing_mishandled", "possible_slot_error", "excessive_chunking", "fragment_chunk", "low_specificity", } BASE_FIELDS = [ "id", "domain", "source_dataset", "instruction", "context", "context_chunks", "streaming_reasoning", "deep_reasoning", "answer", "response", "messages", "text", "num_chunks", "language", "split", "generation_method", "quality_flags", "version", "reasoning_policy", "chunking_method", "chunk_labels", "skip_chunks", "skip_reasons", "reasoning_token_budget", "original_num_chunks", "chunk_split_count", "quality_score", "is_high_quality", "refinement_method", "llm_augmented", "llm_augmentation_model", "rejected_reason", "state_tracking_confidence", ] def read_jsonl(path: Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] with path.open("r", encoding="utf-8") as handle: for line in handle: line = line.strip() if line: rows.append(json.loads(line)) return rows def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None: pd.DataFrame(rows, columns=BASE_FIELDS).to_parquet(path, index=False) def word_count(text: Any) -> int: return len(re.findall(r"\b[\w'-]+\b", str(text))) def normalize(text: Any) -> str: return re.sub(r"\W+", " ", str(text).lower()).strip() def avg(values: list[float]) -> float: return statistics.mean(values) if values else 0.0 def repeated_chunk_ratio(row: dict[str, Any]) -> tuple[int, float]: chunks = [normalize(chunk) for chunk in row.get("context_chunks", []) if normalize(chunk)] counts = Counter(chunks) repeated = sum(count - 1 for count in counts.values() if count > 1) return repeated, repeated / len(chunks) if chunks else 0.0 def hard_fragment(chunk: str) -> bool: text = str(chunk or "").strip() normalized = normalize(text) if not text or not normalized: return True if normalized in {"mr", "mrs", "ms", "dr", "prof", "macmillan"}: return True if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\.?", text): return True if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\s+\.", text): return True return word_count(text) <= 2 and bool(re.fullmatch(r"[\W_]+", text)) def short_fragmentish(chunk: str) -> bool: text = str(chunk or "").strip() if hard_fragment(text): return True if word_count(text) >= 4: return False safe_short = re.search( r"\b(hi|hello|thanks|thank|yes|no|ok|okay|bye|goodbye|wow|well|sure|certainly|yeah|yep|nope|sorry|wait|listen|right|exactly|perfect|interesting|tomorrow|monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b", text, flags=re.IGNORECASE, ) meaningful_short = re.search( r"\b(book|leave|go|wait|stop|help|call|turn|tap|click|wipe|wash|unplug|rinse)\b", text, flags=re.IGNORECASE, ) return not (safe_short or meaningful_short) def keyword_list_style(text: str) -> bool: lower = str(text).lower() if re.search(r"\b(main topic is|especially with|after|because|around)\s+[a-z][a-z'-]+,\s+[a-z][a-z'-]+", lower): return True if re.search(r"\b[a-z][a-z'-]+,\s+[a-z][a-z'-]+,\s+[a-z][a-z'-]+(?:,\s+[a-z][a-z'-]+)?\b", lower): return any(marker in lower for marker in ["user feels", "user is processing", "main topic", "especially with", "dialogue state"]) return False def awkward_answer(row: dict[str, Any]) -> bool: answer = str(row.get("answer", "")) lower = answer.lower() return ( "especially with" in lower or "the main topic is" in lower or "certainly," in lower or keyword_list_style(answer) ) def emotional_keyword_stitching(row: dict[str, Any]) -> bool: if row.get("domain") != "emotional_support": return False stream = str(row.get("streaming_reasoning", "")) deep = str(row.get("deep_reasoning", "")) answer = str(row.get("answer", "")) support_signals = stream.count("support_signal=received") chunks = max(1, int(row.get("num_chunks", 1))) return ( support_signals >= 3 or support_signals / chunks > 0.35 or "especially with" in answer.lower() or keyword_list_style(deep) or keyword_list_style(answer) ) def task_closing_mishandled(row: dict[str, Any]) -> bool: if row.get("domain") != "task_oriented_assistant": return False context = " ".join(row.get("context_chunks", [])) closing = re.search( r"\b(thanks|thank you|goodbye|bye|that'?s all|that is all|all i need|all i needed|all set|take care|good bye)\b", context, flags=re.IGNORECASE, ) asks = re.search(r"\?|what .*(should|would)|please (provide|confirm|tell)|which .* should|share .*", str(row.get("answer", "")), flags=re.IGNORECASE) return bool(closing and asks) def recompute_flags(row: dict[str, Any]) -> list[str]: flags = list(dict.fromkeys(row.get("quality_flags", []))) chunks = row.get("context_chunks", []) repeated, ratio = repeated_chunk_ratio(row) if repeated: flags.append("repeated_context_chunks") if any(hard_fragment(chunk) for chunk in chunks): flags.append("fragment_chunk") if any(short_fragmentish(chunk) for chunk in chunks): flags.append("weak_high_quality_candidate") avg_chunk_words = avg([word_count(chunk) for chunk in chunks]) if avg_chunk_words < 4 or row.get("num_chunks", 0) > 12: flags.append("excessive_chunking") if awkward_answer(row): flags.append("awkward_answer") if emotional_keyword_stitching(row): flags.append("keyword_stitching") if "Dialogue state:" in str(row.get("deep_reasoning", "")): flags.append("weak_high_quality_candidate") if task_closing_mishandled(row): flags.append("closing_mishandled") if ratio > 0.30: flags.append("weak_high_quality_candidate") return list(dict.fromkeys(flags)) def recompute_quality_score(row: dict[str, Any], flags: list[str]) -> float: penalties = { "generic_reasoning": 0.20, "copied_source_response": 0.20, "awkward_answer": 0.25, "keyword_stitching": 0.25, "weak_high_quality_candidate": 0.20, "repeated_context_chunks": 0.10, "fragment_chunk": 0.20, "excessive_chunking": 0.15, "closing_mishandled": 0.20, "possible_slot_error": 0.15, "low_specificity": 0.15, "long_streaming_reasoning": 0.05, "long_deep_reasoning": 0.05, "too_many_skips": 0.05, "weak_context": 0.05, } score = 1.0 - sum(penalties.get(flag, 0.0) for flag in set(flags)) if repeated_chunk_ratio(row)[1] > 0.30: score -= 0.10 if word_count(row.get("streaming_reasoning", "")) > 120: score -= 0.05 if word_count(row.get("deep_reasoning", "")) > 45: score -= 0.05 return round(max(0.0, min(1.0, score)), 3) def is_high_quality(row: dict[str, Any]) -> bool: flags = set(row.get("quality_flags", [])) if row.get("quality_score", 0) < 0.85: return False if flags & EXCLUDED_HQ_FLAGS: return False if repeated_chunk_ratio(row)[1] > 0: return False if word_count(row.get("streaming_reasoning", "")) > 120 or word_count(row.get("deep_reasoning", "")) > 45: return False return True def update_row(row: dict[str, Any]) -> dict[str, Any]: row = dict(row) row["version"] = VERSION row["generation_method"] = GENERATION_METHOD row["refinement_method"] = REFINEMENT_METHOD flags = recompute_flags(row) row["quality_flags"] = flags row["quality_score"] = recompute_quality_score(row, flags) row["is_high_quality"] = is_high_quality(row) return row def quality_counts(rows: list[dict[str, Any]]) -> dict[str, int]: return dict(sorted(Counter(flag for row in rows for flag in row.get("quality_flags", [])).items())) def source_summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: counts = Counter(row["source_dataset"] for row in rows) domains: dict[str, set[str]] = defaultdict(set) for row in rows: domains[row["source_dataset"]].add(row["domain"]) return [{"name": source, "domain": ",".join(sorted(domains[source])), "rows": count} for source, count in sorted(counts.items())] def metrics(rows: list[dict[str, Any]]) -> dict[str, Any]: total_chunks = sum(row.get("num_chunks", 0) for row in rows) skip_chunks = sum(len(row.get("skip_chunks", [])) for row in rows) severe = sum(1 for row in rows if set(row.get("quality_flags", [])) & SEVERE_FLAGS) return { "rows": len(rows), "average_quality_score": avg([float(row.get("quality_score", 0)) for row in rows]), "average_streaming_reasoning_words": avg([word_count(row.get("streaming_reasoning", "")) for row in rows]), "average_deep_reasoning_words": avg([word_count(row.get("deep_reasoning", "")) for row in rows]), "average_num_chunks": avg([row.get("num_chunks", 0) for row in rows]), "average_chunk_length": avg([word_count(chunk) for row in rows for chunk in row.get("context_chunks", [])]), "skip_chunk_ratio": skip_chunks / total_chunks if total_chunks else 0, "severe_flag_percentage": severe / len(rows) if rows else 0, "quality_flags_distribution": quality_counts(rows), } def select_review_samples(rows: list[dict[str, Any]], hq_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: fields = [ "id", "domain", "context_chunks", "chunk_labels", "skip_reasons", "streaming_reasoning", "deep_reasoning", "answer", "quality_flags", "quality_score", "is_high_quality", "refinement_method", "split", ] selected: list[dict[str, Any]] = [] seen: set[str] = set() by_domain: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in hq_rows + rows: by_domain[row["domain"]].append(row) for domain in ["task_oriented_assistant", "emotional_support", "daily_dialogue", "how_to_guidance"]: for row in by_domain.get(domain, [])[:30]: if row["id"] in seen: continue selected.append({field: row.get(field) for field in fields}) seen.add(row["id"]) for row in rows: if len(selected) >= 120: break if row["id"] not in seen: selected.append({field: row.get(field) for field in fields}) seen.add(row["id"]) return selected[:120] def update_dataset_info( train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]], hq_train: list[dict[str, Any]], hq_eval: list[dict[str, Any]], old_info: dict[str, Any], ) -> dict[str, Any]: rows = train_rows + eval_rows hq_rows = hq_train + hq_eval full_metrics = metrics(rows) hq_metrics = metrics(hq_rows) return { **old_info, "version": VERSION, "repo_id": REPO_ID, "generation_method": GENERATION_METHOD, "refinement_method": REFINEMENT_METHOD, "patch_name": "v0.4.1 loading config and high-quality subset patch", "patch_notes": [ "Adds explicit Hugging Face dataset card configs so default loading uses only data/train.parquet and data/eval.parquet.", "Adds a separate high_quality config backed by data/train_high_quality.parquet and data/eval_high_quality.parquet.", "Tightens high-quality subset filtering to remove copied-source responses, awkward answer templates, keyword-stitching, repeated chunks, and weak candidates.", ], "hf_config_fixed": True, "old_v0_4_counts": { "train_rows": old_info.get("train_rows"), "eval_rows": old_info.get("eval_rows"), "high_quality_train_rows": old_info.get("high_quality_train_rows"), "high_quality_eval_rows": old_info.get("high_quality_eval_rows"), "hf_auto_detected_total_rows": 18336, }, "total_rows": len(rows), "train_rows": len(train_rows), "eval_rows": len(eval_rows), "high_quality_train_rows": len(hq_train), "high_quality_eval_rows": len(hq_eval), "domains": dict(sorted(Counter(row["domain"] for row in rows).items())), "source_datasets_used": source_summary(rows), "average_streaming_reasoning_words": full_metrics["average_streaming_reasoning_words"], "average_deep_reasoning_words": full_metrics["average_deep_reasoning_words"], "average_quality_score": full_metrics["average_quality_score"], "high_quality_percentage": len(hq_rows) / len(rows) if rows else 0, "skip_chunk_ratio": full_metrics["skip_chunk_ratio"], "quality_flags_distribution": full_metrics["quality_flags_distribution"], "high_quality_metrics": hq_metrics, "high_quality_filtering_rules": sorted(EXCLUDED_HQ_FLAGS | {"quality_score >= 0.85", "no repeated context chunks", "streaming/deep length limits"}), "llm_augmented_count": sum(1 for row in rows if row.get("llm_augmented")), } def yaml_front_matter() -> str: return f"""--- pretty_name: LifeStreamingCoT language: - en license: apache-2.0 version: "{VERSION}" configs: - config_name: default data_files: - split: train path: data/train.parquet - split: test path: data/eval.parquet - config_name: high_quality data_files: - split: train path: data/train_high_quality.parquet - split: test path: data/eval_high_quality.parquet task_categories: - text-generation tags: - streaming-reasoning - selective-reasoning - quality-refined - supervised-fine-tuning - sft - dialogue - task-oriented-dialogue - life-assistant - streamingthinker size_categories: - 1K None: path = ROOT / "README.md" text = path.read_text(encoding="utf-8") body = re.sub(r"\A---.*?---\s*", "", text, flags=re.DOTALL) body = body.replace( "Current version: v0.4: Quality-Refined Selective Streaming Reasoning", "Current version: v0.4.1: Loading Config and High-Quality Subset Patch", ) body = body.replace( "| v0.4 | Quality refinement, quality scores, high-quality subset |", "| v0.4 | Quality refinement, quality scores, high-quality subset |\n| v0.4.1 | HF loading config fix, stricter high-quality filtering |", ) if "## Version 0.4.1: Loading Config and High-Quality Subset Patch" not in body: section = f""" ## Version 0.4.1: Loading Config and High-Quality Subset Patch v0.4.1 is a patch over v0.4. It fixes Hugging Face loading behavior by adding explicit dataset card configs. The default config now points only to the full dataset files, while the `high_quality` config points only to the stricter high-quality subset files. ```python from datasets import load_dataset full = load_dataset("skyzhou06/LifeStreamingCoT", "default") hq = load_dataset("skyzhou06/LifeStreamingCoT", "high_quality") ``` Expected split sizes for v0.4.1: - `default/train`: {info['train_rows']} - `default/test`: {info['eval_rows']} - `high_quality/train`: {info['high_quality_train_rows']} - `high_quality/test`: {info['high_quality_eval_rows']} The high-quality subset excludes copied-source responses, awkward answer templates, keyword-stitching, repeated context chunks, weak candidates, and severe quality flags. """ body = body.replace("## Version History\n", section + "\n## Version History\n") body = re.sub(r"- Train: \d+", f"- Train: {info['train_rows']}", body) body = re.sub(r"- Eval: \d+", f"- Eval: {info['eval_rows']}", body) body = re.sub(r"- Total: \d+", f"- Total: {info['total_rows']}", body) body = re.sub(r"- High-quality train: \d+", f"- High-quality train: {info['high_quality_train_rows']}", body) body = re.sub(r"- High-quality eval: \d+", f"- High-quality eval: {info['high_quality_eval_rows']}", body) body = body.replace("v0.4 improves quality", "v0.4 improved quality") path.write_text(yaml_front_matter() + body, encoding="utf-8") def sync_scripts() -> None: target = ROOT / "scripts" target.mkdir(parents=True, exist_ok=True) for src in Path("scripts").glob("*.py"): shutil.copy2(src, target / src.name) def main() -> None: old_info = json.loads((ROOT / "dataset_info.json").read_text(encoding="utf-8")) train_rows = [update_row(row) for row in read_jsonl(DATA_DIR / "train.jsonl")] eval_rows = [update_row(row) for row in read_jsonl(DATA_DIR / "eval.jsonl")] hq_train = [row for row in train_rows if row["is_high_quality"]] hq_eval = [row for row in eval_rows if row["is_high_quality"]] if len(hq_train) + len(hq_eval) < 1000: raise RuntimeError("v0.4.1 high-quality filtering produced fewer than 1000 rows.") write_jsonl(DATA_DIR / "train.jsonl", train_rows) write_jsonl(DATA_DIR / "eval.jsonl", eval_rows) write_jsonl(DATA_DIR / "train_high_quality.jsonl", hq_train) write_jsonl(DATA_DIR / "eval_high_quality.jsonl", hq_eval) write_parquet(DATA_DIR / "train.parquet", train_rows) write_parquet(DATA_DIR / "eval.parquet", eval_rows) write_parquet(DATA_DIR / "train_high_quality.parquet", hq_train) write_parquet(DATA_DIR / "eval_high_quality.parquet", hq_eval) info = update_dataset_info(train_rows, eval_rows, hq_train, hq_eval, old_info) (ROOT / "dataset_info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") write_jsonl(ROOT / "samples_for_review.jsonl", select_review_samples(train_rows + eval_rows, hq_train + hq_eval)) update_readme(info) sync_scripts() print(json.dumps({ "version": VERSION, "train_rows": len(train_rows), "eval_rows": len(eval_rows), "high_quality_train_rows": len(hq_train), "high_quality_eval_rows": len(hq_eval), "high_quality_total": len(hq_train) + len(hq_eval), "full_quality_flags": quality_counts(train_rows + eval_rows), "high_quality_flags": quality_counts(hq_train + hq_eval), }, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()