OmAlve commited on
Commit
466cf28
·
verified ·
1 Parent(s): bfd6805

Copy prepare_data_v2.py from IndexLM-0.6B

Browse files
Files changed (1) hide show
  1. prepare_data_v2.py +897 -0
prepare_data_v2.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prepare DIVERSE IndexLM training data from multiple sources:
3
+
4
+ 1. HtmlRAG-train (real Bing-scraped web HTML) — diverse domains
5
+ 2. MultiHopRAG (news domain) — technology, business, sports, entertainment
6
+ 3. HotpotQA (Wikipedia) — structured QA with supporting facts
7
+
8
+ This avoids the Wikipedia-only bias of the original dataset.
9
+
10
+ Output: Conversational messages for SFT with TRL SFTTrainer
11
+ Format: system + user (indexed HTML blocks + query) → assistant (index intervals)
12
+ """
13
+
14
+ import json
15
+ import random
16
+ import re
17
+ import os
18
+ from datasets import load_dataset, Dataset, DatasetDict
19
+ from collections import defaultdict
20
+ from bs4 import BeautifulSoup
21
+ import html as html_lib
22
+
23
+ random.seed(42)
24
+
25
+ # ============ System Prompts ============
26
+
27
+ SYSTEM_PROMPT_QE = """You are IndexLM, a web content extraction model. Given a webpage split into indexed blocks and a user query, identify which blocks contain content relevant to the query.
28
+
29
+ Each block is formatted as: [i] <tag>content</tag>
30
+ Output the indices of relevant blocks as a Python list of [start, end] intervals (inclusive).
31
+ If no relevant content exists, output 'NA'.
32
+
33
+ Example output: [[2,4],[7,7],[10,12]]"""
34
+
35
+ SYSTEM_PROMPT_ME = """You are IndexLM, a web content extraction model. Given a webpage split into indexed blocks, identify which blocks contain the main content of the page (filtering out navigation, advertisements, sidebars, and other non-content elements).
36
+
37
+ Each block is formatted as: [i] <tag>content</tag>
38
+ Output the indices of main content blocks as a Python list of [start, end] intervals (inclusive).
39
+ If no main content exists, output 'NA'.
40
+
41
+ Example output: [[1,3],[5,8],[11,15]]"""
42
+
43
+ # ============ Noise blocks for injection ============
44
+
45
+ NOISE_BLOCKS_REALISTIC = [
46
+ '<nav>Home | About | Contact | Privacy Policy | Terms of Service</nav>',
47
+ '<div class="ad">Advertisement - Continue Reading Below</div>',
48
+ '<div class="sidebar">Related Articles: Top 10 Facts You Didn\'t Know</div>',
49
+ '<footer>© 2024 All Rights Reserved | Terms of Service | Cookie Policy</footer>',
50
+ '<div class="cookie-banner">This website uses cookies to improve your experience. By continuing to use this site, you consent to our use of cookies. Accept | Manage Preferences</div>',
51
+ '<div class="social-share">Share: <a>Twitter</a> | <a>Facebook</a> | <a>LinkedIn</a> | <a>Reddit</a> | <a>Email</a></div>',
52
+ '<nav class="breadcrumb">Home > Category > Subcategory > Current Article</nav>',
53
+ '<div class="newsletter-signup">Subscribe to our newsletter for the latest updates delivered to your inbox weekly.</div>',
54
+ '<div class="popup-overlay">Sign up for free access to premium content! Enter your email below.</div>',
55
+ '<aside class="trending">Trending Now: Latest breaking news and popular stories from around the web</aside>',
56
+ '<div class="comments-section">Comments (0) — Be the first to comment! Please read our community guidelines before posting.</div>',
57
+ '<div class="author-bio">Written by Staff Reporter | Updated: January 15, 2024 | 5 min read</div>',
58
+ '<div class="pagination">← Previous Article | Page 1 of 3 | Next Article →</div>',
59
+ '<div class="search-bar"><form>Search this site... <button>Go</button></form></div>',
60
+ '<div class="category-menu">Categories: Science | Technology | Health | Business | Sports | Entertainment | Politics</div>',
61
+ '<div class="login-prompt">Already a subscriber? Log in for full access. Not a member? Subscribe now starting at $4.99/month.</div>',
62
+ '<div class="related-articles"><h3>You May Also Like</h3><ul><li>10 Things You Didn\'t Know About...</li><li>Breaking: Latest Update on...</li></ul></div>',
63
+ '<div class="video-embed">Watch: Video player requires JavaScript to be enabled. [Video placeholder]</div>',
64
+ '<div class="breaking-news-ticker">BREAKING: Markets rally on latest economic data | Sports: Championship results | Weather: Storm warning issued</div>',
65
+ '<div class="accessibility">Skip to main content | Skip to navigation | Accessibility statement</div>',
66
+ '<div class="gdpr-notice">We value your privacy. We and our partners use tracking technologies to improve your browsing experience, serve personalized content, and analyze traffic.</div>',
67
+ '<div class="app-download">Download our app for a better reading experience! Available on iOS and Android.</div>',
68
+ '<script>/* Google Analytics tracking code */</script>',
69
+ '<div class="print-notice">This article is available in print edition. Subscribe for home delivery.</div>',
70
+ '<div class="sponsored">Sponsored Content | Advertiser Disclosure: Some links on this page are affiliate links.</div>',
71
+ '<div class="feedback">Was this article helpful? Yes | No | Send Feedback</div>',
72
+ '<div class="language-selector">Language: English | Español | Français | Deutsch | 日本語 | 中文</div>',
73
+ '<div class="site-footer"><ul><li>About Us</li><li>Careers</li><li>Advertise</li><li>Press</li><li>Help Center</li><li>Sitemap</li></ul></div>',
74
+ ]
75
+
76
+
77
+ def indices_to_intervals(indices):
78
+ """Convert a sorted list of indices to intervals [[start,end], ...]"""
79
+ if not indices:
80
+ return "NA"
81
+ indices = sorted(set(indices))
82
+ intervals = []
83
+ start = indices[0]
84
+ end = indices[0]
85
+ for i in indices[1:]:
86
+ if i == end + 1:
87
+ end = i
88
+ else:
89
+ intervals.append([start, end])
90
+ start = i
91
+ end = i
92
+ intervals.append([start, end])
93
+ return json.dumps(intervals)
94
+
95
+
96
+ # ============================================================
97
+ # SOURCE 1: HtmlRAG-train (Real Bing-scraped web HTML)
98
+ # ============================================================
99
+
100
+ def extract_text_content(html_str):
101
+ """Extract visible text from an HTML string."""
102
+ try:
103
+ soup = BeautifulSoup(html_str, 'html.parser')
104
+ return soup.get_text(separator=' ', strip=True)
105
+ except:
106
+ # Fallback: strip tags with regex
107
+ clean = re.sub(r'<[^>]+>', ' ', html_str)
108
+ return re.sub(r'\s+', ' ', clean).strip()
109
+
110
+
111
+ def segment_html_to_blocks(html_content):
112
+ """
113
+ Segment real HTML content into indexed blocks.
114
+ Splits by block-level HTML tags and line boundaries.
115
+ """
116
+ blocks = []
117
+
118
+ # Strategy: split by block-level closing/opening tags
119
+ # HtmlRAG uses tags like <div0>, <p>, <h20>, <li>, etc.
120
+ # Split at positions where block-level tags start
121
+ block_tag_pattern = r'(<(?:div|p|h[1-6]|li|ul|ol|table|tr|td|th|article|section|header|footer|nav|aside|main|blockquote|pre|form|figure|figcaption|details|summary|option|title|button|label|select|textarea|hgroup|dl|dd|dt|caption|thead|tbody|tfoot)\b[^>]*>)'
122
+
123
+ # Also handle HtmlRAG numbered tags like <div0>, <h20>, etc.
124
+ block_tag_pattern_numbered = r'(<(?:div|p|h|li|ul|ol|table|tr|td|th|article|section|header|footer|nav|aside|main|blockquote|pre|form|figure|option|title|button|hgroup)\d*[^>]*>)'
125
+
126
+ # Split content by block-level tags
127
+ parts = re.split(block_tag_pattern_numbered, html_content)
128
+
129
+ current_block = ''
130
+ for part in parts:
131
+ part = part.strip()
132
+ if not part:
133
+ continue
134
+
135
+ # Check if this part is a block-level opening tag
136
+ if re.match(block_tag_pattern_numbered, part):
137
+ # Save previous block if it has content
138
+ if current_block.strip():
139
+ blocks.append(current_block.strip())
140
+ current_block = part
141
+ else:
142
+ current_block += ' ' + part
143
+
144
+ # Don't forget the last block
145
+ if current_block.strip():
146
+ blocks.append(current_block.strip())
147
+
148
+ # If tag-based splitting yields too few blocks, fall back to line-based
149
+ if len(blocks) < 5:
150
+ blocks = []
151
+ lines = html_content.split('\n')
152
+ for line in lines:
153
+ line = line.strip()
154
+ if line and len(line) > 5:
155
+ blocks.append(line)
156
+
157
+ # If still too few, split by multiple tags on same line
158
+ if len(blocks) < 5:
159
+ new_blocks = []
160
+ for block in blocks:
161
+ # Try splitting long blocks by inner tags
162
+ if len(block) > 200:
163
+ inner_parts = re.split(r'(</(?:div|p|h[1-6]|li|td|th|article|section)\d*>)', block)
164
+ current = ''
165
+ for ip in inner_parts:
166
+ current += ip
167
+ if re.match(r'</(?:div|p|h[1-6]|li|td|th|article|section)\d*>', ip):
168
+ if current.strip():
169
+ new_blocks.append(current.strip())
170
+ current = ''
171
+ if current.strip():
172
+ new_blocks.append(current.strip())
173
+ else:
174
+ new_blocks.append(block)
175
+ if len(new_blocks) > len(blocks):
176
+ blocks = new_blocks
177
+
178
+ # Filter: extract text and remove blocks with no meaningful content
179
+ def extract_text_simple(s):
180
+ clean = re.sub(r'<[^>]+>', ' ', s)
181
+ return re.sub(r'\s+', ' ', clean).strip()
182
+
183
+ blocks = [b for b in blocks if len(extract_text_simple(b)) > 5]
184
+
185
+ return blocks
186
+
187
+
188
+ def classify_block_as_noise(block_text):
189
+ """Heuristic: classify if a block is likely noise (nav, ad, etc.)."""
190
+ text_lower = block_text.lower()
191
+ noise_indicators = [
192
+ 'cookie', 'privacy policy', 'terms of service', 'advertisement',
193
+ 'subscribe', 'newsletter', 'sign up', 'log in', 'login',
194
+ 'copyright ©', 'all rights reserved', 'skip to', 'accessibility',
195
+ 'share on twitter', 'share on facebook', 'social media',
196
+ 'related articles', 'you may also like', 'trending now',
197
+ 'app download', 'sponsored content', 'affiliate',
198
+ ]
199
+ nav_patterns = ['<nav', '<footer', '<aside', 'class="ad"', 'class="sidebar"',
200
+ 'class="menu"', 'class="social"', 'class="cookie"']
201
+
202
+ for indicator in noise_indicators:
203
+ if indicator in text_lower:
204
+ return True
205
+ for pattern in nav_patterns:
206
+ if pattern in text_lower:
207
+ return True
208
+ return False
209
+
210
+
211
+ def process_htmlrag_example(row):
212
+ """Convert an HtmlRAG example to IndexLM format."""
213
+ user_content = row['messages'][0]['content']
214
+ assistant_content = row['messages'][1]['content']
215
+ score = row.get('score', 0)
216
+
217
+ # Skip low-quality examples
218
+ if score < 0.5:
219
+ return None
220
+
221
+ # Parse out HTML and question
222
+ parts = user_content.split('**Question**:')
223
+ if len(parts) < 2:
224
+ parts = user_content.split('**Question**')
225
+ if len(parts) < 2:
226
+ return None
227
+
228
+ html_raw = parts[0]
229
+ question_raw = parts[1].strip()
230
+
231
+ # Clean up the HTML marker
232
+ html_raw = html_raw.replace('**HTML**: ```', '').rstrip('`').strip()
233
+
234
+ # Extract just the question (remove the instruction part)
235
+ question = question_raw.split('\n')[0].strip().strip('*').strip()
236
+ if not question:
237
+ return None
238
+
239
+ # Segment HTML into blocks
240
+ blocks = segment_html_to_blocks(html_raw)
241
+ if len(blocks) < 3:
242
+ return None
243
+
244
+ # Get the relevant content from assistant output
245
+ relevant_text = extract_text_content(assistant_content)
246
+ relevant_words = set(relevant_text.lower().split())
247
+
248
+ # Build indexed blocks and find relevant ones
249
+ indexed_blocks = []
250
+ relevant_indices = []
251
+ content_indices = []
252
+
253
+ for idx, block in enumerate(blocks, 1):
254
+ # Determine the best tag for this block
255
+ tag_match = re.match(r'<(\w+)', block)
256
+ if tag_match:
257
+ tag = tag_match.group(1)
258
+ # Normalize numbered tags (div0 -> div, h20 -> h2)
259
+ tag = re.sub(r'\d+$', '', tag)
260
+ if not tag:
261
+ tag = 'div'
262
+ else:
263
+ tag = 'p'
264
+
265
+ text = extract_text_content(block)
266
+ if not text or len(text) < 3:
267
+ continue
268
+
269
+ indexed_blocks.append(f"[{idx}] <{tag}>{text}</{tag}>")
270
+
271
+ # Check if this block is noise
272
+ is_noise = classify_block_as_noise(block)
273
+ if not is_noise:
274
+ content_indices.append(idx)
275
+
276
+ # Check relevance by substring matching with assistant output
277
+ # Use the full relevant text as a search target
278
+ text_lower = text.lower()
279
+ relevant_lower = relevant_text.lower()
280
+
281
+ # Method 1: Check if significant portions of relevant text appear in block
282
+ # Split relevant text into 3-word ngrams and check for matches
283
+ rel_words_list = relevant_lower.split()
284
+ matched = False
285
+
286
+ # Check 3-gram overlap
287
+ for i in range(len(rel_words_list) - 2):
288
+ trigram = ' '.join(rel_words_list[i:i+3])
289
+ if trigram in text_lower:
290
+ matched = True
291
+ break
292
+
293
+ # Also check: does the block text appear as a substring in the relevant text?
294
+ if not matched and len(text) > 15:
295
+ # Check if meaningful portion of block appears in relevant output
296
+ block_sentences = [s.strip() for s in text.split('.') if len(s.strip()) > 10]
297
+ for sent in block_sentences:
298
+ if sent.lower() in relevant_lower:
299
+ matched = True
300
+ break
301
+
302
+ # Also check word overlap with a more lenient threshold
303
+ if not matched:
304
+ block_words = set(text_lower.split())
305
+ if relevant_words and block_words:
306
+ overlap_count = len(block_words & relevant_words)
307
+ # At least 3 content words overlap (excluding stopwords)
308
+ stopwords = {'the','a','an','is','are','was','were','in','on','at','to','for','of','and','or','but','with','by','from','as','it','this','that','be','has','have','had','do','does','did','not','no'}
309
+ content_overlap = len((block_words - stopwords) & (relevant_words - stopwords))
310
+ if content_overlap >= 2:
311
+ matched = True
312
+
313
+ if matched:
314
+ relevant_indices.append(idx)
315
+
316
+ if not indexed_blocks or len(indexed_blocks) < 3:
317
+ return None
318
+
319
+ block_text = "\n".join(indexed_blocks)
320
+
321
+ results = []
322
+
323
+ # Query-relevant extraction example
324
+ if relevant_indices:
325
+ intervals = indices_to_intervals(relevant_indices)
326
+ user_msg = f"URL: https://example.com\nQuery: {question}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of blocks relevant to the query."
327
+ results.append({
328
+ "messages": [
329
+ {"role": "system", "content": SYSTEM_PROMPT_QE},
330
+ {"role": "user", "content": user_msg},
331
+ {"role": "assistant", "content": intervals}
332
+ ],
333
+ "task_type": "query_relevant",
334
+ "source": "htmlrag"
335
+ })
336
+
337
+ # Main content extraction example (30% of the time to balance)
338
+ if content_indices and random.random() < 0.3:
339
+ intervals = indices_to_intervals(content_indices)
340
+ user_msg = f"URL: https://example.com\nTitle: Web Page\n\nBlocks:\n{block_text}\n\nOutput the index intervals of main content blocks."
341
+ results.append({
342
+ "messages": [
343
+ {"role": "system", "content": SYSTEM_PROMPT_ME},
344
+ {"role": "user", "content": user_msg},
345
+ {"role": "assistant", "content": intervals}
346
+ ],
347
+ "task_type": "main_content",
348
+ "source": "htmlrag"
349
+ })
350
+
351
+ return results
352
+
353
+
354
+ def load_htmlrag_data():
355
+ """Load and convert HtmlRAG-train data."""
356
+ print("Loading HtmlRAG-train (real web HTML)...")
357
+
358
+ # Use 4k and 8k token variants - good balance of context
359
+ files = [
360
+ 'nq-4k.jsonl', 'nq-8k.jsonl',
361
+ 'asqa-4k.jsonl', 'asqa-8k.jsonl',
362
+ 'trivia-qa-4k.jsonl', 'trivia-qa-8k.jsonl',
363
+ 'musique-4k.jsonl', 'musique-8k.jsonl',
364
+ 'hotpot-qa-4k.jsonl', 'hotpot-qa-8k.jsonl',
365
+ ]
366
+
367
+ all_examples = []
368
+
369
+ for file in files:
370
+ print(f" Processing {file}...")
371
+ try:
372
+ ds = load_dataset('zstanjj/HtmlRAG-train', data_files=file, split='train')
373
+ count = 0
374
+ for row in ds:
375
+ results = process_htmlrag_example(row)
376
+ if results:
377
+ all_examples.extend(results)
378
+ count += len(results)
379
+ print(f" Got {count} examples from {file}")
380
+ except Exception as e:
381
+ print(f" Error loading {file}: {e}")
382
+
383
+ print(f" Total HtmlRAG examples: {len(all_examples)}")
384
+ return all_examples
385
+
386
+
387
+ # ============================================================
388
+ # SOURCE 2: MultiHopRAG (News domain)
389
+ # ============================================================
390
+
391
+ def process_multihoprag():
392
+ """Convert MultiHopRAG news articles into IndexLM format."""
393
+ print("Loading MultiHopRAG (news domain)...")
394
+
395
+ corpus = load_dataset("yixuantt/MultiHopRAG", name="corpus", split="train")
396
+ queries = load_dataset("yixuantt/MultiHopRAG", name="MultiHopRAG", split="train")
397
+
398
+ # Build URL->article lookup
399
+ url_to_article = {}
400
+ for article in corpus:
401
+ url_to_article[article['url']] = article
402
+
403
+ all_examples = []
404
+
405
+ for q_row in queries:
406
+ query = q_row['query']
407
+ evidence_list = q_row['evidence_list']
408
+
409
+ for evidence in evidence_list:
410
+ url = evidence.get('url', '')
411
+ fact = evidence.get('fact', '')
412
+
413
+ if url not in url_to_article or not fact:
414
+ continue
415
+
416
+ article = url_to_article[url]
417
+ title = article.get('title', 'News Article')
418
+ body = article.get('body', '')
419
+ source = article.get('source', 'Unknown')
420
+ category = article.get('category', 'general')
421
+
422
+ if not body or len(body) < 100:
423
+ continue
424
+
425
+ # Split article body into paragraphs
426
+ paragraphs = [p.strip() for p in body.split('\n') if p.strip() and len(p.strip()) > 20]
427
+ if not paragraphs:
428
+ continue
429
+
430
+ # Build indexed blocks with realistic web structure
431
+ blocks = []
432
+ content_indices = []
433
+ relevant_indices = []
434
+ idx = 1
435
+
436
+ # Add realistic header noise
437
+ num_header = random.randint(1, 3)
438
+ for _ in range(num_header):
439
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
440
+ idx += 1
441
+
442
+ # Article title
443
+ blocks.append(f"[{idx}] <h1>{title}</h1>")
444
+ content_indices.append(idx)
445
+ idx += 1
446
+
447
+ # Author/date line
448
+ author = article.get('author', 'Staff Writer')
449
+ published = article.get('published_at', '2024-01-01')
450
+ blocks.append(f"[{idx}] <div class=\"byline\">By {author} | {source} | {published} | Category: {category}</div>")
451
+ content_indices.append(idx)
452
+ idx += 1
453
+
454
+ # Article paragraphs
455
+ fact_words = set(fact.lower().split())
456
+
457
+ for para in paragraphs:
458
+ # Determine tag
459
+ if len(para) < 60 and not para.endswith('.'):
460
+ tag = 'h2'
461
+ else:
462
+ tag = 'p'
463
+
464
+ blocks.append(f"[{idx}] <{tag}>{para}</{tag}>")
465
+ content_indices.append(idx)
466
+
467
+ # Check if paragraph contains the evidence fact
468
+ para_words = set(para.lower().split())
469
+ overlap = len(para_words & fact_words)
470
+ if overlap > 5 or (fact_words and overlap / len(fact_words) > 0.3):
471
+ relevant_indices.append(idx)
472
+
473
+ idx += 1
474
+
475
+ # Occasional mid-article noise
476
+ if random.random() < 0.15:
477
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
478
+ idx += 1
479
+
480
+ # Footer noise
481
+ num_footer = random.randint(1, 4)
482
+ for _ in range(num_footer):
483
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
484
+ idx += 1
485
+
486
+ block_text = "\n".join(blocks)
487
+
488
+ # Query-relevant extraction
489
+ if relevant_indices:
490
+ intervals = indices_to_intervals(relevant_indices)
491
+ user_msg = f"URL: {url}\nQuery: {query}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of blocks relevant to the query."
492
+ all_examples.append({
493
+ "messages": [
494
+ {"role": "system", "content": SYSTEM_PROMPT_QE},
495
+ {"role": "user", "content": user_msg},
496
+ {"role": "assistant", "content": intervals}
497
+ ],
498
+ "task_type": "query_relevant",
499
+ "source": "multihoprag_news"
500
+ })
501
+
502
+ # Main content extraction
503
+ if content_indices and random.random() < 0.4:
504
+ intervals = indices_to_intervals(content_indices)
505
+ user_msg = f"URL: {url}\nTitle: {title}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of main content blocks."
506
+ all_examples.append({
507
+ "messages": [
508
+ {"role": "system", "content": SYSTEM_PROMPT_ME},
509
+ {"role": "user", "content": user_msg},
510
+ {"role": "assistant", "content": intervals}
511
+ ],
512
+ "task_type": "main_content",
513
+ "source": "multihoprag_news"
514
+ })
515
+
516
+ print(f" Total MultiHopRAG examples: {len(all_examples)}")
517
+ return all_examples
518
+
519
+
520
+ # ============================================================
521
+ # SOURCE 3: HotpotQA (Wikipedia - but balanced as minority)
522
+ # ============================================================
523
+
524
+ def process_hotpotqa():
525
+ """Process HotpotQA — kept but as a smaller proportion."""
526
+ print("Loading HotpotQA (Wikipedia domain)...")
527
+ ds = load_dataset("hotpotqa/hotpot_qa", "distractor", split="train")
528
+
529
+ # Reduced from 15K to 5K — wiki should be minority source
530
+ num_samples = min(5000, len(ds))
531
+ ds = ds.shuffle(seed=42).select(range(num_samples))
532
+
533
+ all_examples = []
534
+ skipped = 0
535
+
536
+ for i, row in enumerate(ds):
537
+ if i % 1000 == 0:
538
+ print(f" Processing {i}/{num_samples}...")
539
+
540
+ try:
541
+ titles = row['context']['title']
542
+ sentences_list = row['context']['sentences']
543
+ sf = row['supporting_facts']
544
+
545
+ sf_lookup = defaultdict(set)
546
+ for title, sent_id in zip(sf['title'], sf['sent_id']):
547
+ sf_lookup[title].add(sent_id)
548
+
549
+ blocks = []
550
+ relevant_indices = []
551
+ content_indices = []
552
+ idx = 1
553
+
554
+ # Header noise
555
+ if random.random() < 0.6:
556
+ for _ in range(random.randint(1, 3)):
557
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
558
+ idx += 1
559
+
560
+ for doc_idx, (title, sentences) in enumerate(zip(titles, sentences_list)):
561
+ blocks.append(f"[{idx}] <h2>{title}</h2>")
562
+ content_indices.append(idx)
563
+ if title in sf_lookup:
564
+ relevant_indices.append(idx)
565
+ idx += 1
566
+
567
+ for sent_idx, sentence in enumerate(sentences):
568
+ sentence = sentence.strip()
569
+ if not sentence:
570
+ continue
571
+ blocks.append(f"[{idx}] <p>{sentence}</p>")
572
+ content_indices.append(idx)
573
+ if title in sf_lookup and sent_idx in sf_lookup[title]:
574
+ relevant_indices.append(idx)
575
+ idx += 1
576
+
577
+ if random.random() < 0.3 and doc_idx < len(titles) - 1:
578
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
579
+ idx += 1
580
+
581
+ # Footer noise
582
+ if random.random() < 0.6:
583
+ for _ in range(random.randint(1, 3)):
584
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
585
+ idx += 1
586
+
587
+ if len(relevant_indices) < 1:
588
+ skipped += 1
589
+ continue
590
+
591
+ block_text = "\n".join(blocks)
592
+
593
+ # QE example
594
+ intervals = indices_to_intervals(relevant_indices)
595
+ user_msg = f"URL: https://en.wikipedia.org\nQuery: {row['question']}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of blocks relevant to the query."
596
+ all_examples.append({
597
+ "messages": [
598
+ {"role": "system", "content": SYSTEM_PROMPT_QE},
599
+ {"role": "user", "content": user_msg},
600
+ {"role": "assistant", "content": intervals}
601
+ ],
602
+ "task_type": "query_relevant",
603
+ "source": "hotpotqa_wiki"
604
+ })
605
+
606
+ # ME example (less frequent - wiki is minority)
607
+ if random.random() < 0.3:
608
+ intervals = indices_to_intervals(content_indices)
609
+ user_msg = f"URL: https://en.wikipedia.org\nTitle: {titles[0]}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of main content blocks."
610
+ all_examples.append({
611
+ "messages": [
612
+ {"role": "system", "content": SYSTEM_PROMPT_ME},
613
+ {"role": "user", "content": user_msg},
614
+ {"role": "assistant", "content": intervals}
615
+ ],
616
+ "task_type": "main_content",
617
+ "source": "hotpotqa_wiki"
618
+ })
619
+
620
+ except Exception as e:
621
+ skipped += 1
622
+ continue
623
+
624
+ print(f" Total HotpotQA examples: {len(all_examples)} ({skipped} skipped)")
625
+ return all_examples
626
+
627
+
628
+ # ============================================================
629
+ # SOURCE 4: MS MARCO (Diverse web QA)
630
+ # ============================================================
631
+
632
+ def process_msmarco():
633
+ """Process MS MARCO for diverse web domain QA examples."""
634
+ print("Loading MS MARCO (diverse web QA)...")
635
+
636
+ try:
637
+ ds = load_dataset("microsoft/ms_marco", "v1.1", split="train")
638
+ # Sample a manageable subset
639
+ num_samples = min(5000, len(ds))
640
+ ds = ds.shuffle(seed=99).select(range(num_samples))
641
+ except Exception as e:
642
+ print(f" Could not load MS MARCO: {e}")
643
+ return []
644
+
645
+ all_examples = []
646
+
647
+ for i, row in enumerate(ds):
648
+ if i % 1000 == 0:
649
+ print(f" Processing {i}/{num_samples}...")
650
+
651
+ try:
652
+ query = row['query']
653
+ passages = row['passages']
654
+
655
+ if not passages or not passages.get('passage_text'):
656
+ continue
657
+
658
+ passage_texts = passages['passage_text']
659
+ is_selected = passages.get('is_selected', [0] * len(passage_texts))
660
+
661
+ if not any(is_selected):
662
+ continue
663
+
664
+ # Build blocks from passages (these are real web snippets from Bing)
665
+ blocks = []
666
+ relevant_indices = []
667
+ content_indices = []
668
+ idx = 1
669
+
670
+ # Header noise
671
+ if random.random() < 0.5:
672
+ for _ in range(random.randint(1, 2)):
673
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
674
+ idx += 1
675
+
676
+ for p_idx, (text, selected) in enumerate(zip(passage_texts, is_selected)):
677
+ text = text.strip()
678
+ if not text:
679
+ continue
680
+
681
+ # Simulate different content types
682
+ if p_idx == 0 and random.random() < 0.3:
683
+ tag = 'h1'
684
+ elif len(text) < 80:
685
+ tag = random.choice(['h2', 'h3', 'strong'])
686
+ else:
687
+ tag = 'p'
688
+
689
+ blocks.append(f"[{idx}] <{tag}>{text}</{tag}>")
690
+ content_indices.append(idx)
691
+
692
+ if selected:
693
+ relevant_indices.append(idx)
694
+ idx += 1
695
+
696
+ # Between-passage noise
697
+ if random.random() < 0.2:
698
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
699
+ idx += 1
700
+
701
+ # Footer noise
702
+ if random.random() < 0.5:
703
+ for _ in range(random.randint(1, 2)):
704
+ blocks.append(f"[{idx}] {random.choice(NOISE_BLOCKS_REALISTIC)}")
705
+ idx += 1
706
+
707
+ if not relevant_indices or len(blocks) < 3:
708
+ continue
709
+
710
+ block_text = "\n".join(blocks)
711
+
712
+ # QE example
713
+ intervals = indices_to_intervals(relevant_indices)
714
+ query_type = row.get('query_type', 'general')
715
+ user_msg = f"URL: https://www.bing.com/search\nQuery: {query}\n\nBlocks:\n{block_text}\n\nOutput the index intervals of blocks relevant to the query."
716
+ all_examples.append({
717
+ "messages": [
718
+ {"role": "system", "content": SYSTEM_PROMPT_QE},
719
+ {"role": "user", "content": user_msg},
720
+ {"role": "assistant", "content": intervals}
721
+ ],
722
+ "task_type": "query_relevant",
723
+ "source": f"msmarco_{query_type}"
724
+ })
725
+
726
+ except Exception as e:
727
+ continue
728
+
729
+ print(f" Total MS MARCO examples: {len(all_examples)}")
730
+ return all_examples
731
+
732
+
733
+ # ============================================================
734
+ # NA Examples (no relevant content)
735
+ # ============================================================
736
+
737
+ def create_na_examples(all_examples):
738
+ """Create NA examples by mismatching queries with pages."""
739
+ print("Creating NA examples (mismatched query-page pairs)...")
740
+
741
+ # Get QE examples
742
+ qe_examples = [e for e in all_examples if e['task_type'] == 'query_relevant']
743
+
744
+ if len(qe_examples) < 100:
745
+ print(" Too few QE examples for NA generation")
746
+ return []
747
+
748
+ na_examples = []
749
+
750
+ for i in range(min(500, len(qe_examples) // 5)):
751
+ # Pick two random QE examples
752
+ idx_a = random.randint(0, len(qe_examples) - 1)
753
+ idx_b = (idx_a + random.randint(100, len(qe_examples) - 1)) % len(qe_examples)
754
+
755
+ # Use query from A, blocks from B
756
+ msgs_a = qe_examples[idx_a]['messages']
757
+ msgs_b = qe_examples[idx_b]['messages']
758
+
759
+ # Extract query from A
760
+ user_a = msgs_a[1]['content']
761
+ query_match = re.search(r'Query: (.+?)(\n|$)', user_a)
762
+ if not query_match:
763
+ continue
764
+ query = query_match.group(1).strip()
765
+
766
+ # Extract blocks from B
767
+ user_b = msgs_b[1]['content']
768
+ blocks_match = re.search(r'Blocks:\n(.+?)(\n\nOutput)', user_b, re.DOTALL)
769
+ if not blocks_match:
770
+ continue
771
+ blocks = blocks_match.group(1)
772
+
773
+ user_msg = f"URL: https://example.com\nQuery: {query}\n\nBlocks:\n{blocks}\n\nOutput the index intervals of blocks relevant to the query."
774
+ na_examples.append({
775
+ "messages": [
776
+ {"role": "system", "content": SYSTEM_PROMPT_QE},
777
+ {"role": "user", "content": user_msg},
778
+ {"role": "assistant", "content": "NA"}
779
+ ],
780
+ "task_type": "query_relevant_na",
781
+ "source": "mismatched"
782
+ })
783
+
784
+ print(f" Created {len(na_examples)} NA examples")
785
+ return na_examples
786
+
787
+
788
+ # ============================================================
789
+ # Main Pipeline
790
+ # ============================================================
791
+
792
+ def main():
793
+ print("=" * 60)
794
+ print("Building DIVERSE IndexLM Training Data")
795
+ print("=" * 60)
796
+
797
+ # Collect from all sources
798
+ htmlrag_examples = load_htmlrag_data() # Real web HTML (primary)
799
+ multihoprag_examples = process_multihoprag() # News domain
800
+ hotpotqa_examples = process_hotpotqa() # Wikipedia (minority)
801
+ msmarco_examples = process_msmarco() # Diverse web QA
802
+
803
+ # Combine
804
+ all_examples = htmlrag_examples + multihoprag_examples + hotpotqa_examples + msmarco_examples
805
+
806
+ # Add NA examples
807
+ na_examples = create_na_examples(all_examples)
808
+ all_examples.extend(na_examples)
809
+
810
+ random.shuffle(all_examples)
811
+
812
+ # Print composition
813
+ print(f"\n{'='*60}")
814
+ print(f"Total examples: {len(all_examples)}")
815
+
816
+ source_counts = defaultdict(int)
817
+ type_counts = defaultdict(int)
818
+ for ex in all_examples:
819
+ source_counts[ex.get('source', 'unknown')] += 1
820
+ type_counts[ex['task_type']] += 1
821
+
822
+ print("\nBy source:")
823
+ for s, c in sorted(source_counts.items(), key=lambda x: -x[1]):
824
+ pct = c / len(all_examples) * 100
825
+ print(f" {s}: {c} ({pct:.1f}%)")
826
+
827
+ print("\nBy task type:")
828
+ for t, c in sorted(type_counts.items(), key=lambda x: -x[1]):
829
+ pct = c / len(all_examples) * 100
830
+ print(f" {t}: {c} ({pct:.1f}%)")
831
+
832
+ # Check token lengths
833
+ print("\nChecking token lengths...")
834
+ from transformers import AutoTokenizer
835
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
836
+
837
+ lengths = []
838
+ for ex in random.sample(all_examples, min(500, len(all_examples))):
839
+ text = tokenizer.apply_chat_template(ex['messages'], tokenize=False)
840
+ tokens = tokenizer.encode(text)
841
+ lengths.append(len(tokens))
842
+
843
+ print(f"Token length stats (sample of {len(lengths)}):")
844
+ print(f" Min: {min(lengths)}, Max: {max(lengths)}")
845
+ print(f" Mean: {sum(lengths)/len(lengths):.0f}, Median: {sorted(lengths)[len(lengths)//2]}")
846
+
847
+ # Filter by length
848
+ MAX_LEN = 4096
849
+ filtered = []
850
+ too_long = 0
851
+ for ex in all_examples:
852
+ text = tokenizer.apply_chat_template(ex['messages'], tokenize=False)
853
+ tokens = tokenizer.encode(text)
854
+ if len(tokens) <= MAX_LEN:
855
+ filtered.append(ex)
856
+ else:
857
+ too_long += 1
858
+
859
+ print(f"\nFiltered: {too_long} examples too long (>{MAX_LEN} tokens)")
860
+ print(f"Final dataset size: {len(filtered)}")
861
+
862
+ # Final composition
863
+ final_source_counts = defaultdict(int)
864
+ for ex in filtered:
865
+ final_source_counts[ex.get('source', 'unknown')] += 1
866
+ print("\nFinal composition by source:")
867
+ for s, c in sorted(final_source_counts.items(), key=lambda x: -x[1]):
868
+ pct = c / len(filtered) * 100
869
+ print(f" {s}: {c} ({pct:.1f}%)")
870
+
871
+ # Split
872
+ random.shuffle(filtered)
873
+ eval_size = min(500, len(filtered) // 10)
874
+ train_data = filtered[:-eval_size]
875
+ eval_data = filtered[-eval_size:]
876
+
877
+ print(f"\nTrain: {len(train_data)}, Eval: {len(eval_data)}")
878
+
879
+ # Create HF datasets
880
+ train_ds = Dataset.from_list([{"messages": ex["messages"]} for ex in train_data])
881
+ eval_ds = Dataset.from_list([{"messages": ex["messages"]} for ex in eval_data])
882
+
883
+ # Save locally
884
+ train_ds.save_to_disk("/app/indexlm_train_v2")
885
+ eval_ds.save_to_disk("/app/indexlm_eval_v2")
886
+
887
+ # Push to Hub
888
+ ds_dict = DatasetDict({"train": train_ds, "eval": eval_ds})
889
+ ds_dict.push_to_hub("OmAlve/indexlm-training-data", token=os.environ.get("HF_TOKEN"))
890
+
891
+ print(f"\n{'='*60}")
892
+ print("Done! Dataset pushed to OmAlve/indexlm-training-data")
893
+ print(f"{'='*60}")
894
+
895
+
896
+ if __name__ == "__main__":
897
+ main()