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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json, re, math, os
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# ===============================================================
|
| 7 |
+
# UTILITIES
|
| 8 |
+
# ===============================================================
|
| 9 |
+
|
| 10 |
+
def tokenize(text):
|
| 11 |
+
return re.findall(r"[A-Za-z0-9']+", text.lower())
|
| 12 |
+
|
| 13 |
+
def text_vector(text):
|
| 14 |
+
return Counter(tokenize(text))
|
| 15 |
+
|
| 16 |
+
def centroid(docs):
|
| 17 |
+
C = Counter()
|
| 18 |
+
for d in docs:
|
| 19 |
+
C.update(text_vector(d["text"]))
|
| 20 |
+
return C
|
| 21 |
+
|
| 22 |
+
def cosine(a, b):
|
| 23 |
+
num = 0
|
| 24 |
+
da = 0
|
| 25 |
+
db = 0
|
| 26 |
+
for k in set(a.keys()) | set(b.keys()):
|
| 27 |
+
va = a.get(k,0)
|
| 28 |
+
vb = b.get(k,0)
|
| 29 |
+
num += va*vb
|
| 30 |
+
da += va*va
|
| 31 |
+
db += vb*vb
|
| 32 |
+
if da == 0 or db == 0:
|
| 33 |
+
return 0
|
| 34 |
+
return num / math.sqrt(da*db)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ===============================================================
|
| 38 |
+
# MAIN LOAD FUNCTION
|
| 39 |
+
# ===============================================================
|
| 40 |
+
|
| 41 |
+
def load_jsonl(jsonl_file):
|
| 42 |
+
if jsonl_file is None:
|
| 43 |
+
return None, None, "⚠ No file uploaded."
|
| 44 |
+
|
| 45 |
+
records = []
|
| 46 |
+
with open(jsonl_file.name, "r", encoding="utf8") as f:
|
| 47 |
+
for line in f:
|
| 48 |
+
try:
|
| 49 |
+
records.append(json.loads(line))
|
| 50 |
+
except:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
# build clusters
|
| 54 |
+
cluster_map = defaultdict(list)
|
| 55 |
+
for r in records:
|
| 56 |
+
cluster_map[r.get("cluster", -1)].append(r)
|
| 57 |
+
|
| 58 |
+
# build BM25
|
| 59 |
+
docs_text = [r["text"] for r in records]
|
| 60 |
+
tokenized_docs = [tokenize(t) for t in docs_text]
|
| 61 |
+
|
| 62 |
+
doc_freq = Counter()
|
| 63 |
+
for toks in tokenized_docs:
|
| 64 |
+
for t in set(toks):
|
| 65 |
+
doc_freq[t] += 1
|
| 66 |
+
|
| 67 |
+
Ndocs = len(records)
|
| 68 |
+
avg_len = sum(len(t) for t in tokenized_docs) / Ndocs
|
| 69 |
+
|
| 70 |
+
# Precompute centroids
|
| 71 |
+
centroids = {cid: centroid(docs) for cid, docs in cluster_map.items()}
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"records": records,
|
| 75 |
+
"cluster_map": cluster_map,
|
| 76 |
+
"tokenized_docs": tokenized_docs,
|
| 77 |
+
"doc_freq": doc_freq,
|
| 78 |
+
"Ndocs": Ndocs,
|
| 79 |
+
"avg_len": avg_len,
|
| 80 |
+
"centroids": centroids,
|
| 81 |
+
}, sorted(cluster_map.keys()), f"Loaded {len(records)} records."
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ===============================================================
|
| 85 |
+
# BM25 SEARCH
|
| 86 |
+
# ===============================================================
|
| 87 |
+
|
| 88 |
+
def bm25_score(query, doc_toks, doc_freq, Ndocs, avg_len):
|
| 89 |
+
k=1.5; b=0.75
|
| 90 |
+
score = 0
|
| 91 |
+
q_toks = tokenize(query)
|
| 92 |
+
for q in q_toks:
|
| 93 |
+
df = doc_freq.get(q,0)
|
| 94 |
+
if df == 0:
|
| 95 |
+
continue
|
| 96 |
+
idf = math.log((Ndocs - df + 0.5)/(df + 0.5) + 1)
|
| 97 |
+
tf = doc_toks.count(q)
|
| 98 |
+
denom = tf + k*(1 - b + b*(len(doc_toks)/avg_len))
|
| 99 |
+
score += idf*(tf*(k+1))/denom
|
| 100 |
+
return score
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ===============================================================
|
| 104 |
+
# GRADIO INTERFACE FUNCTIONS
|
| 105 |
+
# ===============================================================
|
| 106 |
+
|
| 107 |
+
def do_view_cluster(state, cid):
|
| 108 |
+
if state is None:
|
| 109 |
+
return "⚠ Upload a file first."
|
| 110 |
+
try:
|
| 111 |
+
cid = int(cid)
|
| 112 |
+
except:
|
| 113 |
+
return "Enter a valid number."
|
| 114 |
+
|
| 115 |
+
cluster_map = state["cluster_map"]
|
| 116 |
+
|
| 117 |
+
if cid not in cluster_map:
|
| 118 |
+
return "❌ Cluster not found."
|
| 119 |
+
|
| 120 |
+
out = [f"=== Cluster {cid} ({len(cluster_map[cid])} docs) ===\n"]
|
| 121 |
+
for d in cluster_map[cid][:20]:
|
| 122 |
+
t = d["text"].strip()
|
| 123 |
+
if len(t) > 1200:
|
| 124 |
+
t = t[:1200] + " … [truncated]"
|
| 125 |
+
out.append(f"\n--- id={d.get('id')} ---\n{t}\n")
|
| 126 |
+
return "\n".join(out)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def do_search(state, query):
|
| 130 |
+
if state is None:
|
| 131 |
+
return "⚠ Upload a file first."
|
| 132 |
+
|
| 133 |
+
records = state["records"]
|
| 134 |
+
tokenized_docs = state["tokenized_docs"]
|
| 135 |
+
doc_freq = state["doc_freq"]
|
| 136 |
+
Ndocs = state["Ndocs"]
|
| 137 |
+
avg_len = state["avg_len"]
|
| 138 |
+
|
| 139 |
+
scores = []
|
| 140 |
+
for r, toks in zip(records, tokenized_docs):
|
| 141 |
+
s = bm25_score(query, toks, doc_freq, Ndocs, avg_len)
|
| 142 |
+
if s > 0:
|
| 143 |
+
scores.append((s, r))
|
| 144 |
+
scores.sort(reverse=True, key=lambda x: x[0])
|
| 145 |
+
|
| 146 |
+
out = [f"=== Results for '{query}' ==="]
|
| 147 |
+
for s, r in scores[:15]:
|
| 148 |
+
out.append(f"\nScore {s:.2f} — Cluster {r['cluster']} — id={r['id']}\n{r['text'][:500]}…\n")
|
| 149 |
+
|
| 150 |
+
return "\n".join(out)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def do_show_topics(state):
|
| 154 |
+
if state is None:
|
| 155 |
+
return "⚠ Upload a file first."
|
| 156 |
+
|
| 157 |
+
STOPWORDS = set("""
|
| 158 |
+
the and to of a in is this that for on with as be or by from at
|
| 159 |
+
an it are was you your if but have we they his her she their our
|
| 160 |
+
subject re fw message thereof all may any doc email
|
| 161 |
+
""".split())
|
| 162 |
+
|
| 163 |
+
out = ["=== Cluster Topics ==="]
|
| 164 |
+
for cid, cent in state["centroids"].items():
|
| 165 |
+
filtered = {w:c for w,c in cent.items()
|
| 166 |
+
if w not in STOPWORDS and len(w) > 2 and c > 1}
|
| 167 |
+
top = [w for w,_ in Counter(filtered).most_common(6)]
|
| 168 |
+
out.append(f"Cluster {cid:<4} | {' '.join(top)}")
|
| 169 |
+
|
| 170 |
+
return "\n".join(out)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def do_entity_search(state, name):
|
| 174 |
+
if state is None:
|
| 175 |
+
return "⚠ Upload a file first."
|
| 176 |
+
|
| 177 |
+
hits = []
|
| 178 |
+
cluster_map = state["cluster_map"]
|
| 179 |
+
|
| 180 |
+
for cid, docs in cluster_map.items():
|
| 181 |
+
count = sum(name.lower() in d["text"].lower() for d in docs)
|
| 182 |
+
if count:
|
| 183 |
+
hits.append((count, cid))
|
| 184 |
+
|
| 185 |
+
hits.sort(reverse=True)
|
| 186 |
+
|
| 187 |
+
out = [f"=== Clusters mentioning '{name}' ==="]
|
| 188 |
+
for count, cid in hits[:20]:
|
| 189 |
+
out.append(f"Cluster {cid}: {count} hits")
|
| 190 |
+
return "\n".join(out)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ===============================================================
|
| 194 |
+
# GRADIO UI
|
| 195 |
+
# ===============================================================
|
| 196 |
+
|
| 197 |
+
with gr.Blocks(title="Epstein Semantic Explorer v5") as demo:
|
| 198 |
+
gr.Markdown("# **Epstein Semantic Explorer v5**
|
| 199 |
+
Upload your `epstein_semantic.jsonl` file.")
|
| 200 |
+
|
| 201 |
+
with gr.Row():
|
| 202 |
+
jsonl_file = gr.File(label="Upload JSONL dataset")
|
| 203 |
+
load_btn = gr.Button("Load Dataset")
|
| 204 |
+
|
| 205 |
+
state = gr.State()
|
| 206 |
+
clusters_box = gr.Number(label="Cluster # to View", value=96)
|
| 207 |
+
query_box = gr.Textbox(label="Search Keyword")
|
| 208 |
+
entity_box = gr.Textbox(label="Search for Entity (name)")
|
| 209 |
+
|
| 210 |
+
output = gr.Textbox(label="Output", lines=30)
|
| 211 |
+
|
| 212 |
+
load_btn.click(load_jsonl, inputs=[jsonl_file], outputs=[state, clusters_box, output])
|
| 213 |
+
clusters_box.change(do_view_cluster, inputs=[state, clusters_box], outputs=output)
|
| 214 |
+
query_box.submit(do_search, inputs=[state, query_box], outputs=output)
|
| 215 |
+
entity_box.submit(do_entity_search, inputs=[state, entity_box], outputs=output)
|
| 216 |
+
|
| 217 |
+
gr.Button("Show Topics").click(do_show_topics, inputs=[state], outputs=output)
|
| 218 |
+
|
| 219 |
+
demo.launch()
|