File size: 15,515 Bytes
495399f
 
 
3851c17
 
 
495399f
 
 
 
3851c17
495399f
 
 
 
 
 
9a2c317
82526ea
 
495399f
 
 
 
 
 
 
 
 
3851c17
495399f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82526ea
 
495399f
 
 
 
 
82526ea
 
 
 
 
 
 
 
 
 
 
 
 
 
3851c17
 
 
 
 
 
 
 
495399f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3851c17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495399f
 
3851c17
495399f
3851c17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495399f
3851c17
495399f
 
3851c17
495399f
 
3851c17
 
 
 
 
 
 
 
 
 
 
 
495399f
3851c17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse
import requests
import httpx
import asyncio
import json
import os
from uuid import uuid4
from typing import List
import google.generativeai as genai
# import google.genai as genai
from utils.bps_parser import parse_bps_json
from utils.db import save_file_metadata, check_duplicate_bps_data
from langchain_core.documents import Document
from dotenv import load_dotenv
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams, PointStruct
from langchain_classic.embeddings import CacheBackedEmbeddings # New Import
from langchain_community.storage import RedisStore # New Import
import redis # New Import

# Load env vars
load_dotenv()

router = APIRouter()

# Config
BPS_API_KEY = os.getenv("BPS_API_KEY") 
BPS_BASE_URL = "https://webapi.bps.go.id/v1/api/list" 
DOMAIN_ID = "5309" # Kabupaten Flores Timur
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
QDRANT_URL = os.getenv("QDRANT_URL")
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")

# Custom Embedding Class
class GoogleGenAIEmbeddingsCustom:
    def __init__(self, api_key, model="models/gemini-embedding-001", output_dimensionality=None):
        genai.configure(api_key=api_key)
        self.model = model
        self.output_dimensionality = output_dimensionality

    def embed_documents(self, texts: List[str]) -> List[List[float]]:
        return [self.embed_query(text) for text in texts]

    def embed_query(self, text: str) -> List[float]:
        result = genai.embed_content(
            model=self.model,
            content=text,
            task_type="retrieval_document",
            output_dimensionality=self.output_dimensionality
        )
        return result['embedding']

# Initialize Embeddings
# Initialize Embeddings
raw_embeddings = GoogleGenAIEmbeddingsCustom(
    model="models/gemini-embedding-001", 
    api_key=GOOGLE_API_KEY,
    output_dimensionality=1536
)

# Setup Embedding Cache
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
try:
    store = RedisStore(redis_url=redis_url, namespace="embedding_cache")
    embeddings = CacheBackedEmbeddings.from_bytes_store(
        underlying_embeddings=raw_embeddings,
        document_embedding_cache=store,
        namespace=raw_embeddings.model
    )
    print(f"βœ… BPS Sync: Embedding Cache enabled with Redis at {redis_url}")
except Exception as e:
    print(f"⚠️ BPS Sync: Redis not available. Using direct embeddings. Error: {e}")
    embeddings = raw_embeddings

# ---------------------------------------------------------------------------
# Redis client for BPS API response caching (subjects & variables).
# TTL: 1 bulan β€” data BPS jarang berubah.
#
# AKTIVASI: Uncomment blok di bawah ketika Redis tersedia (Railway / server kantor).
# ---------------------------------------------------------------------------
# redis_client = redis.asyncio.from_url(redis_url, decode_responses=True)

# Initialize Qdrant Client
client = QdrantClient(
    url=QDRANT_URL,
    api_key=QDRANT_API_KEY,
    timeout=60
)

# Ensure collection exists
COLLECTION_NAME = "dataset_inda"
EXPECTED_DIM = 1536

try:
    if client.collection_exists(COLLECTION_NAME):
        collection_info = client.get_collection(COLLECTION_NAME)
        current_dim = collection_info.config.params.vectors.size
        
        if current_dim != EXPECTED_DIM:
            print(f"⚠️ Dimensi vector tidak cocok! Current: {current_dim}, Expected: {EXPECTED_DIM}")
            print(f"πŸ—‘οΈ Menghapus collection lama dan membuat ulang...")
            client.delete_collection(COLLECTION_NAME)
            client.create_collection(
                collection_name=COLLECTION_NAME,
                vectors_config=VectorParams(size=EXPECTED_DIM, distance=Distance.COSINE)
            )
            print(f"βœ… Collection baru berhasil dibuat dengan dimensi {EXPECTED_DIM}.")
        else:
            print(f"πŸ“ Collection sudah ada dengan dimensi yang benar ({current_dim}).")
    else:
        client.create_collection(
            collection_name=COLLECTION_NAME,
            vectors_config=VectorParams(size=EXPECTED_DIM, distance=Distance.COSINE)
        )
        print(f"πŸ†• Collection baru berhasil dibuat dengan dimensi {EXPECTED_DIM}.")
