allbibek commited on
Commit
2489a92
·
verified ·
1 Parent(s): 84eb043

cosin cross reranker

Browse files
Files changed (1) hide show
  1. app.py +32 -6
app.py CHANGED
@@ -30,28 +30,54 @@ def get_embedding(text: str):
30
  return []
31
 
32
  expanded_text = expand_query(text)
33
- embedding = embedder.encode(expanded_text).tolist()
34
  return embedding
35
 
36
  def fn_semantic(query: str, match_count: int = 100):
37
- embedding = embedder.encode(query).tolist()
 
38
 
39
  response = supabase.rpc(
40
  "search_kbli",
41
- {"query_embedding": embedding, "match_count": match_count}
42
  ).execute()
43
  candidates = response.data or []
44
 
45
  if not candidates:
46
  return {"results": []}
 
 
 
 
 
 
47
 
48
- pairs = [(query, c["judul"] + " " + c["deskripsi"]) for c in candidates]
49
- scores = reranker.predict(pairs)
 
 
 
50
 
51
  for c, s in zip(candidates, scores):
52
  c["rerank_score"] = float(s)
53
 
54
- candidates = sorted(candidates, key=lambda x: x["rerank_score"], reverse=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  return {"results": candidates[:10]}
57
 
 
30
  return []
31
 
32
  expanded_text = expand_query(text)
33
+ embedding = embedder.encode(expanded_text, normalize_embeddings=True).tolist()
34
  return embedding
35
 
36
  def fn_semantic(query: str, match_count: int = 100):
37
+ expanded = expand_query(query)
38
+ embedding_q = embedder.encode(expanded, normalize_embeddings=True).tolist()
39
 
40
  response = supabase.rpc(
41
  "search_kbli",
42
+ {"query_embedding": embedding_q, "match_count": match_count}
43
  ).execute()
44
  candidates = response.data or []
45
 
46
  if not candidates:
47
  return {"results": []}
48
+
49
+ print("=== Candidates BEFORE rerank (top 10) ===")
50
+ for c in candidates[:10]:
51
+ print(c.get("kode"), c.get("judul")[:80], "sim=", c.get("similarity"))
52
+
53
+ pairs = [(expanded, c["judul"] + " " + c["deskripsi"]) for c in candidates]
54
 
55
+ try:
56
+ scores = reranker.predict(pairs)
57
+ except Exception as e:
58
+ print("Reranker error:", e)
59
+ return {"results": sorted(candidates, key=lambda x: x.get("similarity", 0), reverse=True)[:10]}
60
 
61
  for c, s in zip(candidates, scores):
62
  c["rerank_score"] = float(s)
63
 
64
+ print("=== Candidates AFTER rerank (top 10) ===")
65
+ for c in candidates[:10]:
66
+ print(c.get("kode"), c.get("judul")[:80], "sim=", c.get("similarity"), "rerank=", c.get("rerank_score"))
67
+
68
+ rerank_vals = [c["rerank_score"] for c in candidates]
69
+ rmin, rmax = min(rerank_vals), max(rerank_vals)
70
+ for c in candidates:
71
+ if rmax - rmin > 1e-9:
72
+ c["rerank_norm"] = (c["rerank_score"] - rmin) / (rmax - rmin)
73
+ else:
74
+ c["rerank_norm"] = 0.0
75
+
76
+ for c in candidates:
77
+ sim = c.get("similarity", 0.0)
78
+ c["hybrid_score"] = 0.6 * sim + 0.4 * c["rerank_norm"]
79
+
80
+ candidates = sorted(candidates, key=lambda x: x["hybrid_score"], reverse=True)
81
 
82
  return {"results": candidates[:10]}
83