afnrmdhn commited on
Commit
7fff458
Β·
1 Parent(s): 21f2d61

add modified endpoint & datasets

Browse files
.gitignore CHANGED
@@ -32,7 +32,7 @@ MANIFEST
32
 
33
  # FAISS and Pickle
34
  # *.faiss
35
- # *.pkl
36
  *.bak
37
 
38
  # Virtual Environments
 
32
 
33
  # FAISS and Pickle
34
  # *.faiss
35
+ *.pkl
36
  *.bak
37
 
38
  # Virtual Environments
README.md CHANGED
@@ -9,3 +9,560 @@ short_description: backend system for RAG recommednder book
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
12
+
13
+ ---
14
+
15
+ # πŸ“š BackendBooki β€” Laporan Teknis Sistem RAG Rekomendasi Buku
16
+
17
+ > Laporan ini disusun per **22 Juni 2026** berdasarkan analisis kondisi repository terkini dan pembaruan sistem yang telah dilakukan.
18
+
19
+ ---
20
+
21
+ ## Daftar Isi
22
+
23
+ 1. [Penjelasan Sistem](#1-penjelasan-sistem)
24
+ 2. [Struktur Project](#2-struktur-project)
25
+ 3. [Penjelasan Endpoint](#3-penjelasan-endpoint)
26
+ 4. [Cara Clone / Akses Kode](#4-cara-clone--akses-kode)
27
+ 5. [Pembaruan Terbaru](#5-pembaruan-terbaru)
28
+ 6. [Penutup](#6-penutup)
29
+
30
+ ---
31
+
32
+ ## 1. Penjelasan Sistem
33
+
34
+ **BackendBooki** adalah sistem backend berbasis **RAG (Retrieval-Augmented Generation)** yang dirancang untuk merekomendasikan buku pelajaran kepada pengguna. Sistem ini dibangun menggunakan:
35
+
36
+ - **Framework:** Flask (WSGI) dengan wrapper ASGI via `asgiref` agar kompatibel dengan Uvicorn
37
+ - **Deployment Target:** Hugging Face Spaces (Docker SDK, port 7860)
38
+ - **Package Manager:** `uv` (astral-sh) untuk instalasi dependensi yang cepat dan deterministik
39
+ - **Python Runtime:** Python 3.13 (slim image)
40
+ - **LLM & Embedding:** Google Generative AI / Google Gemini (`google-genai`, `langchain-google-genai`, `langchain-google-vertexai`)
41
+ - **Vector Store:** FAISS CPU (`faiss-cpu`) untuk pencarian kemiripan semantik
42
+ - **Reranker:** Jina AI v3 dengan logika *Dynamic Score Gap*
43
+ - **Evaluasi:** RAGAS untuk evaluasi kualitas RAG pipeline
44
+ - **Data:** Dataset buku pelajaran SIBI dalam format `.jsonl` (`sibi_books.jsonl`)
45
+
46
+ Sistem ini memungkinkan pengguna (melalui frontend) untuk:
47
+ - Mendapatkan **rekomendasi buku** berdasarkan query bahasa alami
48
+ - Mendapatkan penjelasan mendalam (**deep dive**) tentang materi dari buku tertentu
49
+ - Admin dapat **mengelola katalog buku** (tambah, ubah, hapus) dengan proses dua langkah yang aman
50
+
51
+ ### Arsitektur Umum
52
+
53
+ ```
54
+ Frontend β†’ REST API (Flask/ASGI) β†’ RAG Pipeline
55
+ β”œβ”€β”€ Embedding (Google GenAI)
56
+ β”œβ”€β”€ Vector Store (FAISS)
57
+ β”œβ”€β”€ Reranker (Jina AI v3)
58
+ └── LLM Generation (Gemini)
59
+ ↑
60
+ sibi_books.jsonl (katalog)
61
+ ```
62
+
63
+ ---
64
+
65
+ ## 2. Struktur Project
66
+
67
+ ```
68
+ backend-booki/
69
+ β”‚
70
+ β”œβ”€β”€ app.py # Entry point ASGI untuk HF Spaces (Uvicorn + asgiref wrapper)
71
+ β”œβ”€β”€ Dockerfile # Docker build untuk deployment HF Spaces (non-root, port 7860)
72
+ β”œβ”€β”€ pyproject.toml # Konfigurasi project & dependensi utama
73
+ β”œβ”€β”€ uv.lock # Lockfile deterministik dari uv
74
+ β”œβ”€β”€ requirements.txt # Export dependensi (autogenerated oleh uv, 842 package)
75
+ β”œβ”€β”€ README.md # Konfigurasi HF Spaces + laporan teknis ini
76
+ β”œβ”€β”€ notebook.ipynb # Notebook interaktif untuk admin & testing pipeline
77
+ β”œβ”€β”€ laporan_perubahan.md # Riwayat pembaruan sistem sebelumnya
78
+ β”œβ”€β”€ pembersihan.md # Catatan proses pembersihan data
79
+ β”œβ”€β”€ .gitignore # File/folder yang dikecualikan dari version control
80
+ β”œβ”€β”€ .gitattributes # Konfigurasi Git attributes
81
+ β”‚
82
+ β”œβ”€β”€ api/ # Modul REST API (Flask routes & app factory)
83
+ β”‚ └── app.py # Flask app factory (create_app), route registration
84
+ β”‚
85
+ β”œβ”€β”€ chunking/ # Modul pemecahan teks (text chunking)
86
+ β”‚
87
+ β”œβ”€β”€ config/ # Konfigurasi global (API keys, path, parameter RAG)
88
+ β”‚
89
+ β”œβ”€β”€ data/ # Dataset & file yang dihasilkan saat runtime
90
+ β”‚ └── sibi_books.jsonl # Katalog buku pelajaran utama (format JSON Lines)
91
+ β”‚
92
+ β”œβ”€β”€ embedding/ # Modul pembuatan embedding vektor
93
+ β”‚
94
+ β”œβ”€β”€ generation/ # Modul generasi jawaban LLM (Gemini)
95
+ β”‚
96
+ β”œβ”€β”€ parsing/ # Modul parsing dokumen PDF
97
+ β”‚
98
+ β”œβ”€β”€ retrieval/ # Modul retrieval + reranking (FAISS + Jina AI)
99
+ β”‚
100
+ β”œβ”€β”€ scripts/ # Script utilitas (ingest data, rebuild index, dll)
101
+ β”‚
102
+ β”œβ”€β”€ summarization/ # Modul pembuatan ringkasan buku otomatis
103
+ β”‚
104
+ └── utils/ # Helper umum (format output, logger, dll)
105
+ ```
106
+
107
+ ### Deskripsi Modul Utama
108
+
109
+ | Modul | Fungsi |
110
+ |-------|--------|
111
+ | `api/` | Menangani semua route HTTP, validasi input, dan response formatting |
112
+ | `chunking/` | Memecah teks PDF menjadi chunk yang optimal untuk embedding |
113
+ | `config/` | Menyimpan konfigurasi terpusat (env vars, threshold RAG, path file) |
114
+ | `data/` | Menyimpan `sibi_books.jsonl`, index FAISS, dan upload PDF sementara |
115
+ | `embedding/` | Membuat vektor embedding menggunakan model Google GenAI |
116
+ | `generation/` | Menyusun prompt dan memanggil LLM Gemini untuk generasi jawaban |
117
+ | `parsing/` | Mengekstrak teks dari file PDF menggunakan PyMuPDF |
118
+ | `retrieval/` | Melakukan pencarian semantik di FAISS + reranking dengan Jina AI |
119
+ | `scripts/` | Script batch untuk ingest dataset awal dan rebuild index |
120
+ | `summarization/` | Menghasilkan ringkasan buku otomatis saat proses ingest |
121
+ | `utils/` | Fungsi utilitas bersama (logging, format data, konversi) |
122
+
123
+ ---
124
+
125
+ ## 3. Penjelasan Endpoint
126
+
127
+ Semua endpoint berjalan di base URL server (contoh lokal: `http://localhost:7860`, HF Spaces: URL Space yang bersangkutan).
128
+
129
+ ---
130
+
131
+ ### 3.1 `POST /recommend` β€” Rekomendasi Buku
132
+
133
+ **Fungsi:** Menerima query bahasa alami dari pengguna dan mengembalikan daftar rekomendasi buku yang relevan beserta jawaban naratif dari LLM.
134
+
135
+ **Tujuan:** Endpoint utama untuk fitur pencarian dan rekomendasi buku di frontend aplikasi Booki.
136
+
137
+ **Cara Akses:**
138
+ ```bash
139
+ curl -X POST http://localhost:7860/recommend \
140
+ -H "Content-Type: application/json" \
141
+ -d '{"query": "Punya buku sains kelas 7?"}'
142
+ ```
143
+
144
+ **Format Input (JSON Body):**
145
+ ```json
146
+ {
147
+ "query": "string β€” pertanyaan atau permintaan pengguna dalam bahasa alami"
148
+ }
149
+ ```
150
+
151
+ **Format Output (JSON):**
152
+ ```json
153
+ {
154
+ "status": "success",
155
+ "query": "Punya buku sains kelas 7?",
156
+ "answer": "Halo Sobat Belajar! Tentu, sistem Booki kami punya beberapa koleksi buku sains kelas 7. Berikut daftarnya ya! ✨",
157
+ "recommendations": [
158
+ {
159
+ "tipe": "Buku Teks",
160
+ "jenjang": "SMP",
161
+ "kelas": "7",
162
+ "mata_pelajaran": "IPA",
163
+ "judul_buku": "Ilmu Pengetahuan Alam Kelas VII",
164
+ "link_sampul": "https://...",
165
+ "link_buku": "https://...",
166
+ "link_sumber": "https://...",
167
+ "summary_text": "Buku IPA Kelas 7 yang difokuskan pada...",
168
+ "book_id": "abcd-efg",
169
+ "similarity_score": 1.25,
170
+ "relevance_score": 0.89
171
+ }
172
+ ]
173
+ }
174
+ ```
175
+
176
+ **Catatan:** Sistem menggunakan *Dynamic Score Gap Reranker* β€” jumlah rekomendasi yang dikembalikan bisa bervariasi tergantung ambang relevansi, bukan selalu berjumlah K tetap.
177
+
178
+ ---
179
+
180
+ ### 3.2 `POST /deep` β€” Deep Dive Materi Buku
181
+
182
+ **Fungsi:** Memberikan penjelasan mendalam tentang suatu topik atau materi dengan mengacu pada konten buku yang relevan dari katalog.
183
+
184
+ **Tujuan:** Membantu pengguna memahami suatu konsep secara lebih rinci, termasuk penulisan rumus matematika dalam format LaTeX.
185
+
186
+ **Cara Akses:**
187
+ ```bash
188
+ curl -X POST http://localhost:7860/deep \
189
+ -H "Content-Type: application/json" \
190
+ -d '{"query": "Jelaskan hukum Newton tentang gerak dan rumusnya"}'
191
+ ```
192
+
193
+ **Format Input (JSON Body):**
194
+ ```json
195
+ {
196
+ "query": "string β€” topik atau konsep yang ingin dijelaskan secara mendalam"
197
+ }
198
+ ```
199
+
200
+ **Format Output (JSON):**
201
+ ```json
202
+ {
203
+ "status": "success",
204
+ "query": "Jelaskan hukum Newton tentang gerak dan rumusnya",
205
+ "answer": "Hukum Newton adalah... Rumus pertama: $$\\sum F = 0$$, Rumus kedua: $$F = ma$$...",
206
+ "sources": [
207
+ {
208
+ "judul_buku": "Fisika untuk SMA/MA Kelas X",
209
+ "book_id": "xyz-123",
210
+ "relevance_score": 0.92
211
+ }
212
+ ]
213
+ }
214
+ ```
215
+
216
+ **Catatan:** Rumus matematika ditulis dalam format LaTeX. Sistem tidak akan menghasilkan tautan gambar palsu (anti-halusinasi diberlakukan ketat).
217
+
218
+ ---
219
+
220
+ ### 3.3 `GET /api/books` β€” Katalog Buku Publik
221
+
222
+ **Fungsi:** Menampilkan daftar buku dari dataset `sibi_books.jsonl` dengan dukungan paginasi dan filter.
223
+
224
+ **Tujuan:** Digunakan frontend untuk menampilkan halaman katalog/browsing buku kepada pengguna umum.
225
+
226
+ **Cara Akses:**
227
+ ```bash
228
+ # Semua buku (halaman 1)
229
+ curl "http://localhost:7860/api/books"
230
+
231
+ # Dengan filter spesifik
232
+ curl "http://localhost:7860/api/books?jenjang=SMA&kelas=10&mata_pelajaran=Fisika"
233
+
234
+ # Dengan pencarian dan paginasi
235
+ curl "http://localhost:7860/api/books?search=matematika&page=2&limit=10"
236
+ ```
237
+
238
+ **Parameter Query:**
239
+
240
+ | Parameter | Default | Keterangan |
241
+ |-----------|---------|------------|
242
+ | `page` | `1` | Nomor halaman paginasi |
243
+ | `limit` | `20` | Jumlah buku per halaman |
244
+ | `search` | β€” | Pencarian pada `judul_buku` atau `book_id` (case-insensitive) |
245
+ | `jenjang` | β€” | Filter jenjang pendidikan (contoh: `"SMA"`, `"SMP"`, `"SD"`) |
246
+ | `kelas` | β€” | Filter kelas (contoh: `"10"`, `"7"`) |
247
+ | `mata_pelajaran` | β€” | Filter mata pelajaran (contoh: `"Fisika"`, `"Matematika"`) |
248
+
249
+ **Format Output (JSON):**
250
+ ```json
251
+ {
252
+ "books": [
253
+ {
254
+ "book_id": "8b32-9c12-...",
255
+ "judul_buku": "Fisika untuk SMA/MA Kelas X",
256
+ "jenjang": "SMA",
257
+ "kelas": "10",
258
+ "mata_pelajaran": "Fisika",
259
+ "tipe": "Buku Teks",
260
+ "link_sampul": "https://...",
261
+ "link_buku": "https://...",
262
+ "link_sumber": "https://...",
263
+ "summary_text": "..."
264
+ }
265
+ ],
266
+ "total_books": 1,
267
+ "total_pages": 1,
268
+ "current_page": 1
269
+ }
270
+ ```
271
+
272
+ ---
273
+
274
+ ### 3.4 `POST /api/admin/extract` β€” Ekstraksi PDF (Langkah 1 dari 2 Penambahan Buku)
275
+
276
+ **Fungsi:** Menerima file PDF buku baru, mengekstrak teks, dan menghasilkan ringkasan otomatis. **Belum** menyimpan ke database atau vector store.
277
+
278
+ **Tujuan:** Memberikan preview hasil ekstraksi kepada admin sebelum konfirmasi penyimpanan final, sehingga admin dapat mengoreksi metadata atau ringkasan jika perlu.
279
+
280
+ **Cara Akses:**
281
+ ```bash
282
+ curl -X POST http://localhost:7860/api/admin/extract \
283
+ -F "file=@/path/ke/buku_fisika.pdf" \
284
+ -F "judul_buku=Fisika SMA" \
285
+ -F "jenjang=SMA" \
286
+ -F "kelas=12" \
287
+ -F "mata_pelajaran=Fisika" \
288
+ -F "tipe=Buku Teks"
289
+ ```
290
+
291
+ **Format Input (Form Data):**
292
+
293
+ | Field | Tipe | Keterangan |
294
+ |-------|------|------------|
295
+ | `file` | File (PDF) | File PDF buku yang akan diunggah (Wajib) |
296
+ | `judul_buku` | string | Judul lengkap buku (Opsional namun direkomendasikan agar ringkasan akurat) |
297
+ | `jenjang` | string | Jenjang pendidikan (Opsional) |
298
+ | `kelas` | string | Kelas 1–12 (Opsional) |
299
+ | `mata_pelajaran` | string | Mata pelajaran (Opsional) |
300
+ | `tipe` | string | Tipe buku, misal "Buku Teks" (Opsional) |
301
+
302
+ **Catatan untuk Frontend:** Saat admin memilih PDF, kirimkan juga meta data form agar model AI dapat mem-parsing rangkuman buku dengan presisi yang lebih baik menggunakan bantuan konteks (judul, jenjang, tipe, dll).
303
+
304
+ **Format Output (JSON):**
305
+ ```json
306
+ {
307
+ "status": "ok",
308
+ "message": "Ekstraksi dan summarisasi selesai",
309
+ "book_id": "8b32-9c12-...",
310
+ "pdf_path": "data/uploads/8b32-9c12-..._buku_fisika.pdf",
311
+ "summary": "Buku fisika untuk kelas 12 membahas tentang gelombang, optik...",
312
+ "metadata_preview": {
313
+ "book_id": "8b32-9c12-...",
314
+ "judul_buku": "Fisika SMA",
315
+ "jenjang": "SMA",
316
+ "kelas": "12",
317
+ "mata_pelajaran": "Fisika",
318
+ "tipe": "Buku Teks"
319
+ }
320
+ }
321
+ ```
322
+
323
+ ---
324
+
325
+ ### 3.5 `POST /api/admin/add` β€” Konfirmasi & Simpan Buku (Langkah 2 dari 2)
326
+
327
+ **Fungsi:** Menyimpan buku ke sistem secara permanen β€” melakukan embedding, mengindeks ke FAISS, dan memperbarui `sibi_books.jsonl`.
328
+
329
+ **Tujuan:** Langkah konfirmasi final setelah admin memverifikasi dan (opsional) mengedit metadata hasil ekstraksi pada langkah sebelumnya.
330
+
331
+ **Cara Akses:**
332
+ ```bash
333
+ curl -X POST http://localhost:7860/api/admin/add \
334
+ -H "Content-Type: application/json" \
335
+ -d '{
336
+ "judul_buku": "Fisika 12",
337
+ "summary": "Buku fisika untuk kelas 12 membahas tentang gelombang...",
338
+ "jenjang": "SMA",
339
+ "kelas": "12",
340
+ "mata_pelajaran": "Fisika",
341
+ "tipe": "Buku Teks",
342
+ "pdf_path": "data/uploads/8b32-9c12-..._buku_fisika.pdf"
343
+ }'
344
+ ```
345
+
346
+ **Format Input (JSON Body):**
347
+
348
+ | Field | Tipe | Keterangan |
349
+ |-------|------|------------|
350
+ | `judul_buku` | string | Judul lengkap buku |
351
+ | `summary` | string | Ringkasan buku (bisa diedit dari hasil ekstraksi) |
352
+ | `jenjang` | string | Jenjang pendidikan (SD / SMP / SMA / SMK) |
353
+ | `kelas` | string | Kelas (1–12) |
354
+ | `mata_pelajaran` | string | Nama mata pelajaran |
355
+ | `tipe` | string | Tipe buku (Buku Teks / Buku Pengayaan / dll) |
356
+ | `pdf_path` | string | Path PDF hasil dari endpoint `/api/admin/extract` |
357
+
358
+ **Format Output (JSON):**
359
+ ```json
360
+ {
361
+ "status": "ok",
362
+ "message": "Book ingested successfully",
363
+ "metadata": {
364
+ "book_id": "8b32-9c12-...",
365
+ "judul_buku": "Fisika 12",
366
+ "tipe": "Buku Teks"
367
+ },
368
+ "summary": "...",
369
+ "chunks": ["chunk teks 1...", "chunk teks 2...", "..."]
370
+ }
371
+ ```
372
+
373
+ ---
374
+
375
+ ### 3.6 `PUT /api/admin/update/<book_id>` β€” Perbarui Metadata Buku
376
+
377
+ **Fungsi:** Memperbarui metadata buku yang sudah ada di sistem berdasarkan `book_id`.
378
+
379
+ **Tujuan:** Memungkinkan admin memperbaiki kesalahan metadata tanpa harus menghapus dan mengunggah ulang buku.
380
+
381
+ **Cara Akses:**
382
+ ```bash
383
+ curl -X PUT http://localhost:7860/api/admin/update/abcd-efg \
384
+ -H "Content-Type: application/json" \
385
+ -d '{
386
+ "metadata": {
387
+ "judul_buku": "Fisika untuk SMA/MA Kelas XII (Edisi Revisi)",
388
+ "kelas": "12"
389
+ },
390
+ "summary_text": "Isi rangkuman yang baru (opsional)"
391
+ }'
392
+ ```
393
+
394
+ **Format Input (JSON Body):**
395
+ ```json
396
+ {
397
+ "metadata": {
398
+ "judul_buku": "Fisika untuk SMA/MA Kelas XII (Edisi Revisi)",
399
+ "kelas": "12"
400
+ },
401
+ "summary_text": "Isi rangkuman yang baru (opsional)"
402
+ }
403
+ ```
404
+ Catatan: JSON ini memungkinkan *partial update*. Jika field `"summary_text"` diberikan dan isinya berubah, maka sistem secara otomatis akan me-*re-embed* ulang summary di FAISS Vector Store. Perubahan metadata akan di-sync langsung ke `sibi_books.jsonl` dan `sibi_books_catalog.jsonl`.
405
+
406
+ **Format Output (JSON):**
407
+ ```json
408
+ {
409
+ "status": "ok",
410
+ "message": "Buku berhasil diupdate",
411
+ "book_id": "abcd-efg",
412
+ "metadata": {
413
+ "judul_buku": "Fisika 12",
414
+ "jenjang": "SMA",
415
+ "kelas": "12",
416
+ "tipe": "Buku Teks"
417
+ }
418
+ }
419
+ ```
420
+
421
+ *Output metadata ini mengembalikan data versi lama (sebelum diupdate) sebagai riwayat perubahan.*
422
+
423
+ ---
424
+
425
+ ### 3.7 `DELETE /api/admin/delete/<book_id>` β€” Hapus Buku
426
+
427
+ **Fungsi:** Menghapus buku dari seluruh sistem (`sibi_books_catalog.jsonl`, `sibi_books.jsonl`, FAISS Summary Index, dan FAISS Fulltext Index) berdasarkan `book_id`.
428
+
429
+ **Tujuan:** Memungkinkan admin menonaktifkan atau menghapus buku yang sudah tidak relevan atau salah diunggah secara permanen.
430
+
431
+ **Cara Akses:**
432
+ ```bash
433
+ curl -X DELETE http://localhost:7860/api/admin/delete/abcd-efg
434
+ ```
435
+
436
+ **Format Input:** Tidak ada request body. `book_id` diambil dari URL path.
437
+
438
+ **Format Output (JSON):**
439
+ ```json
440
+ {
441
+ "status": "ok",
442
+ "message": "Buku berhasil dihapus",
443
+ "book_id": "abcd-efg",
444
+ "metadata": {
445
+ "judul_buku": "Ilmu Pengetahuan Alam Kelas VII",
446
+ "jenjang": "SMP",
447
+ "tipe": "Buku Teks"
448
+ }
449
+ }
450
+ ```
451
+
452
+ **Catatan:** Key `"metadata"` mengembalikan profil buku versi lama (**sebelum dihapus**) sebagai konfirmasi untuk frontend. Penghapusan akan otomatis dimuat ulang oleh `catalog_store` in-memory system.
453
+
454
+ ---
455
+
456
+ ### Ringkasan Endpoint
457
+
458
+ | Method | Path | Akses | Fungsi Singkat |
459
+ |--------|------|-------|----------------|
460
+ | `POST` | `/recommend` | Public | Rekomendasi buku via RAG |
461
+ | `POST` | `/deep` | Public | Penjelasan mendalam materi |
462
+ | `GET` | `/api/books` | Public | Katalog buku dengan filter & paginasi |
463
+ | `POST` | `/api/admin/extract` | Admin | Ekstraksi & preview PDF (step 1) |
464
+ | `POST` | `/api/admin/add` | Admin | Simpan buku ke sistem (step 2) |
465
+ | `PUT` | `/api/admin/update/<id>` | Admin | Perbarui metadata buku |
466
+ | `DELETE` | `/api/admin/delete/<id>` | Admin | Hapus buku dari sistem |
467
+ | `GET` | `/api/admin/books` | Admin | Sama seperti `/api/books`, dengan data internal tambahan jika diperlukan |
468
+
469
+ ---
470
+
471
+ ## 4. Cara Clone / Akses Kode
472
+
473
+ ### Clone Repository
474
+
475
+ ```bash
476
+ git clone https://github.com/pan-don/backend-booki.git
477
+ cd backend-booki
478
+ ```
479
+
480
+ ### Menjalankan Secara Lokal
481
+
482
+ **Prasyarat:** Python 3.13+, `uv` terinstall
483
+
484
+ ```bash
485
+ # 1. Install uv (jika belum)
486
+ curl -LsSf https://astral.sh/uv/install.sh | sh
487
+
488
+ # 2. Install semua dependensi
489
+ uv sync --frozen
490
+
491
+ # 3. Salin dan isi environment variables
492
+ cp .env.example .env
493
+ # Edit .env dan isi GOOGLE_API_KEY, JINA_API_KEY, dll
494
+
495
+ # 4. Jalankan server (development)
496
+ uv run uvicorn app:asgi_app --host 0.0.0.0 --port 7860 --reload
497
+ ```
498
+
499
+ Server akan berjalan di `http://localhost:7860`.
500
+
501
+ ### Menjalankan dengan Docker
502
+
503
+ ```bash
504
+ # Build image
505
+ docker build -t backend-booki .
506
+
507
+ # Jalankan container
508
+ docker run -p 7860:7860 \
509
+ -e GOOGLE_API_KEY=your_key \
510
+ -e JINA_API_KEY=your_key \
511
+ backend-booki
512
+ ```
513
+
514
+ ### Menggunakan Notebook Interaktif
515
+
516
+ File `notebook.ipynb` menyediakan antarmuka interaktif untuk:
517
+ - Testing endpoint `/recommend` dan `/deep`
518
+ - Manajemen buku admin (add/update/delete) dengan menu pilihan interaktif
519
+ - Melihat katalog buku dengan paginasi dan filter
520
+
521
+ Jalankan dengan:
522
+ ```bash
523
+ uv run jupyter notebook notebook.ipynb
524
+ ```
525
+
526
+ ### Akses via Hugging Face Spaces
527
+
528
+ Sistem ini di-deploy di Hugging Face Spaces via Docker SDK. Akses endpoint melalui URL Space yang diberikan oleh HF, pada port yang dirouting secara otomatis ke port 7860 internal.
529
+
530
+ ---
531
+
532
+ ## 5. Pembaruan Terbaru
533
+
534
+ Berikut adalah ringkasan pembaruan signifikan yang telah dilakukan pada sistem:
535
+
536
+ ### Sistem RAG & Retrieval
537
+ - **Dynamic Score Gap Reranker:** Penghapusan buku dari hasil rekomendasi kini tidak lagi bergantung pada threshold statis, melainkan pada deteksi jarak penurunan skor relevansi antar buku secara berurutan
538
+ - **Threshold Adaptif:** Baseline threshold diturunkan (`/recommend`: `0.1`, `/deep`: `0.05`) untuk mengutamakan gap logic dibanding nilai absolut
539
+ - **Konsistensi Format Output:** Endpoint `/recommend` kini mengeluarkan array `recommendations` dengan format key yang 100% konsisten dengan skema `sibi_books.jsonl`
540
+
541
+ ### Sistem Chat & Generasi
542
+ - **Jawaban Pertanyaan Umum:** LLM dapat menjawab pertanyaan tentang identitas sistem, jumlah data, dan cakupan katalog dengan menyisipkan statistik dataset secara dinamis ke system prompt
543
+ - **LaTeX untuk Rumus:** Endpoint `/deep` diwajibkan menggunakan format LaTeX untuk penulisan rumus matematika
544
+ - **Anti-halusinasi Gambar:** Sistem dilarang menghasilkan tautan gambar yang tidak ada dalam konteks dokumen
545
+
546
+ ### Manajemen Admin
547
+ - **Proses Add Buku 2 Langkah:** Pemisahan endpoint `extract` (preview) dan `add` (simpan) untuk memberi kesempatan admin mengoreksi sebelum data masuk ke sistem
548
+ - **Sinkronisasi Delete & Update:** Operasi hapus dan ubah otomatis memperbarui Summary Index, Fulltext Index, dan JSONL secara bersamaan
549
+ - **Return Metadata:** Endpoint update dan delete kini mengembalikan data buku yang diubah/dihapus sebagai konfirmasi
550
+
551
+ ### Notebook & Developer Experience
552
+ - **Menu Input Interaktif:** Notebook admin menggunakan pilihan nomor berbasis katalog (bukan input bebas) untuk field seperti jenjang, tipe, dll
553
+ - **Bug Fix Paginasi:** Perbaikan bug tampilan tabel kosong pada halaman admin books akibat ketidakcocokan format key metadata
554
+
555
+ ---
556
+
557
+ ## 6. Penutup
558
+
559
+ **BackendBooki** merupakan sistem backend RAG yang dirancang modular, dapat dikembangkan, dan siap-deploy di Hugging Face Spaces. Setiap komponen pipeline β€” dari parsing PDF, chunking, embedding, retrieval, reranking, hingga generasi jawaban β€” dipisahkan ke dalam modul tersendiri untuk kemudahan pemeliharaan dan pengujian.
560
+
561
+ Sistem ini menggunakan stack modern Python (uv, Python 3.13, Flask/ASGI) dengan dependensi yang dikunci secara deterministik melalui `uv.lock`, memastikan konsistensi antara lingkungan development dan production.
562
+
563
+ Untuk kontribusi atau pertanyaan lebih lanjut, silakan buka issue atau pull request di repository GitHub:
564
+ πŸ‘‰ **https://github.com/pan-don/backend-booki**
565
+
566
+ ---
567
+
568
+ *Laporan ini diperbarui pada 22 Juni 2026.*
api/app.py CHANGED
@@ -3,25 +3,37 @@ Flask application factory and global component initialization.
3
  Loads vector stores, retriever, reranker, answer generator, and registers blueprints.
4
  """
5
 
 
6
  from pathlib import Path
7
  import sys
8
 
 
 
9
  from flask import Flask, jsonify
10
  from flask_cors import CORS
11
 
12
- sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
13
-
14
- from config.settings import FRONTEND_URL, FULLTEXT_INDEX_PATH, SUMMARY_INDEX_PATH
 
 
 
 
 
 
 
 
15
  from embedding.embedder import GeminiEmbedder
16
  from embedding.vector_store import FulltextVectorStore, SummaryVectorStore
17
  from generation.answer_generator import get_answer_generator
18
  from retrieval.reranker import Reranker
19
  from retrieval.retriever import Retriever
20
  from utils.api_key_manager import create_gemini_embedding_key_manager
 
21
  from utils.logger import configure_root_logger, get_logger
22
 
23
  # Configure root logger once
24
- configure_root_logger(log_file=Path("logs/api.log"), level=20) # INFO
25
  logger = get_logger(__name__)
26
 
27
 
@@ -48,7 +60,6 @@ def create_app() -> Flask:
48
  logger.info("GeminiEmbedder initialized")
49
 
50
  # Get embedding dimension from config or fallback
51
- from config.settings import EMBEDDING_DIM
52
  dimension = EMBEDDING_DIM
53
  logger.info(f"Embedding dimension: {dimension}")
54
 
@@ -69,9 +80,6 @@ def create_app() -> Flask:
69
  answer_generator = get_answer_generator()
70
 
71
  # Load book_metadata_map from jsonl
72
- from config.settings import RAW_DATA_FILE
73
- import json
74
-
75
  book_metadata_map = {}
76
  try:
77
  if RAW_DATA_FILE.exists():
@@ -81,7 +89,7 @@ def create_app() -> Flask:
81
  if line:
82
  book_data = json.loads(line)
83
  # Book ID is expected to be mapped here. Handle common keys or missing 'book_id'
84
- bid = book_data.get('book_id', book_data.get('id'))
85
  if bid:
86
  book_metadata_map[bid] = book_data
87
  logger.info(f"Loaded {len(book_metadata_map)} books into metadata map")
@@ -103,22 +111,15 @@ def create_app() -> Flask:
103
  logger.error(f"Failed to initialize global components: {e}", exc_info=True)
104
  raise
105
 
106
- # ---------------- Register Blueprints ----------------
107
- from api.routes.admin import admin_bp
108
- from api.routes.books import books_bp
109
- from api.routes.deep import deep_bp
110
- from api.routes.recommend import recommend_bp
111
 
112
  app.register_blueprint(recommend_bp, url_prefix='/api')
113
  app.register_blueprint(deep_bp, url_prefix='/api')
114
  app.register_blueprint(admin_bp, url_prefix='/api')
115
  app.register_blueprint(books_bp, url_prefix='/api')
116
 
117
- # Alias routes without /api to avoid 404 when frontend hits root paths
118
- app.register_blueprint(recommend_bp, name="recommend_root")
119
- app.register_blueprint(deep_bp, name="deep_root")
120
- app.register_blueprint(admin_bp, name="admin_root")
121
- app.register_blueprint(books_bp, name="books_root")
122
 
123
  # ---------------- Health Check Endpoint ----------------
124
  @app.route('/', methods=['GET'])
 
3
  Loads vector stores, retriever, reranker, answer generator, and registers blueprints.
4
  """
5
 
6
+ import json
7
  from pathlib import Path
8
  import sys
9
 
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
11
+
12
  from flask import Flask, jsonify
13
  from flask_cors import CORS
14
 
15
+ from api.routes.admin import admin_bp
16
+ from api.routes.books import books_bp
17
+ from api.routes.deep import deep_bp
18
+ from api.routes.recommend import recommend_bp
19
+ from config.settings import (
20
+ EMBEDDING_DIM,
21
+ FRONTEND_URL,
22
+ FULLTEXT_INDEX_PATH,
23
+ RAW_DATA_FILE,
24
+ SUMMARY_INDEX_PATH,
25
+ )
26
  from embedding.embedder import GeminiEmbedder
27
  from embedding.vector_store import FulltextVectorStore, SummaryVectorStore
28
  from generation.answer_generator import get_answer_generator
29
  from retrieval.reranker import Reranker
30
  from retrieval.retriever import Retriever
31
  from utils.api_key_manager import create_gemini_embedding_key_manager
32
+ import utils.catalog_store as catalog_store
33
  from utils.logger import configure_root_logger, get_logger
34
 
35
  # Configure root logger once
36
+ configure_root_logger(log_file=Path("logs/api.routes.log"), level=20) # INFO
37
  logger = get_logger(__name__)
38
 
39
 
 
60
  logger.info("GeminiEmbedder initialized")
61
 
62
  # Get embedding dimension from config or fallback
 
63
  dimension = EMBEDDING_DIM
64
  logger.info(f"Embedding dimension: {dimension}")
65
 
 
80
  answer_generator = get_answer_generator()
81
 
82
  # Load book_metadata_map from jsonl
 
 
 
83
  book_metadata_map = {}
84
  try:
85
  if RAW_DATA_FILE.exists():
 
89
  if line:
90
  book_data = json.loads(line)
91
  # Book ID is expected to be mapped here. Handle common keys or missing 'book_id'
92
+ bid = book_data.get('book_id', book_data.get('id', None))
93
  if bid:
94
  book_metadata_map[bid] = book_data
95
  logger.info(f"Loaded {len(book_metadata_map)} books into metadata map")
 
111
  logger.error(f"Failed to initialize global components: {e}", exc_info=True)
112
  raise
113
 
114
+ logger.info("loading books catalog into memory...")
115
+ catalog_store.load()
116
+ logger.info(f"Catalog ready: {catalog_store.count()} books.")
 
 
117
 
118
  app.register_blueprint(recommend_bp, url_prefix='/api')
119
  app.register_blueprint(deep_bp, url_prefix='/api')
120
  app.register_blueprint(admin_bp, url_prefix='/api')
121
  app.register_blueprint(books_bp, url_prefix='/api')
122
 
 
 
 
 
 
123
 
124
  # ---------------- Health Check Endpoint ----------------
125
  @app.route('/', methods=['GET'])
api/routes/admin.py CHANGED
@@ -1,543 +1,402 @@
 
1
  """
2
- Admin endpoints for managing the RAG system.
3
- - Trigger full re-ingestion pipeline (calls scripts/ingest_all.py)
4
- - Health check for admin endpoints
 
 
 
 
5
  """
6
 
7
  import json
 
 
8
  from pathlib import Path
9
- from api.routes.books import reload_static_cache
10
- from scripts.generate_static_data import generate_static_files
11
-
12
- import sys
13
- import threading
14
  import uuid
15
 
16
  from flask import Blueprint, jsonify, request
17
 
18
- # Add project root to path (ensure scripts module can be imported)
19
- sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
20
-
21
- from utils.logger import get_logger
22
-
23
- logger = get_logger(__name__)
24
- admin_bp = Blueprint('admin', __name__)
 
 
 
 
 
 
25
 
26
- import json
27
- import math
28
- import threading
29
- import uuid
30
 
31
- from werkzeug.utils import secure_filename
32
 
33
- from config.settings import DATA_DIR, FULLTEXT_INDEX_PATH, SUMMARY_INDEX_PATH
34
- from embedding.embedder import GeminiEmbedder
35
- from embedding.vector_store import FulltextVectorStore, SummaryVectorStore
36
 
37
- RAW_DATA_FILE = DATA_DIR / "raw" / "sibi_books.jsonl"
38
-
39
- try:
40
- from scripts.add_book import add_new_book
41
- ADD_BOOK_AVAILABLE = True
42
- except ImportError as e:
43
- logger.error(f"Could not import add_new_book: {e}")
44
- ADD_BOOK_AVAILABLE = False
45
- add_new_book = None
46
-
47
- try:
48
- from scripts.update_book import update_book_metadata
49
- UPDATE_BOOK_AVAILABLE = True
50
- except ImportError as e:
51
- logger.error(f"Could not import update_book_metadata: {e}")
52
- UPDATE_BOOK_AVAILABLE = False
53
- update_book_metadata = None
54
-
55
- try:
56
- from scripts.delete_book import delete_book
57
- DELETE_BOOK_AVAILABLE = True
58
- except ImportError as e:
59
- logger.error(f"Could not import delete_book: {e}")
60
- DELETE_BOOK_AVAILABLE = False
61
- delete_book = None
62
-
63
- # Import ingestion main function (with fallback)
64
- try:
65
- from scripts.add_book import main as ingest_main
66
- INGEST_AVAILABLE = True
67
- except ImportError as e:
68
- logger.error(f"Could not import ingest_all: {e}")
69
- INGEST_AVAILABLE = False
70
- ingest_main = None
71
-
72
-
73
- def _run_ingestion():
74
  """
75
- Run the full ingestion pipeline in background.
76
- This function is intended to be called in a separate thread.
77
  """
 
 
 
78
  try:
79
- logger.info("Starting background ingestion pipeline...")
80
- if ingest_main is not None:
81
- ingest_main()
82
- logger.info("Background ingestion completed successfully")
83
- else:
84
- logger.error("Ingestion function not available")
85
- except Exception as e:
86
- logger.error(f"Background ingestion failed: {e}", exc_info=True)
87
-
88
-
89
- def _parse_metadata_field(raw_metadata):
90
- if raw_metadata is None:
91
- return None
92
- if isinstance(raw_metadata, dict):
93
- return raw_metadata
94
- if isinstance(raw_metadata, str):
95
- raw_metadata = raw_metadata.strip()
96
- if not raw_metadata:
97
- return None
98
- try:
99
- return json.loads(raw_metadata)
100
- except Exception:
101
- return {"metadata": raw_metadata}
102
- return {"metadata": str(raw_metadata)}
103
-
104
-
105
- def _load_metadata_list():
106
- # Legacy fallback logic for METADATA_FILE if needed, but we now use RAW_DATA_FILE
107
- if RAW_DATA_FILE.exists():
108
- from utils.file_utils import stream_jsonl
109
- return list(stream_jsonl(RAW_DATA_FILE))
110
- return []
111
-
112
-
113
- def _save_metadata_list(books):
114
- pass # Managed dynamically by background tasks or direct raw updates now
115
-
116
-
117
- def _add_summary_only_book(book_data):
118
- embedder = GeminiEmbedder()
119
- dimension = len(embedder.embed_text("test"))
120
-
121
- summary_text = book_data.get("summary_text", "").strip()
122
- if not summary_text:
123
- raise ValueError("summary_text is required for summary-only add")
124
-
125
- format_doc = {"metadata": book_data, "summary_text": summary_text}
126
- enhanced_text = embedder._build_enhanced_text(format_doc)
127
- summary_vector = embedder.embed_text(enhanced_text, task_type="RETRIEVAL_DOCUMENT")
128
-
129
- summary_store = SummaryVectorStore(SUMMARY_INDEX_PATH, dimension=dimension)
130
- summary_meta = {
131
- "book_id": book_data.get("book_id"),
132
- "judul_buku": book_data.get("judul_buku", book_data.get("title", "Unknown")),
133
- "title": book_data.get("title", book_data.get("judul_buku", "Unknown")),
134
- "text": summary_text,
135
- "type": "summary",
136
- "jenjang": book_data.get("jenjang"),
137
- "kelas": book_data.get("kelas"),
138
- "mata_pelajaran": book_data.get("mata_pelajaran"),
139
- }
140
- summary_store.add_vectors([summary_vector], [summary_meta])
141
- summary_store._save()
142
-
143
- books = _load_metadata_list()
144
- books.append(book_data)
145
- _save_metadata_list(books)
146
-
147
-
148
- @admin_bp.route('/admin/ingest', methods=['POST'])
149
- def trigger_ingest():
150
  """
151
- Trigger a full re-ingestion of all books.
152
- This endpoint returns immediately while ingestion runs in background.
153
-
154
- Returns:
155
- JSON with status 'started' or error if ingestion not available.
156
  """
157
- if not INGEST_AVAILABLE:
158
- logger.error("Ingestion pipeline not available")
159
- return jsonify({
160
- "status": "error",
161
- "message": "Ingestion pipeline is not available. Check that scripts/ingest_all.py exists and is importable."
162
- }), 500
163
-
164
- # Start ingestion in background thread to avoid blocking
165
- thread = threading.Thread(target=_run_ingestion, daemon=True)
166
- thread.start()
167
-
168
- logger.info("Ingestion pipeline triggered via admin API")
169
- return jsonify({
170
- "status": "started",
171
- "message": "Ingestion pipeline is running in background. Check logs for progress."
172
- }), 202
173
 
 
174
 
175
- @admin_bp.route('/admin/health', methods=['GET'])
176
- def admin_health():
177
- """
178
- Health check for admin endpoints.
179
- """
180
- return jsonify({
181
- "status": "ok",
182
- "ingest_available": INGEST_AVAILABLE
183
- }), 200
184
 
 
 
 
 
 
 
185
 
186
- @admin_bp.route('/admin/books', methods=['GET'])
187
- def get_admin_books():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  """
189
- Returns a paginated list of books from the source-of-truth ledger with optional search filter.
 
190
  """
191
- try:
192
- page = int(request.args.get('page', 1))
193
- limit = int(request.args.get('limit', 20))
194
- search_query = request.args.get('search', '').lower()
195
- if page < 1 or limit < 1:
196
- return jsonify({"error": "Invalid pagination parameters"}), 400
197
-
198
- if not RAW_DATA_FILE.exists():
199
- return jsonify({
200
- "books": [],
201
- "total_books": 0,
202
- "total_pages": 0,
203
- "current_page": page
204
- }), 200
205
-
206
- all_books = []
207
- with open(RAW_DATA_FILE, 'r', encoding='utf-8') as f:
208
- for line in f:
209
- if line.strip():
210
- try:
211
- book_data = json.loads(line)
212
- if search_query:
213
- title = book_data.get('judul_buku', book_data.get('title', '')).lower()
214
- book_id = book_data.get('book_id', '').lower()
215
- if search_query not in title and search_query not in book_id:
216
- continue
217
- all_books.append(book_data)
218
- except json.JSONDecodeError:
219
- continue
220
-
221
- total_books = len(all_books)
222
- total_pages = math.ceil(total_books / limit)
223
-
224
- # Exact slicing
225
- start_idx = (page - 1) * limit
226
- end_idx = start_idx + limit
227
- paginated_books = all_books[start_idx:end_idx]
228
-
229
- return jsonify({
230
- "books": paginated_books,
231
- "total_books": total_books,
232
- "total_pages": total_pages,
233
- "current_page": page
234
- }), 200
235
 
236
- except Exception as e:
237
- logger.error(f"Failed to fetch paginated books: {e}", exc_info=True)
238
- return jsonify({"error": "Internal server error reading catalog"}), 500
 
239
 
 
 
 
 
240
 
241
- @admin_bp.route('/admin/status', methods=['GET'])
242
- def admin_status():
243
  try:
244
- books = _load_metadata_list()
245
-
246
- # Get unique catalogs
247
- jenjang_list = set()
248
- mata_pelajaran_list = set()
249
- kelas_list = set()
250
- tipe_list = set()
251
-
252
- for b in books:
253
- if b.get("jenjang"): jenjang_list.add(b["jenjang"].strip())
254
- if b.get("mata_pelajaran"): mata_pelajaran_list.add(b["mata_pelajaran"].strip())
255
- if b.get("kelas"): kelas_list.add(b["kelas"].strip())
256
- if b.get("tipe"): tipe_list.add(b["tipe"].strip())
257
-
258
- embedder = GeminiEmbedder()
259
- dimension = len(embedder.embed_text("test"))
260
-
261
- summary_total = 0
262
- fulltext_total = 0
263
- summary_active = 0
264
- fulltext_active = 0
265
-
266
- if SUMMARY_INDEX_PATH.exists():
267
- summary_store = SummaryVectorStore(SUMMARY_INDEX_PATH, dimension=dimension)
268
- summary_total = summary_store.index.ntotal
269
- summary_active = summary_store.total_active()
270
-
271
- if FULLTEXT_INDEX_PATH.exists():
272
- fulltext_store = FulltextVectorStore(FULLTEXT_INDEX_PATH, dimension=dimension)
273
- fulltext_total = fulltext_store.index.ntotal
274
- fulltext_active = fulltext_store.total_active()
275
-
276
- return jsonify({
277
- "status": "ok",
278
- "books_count": len(books),
279
- "catalogs": {
280
- "jenjang": sorted(list(jenjang_list)),
281
- "mata_pelajaran": sorted(list(mata_pelajaran_list)),
282
- "kelas": sorted(list(kelas_list)),
283
- "tipe": sorted(list(tipe_list))
284
- },
285
- "summary_index_total": summary_total,
286
- "summary_index_active": summary_active,
287
- "fulltext_index_total": fulltext_total,
288
- "fulltext_index_active": fulltext_active,
289
- "ingest_available": INGEST_AVAILABLE
290
- }), 200
291
  except Exception as e:
292
- logger.error(f"Failed to get admin status: {e}", exc_info=True)
293
- return jsonify({"error": "Failed to get admin status"}), 500
 
 
 
 
 
 
 
 
 
 
 
294
 
 
 
 
 
 
 
 
 
 
 
295
 
296
- @admin_bp.route('/admin/extract', methods=['POST'])
297
- def admin_extract_book():
298
- """
299
- Step 1 of 2 for adding a book: Upload PDF, parse text, and generate summary.
300
- Does NOT save to vector store or JSONL.
301
- """
302
  try:
303
- file = request.files.get('file')
304
-
305
- # We only really need file here, but can accept metadata to guide summary
306
- title = request.form.get("judul_buku", request.form.get("title", "")).strip()
307
- jenjang = request.form.get("jenjang", "").strip()
308
- kelas = request.form.get("kelas", "").strip()
309
- mapel = request.form.get("mata_pelajaran", "").strip()
310
-
311
- if not file or not file.filename:
312
- return jsonify({"error": "PDF file is required for extraction"}), 400
313
-
314
- book_id = str(uuid.uuid4())[:16]
315
-
316
- filename = secure_filename(file.filename)
317
- upload_dir = DATA_DIR / "uploads"
318
- upload_dir.mkdir(parents=True, exist_ok=True)
319
- pdf_path = upload_dir / f"{book_id}_{filename}"
320
- file.save(pdf_path)
321
-
322
- # 1. Parse Text
323
- from parsing.pdf_cleaner import clean_text
324
- from parsing.pdf_parser import parse_pdf_to_text
325
-
326
- raw_text = parse_pdf_to_text(pdf_path)
327
- cleaned_text = clean_text(raw_text)
328
-
329
- # 2. Summarize (if not provided)
330
- summary = request.form.get("summary", "").strip()
331
- if not summary:
332
- from summarization.book_summarizer import summarize_book
333
- meta_for_summary = {
334
- "judul_buku": title,
335
- "jenjang": jenjang,
336
- "kelas": kelas,
337
- "mata_pelajaran": mapel
338
- }
339
- summary = summarize_book(meta_for_summary, cleaned_text)
340
-
341
- return jsonify({
342
- "status": "ok",
343
- "message": "Extraction and summarization complete",
344
- "book_id": book_id,
345
- "pdf_path": str(pdf_path),
346
- "summary": summary,
347
- "metadata_preview": {
348
- "judul_buku": title,
349
- "jenjang": jenjang,
350
- "kelas": kelas,
351
- "mata_pelajaran": mapel
352
- }
353
- }), 200
354
 
355
  except Exception as e:
356
- logger.error(f"Failed to extract book: {e}", exc_info=True)
357
- return jsonify({"error": "Internal server error during extraction"}), 500
 
 
 
 
 
 
 
 
 
 
 
 
358
 
359
- @admin_bp.route('/admin/add', methods=['POST'])
360
- def admin_add_book():
361
  """
362
- Step 2 of 2: Confirm and ingest book.
363
- Expects metadata, summary, and optionally pdf_path (if extracted previously).
 
364
  """
 
 
 
 
 
 
 
 
 
 
 
 
365
  try:
366
- # Check if form data or JSON is being used
367
- if request.is_json:
368
- data = request.get_json()
369
- else:
370
- data = request.form.to_dict()
371
-
372
- title = data.get("judul_buku", data.get("title", "")).strip()
373
- summary = data.get("summary", data.get("summary_text", "")).strip()
374
- jenjang = data.get("jenjang", "").strip()
375
- kelas = data.get("kelas", "").strip()
376
- mapel = data.get("mata_pelajaran", "").strip()
377
- tipe = data.get("tipe", "Buku Teks").strip()
378
- link_sampul = data.get("link_sampul", "").strip()
379
- link_buku = data.get("link_buku", "").strip()
380
- link_sumber = data.get("link_sumber", "").strip()
381
- pdf_path_str = data.get("pdf_path", "").strip()
382
-
383
- book_id = data.get("book_id")
384
- if not book_id:
385
- book_id = str(uuid.uuid4())[:16]
386
-
387
- if not title:
388
- return jsonify({"error": "Title is required"}), 400
389
-
390
- book_data = {
391
- "book_id": book_id,
392
- "judul_buku": title,
393
- "title": title, # duplicate for backward compat during indexing
394
- "summary_text": summary,
395
- "jenjang": jenjang,
396
- "kelas": kelas,
397
- "mata_pelajaran": mapel,
398
- "tipe": tipe,
399
- "link_sampul": link_sampul,
400
- "link_buku": link_buku,
401
- "link_sumber": link_sumber,
402
- "pdf_path": pdf_path_str
403
- }
404
-
405
- # Lazy import to avoid circular dependency
406
- from scripts.add_book import add_new_book
407
-
408
- result_data = {}
409
- if pdf_path_str:
410
- # Reconstruct full path if it's relative
411
- pdf_path = Path(pdf_path_str)
412
- if not pdf_path.exists():
413
- return jsonify({"error": f"PDF file not found at {pdf_path_str}"}), 400
414
-
415
- success, result_data = add_new_book(book_data, interactive=False, override_summary=summary if summary else None)
416
- if not success:
417
- return jsonify({"error": "Failed to ingest PDF into RAG pipeline"}), 500
418
- else:
419
- _add_summary_only_book(book_data)
420
-
421
- # Write to JSONL
422
- # Clean up transient keys
423
- jsonl_data = {k: v for k, v in book_data.items() if k not in ['pdf_path']}
424
-
425
- with open(RAW_DATA_FILE, 'a', encoding='utf-8') as f:
426
- f.write(json.dumps(jsonl_data, ensure_ascii=False) + "\n")
427
-
428
- generate_static_files()
429
- reload_static_cache()
430
-
431
- return jsonify({
432
- "status": "ok",
433
- "message": "Book ingested successfully",
434
- "metadata": jsonl_data,
435
- "summary": result_data.get("summary", summary),
436
- "chunks": result_data.get("chunks", [])
437
- }), 201
438
 
439
  except Exception as e:
440
- logger.error(f"Failed to confirm add book: {e}", exc_info=True)
441
- return jsonify({"error": "Internal server error during ingestion"}), 500
442
 
 
 
 
 
 
 
 
443
 
444
- @admin_bp.route('/admin/update/<book_id>', methods=['PUT'])
445
- def admin_update_book(book_id):
446
- if not UPDATE_BOOK_AVAILABLE:
447
- return jsonify({"error": "Update function not available"}), 500
448
 
449
- data = request.get_json() or {}
450
- title = (data.get("title") or "").strip()
451
- summary = (data.get("summary") or "").strip()
452
- raw_metadata = data.get("metadata")
453
 
454
- metadata_dict = _parse_metadata_field(raw_metadata) or {}
455
- new_metadata = {}
456
- new_metadata.update(metadata_dict)
 
 
 
 
 
 
 
 
 
457
 
458
- if title:
459
- new_metadata["judul_buku"] = title
460
- new_metadata["title"] = title
461
- if summary:
462
- new_metadata["summary_text"] = summary
463
 
464
  try:
465
- from scripts.update_book import update_book_metadata
466
- success = update_book_metadata(book_id, new_metadata)
467
- if not success:
468
- return jsonify({"error": "Failed to update book metadata in vector store"}), 500
469
-
470
- # Update JSONL safely
471
- updated_book = None
472
- if RAW_DATA_FILE.exists():
473
- updated_lines = []
474
- with open(RAW_DATA_FILE, 'r', encoding='utf-8') as f:
475
- for line in f:
476
- if not line.strip(): continue
477
- row = json.loads(line)
478
- if row.get("book_id") == book_id:
479
- row.update(new_metadata)
480
- updated_book = row
481
- updated_lines.append(json.dumps(row, ensure_ascii=False))
482
- with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
483
- f.write("\n".join(updated_lines) + "\n")
484
-
485
- generate_static_files()
486
- reload_static_cache()
487
-
488
- return jsonify({
489
- "status": "ok",
490
- "message": "Book updated successfully",
491
- "book_id": book_id,
492
- "metadata": updated_book
493
- }), 200
494
  except Exception as e:
495
- logger.error(f"Failed to update book {book_id}: {e}", exc_info=True)
496
- return jsonify({"error": "Internal server error during update"}), 500
 
 
 
 
 
 
 
 
497
 
498
 
499
- @admin_bp.route('/admin/delete/<book_id>', methods=['DELETE'])
500
- def admin_delete_book(book_id):
501
- if not DELETE_BOOK_AVAILABLE:
502
- return jsonify({"error": "Delete function not available"}), 500
 
 
 
 
 
 
 
 
 
503
 
504
  try:
505
- from scripts.delete_book import delete_book as delete_from_vector
506
- success = delete_from_vector(book_id)
507
- if not success:
508
- logger.warning("Vector store deletion failed or book not found in index, proceeding with file deletion.")
509
-
510
- # Safe JSONL deletion
511
- deleted_book = None
512
- if RAW_DATA_FILE.exists():
513
- retained_lines = []
514
- with open(RAW_DATA_FILE, 'r', encoding='utf-8') as f:
515
- for line in f:
516
- if not line.strip(): continue
517
- row = json.loads(line)
518
- if row.get("book_id") != book_id:
519
- retained_lines.append(line.strip())
520
- else:
521
- deleted_book = row
522
- with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
523
- if retained_lines:
524
- f.write("\n".join(retained_lines) + "\n")
525
- else:
526
- f.write("")
527
-
528
- generate_static_files()
529
- reload_static_cache()
530
-
531
- return jsonify({
532
- "status": "ok",
533
- "message": "Book deleted successfully",
534
- "book_id": book_id,
535
- "metadata": deleted_book
536
- }), 200
537
- except Exception as e:
538
- logger.error(f"Failed to delete book {book_id}: {e}", exc_info=True)
539
- return jsonify({"error": "Internal server error during deletion"}), 500
540
 
 
 
 
 
 
541
 
542
- # Optional: Endpoint to check ingestion status (if you want to track)
543
- # For simplicity, not implemented here; could be extended with a global flag.
 
 
 
 
 
 
1
+ # api/admin.py
2
  """
3
+ Admin endpoints untuk pengelolaan buku.
4
+
5
+ Alur data saat add/update/delete:
6
+ 1. Update sibi_books_catalog.jsonl (catalog β€” tanpa full_text)
7
+ 2. Update sibi_books.jsonl (sumber FAISS β€” dengan full_text, jika ada)
8
+ 3. Update FAISS index (summary + fulltext vector store)
9
+ 4. catalog_store.reload() (sync in-memory dari file catalog baru)
10
  """
11
 
12
  import json
13
+ import logging
14
+ import os
15
  from pathlib import Path
16
+ import shutil
17
+ import tempfile
 
 
 
18
  import uuid
19
 
20
  from flask import Blueprint, jsonify, request
21
 
22
+ from chunking.text_chunker import chunk_text
23
+ from config.settings import (
24
+ CATALOG_FILE,
25
+ FULLTEXT_INDEX_PATH,
26
+ METADATA_INDEX_PATH,
27
+ RAW_DATA_FILE,
28
+ SUMMARY_INDEX_PATH,
29
+ )
30
+ from embedding.embedder import embed_texts
31
+ from embedding.vector_store import FulltextVectorStore, SummaryVectorStore
32
+ from parsing.pdf_parser import parse_pdf_to_text
33
+ from summarization.book_summarizer import summarize_book
34
+ import utils.catalog_store as catalog_store
35
 
36
+ logger = logging.getLogger(__name__)
37
+ admin_bp = Blueprint("admin", __name__, url_prefix="/api/admin")
 
 
38
 
 
39
 
40
+ # ── Helper: atomic file write ────────────────────────────────────────────────
 
 
41
 
42
+ def _atomic_write_jsonl(path: Path, records: list[dict]) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
+ Tulis list dict ke file JSONL secara atomic menggunakan temp file.
45
+ Mencegah file corrupt jika proses terinterupsi di tengah penulisan.
46
  """
47
+ dir_ = path.parent
48
+ # Tulis ke temp file dulu
49
+ fd, tmp_path = tempfile.mkstemp(dir=dir_, suffix=".tmp")
50
  try:
51
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
52
+ for record in records:
53
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
54
+ # Atomic replace β€” di Unix ini truly atomic
55
+ shutil.move(tmp_path, path)
56
+ except Exception:
57
+ os.unlink(tmp_path)
58
+ raise
59
+
60
+
61
+ def _read_jsonl(path: Path) -> list[dict]:
62
+ """Baca semua record dari file JSONL."""
63
+ if not path.exists():
64
+ return []
65
+ records = []
66
+ with open(path, "r", encoding="utf-8") as f:
67
+ for line in f:
68
+ line = line.strip()
69
+ if line:
70
+ try:
71
+ records.append(json.loads(line))
72
+ except json.JSONDecodeError:
73
+ pass
74
+ return records
75
+
76
+
77
+ def _strip_full_text(record: dict) -> dict:
78
+ """Buat versi catalog (tanpa full_text) dari record lengkap."""
79
+ return {k: v for k, v in record.items() if k != "full_text"}
80
+
81
+
82
+ # ── Step 1: Extract PDF ──────────────────────────────────────────────────────
83
+
84
+ @admin_bp.route("/extract", methods=["POST"])
85
+ def extract_pdf():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  """
87
+ Step 1 dari proses add buku.
88
+ Menerima PDF, extract text, generate summary.
89
+ Belum menyimpan ke database apapun.
 
 
90
  """
91
+ if "file" not in request.files:
92
+ return jsonify({"error": "Field 'file' (PDF) diperlukan"}), 400
93
+
94
+ file = request.files["file"]
95
+ if not file.filename.lower().endswith(".pdf"):
96
+ return jsonify({"error": "File harus berformat PDF"}), 400
97
+
98
+ # Ambil metadata dari request.form jika ada
99
+ metadata = {
100
+ "judul_buku": request.form.get("judul_buku", ""),
101
+ "jenjang": request.form.get("jenjang", ""),
102
+ "kelas": request.form.get("kelas", ""),
103
+ "mata_pelajaran": request.form.get("mata_pelajaran", ""),
104
+ "tipe": request.form.get("tipe", "")
105
+ }
 
106
 
107
+ book_id = str(uuid.uuid4())
108
 
109
+ # Simpan PDF sementara
110
+ upload_dir = Path("data/uploads")
111
+ upload_dir.mkdir(parents=True, exist_ok=True)
112
+ safe_filename = f"{book_id}_{file.filename.replace(' ', '_')}"
113
+ pdf_path = upload_dir / safe_filename
114
+ file.save(pdf_path)
 
 
 
115
 
116
+ try:
117
+ full_text = parse_pdf_to_text(str(pdf_path))
118
+ summary = summarize_book(metadata, full_text)
119
+ except Exception as e:
120
+ logger.error(f"[Admin] Gagal ekstrak PDF: {e}")
121
+ return jsonify({"error": f"Gagal memproses PDF: {str(e)}"}), 500
122
 
123
+ return jsonify({
124
+ "status": "ok",
125
+ "message": "Ekstraksi dan summarisasi selesai",
126
+ "book_id": book_id,
127
+ "pdf_path": str(pdf_path),
128
+ "summary": summary,
129
+ "metadata_preview": {
130
+ "book_id": book_id,
131
+ "judul_buku": metadata["judul_buku"],
132
+ "jenjang": metadata["jenjang"],
133
+ "kelas": metadata["kelas"],
134
+ "mata_pelajaran": metadata["mata_pelajaran"],
135
+ "tipe": metadata["tipe"],
136
+ },
137
+ })
138
+
139
+
140
+ # ── Step 2: Konfirmasi & Simpan ──────────────────────────────────────────────
141
+
142
+ @admin_bp.route("/add", methods=["POST"])
143
+ def add_book():
144
  """
145
+ Step 2 dari proses add buku.
146
+ Menerima metadata final + pdf_path, lakukan embedding, update semua storage.
147
  """
148
+ data = request.get_json(silent=True)
149
+ if not data:
150
+ return jsonify({"error": "Body JSON diperlukan"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+ required = ["judul_buku", "jenjang", "kelas", "mata_pelajaran", "tipe", "pdf_path", "summary"]
153
+ missing = [f for f in required if not data.get(f)]
154
+ if missing:
155
+ return jsonify({"error": f"Field wajib belum diisi: {missing}"}), 400
156
 
157
+ book_id = data.get("book_id") or str(uuid.uuid4())
158
+ pdf_path = Path(data["pdf_path"])
159
+ if not pdf_path.exists():
160
+ return jsonify({"error": f"File PDF tidak ditemukan: {pdf_path}"}), 400
161
 
162
+ # ── 1. Baca full_text dari PDF (untuk FAISS) ──────────────────────────
 
163
  try:
164
+ full_text = parse_pdf_to_text(str(pdf_path))
165
+ chunks = chunk_text(full_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  except Exception as e:
167
+ return jsonify({"error": f"Gagal membaca PDF: {str(e)}"}), 500
168
+
169
+ # ── 2. Bangun metadata record ─────────────────────────────────────────
170
+ metadata = {
171
+ "judul_buku": data["judul_buku"],
172
+ "jenjang": data["jenjang"],
173
+ "kelas": str(data["kelas"]),
174
+ "mata_pelajaran": data["mata_pelajaran"],
175
+ "tipe": data["tipe"],
176
+ "link_sampul": data.get("link_sampul", ""),
177
+ "link_buku": data.get("link_buku", ""),
178
+ "link_sumber": data.get("link_sumber", ""),
179
+ }
180
 
181
+ # ── 3. Record lengkap (untuk sibi_books.jsonl) ────────────────────────
182
+ full_record = {
183
+ "id": book_id,
184
+ "metadata": metadata,
185
+ "summary_text": data["summary"],
186
+ "full_text": full_text,
187
+ }
188
+
189
+ # ── 4. Record catalog (untuk sibi_books_catalog.jsonl) ───────────────
190
+ catalog_record = _strip_full_text(full_record)
191
 
 
 
 
 
 
 
192
  try:
193
+ # ── 5. Update sibi_books.jsonl (append) ──────────────────────────
194
+ with open(RAW_DATA_FILE, "a", encoding="utf-8") as f:
195
+ f.write(json.dumps(full_record, ensure_ascii=False) + "\n")
196
+
197
+ # ── 6. Update sibi_books_catalog.jsonl (append) ──────────────────
198
+ with open(CATALOG_FILE, "a", encoding="utf-8") as f:
199
+ f.write(json.dumps(catalog_record, ensure_ascii=False) + "\n")
200
+
201
+ # ── 7. Embed dan index ke FAISS ───────────────────────────────────
202
+ summary_store = SummaryVectorStore(str(SUMMARY_INDEX_PATH), str(METADATA_INDEX_PATH))
203
+ fulltext_store = FulltextVectorStore(str(FULLTEXT_INDEX_PATH), str(METADATA_INDEX_PATH))
204
+
205
+ summary_store.add(
206
+ book_id=book_id,
207
+ text=data["summary"],
208
+ metadata=metadata,
209
+ )
210
+ for i, chunk in enumerate(chunks):
211
+ fulltext_store.add(
212
+ book_id=book_id,
213
+ text=chunk,
214
+ chunk_index=i,
215
+ metadata=metadata,
216
+ )
217
+
218
+ # ── 8. Reload catalog store ───────────────────────────────────────
219
+ catalog_store.reload()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  except Exception as e:
222
+ logger.error(f"[Admin] Gagal add buku {book_id}: {e}", exc_info=True)
223
+ return jsonify({"error": f"Gagal menyimpan buku: {str(e)}"}), 500
224
+
225
+ logger.info(f"[Admin] Buku berhasil ditambahkan: {book_id} β€” {data['judul_buku']}")
226
+ return jsonify({
227
+ "status": "ok",
228
+ "message": "Buku berhasil ditambahkan",
229
+ "metadata": {**metadata, "book_id": book_id},
230
+ "summary": data["summary"],
231
+ "chunks": len(chunks),
232
+ })
233
+
234
+
235
+ # ── Update ────────────────────────────────────────────────────────────────────
236
 
237
+ @admin_bp.route("/update/<string:book_id>", methods=["PUT"])
238
+ def update_book(book_id: str):
239
  """
240
+ Update metadata dan/atau summary_text sebuah buku.
241
+ FAISS diupdate jika summary berubah (re-embed summary).
242
+ full_text tidak bisa diupdate via endpoint ini β€” gunakan delete + add.
243
  """
244
+ data = request.get_json(silent=True)
245
+ if not data:
246
+ return jsonify({"error": "Body JSON diperlukan"}), 400
247
+
248
+ # Pastikan buku ada di catalog
249
+ existing = catalog_store.get_by_id(book_id)
250
+ if not existing:
251
+ return jsonify({"error": f"Buku '{book_id}' tidak ditemukan"}), 404
252
+
253
+ old_metadata = existing.get("metadata", {}).copy()
254
+ summary_changed = "summary_text" in data and data["summary_text"] != existing.get("summary_text")
255
+
256
  try:
257
+ # ── 1. Update sibi_books_catalog.jsonl ────────────────────────────
258
+ catalog_records = _read_jsonl(Path(CATALOG_FILE))
259
+ updated_catalog = []
260
+ for rec in catalog_records:
261
+ if rec.get("id") == book_id:
262
+ # Merge update ke existing record
263
+ if "metadata" in data:
264
+ rec["metadata"].update(data["metadata"])
265
+ if "summary_text" in data:
266
+ rec["summary_text"] = data["summary_text"]
267
+ updated_catalog.append(rec)
268
+ _atomic_write_jsonl(Path(CATALOG_FILE), updated_catalog)
269
+
270
+ # ── 2. Update sibi_books.jsonl (sync metadata & summary) ─────────
271
+ full_records = _read_jsonl(Path(RAW_DATA_FILE))
272
+ updated_full = []
273
+ for rec in full_records:
274
+ if rec.get("id") == book_id:
275
+ if "metadata" in data:
276
+ rec["metadata"].update(data["metadata"])
277
+ if "summary_text" in data:
278
+ rec["summary_text"] = data["summary_text"]
279
+ updated_full.append(rec)
280
+ _atomic_write_jsonl(Path(RAW_DATA_FILE), updated_full)
281
+
282
+ # ── 3. Update FAISS jika summary berubah ─────────────────────────
283
+ if summary_changed:
284
+ updated_record = next((r for r in updated_catalog if r.get("id") == book_id), None)
285
+ if updated_record:
286
+ summary_store = SummaryVectorStore(
287
+ str(SUMMARY_INDEX_PATH), str(METADATA_INDEX_PATH)
288
+ )
289
+ # Hapus vector lama lalu tambah yang baru
290
+ summary_store.delete(book_id=book_id)
291
+ summary_store.add(
292
+ book_id=book_id,
293
+ text=updated_record["summary_text"],
294
+ metadata=updated_record.get("metadata", {}),
295
+ )
296
+ logger.info(f"[Admin] FAISS summary re-indexed untuk buku: {book_id}")
297
+
298
+ # ── 4. Reload catalog store ───────────────────────────────────────
299
+ catalog_store.reload()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
  except Exception as e:
302
+ logger.error(f"[Admin] Gagal update buku {book_id}: {e}", exc_info=True)
303
+ return jsonify({"error": f"Gagal mengupdate buku: {str(e)}"}), 500
304
 
305
+ logger.info(f"[Admin] Buku berhasil diupdate: {book_id}")
306
+ return jsonify({
307
+ "status": "ok",
308
+ "message": "Buku berhasil diupdate",
309
+ "book_id": book_id,
310
+ "metadata": old_metadata, # metadata sebelum diubah (konsisten dengan kontrak lama)
311
+ })
312
 
 
 
 
 
313
 
314
+ # ── Delete ────────────────────────────────────────────────────────────────────
 
 
 
315
 
316
+ @admin_bp.route("/delete/<string:book_id>", methods=["DELETE"])
317
+ def delete_book(book_id: str):
318
+ """
319
+ Hapus buku dari semua storage:
320
+ - sibi_books_catalog.jsonl
321
+ - sibi_books.jsonl
322
+ - FAISS summary index
323
+ - FAISS fulltext index
324
+ """
325
+ existing = catalog_store.get_by_id(book_id)
326
+ if not existing:
327
+ return jsonify({"error": f"Buku '{book_id}' tidak ditemukan"}), 404
328
 
329
+ old_metadata = existing.get("metadata", {}).copy()
 
 
 
 
330
 
331
  try:
332
+ # ── 1. Hapus dari sibi_books_catalog.jsonl ────────────────────────
333
+ catalog_records = _read_jsonl(Path(CATALOG_FILE))
334
+ _atomic_write_jsonl(
335
+ Path(CATALOG_FILE),
336
+ [r for r in catalog_records if r.get("id") != book_id],
337
+ )
338
+
339
+ # ── 2. Hapus dari sibi_books.jsonl ────────────────────────────────
340
+ full_records = _read_jsonl(Path(RAW_DATA_FILE))
341
+ _atomic_write_jsonl(
342
+ Path(RAW_DATA_FILE),
343
+ [r for r in full_records if r.get("id") != book_id],
344
+ )
345
+
346
+ # ── 3. Hapus dari FAISS summary index ────────────────────────────
347
+ summary_store = SummaryVectorStore(str(SUMMARY_INDEX_PATH), str(METADATA_INDEX_PATH))
348
+ summary_store.delete(book_id=book_id)
349
+
350
+ # ── 4. Hapus dari FAISS fulltext index ───────────────────────────
351
+ fulltext_store = FulltextVectorStore(str(FULLTEXT_INDEX_PATH), str(METADATA_INDEX_PATH))
352
+ fulltext_store.delete(book_id=book_id)
353
+
354
+ # ── 5. Reload catalog store ───────────────────────────────────────
355
+ catalog_store.reload()
356
+
 
 
 
 
357
  except Exception as e:
358
+ logger.error(f"[Admin] Gagal delete buku {book_id}: {e}", exc_info=True)
359
+ return jsonify({"error": f"Gagal menghapus buku: {str(e)}"}), 500
360
+
361
+ logger.info(f"[Admin] Buku berhasil dihapus: {book_id}")
362
+ return jsonify({
363
+ "status": "ok",
364
+ "message": "Buku berhasil dihapus",
365
+ "book_id": book_id,
366
+ "metadata": old_metadata,
367
+ })
368
 
369
 
370
+ # ── Admin: list semua buku (untuk panel admin) ────────────────────────────────
371
+
372
+ @admin_bp.route("/books", methods=["GET"])
373
+ def admin_list_books():
374
+ """
375
+ Versi admin dari daftar buku β€” sama dengan /api/books tapi
376
+ bisa difilter lebih luas dan menampilkan semua field catalog.
377
+ """
378
+ jenjang = request.args.get("jenjang", "").strip() or None
379
+ kelas = request.args.get("kelas", "").strip() or None
380
+ mata_pelajaran = request.args.get("mata_pelajaran", "").strip() or None
381
+ tipe = request.args.get("tipe", "").strip() or None
382
+ search = request.args.get("search", "").strip() or None
383
 
384
  try:
385
+ page = max(1, int(request.args.get("page", 1)))
386
+ limit = min(200, max(1, int(request.args.get("limit", 50))))
387
+ except ValueError:
388
+ return jsonify({"error": "Parameter 'page' dan 'limit' harus berupa angka"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
+ results = catalog_store.query(jenjang=jenjang, kelas=kelas,
391
+ mata_pelajaran=mata_pelajaran, tipe=tipe, search=search)
392
+ total = len(results)
393
+ offset = (page - 1) * limit
394
+ page_data = results[offset : offset + limit]
395
 
396
+ return jsonify({
397
+ "books": page_data,
398
+ "total_books": total,
399
+ "total_pages": max(1, (total + limit - 1) // limit),
400
+ "current_page": page,
401
+ "per_page": limit,
402
+ })
api/routes/books.py CHANGED
@@ -4,16 +4,17 @@ Public endpoints for listing and filtering books in the catalog.
4
 
5
  import json
6
  import math
7
- import threading
8
  from pathlib import Path
9
  import sys
10
-
11
- from flask import Blueprint, current_app, jsonify, request
12
 
13
  # Add project root to path (ensure config module can be imported)
14
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
15
 
16
- from config.settings import RAW_DATA_FILE
 
 
 
17
  from utils.logger import get_logger
18
 
19
  logger = get_logger(__name__)
@@ -23,7 +24,6 @@ _filter_options = None
23
  _book_stats = None
24
  _cache_lock = threading.Lock()
25
 
26
- from config.settings import DATA_DIR
27
  STATIC_FILTERS_FILE = DATA_DIR / "raw" / "static_filters.json"
28
  STATIC_STATS_FILE = DATA_DIR / "raw" / "static_stats.json"
29
 
@@ -72,29 +72,20 @@ def _get_book_stats():
72
  return _book_stats
73
 
74
 
75
- @books_bp.route('/books/filters', methods=['GET'])
76
- def get_book_filters():
77
  """
78
- Returns unique values for filtering options: jenjang, kelas, and mata_pelajaran.
79
- Iterates over the in-memory book_metadata_map for speed and caches it.
80
  """
81
- try:
82
- filters = _get_filter_options()
83
- response = jsonify(filters)
84
- # Add Cache-Control header for caching (1 hour)
85
- response.headers["Cache-Control"] = "public, max-age=3600"
86
- return response, 200
87
 
88
- except Exception as e:
89
- logger.error(f"Failed to fetch book filters: {e}", exc_info=True)
90
- return jsonify({"error": "Internal server error reading filters"}), 500
91
-
92
- @books_bp.route('/books/stats', methods=['GET'])
93
  def get_book_stats():
94
  """
95
  Returns distribution counts per dimension (for treemap visualization).
96
  Iterates over the in-memory book_metadata_map for speed and caches it.
97
- """
98
  try:
99
  stats = _get_book_stats()
100
  response = jsonify(stats)
@@ -106,161 +97,55 @@ def get_book_stats():
106
  return jsonify({"error": "Internal server error reading stats"}), 500
107
 
108
 
109
- @books_bp.route('/books', methods=['GET'])
110
- def get_public_books():
111
  """
112
- Returns a paginated and filtered list of books from the source-of-truth ledger.
113
- Supports filtering by 'jenjang', 'kelas', 'mata_pelajaran' and generic 'search'.
114
- Reads from the in-memory book_metadata_map for speed.
115
  """
116
- try:
117
- page = int(request.args.get('page', 1))
118
- limit = int(request.args.get('limit', 20))
119
-
120
- search_query = request.args.get('search', '').lower()
121
- jenjang_filter = request.args.get('jenjang', '').lower()
122
- kelas_filter = request.args.get('kelas', '').lower()
123
- mapel_filter = request.args.get('mata_pelajaran', '').lower()
124
-
125
- fields_param = request.args.get('fields', '')
126
- fields_list = [f.strip() for f in fields_param.split(',')] if fields_param else None
127
-
128
- if page < 1 or limit < 1:
129
- return jsonify({"error": "Invalid pagination parameters"}), 400
130
-
131
- book_metadata_map = current_app.config.get('book_metadata_map', {})
132
- if not book_metadata_map:
133
- return jsonify({
134
- "books": [],
135
- "total_books": 0,
136
- "total_pages": 0,
137
- "current_page": page
138
- }), 200
139
-
140
- all_books = []
141
-
142
- for book_data in book_metadata_map.values():
143
- # Apply exact filters (AND logic)
144
- if jenjang_filter:
145
- b_jenjang = book_data.get('jenjang', '').lower()
146
- if jenjang_filter not in b_jenjang:
147
- continue
148
-
149
- if kelas_filter:
150
- b_kelas = book_data.get('kelas', '').lower()
151
- if kelas_filter != b_kelas and kelas_filter not in b_kelas:
152
- continue
153
-
154
- if mapel_filter:
155
- b_mapel = book_data.get('mata_pelajaran', '').lower()
156
- if mapel_filter not in b_mapel:
157
- continue
158
-
159
- # Apply search logic and scoring
160
- score = 0
161
- if search_query:
162
- title_lower = book_data.get('judul_buku', book_data.get('title', '')).lower()
163
- mapel_lower = book_data.get('mata_pelajaran', '').lower()
164
- jenjang_lower = book_data.get('jenjang', '').lower()
165
- tipe_lower = book_data.get('tipe', '').lower()
166
-
167
- if search_query == title_lower:
168
- score = 3
169
- elif search_query in title_lower:
170
- score = 2
171
- elif (search_query in mapel_lower or
172
- search_query in jenjang_lower or
173
- search_query in tipe_lower):
174
- score = 1
175
- else:
176
- score = 0 # No match
177
 
178
- if score == 0:
179
- continue # Exclude if there's a search query but no match
180
-
181
- # Use a dict copy to avoid mutating the global in-memory cache
182
- book_dict = dict(book_data)
183
- # Ensure book_id is present
184
- if 'book_id' not in book_dict and 'id' in book_dict:
185
- book_dict['book_id'] = book_dict['id']
186
-
187
- all_books.append((score, book_dict))
188
-
189
- # Sort the results: first by score (descending), then alphabetically by judul_buku (ascending)
190
- all_books.sort(key=lambda x: (-x[0], x[1].get('judul_buku', x[1].get('title', '')).lower()))
191
-
192
- # Extract just the book dicts after sorting
193
- sorted_books = [book for score, book in all_books]
194
-
195
- total_books = len(sorted_books)
196
- total_pages = math.ceil(total_books / limit) if limit > 0 else 0
197
-
198
- # Exact slicing for pagination
199
- start_idx = (page - 1) * limit
200
- end_idx = start_idx + limit
201
- paginated_books = sorted_books[start_idx:end_idx]
202
-
203
- # Apply field filtering if requested
204
- result_books = []
205
- for book in paginated_books:
206
- if fields_list:
207
- filtered_book = {}
208
- for field in fields_list:
209
- val = book.get(field)
210
- if val is not None:
211
- filtered_book[field] = val
212
- # Make sure book_id is always present if fields are requested?
213
- # Let's add it if requested or we assume the frontend requests it.
214
- # Standard practice is to always include the primary key if available.
215
- if 'book_id' not in filtered_book and 'book_id' in book:
216
- filtered_book['book_id'] = book['book_id']
217
- result_books.append(filtered_book)
218
- else:
219
- result_books.append(book)
220
-
221
- # Get total overall books from stats (not just filtered)
222
- stats = _get_book_stats()
223
- overall_total_books = stats.get('total_books', 0)
224
-
225
- response = jsonify({
226
- "books": result_books,
227
- "total_books": total_books, # Total books matching the filter/search
228
- "total_overall_books": overall_total_books, # Total books in catalog
229
- "total_pages": total_pages,
230
- "current_page": page
231
- })
232
-
233
- # Optional: set Cache-Control no-store for paginated responses
234
- # (Though Flask's default is no cache, explicitly setting it is good practice)
235
- response.headers["Cache-Control"] = "no-store"
236
-
237
- return response, 200
238
-
239
- except Exception as e:
240
- logger.error(f"Failed to fetch public books: {e}", exc_info=True)
241
- return jsonify({"error": "Internal server error reading catalog"}), 500
242
-
243
-
244
- @books_bp.route('/books/<string:book_id>', methods=['GET'])
245
- def get_book_detail(book_id):
246
  """
247
- Returns the full details of a specific book by its ID.
248
- Looks up the book in the in-memory book_metadata_map for speed (O(1)).
249
  """
250
- try:
251
- book_metadata_map = current_app.config.get('book_metadata_map', {})
252
- book_data = book_metadata_map.get(book_id)
253
-
254
- if not book_data:
255
- return jsonify({"error": "Book not found"}), 404
256
-
257
- # Ensure book_id is present in the response without mutating the global cache
258
- book_response = dict(book_data)
259
- if 'book_id' not in book_response and 'id' in book_response:
260
- book_response['book_id'] = book_response['id']
261
-
262
- return jsonify(book_response), 200
263
-
264
- except Exception as e:
265
- logger.error(f"Failed to fetch book detail for ID {book_id}: {e}", exc_info=True)
266
- return jsonify({"error": "Internal server error reading book detail"}), 500
 
4
 
5
  import json
6
  import math
 
7
  from pathlib import Path
8
  import sys
9
+ import threading
 
10
 
11
  # Add project root to path (ensure config module can be imported)
12
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
13
 
14
+ from flask import Blueprint, jsonify, request
15
+
16
+ from config.settings import DATA_DIR
17
+ import utils.catalog_store as catalog_store
18
  from utils.logger import get_logger
19
 
20
  logger = get_logger(__name__)
 
24
  _book_stats = None
25
  _cache_lock = threading.Lock()
26
 
 
27
  STATIC_FILTERS_FILE = DATA_DIR / "raw" / "static_filters.json"
28
  STATIC_STATS_FILE = DATA_DIR / "raw" / "static_stats.json"
29
 
 
72
  return _book_stats
73
 
74
 
75
+ @books_bp.route("/api/books/filters", methods=["GET"])
76
+ def get_filter_options():
77
  """
78
+ Kembalikan nilai unik semua filter field.
79
+ Digunakan frontend untuk populate dropdown filter.
80
  """
81
+ return jsonify(catalog_store.get_filter_options())
 
 
 
 
 
82
 
83
+ @books_bp.route('/api/books/stats', methods=['GET'])
 
 
 
 
84
  def get_book_stats():
85
  """
86
  Returns distribution counts per dimension (for treemap visualization).
87
  Iterates over the in-memory book_metadata_map for speed and caches it.
88
+ """
89
  try:
90
  stats = _get_book_stats()
91
  response = jsonify(stats)
 
97
  return jsonify({"error": "Internal server error reading stats"}), 500
98
 
99
 
100
+ @books_bp.route("/api/books", methods=["GET"])
101
+ def list_books():
102
  """
103
+ Endpoint publik untuk menampilkan daftar buku dengan filtering dan paginasi.
104
+ Semua operasi dilakukan dari RAM β€” tidak ada disk I/O.
 
105
  """
106
+ # ── Parameter ────────────────────────────────────────────────────────────
107
+ jenjang = request.args.get("jenjang", "").strip() or None
108
+ kelas = request.args.get("kelas", "").strip() or None
109
+ mata_pelajaran = request.args.get("mata_pelajaran", "").strip() or None
110
+ tipe = request.args.get("tipe", "").strip() or None
111
+ search = request.args.get("search", "").strip() or None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ try:
114
+ page = max(1, int(request.args.get("page", 1)))
115
+ limit = min(100, max(1, int(request.args.get("limit", 20))))
116
+ except ValueError:
117
+ return jsonify({"error": "Parameter 'page' dan 'limit' harus berupa angka"}), 400
118
+
119
+ # ── Query dari in-memory catalog (O(k), bukan O(n) dari disk) ───────────
120
+ results = catalog_store.query(
121
+ jenjang=jenjang,
122
+ kelas=kelas,
123
+ mata_pelajaran=mata_pelajaran,
124
+ tipe=tipe,
125
+ search=search,
126
+ )
127
+
128
+ # ── Paginasi ─────────────────────────────────────────────────────────────
129
+ total_books = len(results)
130
+ total_pages = max(1, (total_books + limit - 1) // limit)
131
+ offset = (page - 1) * limit
132
+ page_data = results[offset : offset + limit]
133
+
134
+ return jsonify({
135
+ "books": page_data,
136
+ "total_books": total_books,
137
+ "total_pages": total_pages,
138
+ "current_page": page,
139
+ "per_page": limit,
140
+ })
141
+
142
+
143
+ @books_bp.route("/api/books/<string:book_id>", methods=["GET"])
144
+ def get_book_detail(book_id: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  """
146
+ Ambil detail satu buku berdasarkan id (O(1) hash lookup).
 
147
  """
148
+ book = catalog_store.get_by_id(book_id)
149
+ if not book:
150
+ return jsonify({"error": f"Buku dengan id '{book_id}' tidak ditemukan"}), 404
151
+ return jsonify(book)
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routes/recommend.py CHANGED
@@ -5,6 +5,7 @@ Performs retrieval on summary index, reranks, and generates recommendations.
5
 
6
  import json
7
  from pathlib import Path
 
8
 
9
  from flask import Blueprint, current_app, jsonify, request
10
 
@@ -75,7 +76,6 @@ def recommend():
75
  answer_generator = current_app.config['answer_generator']
76
 
77
  # Helper: Detect if user query is asking for statistics/system info
78
- import re
79
  def _is_systemic_query(q: str) -> bool:
80
  q_lower = q.lower()
81
  systemic_patterns = [
 
5
 
6
  import json
7
  from pathlib import Path
8
+ import re
9
 
10
  from flask import Blueprint, current_app, jsonify, request
11
 
 
76
  answer_generator = current_app.config['answer_generator']
77
 
78
  # Helper: Detect if user query is asking for statistics/system info
 
79
  def _is_systemic_query(q: str) -> bool:
80
  q_lower = q.lower()
81
  systemic_patterns = [
config/settings.py CHANGED
@@ -1,9 +1,9 @@
1
  import os
2
  from pathlib import Path
3
  from dotenv import load_dotenv
4
-
5
  load_dotenv()
6
 
 
7
  # GEMINI CONFIG
8
  ALLOCATION_EMBEDDING_INDICES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
9
 
@@ -40,6 +40,8 @@ FRONTEND_URL = os.getenv("FRONTEND_URL", "http://localhost:3000")
40
  BASE_DIR = Path(__file__).resolve().parent.parent
41
  DATA_DIR = BASE_DIR / "data"
42
  FAISS_DIR = DATA_DIR / "faiss"
 
43
  SUMMARY_INDEX_PATH = FAISS_DIR / "rec_index.faiss"
44
  FULLTEXT_INDEX_PATH = FAISS_DIR / "chunks_index_new.faiss"
45
- RAW_DATA_FILE = DATA_DIR / "raw" / "sibi_books.jsonl"
 
 
1
  import os
2
  from pathlib import Path
3
  from dotenv import load_dotenv
 
4
  load_dotenv()
5
 
6
+
7
  # GEMINI CONFIG
8
  ALLOCATION_EMBEDDING_INDICES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
9
 
 
40
  BASE_DIR = Path(__file__).resolve().parent.parent
41
  DATA_DIR = BASE_DIR / "data"
42
  FAISS_DIR = DATA_DIR / "faiss"
43
+ RAW_DATA_DIR = DATA_DIR / "raw"
44
  SUMMARY_INDEX_PATH = FAISS_DIR / "rec_index.faiss"
45
  FULLTEXT_INDEX_PATH = FAISS_DIR / "chunks_index_new.faiss"
46
+ RAW_DATA_FILE = RAW_DATA_DIR / "sibi_books.jsonl"
47
+ CATALOG_FILE = RAW_DATA_DIR / "sibi_books_catalog.jsonl"
data/faiss/chunks_index_new.faiss CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c92bfcfdf7a61f5ed3b1e9906f6285897e70836cd202bdf9a163716db2fb9bb2
3
- size 84123693
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8be11c66b40f61bc73537db20e3d19f87247e457a2d603ceedd54fc91d53771
3
+ size 192086061
data/faiss/chunks_index_new.meta.pkl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1e087fd7881fb5cd3ca044b4ef52537b406b70f06f786c3573985bbfca0b1868
3
- size 14421518
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ae7391e848bf03e48485f6a82a733a7a98b539de62e0a0297ed88e646d5da11
3
+ size 52319303
data/faiss/rechunk_checkpoint.json CHANGED
@@ -1,44 +1,99 @@
1
  {
2
  "processed_books": [
3
- "13f6e76881c24c20",
4
- "9540649097ccfcf7",
5
- "d993d35d4fa422fc",
6
- "9f36501be7662487",
7
- "232ad86d2a13db1c",
8
- "932363120d8af666",
9
- "ddd97149a035deaa",
10
- "d8a1eda59d56d28f",
11
- "108eb7596b7567eb",
12
- "d6046db4bc4a9041",
13
- "33df60a1e316eaea",
14
- "cfaa13f50e1fd0f6",
15
- "91018ed827a86dc6",
16
- "f2029620cfdb7257",
17
- "f2f8bcc9ae4d8ac3",
18
- "9d983ba8d10ea56b",
19
- "04585198ead2e1dc",
20
- "9a2e52127a9be1f9",
21
- "ef80c21432ea49fb",
22
- "7df0732272edc3a3",
23
  "5f815f51a443a657",
24
- "a05cc19486acfb5d",
25
- "46e59c8b636646ec",
26
- "27b65614ff0c439c",
27
- "41960ad71de117cb",
28
- "1911384eb4b89f33",
29
- "9e12da82f3bfd2b1",
30
  "1926a3e139d6f9c1",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  "fa8d40ca56d41661",
 
 
 
32
  "b3989b2cde470889",
33
- "8cc02b24e0aeac3e",
34
- "2cf3972f341462d5",
35
  "38813ca418bc2aa2",
36
- "bfabff1009354e10",
37
- "9e1853d52dc94a2b",
38
- "a427131ba37983a9",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  "7f0df6a38f655c8e",
40
- "b4a9cc58a24c7bfc",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  "da849d014824de0d",
42
- "fcfe645e47801e13"
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ]
44
  }
 
1
  {
2
  "processed_books": [
3
+ "0534b2b180c1f439",
4
+ "5ee7828d4b6d7306",
5
+ "8b0df744580293b0",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  "5f815f51a443a657",
7
+ "a427131ba37983a9",
8
+ "b4a9cc58a24c7bfc",
9
+ "a0236452e34adea4",
 
 
 
10
  "1926a3e139d6f9c1",
11
+ "c46f3c777ecd6bf1",
12
+ "5a5a36c4b0737624",
13
+ "75a9c17c7942d9f7",
14
+ "1911384eb4b89f33",
15
+ "8cc02b24e0aeac3e",
16
+ "b4d0695c40ef2592",
17
+ "ed1ea267b1e1269e",
18
+ "46e59c8b636646ec",
19
+ "f2f8bcc9ae4d8ac3",
20
+ "7e42dfe2449be3b7",
21
+ "d11e8b7cb230fb78",
22
+ "8d7c91cda80a1afc",
23
+ "d8a1eda59d56d28f",
24
+ "d993d35d4fa422fc",
25
+ "265b2f4a1443d667",
26
+ "14463118ed24086e",
27
+ "8e8c9104737b0797",
28
+ "9540649097ccfcf7",
29
+ "f2029620cfdb7257",
30
  "fa8d40ca56d41661",
31
+ "54ba2427742d853e",
32
+ "a05cc19486acfb5d",
33
+ "cfaa13f50e1fd0f6",
34
  "b3989b2cde470889",
 
 
35
  "38813ca418bc2aa2",
36
+ "932363120d8af666",
37
+ "9f36501be7662487",
38
+ "ca561289698df95c",
39
+ "2d293b86f7bb8c6b",
40
+ "defb9471ef69e237",
41
+ "7df0732272edc3a3",
42
+ "372963d4694e30c4",
43
+ "4ad2a0067f244e00",
44
+ "a110ed41b7736109",
45
+ "cfc72c4829dd166a",
46
+ "b65000b32e790150",
47
+ "041299c76ddbdc73",
48
+ "f3bb0823559dd9ca",
49
+ "41960ad71de117cb",
50
+ "5e864eb35f85494c",
51
+ "8ffaa896404890d7",
52
+ "91018ed827a86dc6",
53
+ "a96cc21bf0d16555",
54
  "7f0df6a38f655c8e",
55
+ "340024b94562d34a",
56
+ "5252451d64f86176",
57
+ "04585198ead2e1dc",
58
+ "2cf3972f341462d5",
59
+ "9d983ba8d10ea56b",
60
+ "785206cfd8d68e6f",
61
+ "ddd97149a035deaa",
62
+ "18e2b8c4b35dc9c5",
63
+ "6b589907e2353134",
64
+ "d1d6d67640d4ea42",
65
+ "211c00322fb4e2a0",
66
+ "db669c0eb7eb263d",
67
+ "b918269e18651426",
68
+ "3a44c34d12cd41f6",
69
+ "108eb7596b7567eb",
70
+ "1dd49c410059b59b",
71
+ "3c53da141b9d8eda",
72
+ "35346a497791b60e",
73
+ "9e1853d52dc94a2b",
74
+ "bfabff1009354e10",
75
+ "bb1f4eef46abfb5d",
76
+ "94897f21fa8b64b5",
77
+ "084221647ee0a0dd",
78
+ "9e12da82f3bfd2b1",
79
+ "9df24dd7a5edd0ad",
80
+ "33df60a1e316eaea",
81
+ "f0cc02b20287510d",
82
+ "9a2e52127a9be1f9",
83
  "da849d014824de0d",
84
+ "d6046db4bc4a9041",
85
+ "232ad86d2a13db1c",
86
+ "cde1dabeb599a6cb",
87
+ "c6fb5ff9fae6ce01",
88
+ "b6e8d5315950bb37",
89
+ "c426726443b49a2a",
90
+ "824dea20a6613a0c",
91
+ "27b65614ff0c439c",
92
+ "e80177608709cc17",
93
+ "fcfe645e47801e13",
94
+ "ef80c21432ea49fb",
95
+ "4770d29ddb1c7fee",
96
+ "13f6e76881c24c20",
97
+ "d5ecb82b698bfce3"
98
  ]
99
  }
data/raw/sibi_books_catalog.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eaabac67bb3afcaaf716321632940fbbc1ac626c75c8fa67270e7e02a0ece679
3
+ size 748021
scripts/add_book.py CHANGED
@@ -11,6 +11,9 @@ Hasil akhir disimpan di data/faiss/
11
  import json
12
  from pathlib import Path
13
  import sys
 
 
 
14
  import traceback
15
  from typing import Any, Dict, List, Tuple
16
 
@@ -234,6 +237,9 @@ def add_new_book(book_data: Dict[str, Any], interactive: bool = True, override_s
234
  # Append to metadata JSONL
235
  with open(RAW_DATA_FILE, 'a', encoding='utf-8') as f:
236
  f.write(json.dumps(book_data, ensure_ascii=False) + "\n")
 
 
 
237
 
238
  logger.info(f"Successfully added new book {book_data['book_id']} to system.")
239
 
 
11
  import json
12
  from pathlib import Path
13
  import sys
14
+ from api.routes.books import reload_static_cache
15
+ from scripts.generate_static_data import generate_static_files
16
+
17
  import traceback
18
  from typing import Any, Dict, List, Tuple
19
 
 
237
  # Append to metadata JSONL
238
  with open(RAW_DATA_FILE, 'a', encoding='utf-8') as f:
239
  f.write(json.dumps(book_data, ensure_ascii=False) + "\n")
240
+
241
+ generate_static_files()
242
+ reload_static_cache()
243
 
244
  logger.info(f"Successfully added new book {book_data['book_id']} to system.")
245
 
scripts/delete_book.py CHANGED
@@ -4,6 +4,9 @@ Script for deleting a book from metadata and vector stores.
4
  import json
5
  from pathlib import Path
6
  import sys
 
 
 
7
 
8
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
9
 
@@ -40,6 +43,9 @@ def delete_book(book_id: str) -> bool:
40
  with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
41
  for b in books:
42
  f.write(json.dumps(b, ensure_ascii=False) + "\n")
 
 
 
43
  logger.info(f"Removed metadata for book {book_id}")
44
 
45
  try:
 
4
  import json
5
  from pathlib import Path
6
  import sys
7
+ from api.routes.books import reload_static_cache
8
+ from scripts.generate_static_data import generate_static_files
9
+
10
 
11
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
12
 
 
43
  with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
44
  for b in books:
45
  f.write(json.dumps(b, ensure_ascii=False) + "\n")
46
+
47
+ generate_static_files()
48
+ reload_static_cache()
49
  logger.info(f"Removed metadata for book {book_id}")
50
 
51
  try:
scripts/update_book.py CHANGED
@@ -4,6 +4,9 @@ Script for updating a book's description and metadata.
4
  import json
5
  from pathlib import Path
6
  import sys
 
 
 
7
  from typing import Any, Dict
8
 
9
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@@ -43,6 +46,9 @@ def update_book_metadata(book_id: str, new_metadata: Dict[str, Any]) -> bool:
43
  with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
44
  for b in books:
45
  f.write(json.dumps(b, ensure_ascii=False) + "\n")
 
 
 
46
 
47
  logger.info(f"Updated metadata for book {book_id} in {RAW_DATA_FILE}")
48
 
 
4
  import json
5
  from pathlib import Path
6
  import sys
7
+ from api.routes.books import reload_static_cache
8
+ from scripts.generate_static_data import generate_static_files
9
+
10
  from typing import Any, Dict
11
 
12
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
 
46
  with open(RAW_DATA_FILE, 'w', encoding='utf-8') as f:
47
  for b in books:
48
  f.write(json.dumps(b, ensure_ascii=False) + "\n")
49
+
50
+ generate_static_files()
51
+ reload_static_cache()
52
 
53
  logger.info(f"Updated metadata for book {book_id} in {RAW_DATA_FILE}")
54
 
utils/api_key_manager.py CHANGED
@@ -6,6 +6,8 @@ Supports both single key and multiple keys (round-robin rotation).
6
  import logging
7
  from typing import List, Optional, Union
8
 
 
 
9
  logger = logging.getLogger(__name__)
10
 
11
 
@@ -87,12 +89,10 @@ class APIKeyManager:
87
 
88
  def create_gemini_embedding_key_manager() -> "APIKeyManager":
89
  """Factory to create key manager for Gemini embedding pool."""
90
- from config.settings import GEMINI_EMBEDDING_KEYS
91
  return APIKeyManager(GEMINI_EMBEDDING_KEYS, service_name="Gemini-Embedding")
92
 
93
  def create_gemini_qa_key_manager() -> "APIKeyManager":
94
  """Factory to create key manager for Gemini QA pool."""
95
- from config.settings import GEMINI_QA_KEYS
96
  return APIKeyManager(GEMINI_QA_KEYS, service_name="Gemini-QA")
97
 
98
  # Convenience function for usage with config settings
@@ -105,7 +105,6 @@ def create_gemini_key_manager() -> "APIKeyManager":
105
 
106
  def create_jina_key_manager() -> "APIKeyManager":
107
  """Factory for Jina API (single key for now)."""
108
- from config.settings import JINA_API_KEY
109
  if JINA_API_KEY is None:
110
  raise ValueError("JINA_API_KEY not set in .env")
111
  return APIKeyManager(JINA_API_KEY, service_name="Jina")
 
6
  import logging
7
  from typing import List, Optional, Union
8
 
9
+ from config.settings import GEMINI_EMBEDDING_KEYS, GEMINI_QA_KEYS, JINA_API_KEY
10
+
11
  logger = logging.getLogger(__name__)
12
 
13
 
 
89
 
90
  def create_gemini_embedding_key_manager() -> "APIKeyManager":
91
  """Factory to create key manager for Gemini embedding pool."""
 
92
  return APIKeyManager(GEMINI_EMBEDDING_KEYS, service_name="Gemini-Embedding")
93
 
94
  def create_gemini_qa_key_manager() -> "APIKeyManager":
95
  """Factory to create key manager for Gemini QA pool."""
 
96
  return APIKeyManager(GEMINI_QA_KEYS, service_name="Gemini-QA")
97
 
98
  # Convenience function for usage with config settings
 
105
 
106
  def create_jina_key_manager() -> "APIKeyManager":
107
  """Factory for Jina API (single key for now)."""
 
108
  if JINA_API_KEY is None:
109
  raise ValueError("JINA_API_KEY not set in .env")
110
  return APIKeyManager(JINA_API_KEY, service_name="Jina")
utils/catalog_store.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils/catalog_store.py
2
+ """
3
+ In-memory catalog store untuk sibi_books_catalog.jsonl.
4
+
5
+ Catalog dimuat SEKALI saat startup Flask, disimpan di RAM, dan
6
+ di-reload hanya ketika admin melakukan perubahan data (add/update/delete).
7
+
8
+ Struktur catalog entry (sibi_books_catalog.jsonl):
9
+ {
10
+ "id": "uuid-string",
11
+ "metadata": {
12
+ "judul_buku": "...",
13
+ "mata_pelajaran": "...",
14
+ "kelas": "...",
15
+ "jenjang": "...",
16
+ "tipe": "...",
17
+ "link_sampul": "...",
18
+ "link_buku": "...",
19
+ "link_sumber": "..."
20
+ },
21
+ "summary_text": "..."
22
+ # TIDAK ada full_text di file ini
23
+ }
24
+ """
25
+
26
+ import json
27
+ import logging
28
+ from pathlib import Path
29
+ import threading
30
+ from typing import Optional
31
+
32
+ from config.settings import CATALOG_FILE
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # ── Internal state ──────────────────────────────────────────────────────────
37
+ # Lock untuk thread-safety saat reload (Flask + uvicorn bisa multi-thread)
38
+ _lock = threading.RLock()
39
+
40
+ # List utama untuk iterasi (urutan terjaga)
41
+ _catalog: list[dict] = []
42
+
43
+ # Index O(1) lookup by book_id
44
+ _index_by_id: dict[str, dict] = {}
45
+
46
+ # Index untuk filter tanpa scan penuh (pre-computed lowercase)
47
+ # Struktur: { "jenjang": { "sma": [book, ...], "smp": [...] }, "kelas": {...}, ... }
48
+ _filter_index: dict[str, dict[str, list[dict]]] = {
49
+ "jenjang": {},
50
+ "kelas": {},
51
+ "mata_pelajaran": {},
52
+ "tipe": {},
53
+ }
54
+
55
+ _is_loaded = False
56
+
57
+
58
+ # ── Private helpers ──────────────────────────────────────────────────────────
59
+
60
+ def _extract_filter_keys(book: dict) -> dict[str, str]:
61
+ """Ekstrak semua filter key dari satu entry catalog (lowercase, sudah di-strip)."""
62
+ meta = book.get("metadata", {})
63
+ return {
64
+ "jenjang": str(meta.get("jenjang", "")).strip().lower(),
65
+ "kelas": str(meta.get("kelas", "")).strip().lower(),
66
+ "mata_pelajaran": str(meta.get("mata_pelajaran", "")).strip().lower(),
67
+ "tipe": str(meta.get("tipe", "")).strip().lower(),
68
+ }
69
+
70
+
71
+ def _add_to_filter_index(book: dict) -> None:
72
+ """Tambahkan satu buku ke semua bucket filter index."""
73
+ keys = _extract_filter_keys(book)
74
+ for field, value in keys.items():
75
+ if value:
76
+ _filter_index[field].setdefault(value, []).append(book)
77
+
78
+
79
+ def _remove_from_filter_index(book: dict) -> None:
80
+ """Hapus satu buku dari semua bucket filter index."""
81
+ keys = _extract_filter_keys(book)
82
+ for field, value in keys.items():
83
+ if value and value in _filter_index[field]:
84
+ try:
85
+ _filter_index[field][value].remove(book)
86
+ if not _filter_index[field][value]:
87
+ del _filter_index[field][value]
88
+ except ValueError:
89
+ pass
90
+
91
+
92
+ def _build_filter_index(books: list[dict]) -> None:
93
+ """Build ulang seluruh filter index dari awal."""
94
+ global _filter_index
95
+ _filter_index = {"jenjang": {}, "kelas": {}, "mata_pelajaran": {}, "tipe": {}}
96
+ for book in books:
97
+ _add_to_filter_index(book)
98
+
99
+
100
+ # ── Public API ───────────────────────────────────────────────────────────────
101
+
102
+ def load() -> None:
103
+ """
104
+ Muat sibi_books_catalog.jsonl ke RAM.
105
+ Dipanggil SEKALI oleh create_app() saat startup.
106
+ Thread-safe via RLock.
107
+ """
108
+ global _catalog, _index_by_id, _is_loaded
109
+
110
+ catalog_path = Path(CATALOG_FILE)
111
+ if not catalog_path.exists():
112
+ logger.warning(
113
+ f"[CatalogStore] File tidak ditemukan: {catalog_path}. "
114
+ "Catalog kosong β€” jalankan scripts/generate_catalog.py terlebih dahulu."
115
+ )
116
+ _catalog = []
117
+ _index_by_id = {}
118
+ _build_filter_index([])
119
+ _is_loaded = True
120
+ return
121
+
122
+ with _lock:
123
+ new_catalog: list[dict] = []
124
+ new_index: dict[str, dict] = {}
125
+
126
+ with open(catalog_path, "r", encoding="utf-8") as f:
127
+ for lineno, line in enumerate(f, start=1):
128
+ line = line.strip()
129
+ if not line:
130
+ continue
131
+ try:
132
+ book = json.loads(line)
133
+ book_id = book.get("id")
134
+ if not book_id:
135
+ logger.warning(f"[CatalogStore] Baris {lineno}: tidak ada 'id', dilewati.")
136
+ continue
137
+ new_catalog.append(book)
138
+ new_index[book_id] = book
139
+ except json.JSONDecodeError as e:
140
+ logger.error(f"[CatalogStore] Baris {lineno}: JSON error β€” {e}")
141
+
142
+ _catalog = new_catalog
143
+ _index_by_id = new_index
144
+ _build_filter_index(_catalog)
145
+ _is_loaded = True
146
+
147
+ logger.info(f"[CatalogStore] Loaded {len(_catalog)} buku dari {catalog_path}")
148
+
149
+
150
+ def reload() -> None:
151
+ """
152
+ Reload catalog dari disk. Dipanggil oleh endpoint admin
153
+ setelah operasi add / update / delete berhasil.
154
+ """
155
+ logger.info("[CatalogStore] Reload dipicu oleh operasi admin...")
156
+ load()
157
+
158
+
159
+ def get_all() -> list[dict]:
160
+ """Kembalikan semua entry catalog (view, bukan copy β€” jangan dimodifikasi langsung)."""
161
+ return _catalog
162
+
163
+
164
+ def get_by_id(book_id: str) -> Optional[dict]:
165
+ """Lookup O(1) satu buku berdasarkan id."""
166
+ return _index_by_id.get(book_id)
167
+
168
+
169
+ def query(
170
+ jenjang: Optional[str] = None,
171
+ kelas: Optional[str] = None,
172
+ mata_pelajaran: Optional[str] = None,
173
+ tipe: Optional[str] = None,
174
+ search: Optional[str] = None,
175
+ ) -> list[dict]:
176
+ """
177
+ Filter catalog di RAM. Tidak ada disk I/O.
178
+
179
+ Strategi:
180
+ 1. Jika ada filter eksak (jenjang/kelas/mapel/tipe), mulai dari bucket
181
+ terkecil dalam filter_index (intersection-based filtering).
182
+ 2. Jika ada search text, scan hasil filter dengan string matching.
183
+
184
+ Kompleksitas: O(k) di mana k = ukuran bucket filter terkecil,
185
+ bukan O(n) dari seluruh catalog.
186
+ """
187
+ # Normalisasi input filter
188
+ filters: dict[str, str] = {}
189
+ if jenjang:
190
+ filters["jenjang"] = jenjang.strip().lower()
191
+ if kelas:
192
+ filters["kelas"] = str(kelas).strip().lower()
193
+ if mata_pelajaran:
194
+ filters["mata_pelajaran"] = mata_pelajaran.strip().lower()
195
+ if tipe:
196
+ filters["tipe"] = tipe.strip().lower()
197
+
198
+ # ── Step 1: Pilih starting set ──────────────────────────────────────────
199
+ if filters:
200
+ # Ambil bucket dari filter_index, pilih yang paling kecil sebagai anchor
201
+ candidate_sets: list[list[dict]] = []
202
+ for field, value in filters.items():
203
+ bucket = _filter_index.get(field, {}).get(value, [])
204
+ candidate_sets.append(bucket)
205
+
206
+ # Sort ascending by size β€” iterasi dari bucket terkecil
207
+ candidate_sets.sort(key=len)
208
+ base_set = candidate_sets[0]
209
+
210
+ # Intersection: filter base_set terhadap sisa filter
211
+ if len(candidate_sets) > 1:
212
+ # Buat set of id dari tiap bucket untuk intersection cepat
213
+ remaining_id_sets = [
214
+ {b["id"] for b in s} for s in candidate_sets[1:]
215
+ ]
216
+ results = [
217
+ b for b in base_set
218
+ if all(b["id"] in id_set for id_set in remaining_id_sets)
219
+ ]
220
+ else:
221
+ results = list(base_set)
222
+ else:
223
+ results = _catalog # tidak ada filter eksak, pakai semua
224
+
225
+ # ── Step 2: Free-text search (opsional) ──────────────────────────────────
226
+ if search:
227
+ q = search.strip().lower()
228
+ # Cari di judul_buku dan id
229
+ results = [
230
+ b for b in results
231
+ if q in b.get("metadata", {}).get("judul_buku", "").lower()
232
+ or q in b.get("id", "").lower()
233
+ ]
234
+
235
+ return results
236
+
237
+
238
+ def get_filter_options() -> dict:
239
+ """
240
+ Kembalikan semua nilai unik untuk setiap filter field.
241
+ Berguna untuk dropdown di frontend admin.
242
+ """
243
+ return {
244
+ field: sorted(buckets.keys())
245
+ for field, buckets in _filter_index.items()
246
+ if buckets
247
+ }
248
+
249
+
250
+ def count() -> int:
251
+ """Jumlah total buku dalam catalog."""
252
+ return len(_catalog)
253
+
254
+
255
+ def is_loaded() -> bool:
256
+ return _is_loaded