except Exception as e:
    print(f"Error checking/creating collection: {e}")


# ---------------------------------------------------------------------------
# Helper: fetch semua halaman BPS API secara concurrent.
#
# BPS API mengembalikan data terpaginasi:
#   raw_data[0] = {page, pages, total, per_page}  ← info pagination
#   raw_data[1] = [ {...}, {...} ]                 ← item aktual
#
# url_template harus mengandung placeholder "{page}" untuk nomor halaman.
# ---------------------------------------------------------------------------
async def fetch_all_pages(url_template: str) -> list:
    """Fetch semua halaman BPS API secara concurrent menggunakan httpx."""
    all_items: list = []

    async with httpx.AsyncClient(timeout=30) as client_http:
        # --- Page 1: ambil info pagination & data pertama ---
        try:
            res = await client_http.get(url_template.format(page=1))
            data = res.json()
        except Exception as e:
            print(f"[fetch_all_pages] Gagal fetch page 1: {e}")
            return []

        if data.get("status") != "OK":
            return []

        raw_data = data.get("data", [])
        if len(raw_data) < 2 or not isinstance(raw_data[1], list):
            return []

        pagination = raw_data[0]  # {page, pages, total, per_page}
        total_pages = int(pagination.get("pages", 1))
        all_items.extend(raw_data[1])
        print(f"[fetch_all_pages] Page 1/{total_pages} β†’ {len(raw_data[1])} items")

        if total_pages <= 1:
            return all_items

        # --- Page 2..N: concurrent fetch ---
        async def _fetch_page(page_num: int) -> list:
            try:
                r = await client_http.get(url_template.format(page=page_num))
                d = r.json()
                rd = d.get("data", [])
                if len(rd) >= 2 and isinstance(rd[1], list):
                    print(f"[fetch_all_pages] Page {page_num}/{total_pages} β†’ {len(rd[1])} items")
                    return rd[1]
            except Exception as e:
                print(f"[fetch_all_pages] Gagal fetch page {page_num}: {e}")
            return []

        results = await asyncio.gather(*[
            _fetch_page(p) for p in range(2, total_pages + 1)
        ])
        for page_items in results:
            all_items.extend(page_items)

    print(f"[fetch_all_pages] Total items terkumpul: {len(all_items)}")
    return all_items


@router.get("/bps/subjects")
async def get_subjects():
    """Mengambil daftar Subjek (Kategori) dari BPS β€” semua halaman."""
    cache_key = f"bps:subjects:{DOMAIN_ID}"

    # ---------------------------------------------------------------------------
    # REDIS CACHE CHECK β€” Uncomment saat Redis tersedia
    # ---------------------------------------------------------------------------
    # cached = await redis_client.get(cache_key)
    # if cached:
    #     print(f"[get_subjects] Cache HIT β†’ {cache_key}")
    #     return json.loads(cached)
    # ---------------------------------------------------------------------------

    try:
        # BPS subjects tidak terpaginasi per-page via URL, tapi tetap kita pakai
        # fetch_all_pages sebagai future-proof. Placeholder {page} aman meski page=1 saja.
        url_template = (
            f"{BPS_BASE_URL}/model/subject/domain/{DOMAIN_ID}"
            f"/page/{{page}}/key/{BPS_API_KEY}/"
        )
        print(f"[get_subjects] Fetching: {url_template.format(page=1)}")
        subjects = await fetch_all_pages(url_template)
        print(f"[get_subjects] Total subjects: {len(subjects)}")

        # ---------------------------------------------------------------------------
        # REDIS CACHE SAVE β€” Uncomment saat Redis tersedia
        # ---------------------------------------------------------------------------
        # await redis_client.setex(cache_key, 60 * 60 * 24 * 30, json.dumps(subjects))
        # ---------------------------------------------------------------------------

        return subjects
    except Exception as e:
        print(f"[get_subjects] Exception: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/bps/variables/{subject_id}")
