Spaces:
Sleeping
Sleeping
Download api/bps.py from bagustenan/backend: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/bagustenan/backend/resolve/main/api/bps.py
- Command line
-
hf download hf://spaces/bagustenan/backend/api/bps.py
-
curl -L -o bps.py https://huggingface.co/spaces/bagustenan/backend/resolve/main/api/bps.py
15.5 kB
| 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 | |
| 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)) | |
| 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)) | |
| 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)) | |