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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re, json, io, zipfile, shutil, math, gc, uuid
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import List, Dict, Any, Tuple
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pyarrow as pa
|
| 8 |
+
import pyarrow.parquet as pq
|
| 9 |
+
|
| 10 |
+
from bs4 import BeautifulSoup
|
| 11 |
+
import ftfy
|
| 12 |
+
from langdetect import detect, DetectorFactory
|
| 13 |
+
DetectorFactory.seed = 0
|
| 14 |
+
|
| 15 |
+
import gradio as gr
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
|
| 18 |
+
from sentence_transformers import SentenceTransformer
|
| 19 |
+
import faiss
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import hdbscan
|
| 23 |
+
HDBSCAN_AVAILABLE = True
|
| 24 |
+
except Exception:
|
| 25 |
+
HDBSCAN_AVAILABLE = False
|
| 26 |
+
|
| 27 |
+
# ------------------- Helpers -------------------
|
| 28 |
+
URL = re.compile(r"https?://\S+", re.I)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def torch_cuda_available():
|
| 32 |
+
try:
|
| 33 |
+
import torch
|
| 34 |
+
return torch.cuda.is_available()
|
| 35 |
+
except Exception:
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def html_to_text(html: str) -> str:
|
| 40 |
+
if not html:
|
| 41 |
+
return ""
|
| 42 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 43 |
+
for tag in soup(["script", "style"]):
|
| 44 |
+
tag.decompose()
|
| 45 |
+
return soup.get_text(separator="\n")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def strip_quotes_and_sigs(text: str) -> str:
|
| 49 |
+
if not text:
|
| 50 |
+
return ""
|
| 51 |
+
text = re.sub(r"^>.*$", "", text, flags=re.M) # drop quote lines
|
| 52 |
+
res = re.split(r"\n-- ?\n", text)[0]
|
| 53 |
+
res = re.split(r"\nSent from my ", res)[0]
|
| 54 |
+
return res.strip()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def parse_name_email(s: str) -> Tuple[str, str]:
|
| 58 |
+
if not s:
|
| 59 |
+
return "", ""
|
| 60 |
+
m = re.match(r'(?:"?([^"]*)"?\s)?<?([^<>]+@[^<>]+)>?', s)
|
| 61 |
+
if m:
|
| 62 |
+
return (m.group(1) or "").strip(), (m.group(2) or "").strip()
|
| 63 |
+
return "", s.strip()
|
| 64 |
+
|
| 65 |
+
# ------------------- Normalization -------------------
|
| 66 |
+
|
| 67 |
+
def normalize_email_record(raw: Dict[str, Any]) -> Dict[str, Any]:
|
| 68 |
+
subject = raw.get("subject") or raw.get("Subject") or ""
|
| 69 |
+
body_html = raw.get("body_html") or raw.get("html") or ""
|
| 70 |
+
body_text = raw.get("body_text") or raw.get("text") or ""
|
| 71 |
+
headers = raw.get("headers") or {}
|
| 72 |
+
|
| 73 |
+
date_val = raw.get("date") or raw.get("Date") or headers.get("Date") or ""
|
| 74 |
+
msg_id = raw.get("message_id") or raw.get("Message-ID") or headers.get("Message-ID") or ""
|
| 75 |
+
sender = raw.get("from") or raw.get("From") or headers.get("From") or ""
|
| 76 |
+
|
| 77 |
+
if body_html and not body_text:
|
| 78 |
+
body_text = html_to_text(body_html)
|
| 79 |
+
|
| 80 |
+
subject = ftfy.fix_text(subject or "").strip()
|
| 81 |
+
body_text = ftfy.fix_text(body_text or "")
|
| 82 |
+
body_text = strip_quotes_and_sigs(body_text)
|
| 83 |
+
body_text = re.sub(r"\s+", " ", body_text).strip()
|
| 84 |
+
subject_norm = re.sub(r"\s+", " ", subject)
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
lang = detect((subject_norm + " " + body_text[:5000]).strip()) if (subject_norm or body_text) else "unknown"
|
| 88 |
+
except Exception:
|
| 89 |
+
lang = "unknown"
|
| 90 |
+
|
| 91 |
+
from_name, from_email = parse_name_email(sender)
|
| 92 |
+
from_domain = from_email.split("@")[-1].lower() if "@" in from_email else ""
|
| 93 |
+
|
| 94 |
+
iso_date = ""
|
| 95 |
+
if isinstance(date_val, (int, float)):
|
| 96 |
+
try:
|
| 97 |
+
iso_date = pd.to_datetime(int(date_val), unit="s", utc=True).isoformat()
|
| 98 |
+
except Exception:
|
| 99 |
+
pass
|
| 100 |
+
elif isinstance(date_val, str) and date_val:
|
| 101 |
+
try:
|
| 102 |
+
iso_date = pd.to_datetime(date_val, utc=True, errors="coerce").isoformat()
|
| 103 |
+
except Exception:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
thread_key = subject_norm or msg_id
|
| 107 |
+
thread_id = str(pd.util.hash_pandas_object(pd.Series([thread_key], dtype="string")).astype("uint64").iloc[0])
|
| 108 |
+
|
| 109 |
+
text_hash = str(pd.util.hash_pandas_object(pd.Series([body_text], dtype="string")).astype("uint64").iloc[0]) if body_text else ""
|
| 110 |
+
|
| 111 |
+
if not msg_id:
|
| 112 |
+
msg_id = f"gen-{uuid.uuid4().hex}"
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
"message_id": str(msg_id),
|
| 116 |
+
"thread_id": thread_id,
|
| 117 |
+
"date": iso_date,
|
| 118 |
+
"from_name": from_name,
|
| 119 |
+
"from_email": from_email,
|
| 120 |
+
"from_domain": from_domain,
|
| 121 |
+
"subject": subject_norm,
|
| 122 |
+
"body_text": body_text,
|
| 123 |
+
"lang": lang,
|
| 124 |
+
"text_hash": text_hash,
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
# ------------------- Embeddings & Clustering -------------------
|
| 128 |
+
|
| 129 |
+
def embed_texts(model: SentenceTransformer, texts: List[str], batch_size: int, use_gpu: bool) -> np.ndarray:
|
| 130 |
+
embs = []
|
| 131 |
+
for i in tqdm(range(0, len(texts), batch_size), desc="Embedding", leave=False):
|
| 132 |
+
chunk = texts[i:i + batch_size]
|
| 133 |
+
embs.append(model.encode(
|
| 134 |
+
chunk,
|
| 135 |
+
batch_size=min(256, len(chunk)),
|
| 136 |
+
show_progress_bar=False,
|
| 137 |
+
normalize_embeddings=True,
|
| 138 |
+
convert_to_numpy=True,
|
| 139 |
+
device="cuda" if use_gpu else "cpu",
|
| 140 |
+
))
|
| 141 |
+
return np.vstack(embs).astype(np.float32)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def cluster_embeddings(embs: np.ndarray, method: str, min_cluster_size: int, k_hint: int, use_gpu: bool) -> np.ndarray:
|
| 145 |
+
if method == "HDBSCAN" and HDBSCAN_AVAILABLE:
|
| 146 |
+
clust = hdbscan.HDBSCAN(min_cluster_size=min_cluster_size, min_samples=max(5, min_cluster_size // 5), metric='euclidean')
|
| 147 |
+
return clust.fit_predict(embs)
|
| 148 |
+
k = max(10, k_hint or int(max(20, math.sqrt(len(embs) / 50))))
|
| 149 |
+
kmeans = faiss.Kmeans(d=embs.shape[1], k=k, niter=25, verbose=False, gpu=use_gpu)
|
| 150 |
+
kmeans.train(embs)
|
| 151 |
+
_, labels = kmeans.index.search(embs, 1)
|
| 152 |
+
return labels.reshape(-1)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def zero_shot_embed_sim(embs: np.ndarray, model: SentenceTransformer, label_texts: List[str], use_gpu: bool) -> Tuple[np.ndarray, np.ndarray]:
|
| 156 |
+
prompts = [f"This email is about: {t}" for t in label_texts]
|
| 157 |
+
label_embs = model.encode(prompts, normalize_embeddings=True, convert_to_numpy=True, device="cuda" if use_gpu else "cpu").astype(np.float32)
|
| 158 |
+
sims = embs @ label_embs.T
|
| 159 |
+
top_idx = sims.argmax(axis=1)
|
| 160 |
+
top_score = sims[np.arange(len(embs)), top_idx]
|
| 161 |
+
return top_idx, top_score
|
| 162 |
+
|
| 163 |
+
# ------------------- Defaults -------------------
|
| 164 |
+
DEFAULT_LABELS = [
|
| 165 |
+
"Newsletters/Subscriptions",
|
| 166 |
+
"Receipts & Billing",
|
| 167 |
+
"Personal/Family",
|
| 168 |
+
"Work/Colleagues",
|
| 169 |
+
"Meetings & Calendars",
|
| 170 |
+
"Travel/Itineraries",
|
| 171 |
+
"Legal/Contracts",
|
| 172 |
+
"System Notifications",
|
| 173 |
+
"Security/2FA",
|
| 174 |
+
"Hiring/Recruiting",
|
| 175 |
+
"Support Tickets",
|
| 176 |
+
"Politics/Government",
|
| 177 |
+
"Media/Press",
|
| 178 |
+
"Unknown"
|
| 179 |
+
]
|
| 180 |
+
|
| 181 |
+
# ------------------- Search -------------------
|
| 182 |
+
class EmailSearch:
|
| 183 |
+
def __init__(self, df, embs, model):
|
| 184 |
+
self.df = df
|
| 185 |
+
self.embs = embs
|
| 186 |
+
self.model = model
|
| 187 |
+
self.index = faiss.IndexFlatIP(embs.shape[1])
|
| 188 |
+
self.index.add(embs)
|
| 189 |
+
|
| 190 |
+
def query(self, q: str, top_k=20):
|
| 191 |
+
q_emb = self.model.encode([q], normalize_embeddings=True, convert_to_numpy=True)
|
| 192 |
+
scores, idx = self.index.search(q_emb.astype(np.float32), top_k)
|
| 193 |
+
results = self.df.iloc[idx[0]].copy()
|
| 194 |
+
results["score"] = scores[0]
|
| 195 |
+
return results
|
| 196 |
+
|
| 197 |
+
# ------------------- Gradio UI -------------------
|
| 198 |
+
with gr.Blocks(title="Email Organizer & Browser") as demo:
|
| 199 |
+
gr.Markdown("""
|
| 200 |
+
# Email Organizer & Browser (No-Redaction)
|
| 201 |
+
Upload a **.jsonl** or **.json** of emails. The app normalizes, deduplicates, embeds, clusters, labels, and lets you **search** your inbox semantically.
|
| 202 |
+
""")
|
| 203 |
+
|
| 204 |
+
with gr.Row():
|
| 205 |
+
inbox_file = gr.File(label="Upload emails (.jsonl or .json)", file_types=[".jsonl", ".json"])
|
| 206 |
+
|
| 207 |
+
run_btn = gr.Button("Process", variant="primary")
|
| 208 |
+
status = gr.Textbox(label="Status", interactive=False)
|
| 209 |
+
label_counts_df = gr.Dataframe(label="Label counts", interactive=False)
|
| 210 |
+
html_samples = gr.HTML(label="Samples")
|
| 211 |
+
|
| 212 |
+
with gr.Row():
|
| 213 |
+
search_query = gr.Textbox(label="Search emails (keywords, names, etc.)")
|
| 214 |
+
search_btn = gr.Button("Search")
|
| 215 |
+
search_results = gr.Dataframe(label="Search results", interactive=False)
|
| 216 |
+
|
| 217 |
+
state_df = gr.State()
|
| 218 |
+
state_embs = gr.State()
|
| 219 |
+
state_model = gr.State()
|
| 220 |
+
state_search = gr.State()
|
| 221 |
+
|
| 222 |
+
def process_file(inbox_file):
|
| 223 |
+
if inbox_file is None:
|
| 224 |
+
return "Please upload a file", None, None, None, None, None, None
|
| 225 |
+
local_path = inbox_file.name
|
| 226 |
+
recs = []
|
| 227 |
+
if local_path.endswith(".jsonl"):
|
| 228 |
+
with open(local_path, "r", encoding="utf-8") as fh:
|
| 229 |
+
for line in fh:
|
| 230 |
+
try:
|
| 231 |
+
recs.append(json.loads(line))
|
| 232 |
+
except:
|
| 233 |
+
continue
|
| 234 |
+
else:
|
| 235 |
+
with open(local_path, "r", encoding="utf-8") as fh:
|
| 236 |
+
obj = json.load(fh)
|
| 237 |
+
if isinstance(obj, list):
|
| 238 |
+
recs = obj
|
| 239 |
+
elif isinstance(obj, dict):
|
| 240 |
+
recs = [obj]
|
| 241 |
+
normd = [normalize_email_record(r) for r in recs]
|
| 242 |
+
df = pd.DataFrame(normd)
|
| 243 |
+
df = df.drop_duplicates(subset=["message_id", "subject", "text_hash"])
|
| 244 |
+
texts = (df["subject"].fillna("") + "\n\n" + df["body_text"].fillna("").str.slice(0,2000)).tolist()
|
| 245 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 246 |
+
embs = embed_texts(model, texts, 512, torch_cuda_available())
|
| 247 |
+
searcher = EmailSearch(df, embs, model)
|
| 248 |
+
label_counts = df.groupby("from_domain").size().reset_index(name="count").sort_values("count", ascending=False)
|
| 249 |
+
return f"Processed {len(df)} emails", label_counts, df.head(20).to_html(), df, embs, model, searcher
|
| 250 |
+
|
| 251 |
+
run_btn.click(
|
| 252 |
+
process_file,
|
| 253 |
+
inputs=[inbox_file],
|
| 254 |
+
outputs=[status, label_counts_df, html_samples, state_df, state_embs, state_model, state_search]
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
def search_fn(q, df, embs, model, searcher):
|
| 258 |
+
if searcher is None:
|
| 259 |
+
return pd.DataFrame()
|
| 260 |
+
results = searcher.query(q, top_k=20)
|
| 261 |
+
return results[["date","from_email","subject","body_text","score"]]
|
| 262 |
+
|
| 263 |
+
search_btn.click(
|
| 264 |
+
search_fn,
|
| 265 |
+
inputs=[search_query, state_df, state_embs, state_model, state_search],
|
| 266 |
+
outputs=[search_results]
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
demo.launch()
|