# api/admin.py """ Admin endpoints untuk pengelolaan buku. Alur data saat add/update/delete: 1. Update sibi_books_catalog.jsonl (catalog — tanpa full_text) 2. Update sibi_books.jsonl (sumber FAISS — dengan full_text, jika ada) 3. Update FAISS index (summary + fulltext vector store) 4. catalog_store.reload() (sync in-memory dari file catalog baru) """ import json import logging import os from pathlib import Path import shutil import tempfile import uuid from flask import Blueprint, jsonify, request from chunking.text_chunker import chunk_text from config.settings import ( CATALOG_FILE, FULLTEXT_INDEX_PATH, EMBEDDING_DIM, RAW_DATA_FILE, SUMMARY_INDEX_PATH, ) from embedding.vector_store import FulltextVectorStore, SummaryVectorStore from parsing.pdf_parser import parse_pdf_to_text from summarization.book_summarizer import summarize_book import utils.catalog_store as catalog_store logger = logging.getLogger(__name__) admin_bp = Blueprint("admin", __name__) # ── Helper: atomic file write ──────────────────────────────────────────────── def _atomic_write_jsonl(path: Path, records: list[dict]) -> None: """ Tulis list dict ke file JSONL secara atomic menggunakan temp file. Mencegah file corrupt jika proses terinterupsi di tengah penulisan. """ dir_ = path.parent # Tulis ke temp file dulu fd, tmp_path = tempfile.mkstemp(dir=dir_, suffix=".tmp") try: with os.fdopen(fd, "w", encoding="utf-8") as f: for record in records: f.write(json.dumps(record, ensure_ascii=False) + "\n") # Atomic replace — di Unix ini truly atomic shutil.move(tmp_path, path) except Exception: os.unlink(tmp_path) raise def _read_jsonl(path: Path) -> list[dict]: """Baca semua record dari file JSONL.""" if not path.exists(): return [] records = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line: try: records.append(json.loads(line)) except json.JSONDecodeError: pass return records def _strip_full_text(record: dict) -> dict: """Buat versi catalog (tanpa full_text) dari record lengkap.""" return {k: v for k, v in record.items() if k != "full_text"} # ── Step 1: Extract PDF ────────────────────────────────────────────────────── @admin_bp.route("/extract", methods=["POST"]) def extract_pdf(): """ Step 1 dari proses add buku. Menerima PDF, extract text, generate summary. Belum menyimpan ke database apapun. """ if "file" not in request.files: return jsonify({"error": "Field 'file' (PDF) diperlukan"}), 400 file = request.files["file"] if not file.filename.lower().endswith(".pdf"): return jsonify({"error": "File harus berformat PDF"}), 400 # Ambil metadata dari request.form jika ada metadata = { "judul_buku": request.form.get("judul_buku", ""), "jenjang": request.form.get("jenjang", ""), "kelas": request.form.get("kelas", ""), "mata_pelajaran": request.form.get("mata_pelajaran", ""), "tipe": request.form.get("tipe", "") } book_id = str(uuid.uuid4()) # Simpan PDF sementara upload_dir = Path("data/uploads") upload_dir.mkdir(parents=True, exist_ok=True) safe_filename = f"{book_id}_{file.filename.replace(' ', '_')}" pdf_path = upload_dir / safe_filename file.save(pdf_path) try: full_text = parse_pdf_to_text(str(pdf_path)) summary = summarize_book(metadata, full_text) except Exception as e: logger.error(f"[Admin] Gagal ekstrak PDF: {e}") return jsonify({"error": f"Gagal memproses PDF: {str(e)}"}), 500 return jsonify({ "status": "ok", "message": "Ekstraksi dan summarisasi selesai", "book_id": book_id, "pdf_path": str(pdf_path), "summary": summary, "metadata_preview": { "book_id": book_id, "judul_buku": metadata["judul_buku"], "jenjang": metadata["jenjang"], "kelas": metadata["kelas"], "mata_pelajaran": metadata["mata_pelajaran"], "tipe": metadata["tipe"], }, }) # ── Step 2: Konfirmasi & Simpan ────────────────────────────────────────────── @admin_bp.route("/add", methods=["POST"]) def add_book(): """ Step 2 dari proses add buku. Menerima metadata final + pdf_path, lakukan embedding, update semua storage. """ data = request.get_json(silent=True) if not data: return jsonify({"error": "Body JSON diperlukan"}), 400 required = ["judul_buku", "jenjang", "kelas", "mata_pelajaran", "tipe", "pdf_path", "summary"] missing = [f for f in required if not data.get(f)] if missing: return jsonify({"error": f"Field wajib belum diisi: {missing}"}), 400 book_id = data.get("book_id") or str(uuid.uuid4()) pdf_path = Path(data["pdf_path"]) if not pdf_path.exists(): return jsonify({"error": f"File PDF tidak ditemukan: {pdf_path}"}), 400 # ── 1. Baca full_text dari PDF (untuk FAISS) ────────────────────────── try: full_text = parse_pdf_to_text(str(pdf_path)) chunks = chunk_text(full_text) except Exception as e: return jsonify({"error": f"Gagal membaca PDF: {str(e)}"}), 500 # ── 2. Bangun metadata record ───────────────────────────────────────── metadata = { "judul_buku": data["judul_buku"], "jenjang": data["jenjang"], "kelas": str(data["kelas"]), "mata_pelajaran": data["mata_pelajaran"], "tipe": data["tipe"], "link_sampul": data.get("link_sampul", ""), "link_buku": data.get("link_buku", ""), "link_sumber": data.get("link_sumber", ""), } # ── 3. Record lengkap (untuk sibi_books.jsonl) ──────────────────────── full_record = { "id": book_id, "metadata": metadata, "summary_text": data["summary"], "full_text": full_text, } # ── 4. Record catalog (untuk sibi_books_catalog.jsonl) ─────────────── catalog_record = _strip_full_text(full_record) try: # ── 5. Update sibi_books.jsonl (append) ────────────────────────── with open(RAW_DATA_FILE, "a", encoding="utf-8") as f: f.write(json.dumps(full_record, ensure_ascii=False) + "\n") # ── 6. Update sibi_books_catalog.jsonl (append) ────────────────── with open(CATALOG_FILE, "a", encoding="utf-8") as f: f.write(json.dumps(catalog_record, ensure_ascii=False) + "\n") # ── 7. Embed dan index ke FAISS ─────────────────────────────────── summary_store = SummaryVectorStore(str(SUMMARY_INDEX_PATH), EMBEDDING_DIM) fulltext_store = FulltextVectorStore(str(FULLTEXT_INDEX_PATH), EMBEDDING_DIM) summary_store.add( book_id=book_id, text=data["summary"], metadata=metadata, ) for i, chunk in enumerate(chunks): fulltext_store.add( book_id=book_id, text=chunk, chunk_index=i, metadata=metadata, ) # ── 8. Reload catalog store ─────────────────────────────────────── catalog_store.reload() except Exception as e: logger.error(f"[Admin] Gagal add buku {book_id}: {e}", exc_info=True) return jsonify({"error": f"Gagal menyimpan buku: {str(e)}"}), 500 logger.info(f"[Admin] Buku berhasil ditambahkan: {book_id} — {data['judul_buku']}") return jsonify({ "status": "ok", "message": "Buku berhasil ditambahkan", "metadata": {**metadata, "book_id": book_id}, "summary": data["summary"], "chunks": len(chunks), }) # ── Update ──────────────────────────────────────────────────────────────────── @admin_bp.route("/update/", methods=["PUT"]) def update_book(book_id: str): """ Update metadata dan/atau summary_text sebuah buku. FAISS diupdate jika summary berubah (re-embed summary). full_text tidak bisa diupdate via endpoint ini — gunakan delete + add. """ data = request.get_json(silent=True) if not data: return jsonify({"error": "Body JSON diperlukan"}), 400 # Pastikan buku ada di catalog existing = catalog_store.get_by_id(book_id) if not existing: return jsonify({"error": f"Buku '{book_id}' tidak ditemukan"}), 404 old_metadata = existing.get("metadata", {}).copy() summary_changed = "summary_text" in data and data["summary_text"] != existing.get("summary_text") try: # ── 1. Update sibi_books_catalog.jsonl ──────────────────────────── catalog_records = _read_jsonl(Path(CATALOG_FILE)) updated_catalog = [] for rec in catalog_records: if rec.get("id") == book_id: # Merge update ke existing record if "metadata" in data: rec["metadata"].update(data["metadata"]) if "summary_text" in data: rec["summary_text"] = data["summary_text"] updated_catalog.append(rec) _atomic_write_jsonl(Path(CATALOG_FILE), updated_catalog) # ── 2. Update sibi_books.jsonl (sync metadata & summary) ───────── full_records = _read_jsonl(Path(RAW_DATA_FILE)) updated_full = [] for rec in full_records: if rec.get("id") == book_id: if "metadata" in data: rec["metadata"].update(data["metadata"]) if "summary_text" in data: rec["summary_text"] = data["summary_text"] updated_full.append(rec) _atomic_write_jsonl(Path(RAW_DATA_FILE), updated_full) # ── 3. Update FAISS jika summary berubah ───────────────────────── if summary_changed: updated_record = next((r for r in updated_catalog if r.get("id") == book_id), None) if updated_record: summary_store = SummaryVectorStore( str(SUMMARY_INDEX_PATH), EMBEDDING_DIM ) # Hapus vector lama lalu tambah yang baru summary_store.delete(book_id=book_id) summary_store.add( book_id=book_id, text=updated_record["summary_text"], metadata=updated_record.get("metadata", {}), ) logger.info(f"[Admin] FAISS summary re-indexed untuk buku: {book_id}") # ── 4. Reload catalog store ─────────────────────────────────────── catalog_store.reload() except Exception as e: logger.error(f"[Admin] Gagal update buku {book_id}: {e}", exc_info=True) return jsonify({"error": f"Gagal mengupdate buku: {str(e)}"}), 500 logger.info(f"[Admin] Buku berhasil diupdate: {book_id}") return jsonify({ "status": "ok", "message": "Buku berhasil diupdate", "book_id": book_id, "metadata": old_metadata, # metadata sebelum diubah (konsisten dengan kontrak lama) }) # ── Delete ──────────────────────────────────────────────────────────────────── @admin_bp.route("/delete/", methods=["DELETE"]) def delete_book(book_id: str): """ Hapus buku dari semua storage: - sibi_books_catalog.jsonl - sibi_books.jsonl - FAISS summary index - FAISS fulltext index """ existing = catalog_store.get_by_id(book_id) if not existing: return jsonify({"error": f"Buku '{book_id}' tidak ditemukan"}), 404 old_metadata = existing.get("metadata", {}).copy() try: # ── 1. Hapus dari sibi_books_catalog.jsonl ──────────────────────── catalog_records = _read_jsonl(Path(CATALOG_FILE)) _atomic_write_jsonl( Path(CATALOG_FILE), [r for r in catalog_records if r.get("id") != book_id], ) # ── 2. Hapus dari sibi_books.jsonl ──────────────────────────────── full_records = _read_jsonl(Path(RAW_DATA_FILE)) _atomic_write_jsonl( Path(RAW_DATA_FILE), [r for r in full_records if r.get("id") != book_id], ) # ── 3. Hapus dari FAISS summary index ──────────────────────────── summary_store = SummaryVectorStore(str(SUMMARY_INDEX_PATH), EMBEDDING_DIM) summary_store.delete(book_id=book_id) # ── 4. Hapus dari FAISS fulltext index ─────────────────────────── fulltext_store = FulltextVectorStore(str(FULLTEXT_INDEX_PATH), EMBEDDING_DIM) fulltext_store.delete(book_id=book_id) # ── 5. Reload catalog store ─────────────────────────────────────── catalog_store.reload() except Exception as e: logger.error(f"[Admin] Gagal delete buku {book_id}: {e}", exc_info=True) return jsonify({"error": f"Gagal menghapus buku: {str(e)}"}), 500 logger.info(f"[Admin] Buku berhasil dihapus: {book_id}") return jsonify({ "status": "ok", "message": "Buku berhasil dihapus", "book_id": book_id, "metadata": old_metadata, }) # ── Admin: list semua buku (untuk panel admin) ──────────────────────────────── @admin_bp.route("/books", methods=["GET"]) def admin_list_books(): """ Versi admin dari daftar buku — sama dengan /api/books tapi bisa difilter lebih luas dan menampilkan semua field catalog. """ jenjang = request.args.get("jenjang", "").strip() or None kelas = request.args.get("kelas", "").strip() or None mata_pelajaran = request.args.get("mata_pelajaran", "").strip() or None tipe = request.args.get("tipe", "").strip() or None search = request.args.get("search", "").strip() or None try: page = max(1, int(request.args.get("page", 1))) limit = min(200, max(1, int(request.args.get("limit", 50)))) except ValueError: return jsonify({"error": "Parameter 'page' dan 'limit' harus berupa angka"}), 400 results = catalog_store.query(jenjang=jenjang, kelas=kelas, mata_pelajaran=mata_pelajaran, tipe=tipe, search=search) total = len(results) offset = (page - 1) * limit page_data = results[offset : offset + limit] return jsonify({ "books": page_data, "total_books": total, "total_pages": max(1, (total + limit - 1) // limit), "current_page": page, "per_page": limit, })