""" Raw text collection for a Turkish STS dataset. Collects individual Turkish sentences from two domains and writes them to raw_sentences.csv. It does NOT pair anything and does NOT score anything -- every pairing decision is left to the person building the dataset. What it does do is attach the metadata that makes pairing possible: doc_id sentences from the same article share one id, so you can pair a headline with its own lede, or two sentences from one Wikipedia lead paragraph (the "discourse distance" axis). event_id headlines from DIFFERENT outlets covering the SAME story share one id. These are naturally occurring paraphrases -- the backbone of the high-similarity rows. category so you can pair within a topic (low-but-nonzero similarity) or across topics (zero), and so you can check that your final score distribution is not just a proxy for topic. Sources: public RSS feeds and the Wikipedia REST API. Wikipedia text is CC BY-SA 4.0; news headlines are quoted with source and URL recorded per row. Usage: python3 collect_raw.py """ import csv import html import json import re import time import unicodedata import urllib.parse import urllib.request import xml.etree.ElementTree as ET from pathlib import Path HERE = Path(__file__).parent # Wikimedia asks for a descriptive User-Agent with a contact address and # rate-limits anonymous clients that hammer the REST API. UA = "sts-tr-dataset-coursework/1.0 (https://tr.wikipedia.org; coursework)" TIMEOUT = 20 # (outlet, category, url). Multiple outlets per category is deliberate: it is # what makes same-event cross-outlet clustering possible. FEEDS = [ ("hurriyet", "gundem", "https://www.hurriyet.com.tr/rss/gundem"), ("hurriyet", "ekonomi", "https://www.hurriyet.com.tr/rss/ekonomi"), ("hurriyet", "spor", "https://www.hurriyet.com.tr/rss/spor"), ("hurriyet", "teknoloji", "https://www.hurriyet.com.tr/rss/teknoloji"), ("hurriyet", "dunya", "https://www.hurriyet.com.tr/rss/dunya"), ("hurriyet", "magazin", "https://www.hurriyet.com.tr/rss/kelebek"), ("cumhuriyet", "gundem", "https://www.cumhuriyet.com.tr/rss"), ("cumhuriyet", "ekonomi", "https://www.cumhuriyet.com.tr/rss/ekonomi"), ("cumhuriyet", "spor", "https://www.cumhuriyet.com.tr/rss/spor"), ("cumhuriyet", "bilim", "https://www.cumhuriyet.com.tr/rss/bilim-teknoloji"), ("aa", "gundem", "https://www.aa.com.tr/tr/rss/default?cat=guncel"), ("bbc", "dunya", "https://feeds.bbci.co.uk/turkce/rss.xml"), ("euronews", "dunya", "https://tr.euronews.com/rss?level=theme&name=news"), ("haberturk", "gundem", "https://www.haberturk.com/rss"), ("milliyet", "gundem", "https://www.milliyet.com.tr/rss/rssnew/gundemrss.xml"), ("indyturk", "gundem", "https://www.indyturk.com/rss.xml"), ] # Chosen by hand for topical spread. Random Turkish Wikipedia articles are # mostly village and footballer stubs, which would collapse the topic variety. WIKI = { "bilim": [ "Fotosentez", "Kara delik", "DNA", "Evrim", "Periyodik tablo", "Kuantum mekaniği", "İklim değişikliği", "Yerçekimi", "Volkan", "Deprem", ], "tarih": [ "Osmanlı İmparatorluğu", "İstanbul'un fethi", "Fransız Devrimi", "I. Dünya Savaşı", "İpek Yolu", "Rönesans", "Mustafa Kemal Atatürk", "Antik Mısır", "Bizans İmparatorluğu", ], "cografya": [ "Ağrı Dağı", "Kapadokya", "Amazon Yağmur Ormanları", "Van Gölü", "Nil Nehri", "Himalayalar", "Sahra Çölü", "Karadeniz", "Pamukkale", ], "sanat": [ "Orhan Pamuk", "Yaşar Kemal", "Mona Lisa", "İzlenimcilik", "Nâzım Hikmet", "Divan edebiyatı", "Caz", "Opera", "Mimar Sinan", ], "teknoloji": [ "Yapay zekâ", "İnternet", "Blok zinciri", "Elektrikli otomobil", "Güneş enerjisi", "Üç boyutlu yazıcı", "Robot", "Bulut bilişim", ], "tip": [ "Diyabet", "Kalp", "Bağışıklık sistemi", "Uyku", "Anestezi", "Antibiyotik", "Aşı", "Vitamin", ], "spor": [ "Futbol", "Olimpiyat Oyunları", "Satranç", "Basketbol", "Maraton", ], "toplum": [ "Demokrasi", "Enflasyon", "Sokrates", "Etik", "Kentleşme", "Küreselleşme", "Anayasa", ], "doga": [ "Bal arısı", "Kelebek", "Mercan resifi", "Dev panda", "Göçmen kuş", "Zeytin", "Kurt", ], } # -------------------------------------------------------------------------- # text cleaning # -------------------------------------------------------------------------- TAG_RE = re.compile(r"<[^>]+>") WS_RE = re.compile(r"\s+") # Turkish abbreviations whose trailing dot must not end a sentence. ABBREV = { "dr", "prof", "doç", "av", "sn", "no", "bkz", "vb", "vs", "yy", "bl", "md", "mah", "cad", "sok", "apt", "st", "mr", "mrs", "ör", "örn", "yrd", "öğr", "gör", "tel", "faks", "alb", "gen", "tuğg", "hz", "sy", "s", } BOILERPLATE = re.compile( r"(devamı için|tıklayın|abone ol|haberin detayları|son dakika haber|" r"i̇şte o anlar|video izle|fotoğraf galeri|reklam)", re.IGNORECASE ) def clean(text): if not text: return "" text = html.unescape(TAG_RE.sub(" ", html.unescape(text))) text = unicodedata.normalize("NFC", text) text = text.replace(" ", " ").replace("​", "") # Wikipedia footnote markers and pronunciation brackets. text = re.sub(r"\[[^\]]*\]", "", text) return WS_RE.sub(" ", text).strip() def split_sentences(text): """Sentence splitter tuned for Turkish: does not break on abbreviations, ordinals (`3. sırada`), or decimals (`1.500`).""" out, buf = [], [] parts = re.split(r"(?<=[.!?…])\s+", text) for part in parts: buf.append(part) stripped = part.rstrip() last = stripped.split()[-1].lower().rstrip(".!?…") if stripped.split() else "" ends_abbrev = last in ABBREV ends_number = bool(re.search(r"\d\.$", stripped)) if not (ends_abbrev or ends_number) and re.search(r"[.!?…]$", stripped): out.append(" ".join(buf).strip()) buf = [] if buf: out.append(" ".join(buf).strip()) return [s for s in out if s] def usable(s, headline=False): """Keep sentences a human could reasonably score. Rejects fragments, walls of text, all-caps clickbait, and site boilerplate.""" if not (35 <= len(s) <= 210): return False if len(s.split()) < 5: return False if BOILERPLATE.search(s): return False letters = [c for c in s if c.isalpha()] if letters and sum(c.isupper() for c in letters) / len(letters) > 0.4: return False if s.count('"') > 4 or "http" in s or "@" in s: return False if not headline and not re.search(r"[.!?…]$", s): return False return True # -------------------------------------------------------------------------- # fetching # -------------------------------------------------------------------------- def get(url, tries=4): """Fetch with exponential backoff. The Wikipedia REST API returns 429 to anonymous clients well below the rate a naive loop hits it at, and a bare request loop silently loses a third of the articles to that.""" delay = 1.0 for attempt in range(tries): req = urllib.request.Request(url, headers={"User-Agent": UA}) try: with urllib.request.urlopen(req, timeout=TIMEOUT) as r: return r.read() except urllib.error.HTTPError as e: if e.code not in (429, 500, 502, 503) or attempt == tries - 1: raise time.sleep(delay) delay *= 2 except Exception: if attempt == tries - 1: raise time.sleep(delay) delay *= 2 def collect_news(): """One row per headline and one per lede. They share a doc_id, so a headline can be paired with its own article's first sentence.""" rows = [] for outlet, category, url in FEEDS: try: root = ET.fromstring(get(url)) except Exception as e: print(f" skip {outlet}/{category}: {type(e).__name__}") continue n = 0 for item in root.iter("item"): if n >= 12: break title = clean(item.findtext("title")) desc = clean(item.findtext("description")) link = clean(item.findtext("link")) if not usable(title, headline=True): continue doc = f"{outlet}-{category}-{n}" rows.append(dict(sentence=title, domain="haber", category=category, source=outlet, doc_id=doc, role="baslik", url=link)) # The lede: first sentence of the description, if it is not just # the headline repeated. for s in split_sentences(desc)[:1]: if usable(s) and s.lower() != title.lower(): rows.append(dict(sentence=s, domain="haber", category=category, source=outlet, doc_id=doc, role="spot", url=link)) n += 1 print(f" {outlet}/{category}: {n} articles") time.sleep(0.3) return rows def collect_wiki(): """First two or three sentences of each article's lead paragraph. Sentences sharing a doc_id are adjacent in the original text.""" rows = [] for category, titles in WIKI.items(): got = 0 for title in titles: slug = urllib.parse.quote(title.replace(" ", "_"), safe="") url = f"https://tr.wikipedia.org/api/rest_v1/page/summary/{slug}" try: d = json.loads(get(url)) except Exception as e: print(f" skip wiki: {title} ({type(e).__name__})") continue extract = clean(d.get("extract", "")) page = d.get("content_urls", {}).get("desktop", {}).get("page", "") doc = f"wiki-{slug}" kept = 0 for i, s in enumerate(split_sentences(extract)): if kept >= 3: break if usable(s): rows.append(dict(sentence=s, domain="vikipedi", category=category, source="wikipedia", doc_id=doc, role=f"lead{i + 1}", url=page)) kept += 1 got += kept > 0 time.sleep(0.6) print(f" wiki/{category}: {got} articles") return rows # -------------------------------------------------------------------------- # same-event clustering # -------------------------------------------------------------------------- TR_LOWER = str.maketrans("IİÎÂÛ", "ıiiau") TOKEN_RE = re.compile(r"[0-9a-zçğıöşü]+") STOP = { "ve", "ile", "için", "bir", "bu", "da", "de", "mi", "mı", "mu", "mü", "ne", "olarak", "sonra", "önce", "kadar", "daha", "en", "gibi", "ama", "fakat", "ancak", "her", "çok", "son", "yeni", "o", "ki", "ise", "veya", "ya", } def keywords(s): toks = TOKEN_RE.findall(s.translate(TR_LOWER).lower()) # Truncate to a 5-char prefix as a crude stemmer: Turkish suffixes make # exact token matching miss "seçimde"/"seçimler"/"seçimin". return {t[:5] for t in toks if len(t) > 3 and t not in STOP} def cluster_events(rows): """Group headlines from different outlets that describe the same story. Single-outlet groups are left unclustered.""" heads = [r for r in rows if r.get("role") == "baslik"] parent = list(range(len(heads))) kws = [keywords(h["sentence"]) for h in heads] # Document frequency over headlines. Without this, unrelated stories get # merged by shared news-desk vocabulary ("sonuçları", "açıklandı", # "sorgulama"). A story is identified by its rare words -- the names, # places and numbers -- so only those may bind a cluster. df = {} for k in kws: for t in k: df[t] = df.get(t, 0) + 1 rare = {t for t, c in df.items() if c <= 4} def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(len(heads)): if len(kws[i]) < 3: continue for j in range(i + 1, len(heads)): if heads[i]["source"] == heads[j]["source"]: continue # same outlet reposting is not independent coverage if len(kws[j]) < 3: continue shared = kws[i] & kws[j] overlap = len(shared) / min(len(kws[i]), len(kws[j])) # Two distinctive words in common, on top of general overlap. if overlap >= 0.4 and len(shared & rare) >= 2: parent[find(i)] = find(j) groups = {} for i in range(len(heads)): groups.setdefault(find(i), []).append(i) n = 0 for members in groups.values(): if len(members) < 2: continue n += 1 for i in members: heads[i]["event_id"] = f"E{n:02d}" # Carry the event id onto that article's lede too. for r in rows: if r["doc_id"] == heads[i]["doc_id"]: r["event_id"] = f"E{n:02d}" return n def main(): print("news feeds:") rows = collect_news() print("wikipedia:") rows += collect_wiki() # Drop near-duplicate sentences (outlets repost, wiki leads echo titles). seen, unique = set(), [] for r in rows: key = " ".join(sorted(keywords(r["sentence"])))[:160] if key and key in seen: continue seen.add(key) r.setdefault("event_id", "") unique.append(r) n_events = cluster_events(unique) for i, r in enumerate(unique, 1): r["id"] = i cols = ["id", "sentence", "domain", "category", "source", "doc_id", "role", "event_id", "url"] with open(HERE / "raw_sentences.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=cols) w.writeheader() w.writerows(unique) by_domain, by_cat = {}, {} for r in unique: by_domain[r["domain"]] = by_domain.get(r["domain"], 0) + 1 by_cat[r["category"]] = by_cat.get(r["category"], 0) + 1 print(f"\n{len(unique)} sentences -> raw_sentences.csv") print(" by domain :", by_domain) print(" by category:", dict(sorted(by_cat.items(), key=lambda x: -x[1]))) print(f" multi-outlet event clusters: {n_events}") if __name__ == "__main__": main()