From 14b84fe28d8b1be466c35edd66a7ada5e2d91dd5 Mon Sep 17 00:00:00 2001 From: Debby Date: Wed, 4 Nov 2026 21:15:11 +0700 Subject: [PATCH] update bigquery_cleaned_1 --- scripts/bigquery_cleaned_layer.py | 385 ++++++++++++++++++++---------- 1 file changed, 260 insertions(+), 125 deletions(-) diff --git a/scripts/bigquery_cleaned_layer.py b/scripts/bigquery_cleaned_layer.py index b8c3a32..da23651 100644 --- a/scripts/bigquery_cleaned_layer.py +++ b/scripts/bigquery_cleaned_layer.py @@ -14,14 +14,15 @@ Usage: python bigquery_cleaned_layer.py """ -import pandas as pd -import numpy as np -from datetime import datetime -import logging -from typing import Dict +import re import json +import logging +from datetime import datetime +from typing import Dict, Optional -from scripts.bigquery_config import get_bigquery_client, CONFIG, get_table_id +import pandas as pd + +from scripts.bigquery_config import get_bigquery_client from scripts.bigquery_helpers import ( log_update, load_to_bigquery, @@ -36,16 +37,36 @@ from google.cloud import bigquery # LOAD STAGING DATA # ============================================================================= +REQUIRED_INPUT_COLUMNS = [ + 'source', 'indicator_original', 'indicator_standardized', 'country', + 'year', 'year_range', 'value', 'unit', +] + + def load_staging_data(client: bigquery.Client) -> pd.DataFrame: """Load data dari staging_integrated (STAGING/Silver layer).""" print("\nLoading data from staging_integrated (fs_asean_silver)...") df_staging = read_from_bigquery(client, 'staging_integrated', layer='silver') print(f" ✓ Loaded : {len(df_staging):,} rows") print(f" Columns : {len(df_staging.columns)}") + + if df_staging.empty: + print(" ⚠ staging_integrated kosong.") + return df_staging + + missing_cols = [c for c in REQUIRED_INPUT_COLUMNS if c not in df_staging.columns] + if missing_cols: + raise ValueError(f"Kolom wajib tidak ada di staging_integrated: {missing_cols}") + print(f" Sources : {df_staging['source'].nunique()}") print(f" Indicators : {df_staging['indicator_standardized'].nunique()}") print(f" Countries : {df_staging['country'].nunique()}") - print(f" Year range : {int(df_staging['year'].min())}-{int(df_staging['year'].max())}") + + years = pd.to_numeric(df_staging['year'], errors='coerce').dropna() + if not years.empty: + print(f" Year range : {int(years.min())}-{int(years.max())}") + else: + print(" Year range : - (kolom year kosong)") return df_staging @@ -66,7 +87,7 @@ COLUMN_CONSTRAINTS = { } -def truncate_string(value, max_length: int) -> str: +def truncate_string(value, max_length: int): """Truncate string ke max_length, return as-is jika None/NaN.""" if pd.isna(value): return value @@ -94,7 +115,7 @@ def apply_column_constraints(df: pd.DataFrame) -> pd.DataFrame: truncation_report[column] = { 'count' : int(truncated_count), 'max_length': max_length, - 'examples' : df_constrained[mask][column].head(3).tolist() + 'examples' : df_constrained.loc[mask, column].head(3).tolist() } df_constrained[column] = df_constrained[column].apply( lambda x: truncate_string(x, max_length) @@ -142,6 +163,8 @@ ASEAN_MAPPING = { 'VIET NAM' : 'Vietnam', } +ASEAN_COUNTRIES = set(ASEAN_MAPPING.values()) + def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'country') -> tuple: """ @@ -156,17 +179,26 @@ def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'cou def map_country(country): if pd.isna(country): return country - s = str(country).strip() + # rapikan spasi & apostrof melengkung sebelum lookup + s = re.sub(r'\s+', ' ', str(country).strip().replace('’', "'")) mapped = ASEAN_MAPPING.get(s.upper(), s) return mapped[:100] if len(mapped) > 100 else mapped - original = df_clean[country_column].copy() - df_clean[country_column] = df_clean[country_column].apply(map_country) - changes = {orig: new for orig, new in zip(original, df_clean[country_column]) if orig != new} + original = df_clean[country_column].copy() + df_clean[country_column] = original.apply(map_country) + + # NaN != NaN bernilai True, jadi baris NaN harus dikecualikan secara eksplisit + changed = original.notna() & (original != df_clean[country_column]) + changes = dict(zip(original[changed], df_clean.loc[changed, country_column])) + + unmapped = sorted( + set(df_clean[country_column].dropna().unique()) - ASEAN_COUNTRIES + ) return df_clean, { - 'countries_mapped': len(set(changes.keys())), + 'countries_mapped': len(changes), 'changes' : changes, + 'non_asean_values': unmapped, } @@ -174,14 +206,8 @@ def standardize_country_names_asean(df: pd.DataFrame, country_column: str = 'cou # PILLAR CLASSIFICATION # ============================================================================= -def assign_pillar(indicator_name: str) -> str: - """ - Assign pillar berdasarkan keyword indikator. - Return values: 'Availability', 'Access', 'Utilization', 'Stability', 'Sustainability' - All ≤ 20 chars (varchar(20) constraint). - """ - if pd.isna(indicator_name): - return 'Sustainability' +def _match_pillar(indicator_name) -> Optional[str]: + """Return pillar jika ada keyword yang cocok, None jika tidak ada.""" ind = str(indicator_name).lower() for kw in ['requirement', 'coefficient', 'losses', 'fat supply']: @@ -215,21 +241,73 @@ def assign_pillar(indicator_name: str) -> str: ]): return 'Utilization' - return 'Sustainability' + return None + + +def assign_pillar(indicator_name: str) -> str: + """ + Assign pillar berdasarkan keyword indikator. + Return values: 'Availability', 'Access', 'Utilization', 'Stability', 'Sustainability' + All ≤ 20 chars (varchar(20) constraint). + Indikator tanpa keyword yang cocok jatuh ke 'Sustainability' (default). + """ + if pd.isna(indicator_name): + return 'Sustainability' + return _match_pillar(indicator_name) or 'Sustainability' # ============================================================================= # DIRECTION CLASSIFICATION # ============================================================================= -def assign_direction(indicator_name: str) -> str: - """ - Assign direction berdasarkan indikator. - Return values: 'higher_better' (13 chars) atau 'lower_better' (12 chars) - Both ≤ 15 chars (varchar(15) constraint). - """ - if pd.isna(indicator_name): - return 'higher_better' +_HIGHER_BETTER_EXCEPTIONS = [ + 'exclusive breastfeeding', + 'dietary energy supply', + 'dietary energy supply adequacy', + 'average fat supply', + 'average protein supply', + 'supply of protein of animal origin', +] + +_LOWER_BETTER_KEYWORDS = [ + 'prevalence of undernourishment', + 'prevalence of severe food insecurity', + 'prevalence of moderate or severe food insecurity', + 'prevalence of moderate food insecurity', + 'prevalence of wasting', + 'prevalence of stunting', + 'prevalence of overweight', + 'prevalence of obesity', + 'prevalence of anemia', + 'prevalence of low birthweight', + 'number of people undernourished', + 'number of severely food insecure', + 'number of moderately or severely food insecure', + 'number of children under 5 years affected by wasting', + 'number of children under 5 years of age who are overweight', + 'number of children under 5 years of age who are stunted', + 'number of newborns with low birthweight', + 'number of obese adults', + 'number of women of reproductive age', + 'percentage of children under 5 years affected by wasting', + 'percentage of children under 5 years of age who are overweight', + 'percentage of children under 5 years of age who are stunted', + 'cereal import dependency', + 'import dependency', + 'value of food imports in total merchandise exports', + 'value of food imports', + 'variability of food production', + 'variability of food supply', + 'per capita food production variability', + 'per capita food supply variability', + 'coefficient of variation', + 'incidence of caloric losses', + 'food losses', +] + + +def _match_direction(indicator_name) -> Optional[str]: + """Return direction jika ada keyword yang cocok, None jika tidak ada.""" ind = str(indicator_name).lower() # Spesifik lower_better @@ -237,57 +315,26 @@ def assign_direction(indicator_name: str) -> str: return 'lower_better' # Higher_better exceptions — cek sebelum lower_better keywords - for kw in [ - 'exclusive breastfeeding', - 'dietary energy supply', - 'dietary energy supply adequacy', - 'average fat supply', - 'average protein supply', - 'supply of protein of animal origin', - ]: - if kw in ind: - return 'higher_better' + if any(kw in ind for kw in _HIGHER_BETTER_EXCEPTIONS): + return 'higher_better' # Lower_better — masalah yang harus diminimalkan - for kw in [ - 'prevalence of undernourishment', - 'prevalence of severe food insecurity', - 'prevalence of moderate or severe food insecurity', - 'prevalence of moderate food insecurity', - 'prevalence of wasting', - 'prevalence of stunting', - 'prevalence of overweight', - 'prevalence of obesity', - 'prevalence of anemia', - 'prevalence of low birthweight', - 'number of people undernourished', - 'number of severely food insecure', - 'number of moderately or severely food insecure', - 'number of children under 5 years affected by wasting', - 'number of children under 5 years of age who are overweight', - 'number of children under 5 years of age who are stunted', - 'number of newborns with low birthweight', - 'number of obese adults', - 'number of women of reproductive age', - 'percentage of children under 5 years affected by wasting', - 'percentage of children under 5 years of age who are overweight', - 'percentage of children under 5 years of age who are stunted', - 'cereal import dependency', - 'import dependency', - 'value of food imports in total merchandise exports', - 'value of food imports', - 'variability of food production', - 'variability of food supply', - 'per capita food production variability', - 'per capita food supply variability', - 'coefficient of variation', - 'incidence of caloric losses', - 'food losses', - ]: - if kw in ind: - return 'lower_better' + if any(kw in ind for kw in _LOWER_BETTER_KEYWORDS): + return 'lower_better' - return 'higher_better' + return None + + +def assign_direction(indicator_name: str) -> str: + """ + Assign direction berdasarkan indikator. + Return values: 'higher_better' (13 chars) atau 'lower_better' (12 chars) + Both ≤ 15 chars (varchar(15) constraint). + Indikator tanpa keyword yang cocok jatuh ke 'higher_better' (default). + """ + if pd.isna(indicator_name): + return 'higher_better' + return _match_direction(indicator_name) or 'higher_better' # ============================================================================= @@ -305,11 +352,11 @@ class CleanedDataLoader: Pipeline steps: 1. Standardize country names (ASEAN) - 2. Remove missing values + 2. Remove missing values (hanya kolom wajib) 3. Remove duplicates - 4. Add pillar classification - 5. Add direction classification - 6. Apply column constraints + 4. Add pillar & direction classification + 5. Apply column constraints & cast tipe data + 6. Validate 7. Load ke BigQuery 8. Log ke Audit layer """ @@ -327,13 +374,28 @@ class CleanedDataLoader: bigquery.SchemaField("direction", "STRING", mode="REQUIRED"), ] - def __init__(self, client: bigquery.Client, load_mode: str = 'full_refresh'): - self.client = client - self.load_mode = load_mode - self.logger = logging.getLogger(self.__class__.__name__) + # Kolom yang benar-benar wajib ada (sesuai mode REQUIRED di schema + value + # karena baris tanpa nilai tidak berguna untuk analisis). + # year, year_range, unit bersifat NULLABLE sehingga TIDAK boleh membuat baris dibuang. + REQUIRED_NOT_NULL = [ + 'source', 'indicator_original', 'indicator_standardized', 'country', 'value' + ] + + # Kunci unik satu observasi. source & year_range ikut agar data dari sumber + # berbeda / periode berbeda tidak saling menimpa. + DEDUP_KEY = ['source', 'indicator_standardized', 'country', 'year', 'year_range'] + + OUTPUT_COLUMNS = [f.name for f in SCHEMA] + + def __init__(self, client: bigquery.Client, load_mode: str = 'full_refresh', + filter_non_asean: bool = False): + self.client = client + self.load_mode = load_mode + self.filter_non_asean = filter_non_asean + self.logger = logging.getLogger(self.__class__.__name__) self.logger.propagate = False - self.table_name = 'cleaned_integrated' - self.target_layer = 'silver' + self.table_name = 'cleaned_integrated' + self.target_layer = 'silver' self.metadata = { 'source_class' : self.__class__.__name__, @@ -355,37 +417,74 @@ class CleanedDataLoader: def _step_standardize_countries(self, df: pd.DataFrame) -> pd.DataFrame: print("\n [Step 1/5] Standardize country names...") df, report = standardize_country_names_asean(df, country_column='country') - print(f" ✓ ASEAN countries mapped : {report['countries_mapped']}") - unique_countries = sorted(df['country'].unique()) + print(f" ✓ Country name variants mapped : {report['countries_mapped']}") + + if report['non_asean_values']: + print(f" ⚠ Non-ASEAN values found : {report['non_asean_values']}") + if self.filter_non_asean: + before = len(df) + df = df[df['country'].isin(ASEAN_COUNTRIES)] + print(f" ✓ Non-ASEAN rows removed : {before - len(df):,}") + + unique_countries = sorted(df['country'].dropna().unique()) print(f" Countries ({len(unique_countries)}) : {', '.join(unique_countries)}") - log_update(self.client, 'STAGING', 'staging_integrated', + # Log ke tabel TARGET (bukan staging_integrated) agar audit trail benar + log_update(self.client, 'STAGING', self.table_name, 'standardize_asean', report['countries_mapped']) return df def _step_remove_missing(self, df: pd.DataFrame) -> pd.DataFrame: print("\n [Step 2/5] Remove missing values...") rows_before = len(df) - df_clean = df.dropna(subset=list(df.columns)) - rows_after = len(df_clean) - removed = rows_before - rows_after + df_clean = df.copy() + + # String kosong / whitespace dianggap missing + for col in df_clean.select_dtypes(include='object').columns: + df_clean[col] = df_clean[col].replace(r'^\s*$', pd.NA, regex=True) + + # Hanya kolom wajib — year_range / unit NULLABLE dan sering kosong + df_clean = df_clean.dropna(subset=self.REQUIRED_NOT_NULL) + + # Observasi harus punya periode: minimal year ATAU year_range + has_period = df_clean['year'].notna() | df_clean['year_range'].notna() + df_clean = df_clean[has_period] + + rows_after = len(df_clean) + removed = rows_before - rows_after print(f" Rows before : {rows_before:,}") print(f" Rows after : {rows_after:,}") - print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)") - print(f" Retention : {rows_after/rows_before*100:.1f}%") + if rows_before: + print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)") + print(f" Retention : {rows_after/rows_before*100:.1f}%") return df_clean def _step_remove_duplicates(self, df: pd.DataFrame) -> pd.DataFrame: print("\n [Step 3/5] Remove duplicates...") + if df.empty: + return df + + key = self.DEDUP_KEY exact_dups = df.duplicated().sum() - data_dups = df.duplicated(subset=['indicator_standardized', 'country', 'year', 'value']).sum() - print(f" Exact duplicates : {exact_dups:,}") - print(f" Data duplicates : {data_dups:,}") - rows_before = len(df) - df_clean = df.drop_duplicates( - subset=['indicator_standardized', 'country', 'year'], keep='first' + key_dups = df.duplicated(subset=key).sum() + # duplikat kunci dengan nilai berbeda = konflik data, perlu perhatian + conflicts = ( + df.groupby(key, dropna=False)['value'].nunique().gt(1).sum() ) - removed = rows_before - len(df_clean) - print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)") + print(f" Exact duplicates : {exact_dups:,}") + print(f" Key duplicates : {key_dups:,}") + if conflicts: + print(f" ⚠ Key dengan nilai berbeda (konflik): {conflicts:,} " + f"— baris pertama (urut deterministik) dipertahankan") + + rows_before = len(df) + # Urutkan dulu agar keep='first' deterministik antar-run + df_sorted = df.sort_values( + key + ['indicator_original', 'value'], + na_position='last', kind='mergesort' + ) + df_clean = df_sorted.drop_duplicates(subset=key, keep='first') + removed = rows_before - len(df_clean) + print(f" Rows removed : {removed:,} ({removed/rows_before*100:.1f}%)") return df_clean def _step_add_classifications(self, df: pd.DataFrame) -> pd.DataFrame: @@ -394,21 +493,44 @@ class CleanedDataLoader: df['pillar'] = df['indicator_standardized'].apply(assign_pillar) df['direction'] = df['indicator_standardized'].apply(assign_direction) - pillar_counts = df['pillar'].value_counts() - print(f" ✓ Pillar distribution:") - for pillar, count in pillar_counts.items(): + # Laporkan indikator yang jatuh ke nilai default (tidak ada keyword cocok) + indicators = df['indicator_standardized'].drop_duplicates() + no_pillar = [i for i in indicators if _match_pillar(i) is None] + no_dir = [i for i in indicators if _match_direction(i) is None] + if no_pillar: + print(f" ⚠ {len(no_pillar)} indikator tanpa rule pillar (default 'Sustainability'):") + for ind in no_pillar[:10]: + print(f" - {ind}") + if no_dir: + print(f" ℹ {len(no_dir)} indikator tanpa rule direction (default 'higher_better'):") + for ind in no_dir[:10]: + print(f" - {ind}") + + print(" ✓ Pillar distribution:") + for pillar, count in df['pillar'].value_counts().items(): print(f" - {pillar}: {count:,}") - direction_counts = df['direction'].value_counts() - print(f" ✓ Direction distribution:") - for direction, count in direction_counts.items(): - pct = count / len(df) * 100 - print(f" - {direction}: {count:,} ({pct:.1f}%)") + print(" ✓ Direction distribution:") + for direction, count in df['direction'].value_counts().items(): + print(f" - {direction}: {count:,} ({count / len(df) * 100:.1f}%)") return df def _step_apply_constraints(self, df: pd.DataFrame) -> pd.DataFrame: - print("\n [Step 5/5] Apply column constraints...") - return apply_column_constraints(df) + print("\n [Step 5/5] Apply column constraints & cast types...") + df = apply_column_constraints(df) + + # Cast sesuai schema BigQuery: year INTEGER (nullable), value FLOAT. + # Tanpa ini year bisa menjadi float64 dan gagal/berubah saat load. + df['year'] = pd.to_numeric(df['year'], errors='coerce').astype('Int64') + df['value'] = pd.to_numeric(df['value'], errors='coerce').astype('float64') + + # Baris yang valuenya tidak bisa di-cast tidak boleh lolos + bad_value = df['value'].isna().sum() + if bad_value: + print(f" ⚠ {bad_value:,} baris dibuang: value bukan angka") + df = df.dropna(subset=['value']) + + return df[self.OUTPUT_COLUMNS].reset_index(drop=True) # ------------------------------------------------------------------ # VALIDATION @@ -442,10 +564,11 @@ class CleanedDataLoader: column_length_check = {} for col, max_len in COLUMN_CONSTRAINTS.items(): if col in df.columns: - max_actual = df[col].astype(str).str.len().max() + max_actual = df[col].dropna().astype(str).str.len().max() + max_actual = 0 if pd.isna(max_actual) else int(max_actual) column_length_check[col] = { 'max_length_constraint': max_len, - 'max_actual_length' : int(max_actual), + 'max_actual_length' : max_actual, 'within_limit' : bool(max_actual <= max_len) } validation['column_length_check'] = column_length_check @@ -473,8 +596,14 @@ class CleanedDataLoader: df = self._step_standardize_countries(df) df = self._step_remove_missing(df) df = self._step_remove_duplicates(df) - df = self._step_add_classifications(df) - df = self._step_apply_constraints(df) + df = self._step_add_classifications(df) if not df.empty else df + df = self._step_apply_constraints(df) if not df.empty else df + + # Pengaman: WRITE_TRUNCATE dengan DataFrame kosong akan MENGHAPUS tabel target. + if df.empty: + print("\n ERROR: Hasil cleaning kosong — load dibatalkan, " + "tabel cleaned_integrated tidak diubah.") + return 0 self.metadata['rows_transformed'] = len(df) @@ -512,7 +641,11 @@ class CleanedDataLoader: ).total_seconds() self.metadata['execution_timestamp'] = self.metadata['start_time'] self.metadata['completeness_pct'] = validation.get('completeness_pct', 0) - self.metadata['config_snapshot'] = json.dumps({'load_mode': self.load_mode}) + self.metadata['config_snapshot'] = json.dumps({ + 'load_mode' : self.load_mode, + 'filter_non_asean': self.filter_non_asean, + 'dedup_key' : self.DEDUP_KEY, + }) self.metadata['validation_metrics'] = json.dumps(validation) save_etl_metadata(self.client, self.metadata) @@ -526,11 +659,11 @@ class CleanedDataLoader: print(f" Year range : {yr['min']}–{yr['max']}") print(f" Indicators : {validation.get('unique_indicators', '-')}") print(f" Countries : {validation.get('unique_countries', '-')}") - print(f"\n Schema Validation:") + print("\n Schema Validation:") for col, info in validation.get('column_length_check', {}).items(): status = "✓" if info['within_limit'] else "✗" print(f" {status} {col}: {info['max_actual_length']}/{info['max_length_constraint']}") - print(f"\n Metadata → [AUDIT] etl_metadata") + print("\n Metadata → [AUDIT] etl_metadata") return rows_loaded @@ -545,12 +678,14 @@ def run_cleaned_integration(): Dipanggil oleh DAG setelah task staging_integration_to_silver selesai. """ - from scripts.bigquery_config import get_bigquery_client client = get_bigquery_client() df_staging = load_staging_data(client) loader = CleanedDataLoader(client, load_mode='full_refresh') rows = loader.run(df_staging) print(f"Cleaned layer loaded: {rows:,} rows") + if rows == 0: + # Gagalkan task Airflow agar tidak lanjut ke layer berikutnya dengan data lama/kosong + raise ValueError("Cleaned layer menghasilkan 0 rows — periksa staging_integrated.") # ============================================================================= @@ -566,7 +701,7 @@ if __name__ == "__main__": print(" Audit : AUDIT → etl_logs, etl_metadata") print("=" * 60) - logger = setup_logging() + setup_logging() client = get_bigquery_client() df_staging = load_staging_data(client) @@ -577,5 +712,5 @@ if __name__ == "__main__": print("\n" + "=" * 60) print("✓ CLEANED LAYER ETL COMPLETED") print(f" 🥈 STAGING (Silver) : cleaned_integrated ({final_count:,} rows)") - print(f" 📋 AUDIT : etl_logs, etl_metadata") + print(" 📋 AUDIT : etl_logs, etl_metadata") print("=" * 60) \ No newline at end of file