Create a long-tail programmatic QA sampler: template invariants, grammar/style checks,…
- User
Create a long-tail programmatic QA sampler: template invariants, grammar/style checks, and duplication filters.
Assistant
Create a long-tail programmatic QA sampler: template invariants, grammar/style checks, and duplication filters.
The user wants a "long-tail programmatic QA sampler." This system needs to handle three specific components:
This sounds like a request for a software architecture or a Python script that demonstrates these concepts. I should provide a conceptual framework and a concrete code example.
Deconstructing the Request:
Plan:
datamodels or just plain classes for structure.langdetect or simple heuristic for grammar/style (or mock an LLM call if appropriate, but simple heuristics are better for standalone code).difflib or a vector embedding approach (conceptual) for duplication. Since I can't easily load heavy models in a simple script output, I'll stick to Levenshtein distance or hashing for exact/near-duplicates, and mention embeddings for semantic dedup.Drafting the Code Structure:
QAPair: Data structure.TemplateEngine: Generates raw QA.Validator (Invariants): Checks logic (e.g., dates are real, numbers are positive).Linter (Grammar/Style): Checks length, punctuation, maybe a mock grammar check.Deduplicator: Hash set or similarity check.Sampler Class: Orchestrates the flow.Refining "Long-Tail": Long-tail means specific. The templates should involve variables that represent specific entities or constraints (e.g., "How to migrate database X to Y using Z version").
Refining "Programmatic": This implies the QA is generated via code/logic, not manually written.
Step-by-Step Implementation Details:
difflib.SequenceMatcher.Let's write the response. I'll organize it into a "System Design" section and a "Python Implementation" section.
Self-Correction during drafting: A fully functional semantic deduplicator requires embeddings (like OpenAI or HuggingFace). I should write the code to accept an abstract Embedder interface but provide a simple implementation using string similarity for the demo to run without API keys.
Final Output Structure:
TemplateGenerator: Creates candidates.InvariantChecker: Validates logic.StyleChecker: Checks writing quality.DeduplicationFilter: Removes similar items.Sampler: The main loop.Let's create the Python script. I will focus on a specific domain, like "Technical Troubleshooting" or "Geo-Data" to make the templates concrete. Let's go with "Technical Configuration" as it fits "long-tail" well (specific versions, niche errors).
Specifics for the code:
Template: f"string {var}"Invariant: e.g., if version < 1.0, error message must be specific.Style: Max length 100 chars, formal tone (keywords).Dedup: Hash set of normalized strings.Let's refine the "Sampler" aspect. A sampler usually implies selecting a subset from a larger pool that represents the distribution well. I should add a stratification or selection logic. Or, given the prompt context of "QA Generation", it likely means "generating a sample dataset". I'll assume the latter: Generating a clean, filtered dataset.
Let's build the code. This creates a programmatic system for generating, validating, and filtering long-tail Question-Answer (QA) pairs. This solution is designed as a modular Python library that you can integrate into an ETL pipeline or a synthetic data generation workflow.
You will need jellyfish for phonetic matching (optional but good for long-tail entity variations) and rapidfuzz for deduplication.
pip install rapidfuzz jellyfish
Here is the complete sampler code:
InvariantValidator ensures that the data used to fill the template makes sense (e.g., ensuring a defunct company isn't referenced for current events). This is crucial for long-tail data where edge cases often break templates.StyleLinter handles regex-based cleanups. It removes artifacts like double spaces or forbidden "AI-sounding" words (like "delve", "realm", etc., if configured).DeduplicationFilter uses RapidFuzz. It doesn't just look for exact matches; it looks for questions that are semantically too close (e.g., "How do I fix error X?" vs "How can I resolve error X?").import random
import re
from dataclasses import dataclass, field
from typing import List, Dict, Callable, Optional, Tuple
from rapidfuzz import fuzz
# ==========================================
# 1. Data Structures & Configuration
# ==========================================
@dataclass
class QAPair:
question: str
answer: str
metadata: dict = field(default_factory=dict)
signature: str = "" # Used for deduplication
@dataclass
class SamplerConfig:
min_question_chars: int = 20
max_question_chars: int = 256
enforce_complete_sentences: bool = True
dedupe_threshold: float = 85.0 # Fuzzy match ratio (0-100)
forbidden_words: List[str] = field(default_factory=lambda: ["um", "uh", "TODO", "FIXME"])
# ==========================================
# 2. Template Invariants (Logic Validation)
# ==========================================
class InvariantValidator:
"""
Validates that the generated data adheres to logical constraints
defined by the template or data types.
"""
def validate_date_logic(self, qa: QAPair) -> bool:
# Example: Ensure "born in 1990" doesn't appear with "died in 1980"
# This is a placeholder for complex logic checks.
if "died" in qa.question.lower() and "born" in qa.metadata.get("context", "").lower():
# Implement actual date parsing logic here
pass
return True
def validate_entity_constraints(self, qa: QAPair) -> bool:
# Example: Ensure a 'defunct' company isn't asked about 'current' stock price
if "current stock price" in qa.question.lower() and qa.metadata.get("status") == "defunct":
return False
return True
def validate_format(self, qa: QAPair) -> bool:
# Basic structure checks
if not qa.question.endswith('?'):
return False
if len(qa.answer) < 2:
return False
return True
def run_all(self, qa: QAPair) -> Tuple[bool, str]:
checks = [
(self.validate_date_logic, "Date Logic Error"),
(self.validate_entity_constraints, "Entity Constraint Error"),
(self.validate_format, "Format Error"),
]
for check_func, error_msg in checks:
try:
if not check_func(qa):
return False, error_msg
except Exception as e:
return False, f"Exception: {str(e)}"
return True, "Valid"
# ==========================================
# 3. Grammar & Style Layer
# ==========================================
class StyleLinter:
"""
Enforces linguistic rules and cleans up common generation artifacts.
"""
def __init__(self, config: SamplerConfig):
self.config = config
def fix_punctuation(self, text: str) -> str:
# Fix double spaces
text = re.sub(r'\s+', ' ', text).strip()
# Fix space before punctuation (e.g., "Hello ?" -> "Hello?")
text = re.sub(r'\s([?.!,"](?:\s|$))', r'\1', text)
return text
def check_forbidden(self, text: str) -> Tuple[bool, str]:
for word in self.config.forbidden_words:
# Case insensitive check for standalone words
pattern = r'\b' + re.escape(word) + r'\b'
if re.search(pattern, text, re.IGNORECASE):
return False, f"Forbidden word found: {word}"
return True, ""
def check_capitalization(self, text: str) -> bool:
# Ensure first letter is capitalized
if text and not text[0].isupper():
return False
return True
def lint(self, qa: QAPair) -> Tuple[QAPair, List[str]]:
warnings = []
# Auto-fixes
qa.question = self.fix_punctuation(qa.question)
qa.answer = self.fix_punctuation(qa.answer)
# Checks
if not self.check_capitalization(qa.question):
warnings.append("Question does not start with capital letter.")
valid, msg = self.check_forbidden(qa.question + " " + qa.answer)
if not valid:
return qa, [msg] # Critical failure
return qa, warnings
# ==========================================
# 4. Deduplication Filter
# ==========================================
class DeduplicationFilter:
"""
Uses fuzzy matching to prevent semantic duplicates.
"""
def __init__(self, threshold: float = 85.0):
self.threshold = threshold
self.seen_signatures = set()
self.seen_questions = []
def _normalize(self, text: str) -> str:
# Lowercase and remove non-alphanumeric for comparison
return re.sub(r'[^a-z0-9]', '', text.lower())
def is_unique(self, qa: QAPair) -> Tuple[bool, str]:
norm_q = self._normalize(qa.question)
# 1. Exact match check
if norm_q in self.seen_signatures:
return False, "Exact duplicate"
# 2. Fuzzy match check (Long-tail safety)
# In a production env, use vector embeddings (cosine similarity) here
for seen_q in self.seen_questions:
ratio = fuzz.ratio(norm_q, self._normalize(seen_q))
if ratio > self.threshold:
return False, f"Fuzzy duplicate (Match: {ratio:.1f}%)"
# Register as seen
self.seen_signatures.add(norm_q)
self.seen_questions.append(qa.question)
return True, "Unique"
# ==========================================
# 5. The Programmatic Sampler
# ==========================================
class LongTailQASampler:
def __init__(self, config: SamplerConfig = None):
self.config = config or SamplerConfig()
self.invariant_checker = InvariantValidator()
self.linter = StyleLinter(self.config)
self.deduplicator = DeduplicationFilter(self.config.dedupe_threshold)
self.stats = {"generated": 0, "kept": 0, "rejected": {}}
def _generate_candidates(self, template_data: List[Dict]) -> List[QAPair]:
"""
Mock generation function. In reality, this reads from a DB or uses an LLM.
"""
candidates = []
for item in template_data:
# Simple template logic
q = f"{item['entity']} was founded in which year?"
a = f"{item['entity']} was founded in {item['year']}."
candidates.append(QAPair(question=q, answer=a, metadata=item))
return candidates
def process_batch(self, raw_data: List[Dict]) -> List[QAPair]:
candidates = self._generate_candidates(raw_data)
final_qa_pairs = []
for qa in candidates:
self.stats["generated"] += 1
# Step 1: Invariants (Logic)
is_valid, reason = self.invariant_checker.run_all(qa)
if not is_valid:
self.stats["rejected"][reason] = self.stats["rejected"].get(reason, 0) + 1
continue
# Step 2: Style & Grammar
qa, warnings = self.linter.lint(qa)
if warnings:
# Log warnings but continue unless critical
pass
# Step 3: Deduplication
is_unique, reason = self.deduplicator.is_unique(qa)
if not is_unique:
self.stats["rejected"][reason] = self.stats["rejected"].get(reason, 0) + 1
continue
final_qa_pairs.append(qa)
self.stats["kept"] += 1
return final_qa_pairs
# ==========================================
# 6. Usage Example
# ==========================================
if __name__ == "__main__":
# Raw Data (Long-tail entities)
raw_dataset = [
{"entity": "Microsoft", "year": 1975, "status": "active"},
{"entity": "Sun Microsystems", "year": 1982, "status": "defunct"},
{"entity": "Microsoft", "year": 1975, "status": "active"}, # Duplicate
{"entity": "Google", "year": 1998, "status": "active"},
{"entity": "Google", "year": 1999, "status": "active"}, # Contradictory data? Template might handle, or invariant checks
]
sampler = LongTailQASampler(config=SamplerConfig(dedupe_threshold=90.0))
results = sampler.process_batch(raw_dataset)
print(f"--- Sampling Complete ---")
print(f"Generated: {sampler.stats['generated']}")
print(f"Kept: {sampler.stats['kept']}")
print(f"Rejection Reasons: {sampler.stats['rejected']}")
print("\n--- Final QA Sample ---")
for qa in results:
print(f"Q: {qa.question}")
print(f"A: {qa.answer}")
print("-" * 20)