Skip to content

parse_ind

topic_segmentation.news_dataset.parse_ind

Parse saved pages in data/pages/independent_subheadings/ into data/outputs/ind_segments.json.

is_noise_heading(text: str) -> bool

Source code in src/topic_segmentation/news_dataset/parse_ind.py
74
75
76
def is_noise_heading(text: str) -> bool:
    t = text.lower().strip()
    return len(t) < 3 or any(pat in t for pat in NOISE_PATTERNS)

is_skip_container(el) -> bool

Source code in src/topic_segmentation/news_dataset/parse_ind.py
79
80
81
82
83
84
85
def is_skip_container(el) -> bool:
    if el.name in ("aside", "nav", "form"):
        return True
    cls = set(el.get("class") or [])
    if cls & SKIP_DIV_CLASSES:
        return True
    return False
Source code in src/topic_segmentation/news_dataset/parse_ind.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def is_link_only_list(el) -> bool:
    if el.name not in ("ul", "ol"):
        return False
    items = el.find_all("li", recursive=False)
    if not items:
        return False
    for li in items:
        li_text = li.get_text(" ", strip=True)
        a_text = "".join(a.get_text(" ", strip=True) for a in li.find_all("a"))
        if not li_text or not a_text:
            return False
        if li_text == a_text:
            continue
        if len(a_text) / len(li_text) >= 0.6:
            continue
        return False
    return True

is_trailing_element(el) -> bool

Source code in src/topic_segmentation/news_dataset/parse_ind.py
107
108
109
110
111
112
113
114
115
def is_trailing_element(el) -> bool:
    if el.name in ("h2", "h3", "h4"):
        t = el.get_text(" ", strip=True).lower().rstrip(":")
        if t in TRAILING_HEADINGS:
            return True
    text_lower = el.get_text(" ", strip=True).lower()
    if any(text_lower.startswith(p) for p in TRAILING_TEXT_PREFIXES):
        return True
    return False

clean_inner_html(el) -> str

Source code in src/topic_segmentation/news_dataset/parse_ind.py
118
119
120
121
122
123
124
125
126
127
128
129
130
def clean_inner_html(el) -> str:
    el_copy = copy.deepcopy(el)
    for tag in el_copy.find_all(True):
        if tag.name == "script":
            tag.decompose()
            continue
        for attr in STRIP_ATTRS:
            tag.attrs.pop(attr, None)
        if tag.name == "a" and (tag.get("href") or "").startswith("/"):
            tag["href"] = "https://www.independent.co.uk" + tag["href"]
            tag["target"] = "_blank"
            tag["rel"] = "noopener"
    return el_copy.decode_contents().strip()

collect_elements(container) -> list

Collect content elements from the article body.

Source code in src/topic_segmentation/news_dataset/parse_ind.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def collect_elements(container) -> list:
    """Collect content elements from the article body."""
    elements = []
    for el in container.children:
        if not hasattr(el, "name") or el.name is None:
            continue
        if is_skip_container(el):
            continue

        cls = set(el.get("class") or [])

        # Section subheading div or content list wrapped in sc-kk992l-0
        if el.name == "div" and "sc-kk992l-0" in cls:
            inner_list = el.find(["ul", "ol"])
            inner_head = el.find(["h2", "h3", "h4"])
            if inner_list and not inner_head:
                # Include content lists and skip link-only "Read more" lists.
                if not is_link_only_list(inner_list):
                    elements.append(inner_list)
            else:
                elements.append(el)
            continue

        # Image div (contains a figure with an actual image)
        if el.name == "div" and "image" in cls:
            fig = el.find("figure")
            if fig:
                img = fig.find("img")
                if img and (img.get("src") or "").startswith("http"):
                    elements.append(fig)
            continue

        # Content elements
        if el.name in ("p", "ul", "ol", "blockquote"):
            if not is_link_only_list(el):
                elements.append(el)
            continue

        # Skip unrecognized divs, including ads and empty wrappers.

    return elements

process_article(aid: str, raw_html: str, meta: dict)

