SanjayH9305's picture
Add OFF_DataQuality project with sanitized code and enriched README
ba71465 verified
|
Raw History Blame Contribute Delete
8.91 kB
# 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.