Spaces:
Sleeping
Sleeping
Create data_utils.py
Browse files- data_utils.py +104 -0
data_utils.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import math
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
|
| 6 |
+
STOPWORDS = set("""
|
| 7 |
+
a an and the or for nor but so yet of to in on with at by from as is are was were be being been
|
| 8 |
+
i you he she it we they them us our your their this that these those here there
|
| 9 |
+
""".split())
|
| 10 |
+
|
| 11 |
+
def dedupe_sentences(text: str) -> str:
|
| 12 |
+
parts = re.split(r'(?<=[.!?])\s+', text.strip())
|
| 13 |
+
seen, out = set(), []
|
| 14 |
+
for p in parts:
|
| 15 |
+
norm = re.sub(r'\s+', ' ', p.strip().lower())
|
| 16 |
+
if norm and norm not in seen:
|
| 17 |
+
seen.add(norm); out.append(p.strip())
|
| 18 |
+
return " ".join(out).strip()
|
| 19 |
+
|
| 20 |
+
def strip_labels(text: str) -> str:
|
| 21 |
+
patterns = [r'^\s*(hook|body|takeaway|cta):\s*', r'^\s*(Hook|Body|Takeaway|CTA):\s*']
|
| 22 |
+
lines = text.splitlines()
|
| 23 |
+
cleaned = []
|
| 24 |
+
for line in lines:
|
| 25 |
+
L = line
|
| 26 |
+
for p in patterns:
|
| 27 |
+
L = re.sub(p, '', L)
|
| 28 |
+
cleaned.append(L)
|
| 29 |
+
return "\n".join(cleaned).strip()
|
| 30 |
+
|
| 31 |
+
def load_posts(file) -> pd.DataFrame:
|
| 32 |
+
name = file.name.lower()
|
| 33 |
+
if name.endswith(".csv"):
|
| 34 |
+
df = pd.read_csv(file)
|
| 35 |
+
elif name.endswith(".json"):
|
| 36 |
+
df = pd.read_json(file, lines=False)
|
| 37 |
+
else:
|
| 38 |
+
raise ValueError("Upload CSV or JSON.")
|
| 39 |
+
cand = [c for c in df.columns if c.lower() in ("text","post","content","body")]
|
| 40 |
+
if not cand:
|
| 41 |
+
raise ValueError("Dataset must include 'text' (or post/content/body).")
|
| 42 |
+
if "text" not in df.columns:
|
| 43 |
+
df["text"] = df[cand[0]]
|
| 44 |
+
df["text"] = df["text"].fillna("").astype(str)
|
| 45 |
+
return df[["text"]]
|
| 46 |
+
|
| 47 |
+
def simple_rake(text, min_len=2, max_len=3, top_k=12):
|
| 48 |
+
words = re.findall(r"[A-Za-z0-9#+\-_/']+", text.lower())
|
| 49 |
+
phrases, cur = [], []
|
| 50 |
+
for w in words:
|
| 51 |
+
if w in STOPWORDS:
|
| 52 |
+
if cur:
|
| 53 |
+
phrases.append(" ".join(cur)); cur = []
|
| 54 |
+
else:
|
| 55 |
+
cur.append(w)
|
| 56 |
+
if cur:
|
| 57 |
+
phrases.append(" ".join(cur))
|
| 58 |
+
freq, degree, scores = {}, {}, {}
|
| 59 |
+
for ph in phrases:
|
| 60 |
+
toks = ph.split()
|
| 61 |
+
for t in toks:
|
| 62 |
+
freq[t] = freq.get(t,0)+1
|
| 63 |
+
degree[t] = degree.get(t,0)+(len(toks)-1)
|
| 64 |
+
for ph in phrases:
|
| 65 |
+
scores[ph] = sum((degree.get(t,0)+1)/ (freq.get(t,1)) for t in ph.split())
|
| 66 |
+
ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 67 |
+
return [p for p,_ in ranked if min_len <= len(p.split()) <= max_len][:top_k]
|
| 68 |
+
|
| 69 |
+
def tfidf_builder(texts: List[str], top_k=8):
|
| 70 |
+
docs = [re.findall(r"[A-Za-z0-9#+\-_/']+", t.lower()) for t in texts]
|
| 71 |
+
vocab = {}
|
| 72 |
+
for d in docs:
|
| 73 |
+
for w in set(d):
|
| 74 |
+
vocab[w] = vocab.get(w,0)+1
|
| 75 |
+
N = len(docs)
|
| 76 |
+
def score(text):
|
| 77 |
+
doc = re.findall(r"[A-Za-z0-9#+\-_/']+", text.lower())
|
| 78 |
+
tf = {}
|
| 79 |
+
for w in doc:
|
| 80 |
+
tf[w] = tf.get(w,0)+1
|
| 81 |
+
scores = {}
|
| 82 |
+
for w,c in tf.items():
|
| 83 |
+
df = vocab.get(w,1)
|
| 84 |
+
idf = math.log((N+1)/(df+1))+1
|
| 85 |
+
scores[w] = (c/len(doc))*idf
|
| 86 |
+
ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 87 |
+
return [w for w,_ in ranked[:top_k]]
|
| 88 |
+
return score
|
| 89 |
+
|
| 90 |
+
def extract_keywords(topic: str, df: pd.DataFrame|None) -> List[str]:
|
| 91 |
+
if df is not None and len(df):
|
| 92 |
+
sample = df["text"].sample(min(30, len(df)), random_state=42).tolist()
|
| 93 |
+
rake_kw = simple_rake(" ".join(sample + [topic]), min_len=2, max_len=3, top_k=12)
|
| 94 |
+
tfidf_fn = tfidf_builder(df["text"].tolist(), top_k=8)
|
| 95 |
+
kw2 = tfidf_fn(topic + " " + " ".join(sample[:5]))
|
| 96 |
+
raw = rake_kw + kw2
|
| 97 |
+
else:
|
| 98 |
+
raw = simple_rake(topic, min_len=1, max_len=2, top_k=8)
|
| 99 |
+
seen, out = set(), []
|
| 100 |
+
for k in raw:
|
| 101 |
+
k2 = re.sub(r"\s+"," ",k.strip().lower())
|
| 102 |
+
if k2 and k2 not in seen:
|
| 103 |
+
seen.add(k2); out.append(k2)
|
| 104 |
+
return out[:12]
|