async def get_variables(subject_id: int):
    """Mengambil daftar Variabel (Tabel) berdasarkan Subjek β€” semua halaman."""
    cache_key = f"bps:variables:{DOMAIN_ID}:{subject_id}"

    # ---------------------------------------------------------------------------
    # REDIS CACHE CHECK β€” Uncomment saat Redis tersedia
    # ---------------------------------------------------------------------------
    # cached = await redis_client.get(cache_key)
    # if cached:
    #     print(f"[get_variables] Cache HIT β†’ {cache_key}")
    #     return json.loads(cached)
    # ---------------------------------------------------------------------------

    try:
        url_template = (
            f"{BPS_BASE_URL}/model/var/domain/{DOMAIN_ID}"
            f"/subject/{subject_id}/page/{{page}}/key/{BPS_API_KEY}/"
        )
        raw_items = await fetch_all_pages(url_template)

        # Map ke format yang diharapkan frontend: {val, label, unit, subj}
        mapped_vars = [
            {
                "val":  item.get("var_id"),
                "label": item.get("title"),
                "unit":  item.get("unit"),
                "subj":  item.get("sub_name"),
            }
            for item in raw_items
        ]
        print(f"[get_variables] subject={subject_id} β†’ {len(mapped_vars)} variables")

        # ---------------------------------------------------------------------------
        # REDIS CACHE SAVE β€” Uncomment saat Redis tersedia
        # ---------------------------------------------------------------------------
        # await redis_client.setex(cache_key, 60 * 60 * 24 * 30, json.dumps(mapped_vars))
        # ---------------------------------------------------------------------------

        return mapped_vars
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/bps/sync-variable")
async def sync_variable(
    var_id: int = Query(..., description="ID Variabel"),
    start_year: int = Query(120, description="Kode Tahun Mulai (120=2020)"), # Default 5 tahun terakhir
    end_year: int = Query(125, description="Kode Tahun Akhir (125=2025)")
):
    """
    Smart Sync:
    1. Iterasi tahun dari end_year ke start_year.
    2. Jika ada data, parse dan embed.
    3. Gunakan delay agar tidak kena rate limit Gemini.
    """
    import time
    
    results = []
    total_chunks = 0
    
    try:
        # Loop mundur dari tahun terbaru
        for th in range(end_year, start_year - 1, -1):
            try:
                print(f'Processing year: {th}')
                # 0. Check for duplicates
                if check_duplicate_bps_data(var_id, th):
                    print(f"Skipping Var {var_id} Year {th}: Already exists in database")
                    results.append({
                        "year": th,
                        "label": f"{th}",
                        "count": 0,
                        "title": f"Skipped (duplicate)",
                        "skipped": True
                    })
                    continue
                
                # 1. Fetch BPS
                # Pattern: model/data/domain/{domain}/var/{var}/th/{th}/key/{key}
                url = f"{BPS_BASE_URL}/model/data/domain/{DOMAIN_ID}/var/{var_id}/th/{th}/key/{BPS_API_KEY}/"
                response = requests.get(url)
                data = response.json()
                
                # Skip jika data tidak tersedia
                if data.get("status") != "OK" or not data.get("datacontent"):
                    print(f"Skipping Var {var_id} Year {th}: No Data")
                    continue
                
                print(f"Get data for {th} with status {data.get('status')}")
                # 2. Parse
                sentences = parse_bps_json(data)
                if not sentences: continue
                
                # 3. Create Documents
                var_label = data["var"][0]["label"]
                tahun_label = data["tahun"][0]["label"]
                
                print(f"Make documents for year: {th}")
                documents = [
                    Document(
                        page_content=s, 
                        metadata={
                            "source": "BPS API", 
                            "var_id": var_id, 
                            "year_code": th,
                            "title": f"{var_label} - {tahun_label}"
                        }
                    ) 
                    for s in sentences
                ]
                
                # 4. Embed (Dengan Retry/Delay sederhana)
                # Gemini Free Tier limit ~15 RPM. Kita sleep 2 detik per batch tahun.
                points = []
                
                for doc in documents:
                    embedding = embeddings.embed_query(doc.page_content)

                    point = PointStruct(
                        id=str(uuid4()),
                        vector=embedding,
                        payload={
                            "page_content": doc.page_content,
                            **doc.metadata
                        }
                    )
                    points.append(point)

                print(f"Upserting {len(points)} points for year: {th}")
                client.upsert(collection_name=COLLECTION_NAME, points=points)
                
                # 5. Save to Database (Direct PostgreSQL)
                # Get subject name from var_id (we need to fetch it or pass it as param)
                # For now, we'll use a placeholder or fetch it
                subject_name = data.get("subject", [{}])[0].get("label", "Unknown") if data.get("subject") else "Unknown"
                
                print(f"Saving metadata for year: {th}")
                save_file_metadata(
                    name=f"{var_label} - {tahun_label}",
                    file_type="bps",
                    bps_var_id=var_id,
                    bps_year=th,
                    bps_subject=subject_name
                )

                total_chunks += len(documents)
                results.append({
                    "year": th,
                    "label": tahun_label,
                    "count": len(documents),
                    "title": f"{var_label} - {tahun_label}",
                    "skipped": False
                })
                
                print(f"Synced year: {th}")
                # Jeda untuk safety rate limit
                time.sleep(2) 
                
            except Exception as e:
                print(f"Error syncing year {th}: {e}")
                continue

        if total_chunks == 0:
             return JSONResponse(content={"message": "No data found for the selected range", "synced": []})

        return JSONResponse(content={
            "message": "Sync completed",
            "total_chunks": total_chunks,
            "details": results
        })

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))