File size: 4,903 Bytes
495399f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import os

def parse_bps_excel(file_path: str) -> list[str]:
    """
    Membaca file Excel dari BPS dan mengubahnya menjadi daftar kalimat (chunks).
    
    Logika:
    1. Mencari baris header yang berisi 'Kabupaten' atau 'Kota'.
    2. Mengambil baris-baris di atas header sebagai 'Konteks/Judul'.
    3. Mengiterasi setiap sel data untuk membuat kalimat deklaratif.
    """
    try:
        # Baca raw data
        df_raw = pd.read_excel(file_path, header=None)
        
        # 1. Cari batas antara Header dan Data
        # Kita asumsikan baris data dimulai ketika kolom pertama berisi nama wilayah (Provinsi/Kabupaten/Kota)
        # DAN kolom kedua berisi angka.
        data_start_idx = -1
        header_rows = []
        
        for i, row in df_raw.iterrows():
            first_cell = str(row[0]).strip().lower()
            
            # Deteksi keyword wilayah di kolom pertama
            is_region_row = any(x in first_cell for x in ["provinsi", "kabupaten", "kota", "indonesia"])
            
            # Cek apakah kolom-kolom berikutnya berisi angka (indikasi baris data)
            # Kita cek 3 kolom sampel
            has_numbers = False
            number_count = 0
            for val in row[1:5]: 
                try:
                    float(str(val).replace(',', '.'))
                    number_count += 1
                except:
                    pass
            
            if number_count >= 1 and is_region_row:
                data_start_idx = i
                break
        
        if data_start_idx == -1:
            # Fallback: Cari baris yang ada kata "Kabupaten" atau "Kota" sebagai header terakhir
            for i, row in df_raw.iterrows():
                if any(x in str(row[0]).lower() for x in ["kabupaten", "kota", "provinsi"]):
                    data_start_idx = i + 1
                    break
        
        if data_start_idx == -1:
             return ["Error: Tidak dapat mendeteksi struktur tabel. Pastikan ada kolom wilayah (Provinsi/Kab/Kota)."]

        # 2. Ekstrak Judul (Baris paling atas sebelum header kompleks)
        # Asumsi: Header kompleks biasanya 2-3 baris di atas data
        # Judul biasanya di baris 0 atau 1
        title_parts = []
        for i in range(max(0, data_start_idx - 4)): # Ambil beberapa baris teratas
            row_vals = [str(x).strip() for x in df_raw.iloc[i] if pd.notna(x) and str(x).strip() != ""]
            if row_vals:
                # Jika baris ini bukan bagian dari header kolom (misal bukan '2025', 'Semester'), anggap judul
                if not any(k in str(row_vals).lower() for k in ["semester", "tahun", "jumlah", "persentase"]):
                     title_parts.extend(row_vals)
        
        full_title = " ".join(title_parts[:2]) # Batasi judul agar tidak terlalu panjang
        
        # 3. Proses Multi-Level Header
        # Ambil baris-baris header (di atas data_start_idx)
        # Biasanya 2-3 baris di atas data adalah header kolom
        header_start = max(0, data_start_idx - 3) 
        header_end = data_start_idx
        
        df_headers = df_raw.iloc[header_start:header_end, :]
        
        # Forward Fill (untuk merged cells horizontal)
        df_headers = df_headers.ffill(axis=1)
        # Forward Fill (untuk merged cells vertikal - optional, tapi pandas read_excel biasanya handle ini jika format benar)
        df_headers = df_headers.ffill(axis=0)

        # Flatten headers: Gabungkan baris-baris header menjadi satu string
        new_columns = []
        for col_idx in range(df_headers.shape[1]):
            col_parts = []
            for row_idx in range(df_headers.shape[0]):
                val = str(df_headers.iloc[row_idx, col_idx]).strip()
                if val != "nan" and val != "" and val not in col_parts:
                    col_parts.append(val)
            new_columns.append(" - ".join(col_parts))
            
        # 4. Baca Data
        df = df_raw.iloc[data_start_idx:].copy()
        df.columns = new_columns
        
        # Bersihkan nama kolom pertama (Wilayah)
        region_col = df.columns[0]
        
        sentences = []
        
        for _, row in df.iterrows():
            region = row[region_col]
            if pd.isna(region) or str(region).strip() == "": continue
            
            for col in df.columns[1:]:
                val = row[col]
                if pd.isna(val) or str(val).strip() in ["-", ""]: continue
                
                clean_val = str(val).replace(",", ".")
                
                # Format: [Judul]. Wilayah: [X]. Kategori: [Header Kolom]. Nilai: [Y].
                sentence = f"{full_title}. Wilayah: {region}. Kategori: {col}. Nilai: {clean_val}."
                sentences.append(sentence)
                
        return sentences

    except Exception as e:
        return [f"Error parsing Excel: {str(e)}"]