Source code in src/topic_segmentation/news_dataset/parse_ind.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def process_article(aid: str, raw_html: str, meta: dict):
    soup = BeautifulSoup(ftfy.fix_text(raw_html), "html.parser")

    article = soup.find("article")
    if not article:
        return None

    # Article header (inside article, contains title/standfirst/hero)
    art_header = article.find("header")

    # Title
    h1 = art_header.find("h1") if art_header else article.find("h1")
    title = h1.get_text(" ", strip=True) if h1 else meta.get("title", "")

    # Standfirst: h2.sc-1cmj4ml-0 inside article header
    standfirst_text = None
    if art_header:
        sf = art_header.find("h2", class_=lambda c: c and "sc-1cmj4ml-0" in c)
        if sf:
            text = sf.get_text(" ", strip=True)
            if text and not text.lower().startswith("sign up"):
                standfirst_text = text

    # Hero image from article header figure
    hero_img_src = None
    hero_img_cap = None
    if art_header:
        fig = art_header.find("figure")
        if fig:
            img = fig.find("img")
            if img and (img.get("src") or "").startswith("http"):
                hero_img_src = img["src"]
                figcap = fig.find("figcaption")
                if figcap:
                    hero_img_cap = figcap.get_text(" ", strip=True)

    # Content div
    main_wrapper = article.find("div", class_=lambda c: c and "main-wrapper" in c)
    if not main_wrapper:
        return None
    content = main_wrapper.find("div", class_=lambda c: c and "sc-jbiisr-0" in c)
    if not content:
        return None

    sentences, html_parts, labels, title_labels = [], [], [], []

    if standfirst_text:
        sentences.append(standfirst_text)
        html_parts.append({"tag": "p", "html": standfirst_text})
        labels.append(0)
        title_labels.append(1)

    if hero_img_src:
        cap_html = f"<figcaption>{hero_img_cap}</figcaption>" if hero_img_cap else ""
        sentences.append(hero_img_cap or "")
        html_parts.append({"tag": "figure", "html": f'<img src="{hero_img_src}" style="max-width:100%">{cap_html}'})
        labels.append(0)
        title_labels.append(0)

    first_elem = not (standfirst_text or hero_img_src)

    for el in collect_elements(content):
        if is_trailing_element(el):
            break

        # Figure (body image)
        if el.name == "figure":
            img = el.find("img")
            if not img:
                continue
            src = img.get("src", "")
            if not src:
                continue
            figcap = el.find("figcaption")
            cap_text = figcap.get_text(" ", strip=True) if figcap else ""
            cap_html = f"<figcaption>{cap_text}</figcaption>" if cap_text else ""
            sentences.append(cap_text)
            html_parts.append({"tag": "figure", "html": f'<img src="{src}" style="max-width:100%">{cap_html}'})
            labels.append(0)
            title_labels.append(0)
            first_elem = False
            continue

        # Section subheading div (sc-kk992l-0)
        if el.name == "div" and "sc-kk992l-0" in set(el.get("class") or []):
            text = el.get_text(" ", strip=True)
            if not text or is_noise_heading(text):
                continue
            if len(text) > 200:
                continue
            inner_head = el.find(["h2", "h3", "h4"])
            tag = inner_head.name if inner_head else "h3"
            sentences.append(text)
            html_parts.append({"tag": tag, "html": text})
            labels.append(0 if first_elem else 1)
            title_labels.append(1)
            first_elem = False
            continue

        text = el.get_text(" ", strip=True)
        if not text:
            continue

        if any(text.lower().startswith(p) for p in SKIP_PARA_PREFIXES):
            continue

        sentences.append(text)
        html_parts.append({"tag": el.name, "html": clean_inner_html(el)})
        labels.append(0)
        title_labels.append(0)
        first_elem = False

    # Remove trailing headings without following content.
    while sentences and title_labels[-1] == 1:
        sentences.pop()
        html_parts.pop()
        labels.pop()
        title_labels.pop()

    if not sentences:
        return None

    return {
        "articleId": aid,
        "outlet": "Independent",
        "title": title,
        "url": meta.get("url", ""),
        "sentences": sentences,
        "html_parts": html_parts,
        "labels": labels,
        "title_labels": title_labels,
        "num_sections": labels.count(1) + 1,
    }

main()

Source code in src/topic_segmentation/news_dataset/parse_ind.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def main():
    with open(ROOT / "data/articles.json", encoding="latin-1") as f:
        all_meta = {a["articleId"]: a for a in json.load(f)}

    results = []
    seen_content: set = set()
    skipped = 0
    for html_file in sorted((ROOT / "data/pages/independent_subheadings").glob("*.html")):
        aid = html_file.stem
        raw = html_file.read_text(encoding="utf-8")
        rec = process_article(aid, raw, all_meta.get(aid, {}))
        if not rec:
            skipped += 1
            continue
        content = (rec.get("title", "") + "".join(rec["sentences"]))
        if content in seen_content:
            skipped += 1
            continue
        seen_content.add(content)
        results.append(rec)

    one_section = sum(1 for r in results if r["num_sections"] == 1)
    results = [r for r in results if r["num_sections"] >= 2]
    print(f"Processed {len(results)} articles ({skipped} skipped/duplicate)")
    print(f"  1 section: {one_section}, 2+ sections: {len(results) - one_section}")

    (ROOT / "data/outputs").mkdir(parents=True, exist_ok=True)
    seg_path = ROOT / "data/outputs/ind_segments.json"
    with open(seg_path, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print(f"Saved {seg_path}")