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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ee5ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""
src/bm25.py  β€”  BM25 keyword retrieval
Uses LangChain's BM25Retriever with the custom tokenizer from utils.py.

Document schema (one LangChain Document per product):
  page_content : text BM25 scores against =
                   title + features + description + categories +
                   details (flattened) + store + top-k review titles & texts
  metadata     : structured fields for display in app.py
                   (parent_asin, title, main_category, price, store,
                    categories, features, description, details, top_reviews)

Data source expected: HuggingFace Dataset objects as loaded in
  milestone1_exploration.ipynb via load_dataset("McAuley-Lab/Amazon-Reviews-2023", ...)
  OR the saved .jsonl subsets in data/raw/.
"""

import json
import pickle
from pathlib import Path
from typing import Any
import sys
from datasets import Dataset
from langchain_community.retrievers import BM25Retriever
from langchain_core.documents import Document
ROOT_FOLDER = Path(__file__).resolve().parent.parent

sys.path.append(str(ROOT_FOLDER))
from src.utils import simple_tokenize, extract_image
from src.eda_helpers import get_best_reviews


# ── field helpers ─────────────────────────────────────────────────────────────

def _coerce_str(value: Any) -> str:
    """Safely flatten any metadata field to a plain string."""
    if value is None:
        return ""
    if isinstance(value, list):
        return " ".join(_coerce_str(v) for v in value)
    if isinstance(value, dict):
        return " ".join(f"{k} {_coerce_str(v)}" for k, v in value.items())
    s = str(value)
    # treat the literal string "None" as empty
    return "" if s.strip().lower() == "none" else s


def _parse_details(details: Any) -> dict:
    """
    'details' in this dataset is stored as a JSON string, e.g.:
        '{"Brand": "Luzianne", "Item Form": "Ground", ...}'
    Parse it safely; return an empty dict on failure.
    """
    if not details:
        return {}
    if isinstance(details, dict):
        return details
    try:
        return json.loads(str(details))
    except (json.JSONDecodeError, TypeError):
        return {}


def _parse_price(price: Any) -> float | None:
    """price can be a float, an int, or the string 'None'."""
    if price is None:
        return None
    try:
        v = float(price)
        return None if v != v else v   # NaN guard
    except (ValueError, TypeError):
        return None


# ── review selection ──────────────────────────────────────────────────────────

def get_top_reviews(
    reviews_dataset_dict,
    parent_asin: str,
    k: int = 5,
) -> list[dict]:
    """
    Select the top-k reviews for a product using get_best_reviews() from
    eda_helpers.py (weighted score: helpful_vote 50%, verified_purchase 30%,
    rating extremity 20%).

    Parameters
    ----------
    reviews_dataset_dict : the full reviews DatasetDict (raw_reviews) β€”
                           NOT the pre-selected 'full' split, because
                           get_best_reviews() selects 'full' internally.
    parent_asin          : product identifier
    k                    : number of reviews to return

    Returns
    -------
    List of dicts with keys: title, text, rating, helpful_vote
    """
    result = get_best_reviews(reviews_dataset_dict, parent_asin, top_k=k)

    # get_best_reviews returns (total_count, Dataset) when top_k is set,
    # or a bare Dataset with 0 rows when no reviews are found.
    if isinstance(result, tuple):
        _, matched = result
    else:
        matched = result

    if len(matched) == 0:
        return []

    return [
        {
            "title":        row.get("title", "") or "",
            "text":         row.get("text", "") or "",
            "rating":       row.get("rating"),
            "helpful_vote": row.get("helpful_vote", 0),
        }
        for row in matched
    ]


# ── document construction ─────────────────────────────────────────────────────

def format_review(review: dict) -> str:
    """Format a single review the same way as in the notebook."""
    return (
        f"Review (Rating: {review['rating']}): "
        f"{review['title']}. "
        f"{review['text']}\n    "
    )


def build_page_content(product: dict, top_reviews: list[dict]) -> str:
    """
    Build the page_content string that BM25 will index.
    Mirrors the create_document() structure in milestone1_exploration.ipynb.
    """
    title       = _coerce_str(product.get("title"))
    description = " ".join(product.get("description") or [])
    features    = "\n".join(product.get("features") or [])
    categories  = " > ".join(product.get("categories") or [])
    store       = _coerce_str(product.get("store"))
    details     = _parse_details(product.get("details"))
    details_str = " ".join(f"{k}: {v}" for k, v in details.items())

    review_lines = "".join(format_review(r) for r in top_reviews)
    n_reviews    = len(top_reviews)

    return f"""Product: {title}
