File size: 8,905 Bytes
ba71465 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | # OFF_DataQuality: Perl-to-Python Data Quality Migration & Benchmarking Framework
## Overview
**OFF_DataQuality** is an end-to-end framework designed to modernize legacy data quality validation logic for **Open Food Facts (OFF)**.
Historically, Open Food Facts relied on legacy **Perl (`.pl`)** scripts to enforce quality controls across millions of food products—ranging from energy unit conversions (kcal vs. kJ) and macro-nutrient balance checks (sugars, fats, carbohydrates) to jurisdiction-specific allergen and packaging compliance regulations.
This project provides an automated pipeline for:
1. **Extracting** relational, threshold, and logic conditions from legacy Perl scripts.
2. **Migrating** rules into modern **Python** validation logic using LLMs (Groq / GPT-oss-120b) with deterministic fallback templates and semantic guardrail verification.
3. **Generating Declarative Targets** for **dbt-core** (DuckDB SQL tests) and **SodaCL** (Soda data quality contracts).
4. **Benchmarking Parity** across legacy Perl outputs vs. Python, dbt, and Soda execution engines with conservative statistical confidence scoring (95% Wilson bounds & Beta posteriors).
5. **Interactive Dashboarding** to inspect side-by-side rule performance, win distributions by complexity (simple, medium, intricate), and legal traceability metadata.
---
## Core Architecture & Workflow
```mermaid
flowchart TD
A[Legacy Perl Rules .pl] --> B[Perl Logic Extractor]
B --> C{Migration Engine}
C -->|LLM / Groq GPT-oss-120b| D[Python Rules]
C -->|Declarative Generator| E[dbt DuckDB SQL Tests]
C -->|Declarative Generator| F[SodaCL YAML Contracts]
D --> G[Semantic Guardrails Verification]
E --> H[DuckDB Parity Execution]
F --> H
G --> H
H --> I[Statistical Confidence & Parity Validator]
I --> J[Streamlit Comparison Dashboard]
```
---
## Key Features
### 1. Automated Perl Rule Extraction & Translation
- **Perl Extractor (`extractor/perl_logic_extractor.py`)**: Parses legacy `.pl` condition files to isolate numeric bounds, relational field constraints, and tag generation logic.
- **LLM Converter (`migration/llm_converter.py`)**: Translates extracted rules into executable Python functions via LLM API calls with 2-stage runtime and semantic contract validation.
- **Deterministic Fallback**: If LLM API access is unavailable or semantic checks fail, the system falls back to deterministic rule templates.
### 2. Multi-Engine Declarative Pilot (`dbt` & `SodaCL`)
- **dbt Target**: Automatically generates dbt SQL test models and `count_violations` macros backed by DuckDB.
- **SodaCL Target**: Automatically generates SodaCL contract YAML files for automated data quality scanning.
### 3. Statistical Parity & Confidence Scoring
Rule confidence is computed conservatively to prevent inflation on sparse evidence:
$$ ext{overall\_confidence} = ext{llm\_confidence} imes ext{parity\_ci\_lower\_95} imes ext{evidence\_ci\_lower\_95}$$
Where `parity_ci_lower_95` uses the **Wilson score interval** and `evidence_ci_lower_95` uses a **Beta posterior credible bound** on positive violation matches.
### 4. Jurisdiction Profile Layers
- **`global`**: Generic Open Food Facts nutrient consistency and boundary rules.
- **`canada`**: Phase-1 Canadian regulatory proxy rules (e.g., Front-of-Package (FOP) symbols, bilingual label indicators, allergen statements) with legal citations, source URLs, and review metadata.
- **`hybrid`**: Unified execution across both global and Canadian rule sets.
### 5. Interactive Streamlit Dashboard
An interactive UI (`dashboard/app.py`) presenting per-rule accuracy, side-by-side code/SQL comparisons, engine recommendations, and legal traceability metadata.
---
## Repository Structure
```text
OFF_DataQuality/
├── README.md # Project documentation and execution guide
├── requirements.txt # Core dependencies (duckdb, streamlit, pandas, openai, dbt, soda)
├── pytest.ini # Test configuration
├── inspect_duckdb.py # Utility script for inspecting DuckDB tables
├── config/
│ ├── hypercorn.toml # Server configuration
│ └── custom-covers/ # Custom asset configuration directories
├── dashboard/
│ └── app.py # Interactive Streamlit parity comparison dashboard
├── data/
│ ├── load_dataset.py # Streamed product dataset loader (real OFF JSONL / sample)
│ └── sample_products.jsonl # 400 sample OFF product records for out-of-the-box execution
├── declarative/
│ └── check_runners.py # Declarative dbt & Soda check generation & execution
├── duckdb_utils/
│ └── create_tables.py # In-memory DuckDB table creation & schema setup
├── extractor/
│ └── perl_logic_extractor.py # Legacy Perl script logic parser
├── llm-test/
│ └── test_groq.py # Verification script for Groq API integration
├── migration/
│ └── llm_converter.py # LLM translation pipeline with semantic guardrails
├── perl_checks/
│ ├── legacy_checks.py # Simulated & file-based legacy Perl rule runner
│ └── rules/ # 19 legacy Perl validation rules (.pl)
├── python_checks/
│ └── generated_checks.py # Auto-generated Python quality check routines
├── results/
│ ├── engine_comparison.json # Pre-computed benchmark comparison report
│ ├── migration_results.json # Migration execution output
│ └── declarative_runtime/ # Generated dbt & Soda test models and contracts
├── rulepacks/
│ └── registry.py # Global, Canada, and Hybrid rule-pack registry
├── tests/ # Comprehensive pytest suite
└── validation/
├── parity_validator.py # End-to-end parity validation pipeline
├── engine_comparison.py # Multi-engine comparative benchmark suite
└── verification.py # Semantic and runtime verification contracts
```
---
## Security & Publishing Norms
- **No Hardcoded Credentials**: API keys (such as `GROQ_API_KEY`) are read strictly from environment variables.
- **Sanitized Configurations**: Local secret keys, temporary logs, and local SQLite/DuckDB binary database files are excluded.
- **Reproducible Sample Dataset**: Includes 400 sample product records (`data/sample_products.jsonl`) so the entire pipeline can be benchmarked offline out-of-the-box.
---
## Quick Start
### 1. Installation
Clone the repository and install dependencies:
```bash
git clone https://huggingface.co/datasets/offCanada/Final_Deliverables
cd Final_Deliverables/OFF_DataQuality
pip install -r requirements.txt
```
### 2. Run Parity Validator Pipeline
Run parity validation on sample products using the default Python target:
```bash
python -m validation.parity_validator --size 300 --seed 17
```
Run with declarative targets (`dbt` or `soda`):
```bash
python -m validation.parity_validator --size 300 --execution-engine dbt
python -m validation.parity_validator --size 300 --execution-engine soda
```
Run using file-based Perl rule files:
```bash
python -m validation.parity_validator --size 300 --perl-rules-dir perl_checks/rules
```
### 3. Run Multi-Engine Comparison Benchmark
Execute a comparison experiment across Python, dbt, and Soda engines:
```bash
python -m validation.engine_comparison --size 300 --mode off --llm-provider groq
```
Run with specific rule profiles:
```bash
python -m validation.engine_comparison --size 300 --profile global
python -m validation.engine_comparison --size 300 --profile canada
python -m validation.engine_comparison --size 300 --profile hybrid
```
### 4. Launch the Streamlit Dashboard
Explore benchmark metrics, engine recommendations, and rule details interactively:
```bash
streamlit run dashboard/app.py
```
### 5. Running with Groq LLM Integration (Optional)
To enable real LLM translation via Groq:
```powershell
# Windows PowerShell
$env:GROQ_API_KEY="your_groq_api_key_here"
```
```bash
# Bash / Linux / macOS
export GROQ_API_KEY="your_groq_api_key_here"
```
Then run with Groq provider:
```bash
python -m validation.parity_validator --size 300 --llm-provider groq --llm-model openai/gpt-oss-120b
```
### 6. Automated Testing
Run the test suite using `pytest`:
```bash
pytest -q
```
---
## License & Attribution
This project is part of the **Open Food Facts (Canada)** data quality modernization effort. All product sample data and rule definitions conform to Open Food Facts open-data specifications.
|