Category: {categories}
Store: {store}

Features:
    {features}

Description:
    {description}

Details:
    {details_str}

Top Reviews (showing {n_reviews}):
    {review_lines}"""

def build_document(product: dict, top_reviews: list[dict]) -> Document | None:
    """
    Build one LangChain Document for a single product row from the metadata Dataset.
    Returns None if there is no indexable text.
    """
    page_content = build_page_content(product, top_reviews)
    if not page_content.strip():
        return None

    details_dict = _parse_details(product.get("details"))

    metadata = {
        "parent_asin":    product.get("parent_asin", ""),
        "title":          _coerce_str(product.get("title")),
        "main_category":  _coerce_str(product.get("main_category")),
        "price":          _parse_price(product.get("price")),
        "store":          _coerce_str(product.get("store")),
        "categories":     _coerce_str(product.get("categories")),
        "features":       _coerce_str(product.get("features")),
        "description":    _coerce_str(product.get("description")),
        "details":        details_dict,
        "average_rating": product.get("average_rating"),
        "rating_number":  product.get("rating_number"),
        "image":      extract_image(product),
        "top_reviews":    top_reviews,
    }

    return Document(page_content=page_content, metadata=metadata)


def pregroup_reviews(
    reviews_dataset_dict,
    max_reviews_per_product: int = 5,
) -> dict:
    """
    Pre-group top-k reviews per product using DuckDB for efficient scoring
    and ranking β€” never loads all 14M reviews into Python memory at once.

    Uses a single SQL query with ROW_NUMBER() to rank reviews per product
    by the same weighted score as eda_helpers.get_best_reviews():
        helpful_vote 50% (log-scaled) + verified_purchase 30% + rating extremity 20%
    """
    import duckdb

    print("Pre-grouping reviews via DuckDB (memory-efficient) ...")
    arrow_table = reviews_dataset_dict["full"].data.table

    k = max_reviews_per_product
    query = f"""
        WITH scored AS (
            SELECT
                parent_asin,
                title,
                text,
                rating,
                helpful_vote,
                verified_purchase,
                (
                    0.5 * (LN(1 + GREATEST(COALESCE(helpful_vote, 0), 0)))
                    + 0.3 * (CASE WHEN verified_purchase THEN 1.0 ELSE 0.0 END)
                    + 0.2 * (ABS(COALESCE(rating, 3.0) - 3.0) / 2.0)
                ) AS score
            FROM arrow_table
            WHERE parent_asin IS NOT NULL AND parent_asin != ''
        ),
        ranked AS (
            SELECT *,
                ROW_NUMBER() OVER (
                    PARTITION BY parent_asin
                    ORDER BY score DESC
                ) AS rn
            FROM scored
        )
        SELECT parent_asin, title, text, rating, helpful_vote
        FROM ranked
        WHERE rn <= {k}
        ORDER BY parent_asin, rn
    """

    rows = duckdb.query(query).fetchall()
    cols = ["parent_asin", "title", "text", "rating", "helpful_vote"]

    result = {}
    for row in rows:
        r           = dict(zip(cols, row))
        asin        = r.pop("parent_asin")
        result.setdefault(asin, []).append(r)

    print(f"  {len(result):,} unique parent_asins grouped")
    print("  pre-grouping done")
    return result


def build_documents(
    metadata_dataset: Dataset,
    reviews_dataset_dict,
    max_products: int | None = None,
    max_reviews_per_product: int = 5,
    reviews_lookup: dict | None = None,
) -> list[Document]:
    """
    Build one LangChain Document per product.

    Pass reviews_lookup (from pregroup_reviews) to skip per-product DuckDB
    queries entirely β€” much faster for large datasets.
    """
    total = len(metadata_dataset)
    n     = min(total, max_products) if max_products else total
    print(f"Building documents for {n} products ...")

    docs = []
    for i in range(n):
        product     = metadata_dataset[i]
        parent_asin = product.get("parent_asin", "")

        if reviews_lookup is not None:
            top_reviews = reviews_lookup.get(parent_asin, [])[:max_reviews_per_product]
        else:
            top_reviews = get_top_reviews(
                reviews_dataset_dict, parent_asin, k=max_reviews_per_product
            )

        doc = build_document(product, top_reviews)
        if doc:
            docs.append(doc)

        if (i + 1) % 500 == 0:
            print(f"  ... {i + 1}/{n} products processed")

    print(f"  -> {len(docs)} documents built (skipped {n - len(docs)} empty)")
    return docs


# ── index build & persist ─────────────────────────────────────────────────────

def build_and_save(
    documents: list[Document],
    index_path: str | Path = "data/processed/bm25_index.pkl",
    corpus_path: str | Path = "data/processed/bm25_corpus.pkl",
) -> BM25Retriever:
    """
    Build a BM25Retriever from documents, then pickle both the
    tokenized corpus and the retriever to disk.

    Parameters
    ----------
    documents   : output of build_documents()
    index_path  : e.g. 'data/processed/bm25_index.pkl'
    corpus_path : e.g. 'data/processed/bm25_corpus.pkl'

    Returns
    -------
    The fitted BM25Retriever instance.
    """
    index_path  = Path(index_path)
    corpus_path = Path(corpus_path)
    index_path.parent.mkdir(parents=True, exist_ok=True)

    print(f"Fitting BM25 index over {len(documents)} documents …")
    retriever = BM25Retriever.from_documents(
        documents,
        preprocess_func=simple_tokenize,
    )

    # Save tokenized corpus separately β€” useful for inspection in the notebook
    tokenized_corpus = [simple_tokenize(doc.page_content) for doc in documents]
    with open(corpus_path, "wb") as f:
        pickle.dump(tokenized_corpus, f)
    print(f"Tokenized corpus saved β†’ {corpus_path}")

    with open(index_path, "wb") as f:
        pickle.dump(retriever, f)
    print(f"BM25 index saved       β†’ {index_path}")

    return retriever


# ── load ──────────────────────────────────────────────────────────────────────

def load(index_path: str | Path = "data/processed/bm25_index.pkl") -> BM25Retriever:
    """
    Load a previously saved BM25Retriever from disk.
    Call this in app.py instead of rebuilding every time.
    """
    index_path = Path(index_path)
    if not index_path.exists():
        raise FileNotFoundError(
            f"BM25 index not found at '{index_path}'.\n"
            "Run build_and_save() from your notebook first."
        )
    with open(index_path, "rb") as f:
        retriever = pickle.load(f)
    print(f"BM25 index loaded ← {index_path}")
    return retriever


# ── search ────────────────────────────────────────────────────────────────────

def search(
    retriever: BM25Retriever,
    query: str,
    top_k: int = 3,
) -> list[dict]:
    """
    Search the BM25Retriever for a query, returning metadata of top-k results.
    
    Performs a BM25 keyword search on the indexed documents. Tokenizes the query
    using the same tokenizer as the index, computes BM25 scores for all documents,
    and returns structured metadata (including score) for the top-k matches.
    """
    retriever.k = top_k
    
    # Tokenize query the same way the index was built
    tokenized_query = simple_tokenize(query)
    
    # Get raw BM25 scores for ALL documents
    scores = retriever.vectorizer.get_scores(tokenized_query)  # np.ndarray, len = n_docs
    
    # Get indices of top-k scores
    top_indices = sorted(
        range(len(scores)),
        key=scores.__getitem__,
        reverse=True
    )[:top_k]

    # Collect metadata for top results, including score
    return [
        {**retriever.docs[i].metadata, "score": scores[i]}
        for i in top_indices
    ]


# ── notebook entry point ──────────────────────────────────────────────────────

def build_from_hf_datasets(
    metadata_dataset: Dataset,
    reviews_dataset_dict,
    index_path: str | Path = "data/processed/tokenisation/bm25_index.pkl",
    corpus_path: str | Path = "data/processed/tokenisation/bm25_corpus.pkl",
    max_products: int | None = None,
    max_reviews_per_product: int = 5,
) -> BM25Retriever:
    """
    End-to-end helper to call from milestone1_exploration.ipynb.

    Example usage in the notebook:
    --------------------------------
    from src.bm25 import build_from_hf_datasets, load, search

    retriever = build_from_hf_datasets(
        metadata_dataset=raw_metadata['full'],   
        reviews_dataset_dict=raw_reviews,        
        max_products=500,                        
    )

    # Later in app.py β€” just load the saved index:
    # retriever = load("data/processed/bm25_index.pkl")
    # results   = search(retriever, "something sweet for a cheese board")
    """
    reviews_lookup = pregroup_reviews(reviews_dataset_dict, max_reviews_per_product)
    docs = build_documents(
        metadata_dataset,
        reviews_dataset_dict,
        max_products=max_products,
        max_reviews_per_product=max_reviews_per_product,
        reviews_lookup=reviews_lookup,
    )
    return build_and_save(docs, index_path=index_path, corpus_path=corpus_path)


def build_from_hf_datasets_batched(
    metadata_dataset: Dataset,
    reviews_dataset_dict,
    index_path: str | Path = "data/processed/tokenisation/bm25_index.pkl",
    corpus_path: str | Path = "data/processed/tokenisation/bm25_corpus.pkl",
    batch_size: int = 2000,
    max_reviews_per_product: int = 5,
    max_products: int | None = None,
) -> BM25Retriever:
    """
    Memory-safe version of build_from_hf_datasets β€” builds documents in
    batches to avoid OOM kernel crashes on large datasets.

    Checkpoints completed batches to data/processed/checkpoints/ after each
    batch, so if the kernel dies mid-run you can resume from the last
    completed batch instead of starting over.

    Example usage in the notebook:
    --------------------------------
    retriever = build_from_hf_datasets_batched(
        metadata_dataset=raw_metadata['full'],
        reviews_dataset_dict=raw_reviews,
        batch_size=5000,
        max_reviews_per_product=3,
        max_products=60000,   # None = use all
    )
    """
    index_path  = Path(index_path)
    corpus_path = Path(corpus_path)

    # checkpoint folder lives next to the index
    checkpoint_dir = index_path.parent / "checkpoints"
    checkpoint_dir.mkdir(parents=True, exist_ok=True)

    total = min(len(metadata_dataset), max_products) if max_products else len(metadata_dataset)

    # find resume point β€” checkpoints named docs_0.pkl, docs_2000.pkl, ...
    existing = sorted(checkpoint_dir.glob("docs_*.pkl"))
    if existing:
        last_ckpt    = existing[-1]
        resume_start = int(last_ckpt.stem.split("_")[1]) + batch_size
        print(f"Resuming from product {resume_start} "
              f"({len(existing)} checkpoint(s) found)")
        all_docs = []
        for ckpt in existing:
            with open(ckpt, "rb") as f:
                all_docs.extend(pickle.load(f))
        print(f"  loaded {len(all_docs)} docs from checkpoints")
    else:
        resume_start = 0
        all_docs     = []
        print(f"Starting fresh β€” {total} products to process")

    # pre-group all reviews once
    reviews_lookup = pregroup_reviews(reviews_dataset_dict, max_reviews_per_product)

    # batch loop
    for start in range(resume_start, total, batch_size):
        end   = min(start + batch_size, total)
        print(f"\nBatch {start}-{end} of {total} ...")

        batch      = metadata_dataset.select(range(start, end))
        batch_docs = build_documents(
            batch,
            reviews_dataset_dict,
            max_products=None,
            max_reviews_per_product=max_reviews_per_product,
            reviews_lookup=reviews_lookup,
        )
        all_docs.extend(batch_docs)

        # save checkpoint for this batch
        ckpt_path = checkpoint_dir / f"docs_{start}.pkl"
        with open(ckpt_path, "wb") as f:
            pickle.dump(batch_docs, f)
        print(f"  checkpoint saved -> {ckpt_path.name}")
        print(f"  cumulative docs  : {len(all_docs)}")

    # build final index
    print(f"\nAll batches done - {len(all_docs)} total documents.")
    retriever = build_and_save(all_docs, index_path=index_path, corpus_path=corpus_path)

    # clean up checkpoints now that final index is safely written
    for ckpt in checkpoint_dir.glob("docs_*.pkl"):
        ckpt.unlink()
    print("Checkpoints cleaned up.")

    return retriever