Amvhunt commited on
Commit
2f46ffb
·
verified ·
1 Parent(s): afda734

Upload tarot_labyrinthos_scraper_rag_sft_nlp_pipeline.py

Browse files
tarot_labyrinthos_scraper_rag_sft_nlp_pipeline.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Tarot Labyrinthos Dataset Builder (MAX)
4
+
5
+ This script scrapes labyrinthos.co tarot meanings pages and generates:
6
+
7
+ 1) FULL MASTER JSON (raw structured dump)
8
+ output/tarot_cards_labyrinthos_full.json
9
+
10
+ 2) RAG DATASET (chunked JSONL)
11
+ output/rag_chunks.jsonl
12
+
13
+ 3) SFT TRAINING DATASET (ChatML-style JSONL)
14
+ output/train_sft.jsonl
15
+
16
+ 4) NLP DATASETS (classification/NER-like + keyword normalization)
17
+ output/nlp_intents.jsonl
18
+ output/nlp_keywords.jsonl
19
+
20
+ Notes:
21
+ - This script is designed to be robust against HTML changes.
22
+ - It uses heading-based extraction (h2/h3) + fallback regex extraction.
23
+ - It includes throttling to reduce ban risk.
24
+
25
+ Requirements:
26
+ pip install requests beautifulsoup4 lxml tqdm
27
+
28
+ Run:
29
+ python tarot_labyrinthos_pipeline.py
30
+
31
+ """
32
+
33
+ import os
34
+ import re
35
+ import json
36
+ import time
37
+ import random
38
+ import hashlib
39
+ import requests
40
+ from bs4 import BeautifulSoup
41
+ from tqdm import tqdm
42
+
43
+
44
+ BASE = "https://labyrinthos.co"
45
+ LIST_URL = "https://labyrinthos.co/blogs/tarot-card-meanings-list"
46
+
47
+ OUT_DIR = "output"
48
+
49
+ FULL_JSON = os.path.join(OUT_DIR, "tarot_cards_labyrinthos_full.json")
50
+ RAG_JSONL = os.path.join(OUT_DIR, "rag_chunks.jsonl")
51
+ SFT_JSONL = os.path.join(OUT_DIR, "train_sft.jsonl")
52
+
53
+ NLP_INTENTS_JSONL = os.path.join(OUT_DIR, "nlp_intents.jsonl")
54
+ NLP_KEYWORDS_JSONL = os.path.join(OUT_DIR, "nlp_keywords.jsonl")
55
+
56
+ HEADERS = {
57
+ "User-Agent": (
58
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
59
+ "(KHTML, like Gecko) Chrome/122.0 Safari/537.36"
60
+ )
61
+ }
62
+
63
+
64
+ # ----------------------------
65
+ # Utils
66
+ # ----------------------------
67
+
68
+ def clean_text(text: str) -> str:
69
+ if not text:
70
+ return ""
71
+ text = re.sub(r"\r", "", text)
72
+ text = re.sub(r"[ \t]+", " ", text)
73
+ text = re.sub(r"\n{3,}", "\n\n", text)
74
+ return text.strip()
75
+
76
+
77
+ def slugify(name: str) -> str:
78
+ s = name.lower().strip()
79
+ s = re.sub(r"[’']", "", s)
80
+ s = re.sub(r"[^a-z0-9]+", "-", s)
81
+ s = re.sub(r"-{2,}", "-", s)
82
+ return s.strip("-")
83
+
84
+
85
+ def safe_sleep():
86
+ # Anti-ban: jittered sleep
87
+ time.sleep(random.uniform(0.7, 1.6))
88
+
89
+
90
+ def sha1_id(text: str) -> str:
91
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16]
92
+
93
+
94
+ # ----------------------------
95
+ # Networking
96
+ # ----------------------------
97
+
98
+ def request_html(url: str, retries: int = 6) -> str:
99
+ last_err = None
100
+
101
+ for attempt in range(retries):
102
+ try:
103
+ r = requests.get(url, headers=HEADERS, timeout=60)
104
+
105
+ if r.status_code == 429:
106
+ # rate limited
107
+ time.sleep(8 + attempt * 2)
108
+ continue
109
+
110
+ if r.status_code >= 500:
111
+ time.sleep(4 + attempt)
112
+ continue
113
+
114
+ r.raise_for_status()
115
+ return r.text
116
+
117
+ except Exception as e:
118
+ last_err = e
119
+ time.sleep(2 + attempt)
120
+
121
+ raise last_err
122
+
123
+
124
+ # ----------------------------
125
+ # Scraping
126
+ # ----------------------------
127
+
128
+ def get_card_links() -> list:
129
+ html = request_html(LIST_URL)
130
+ soup = BeautifulSoup(html, "lxml")
131
+
132
+ links = set()
133
+
134
+ for a in soup.select("a[href]"):
135
+ href = a.get("href", "").strip()
136
+
137
+ # Example:
138
+ # /blogs/tarot-card-meanings-list/the-tower-meaning-major-arcana-tarot-card-meanings
139
+ if href.startswith("/blogs/tarot-card-meanings-list/") and "meaning" in href:
140
+ links.add(BASE + href)
141
+
142
+ return sorted(list(links))
143
+
144
+
145
+ def extract_article_container(soup: BeautifulSoup):
146
+ # Try known containers
147
+ candidates = []
148
+
149
+ for selector in ["article", ".rte", ".article__content", ".blog__content", ".main-content"]:
150
+ node = soup.select_one(selector)
151
+ if node:
152
+ txt = node.get_text("\n", strip=True)
153
+ if len(txt) > 500:
154
+ candidates.append((len(txt), node))
155
+
156
+ if candidates:
157
+ candidates.sort(key=lambda x: x[0], reverse=True)
158
+ return candidates[0][1]
159
+
160
+ # fallback
161
+ return soup
162
+
163
+
164
+ def normalize_heading(h: str) -> str:
165
+ if not h:
166
+ return ""
167
+ h = clean_text(h).lower()
168
+ h = re.sub(r"[^a-z0-9\s]", "", h)
169
+ h = re.sub(r"\s+", " ", h).strip()
170
+ return h
171
+
172
+
173
+ def extract_sections_from_html(container) -> dict:
174
+ """
175
+ Splits article into sections using headings (h1/h2/h3).
176
+ Returns dict: {section_title: section_text}
177
+
178
+ This is the key part that makes Love/Career/Health parsing possible.
179
+ """
180
+
181
+ sections = {}
182
+ current_title = "main"
183
+ buffer = []
184
+
185
+ def flush():
186
+ nonlocal buffer, current_title
187
+ if buffer:
188
+ content = clean_text("\n".join(buffer))
189
+ if content:
190
+ if current_title in sections:
191
+ sections[current_title] += "\n\n" + content
192
+ else:
193
+ sections[current_title] = content
194
+ buffer = []
195
+
196
+ for elem in container.find_all(["h1", "h2", "h3", "p", "ul", "ol", "blockquote"], recursive=True):
197
+ if elem.name in ["h1", "h2", "h3"]:
198
+ flush()
199
+ current_title = normalize_heading(elem.get_text(" ", strip=True))
200
+ else:
201
+ text = elem.get_text("\n", strip=True)
202
+ if text:
203
+ buffer.append(text)
204
+
205
+ flush()
206
+ return sections
207
+
208
+
209
+ def parse_keywords_from_text(text: str) -> str:
210
+ if not text:
211
+ return ""
212
+
213
+ m = re.search(r"(keywords|key words)\s*[:\-]\s*(.+)", text, re.IGNORECASE)
214
+ if m:
215
+ return clean_text(m.group(2))
216
+
217
+ return ""
218
+
219
+
220
+ def pick_section(sections: dict, keys: list) -> str:
221
+ for k in keys:
222
+ nk = normalize_heading(k)
223
+ for title, content in sections.items():
224
+ if nk in title:
225
+ return content
226
+ return ""
227
+
228
+
229
+ # ----------------------------
230
+ # Tarot card metadata guessing
231
+ # ----------------------------
232
+
233
+ def guess_arcana_and_suit(name: str):
234
+ n = name.lower().strip()
235
+
236
+ major_names = {
237
+ "the fool", "the magician", "the high priestess", "the empress", "the emperor",
238
+ "the hierophant", "the lovers", "the chariot", "strength", "the hermit",
239
+ "wheel of fortune", "justice", "the hanged man", "death", "temperance",
240
+ "the devil", "the tower", "the star", "the moon", "the sun",
241
+ "judgement", "judgment", "the world"
242
+ }
243
+
244
+ if n in major_names:
245
+ return "Major Arcana", None, "major"
246
+
247
+ if " of wands" in n:
248
+ return "Minor Arcana", "Wands", "minor"
249
+ if " of cups" in n:
250
+ return "Minor Arcana", "Cups", "minor"
251
+ if " of swords" in n:
252
+ return "Minor Arcana", "Swords", "minor"
253
+ if " of pentacles" in n:
254
+ return "Minor Arcana", "Pentacles", "minor"
255
+
256
+ return "Major Arcana", None, "major"
257
+
258
+
259
+ def guess_value(name: str) -> int:
260
+ major_map = {
261
+ "the fool": 0,
262
+ "the magician": 1,
263
+ "the high priestess": 2,
264
+ "the empress": 3,
265
+ "the emperor": 4,
266
+ "the hierophant": 5,
267
+ "the lovers": 6,
268
+ "the chariot": 7,
269
+ "strength": 8,
270
+ "the hermit": 9,
271
+ "wheel of fortune": 10,
272
+ "justice": 11,
273
+ "the hanged man": 12,
274
+ "death": 13,
275
+ "temperance": 14,
276
+ "the devil": 15,
277
+ "the tower": 16,
278
+ "the star": 17,
279
+ "the moon": 18,
280
+ "the sun": 19,
281
+ "judgement": 20,
282
+ "judgment": 20,
283
+ "the world": 21
284
+ }
285
+
286
+ n = name.lower().strip()
287
+ if n in major_map:
288
+ return major_map[n]
289
+
290
+ if n.startswith("ace of"):
291
+ return 1
292
+ if n.startswith("two of"):
293
+ return 2
294
+ if n.startswith("three of"):
295
+ return 3
296
+ if n.startswith("four of"):
297
+ return 4
298
+ if n.startswith("five of"):
299
+ return 5
300
+ if n.startswith("six of"):
301
+ return 6
302
+ if n.startswith("seven of"):
303
+ return 7
304
+ if n.startswith("eight of"):
305
+ return 8
306
+ if n.startswith("nine of"):
307
+ return 9
308
+ if n.startswith("ten of"):
309
+ return 10
310
+ if n.startswith("page of"):
311
+ return 11
312
+ if n.startswith("knight of"):
313
+ return 12
314
+ if n.startswith("queen of"):
315
+ return 13
316
+ if n.startswith("king of"):
317
+ return 14
318
+
319
+ return -1
320
+
321
+
322
+ # ----------------------------
323
+ # Main parser per card
324
+ # ----------------------------
325
+
326
+ def parse_card_page(url: str):
327
+ html = request_html(url)
328
+ soup = BeautifulSoup(html, "lxml")
329
+
330
+ h1 = soup.find("h1")
331
+ if not h1:
332
+ return None
333
+
334
+ title = clean_text(h1.get_text(" ", strip=True))
335
+
336
+ container = extract_article_container(soup)
337
+ sections = extract_sections_from_html(container)
338
+
339
+ full_text = clean_text(container.get_text("\n", strip=True))
340
+ keywords = parse_keywords_from_text(full_text)
341
+
342
+ # Core meanings
343
+ upright = pick_section(sections, ["upright meaning", "upright"])
344
+ reversed_ = pick_section(sections, ["reversed meaning", "reversed"])
345
+
346
+ # Extended meaning sections
347
+ symbolism = pick_section(sections, ["symbolism", "symbols"])
348
+ correspondences = pick_section(sections, ["correspondences", "astrology", "element"])
349
+ historical = pick_section(sections, ["history", "historical"])
350
+ psychological = pick_section(sections, ["psychological", "psychology"])
351
+
352
+ love = pick_section(sections, ["love meaning", "love tarot meaning", "love"])
353
+ career = pick_section(sections, ["career meaning", "career"])
354
+ money = pick_section(sections, ["money meaning", "finance meaning", "finances", "money"])
355
+ health = pick_section(sections, ["health meaning", "health"])
356
+ spirituality = pick_section(sections, ["spiritual meaning", "spirituality meaning", "spirituality"])
357
+
358
+ faq = pick_section(sections, ["faq", "questions"])
359
+
360
+ # Description heuristic: first long paragraph
361
+ paragraphs = [p.strip() for p in full_text.split("\n") if len(p.strip()) > 70]
362
+ description = paragraphs[0] if paragraphs else ""
363
+
364
+ arcana, suit, ctype = guess_arcana_and_suit(title)
365
+ value = guess_value(title)
366
+
367
+ card = {
368
+ "slug": slugify(title),
369
+ "name": title,
370
+ "arcana": arcana,
371
+ "suit": suit,
372
+ "type": ctype,
373
+ "value": value,
374
+ "image_url": "",
375
+ "source_url": url,
376
+ "translations": {
377
+ "en": {
378
+ "name": title,
379
+ "keywords": keywords,
380
+ "upright_meaning": upright,
381
+ "reversed_meaning": reversed_,
382
+ "description": description,
383
+ "full_interpretation": full_text,
384
+ "symbolism": symbolism,
385
+ "historical": historical,
386
+ "psychological": psychological,
387
+ "correspondences": correspondences,
388
+ "faq": faq,
389
+
390
+ # EXTRA FIELDS FOR NLP/RAG
391
+ "love": love,
392
+ "career": career,
393
+ "money": money,
394
+ "health": health,
395
+ "spirituality": spirituality
396
+ }
397
+ }
398
+ }
399
+
400
+ return card
401
+
402
+
403
+ # ----------------------------
404
+ # Chunking for RAG
405
+ # ----------------------------
406
+
407
+ def chunk_text(text: str, chunk_size: int = 1200, overlap: int = 220):
408
+ text = clean_text(text)
409
+ if not text:
410
+ return []
411
+
412
+ chunks = []
413
+ start = 0
414
+
415
+ while start < len(text):
416
+ end = start + chunk_size
417
+ chunk = text[start:end]
418
+ chunk = chunk.strip()
419
+
420
+ if chunk:
421
+ chunks.append(chunk)
422
+
423
+ start = end - overlap
424
+ if start < 0:
425
+ start = 0
426
+
427
+ return chunks
428
+
429
+
430
+ def write_jsonl(path: str, rows: list):
431
+ with open(path, "w", encoding="utf-8") as f:
432
+ for r in rows:
433
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
434
+
435
+
436
+ def make_rag_chunks(cards: list):
437
+ rows = []
438
+
439
+ for card in cards:
440
+ en = card["translations"]["en"]
441
+
442
+ base_tags = [
443
+ card["type"],
444
+ card["arcana"].replace(" ", "_").lower(),
445
+ card["slug"],
446
+ ]
447
+
448
+ if card["suit"]:
449
+ base_tags.append(card["suit"].lower())
450
+
451
+ section_map = {
452
+ "keywords": en.get("keywords", ""),
453
+ "upright_meaning": en.get("upright_meaning", ""),
454
+ "reversed_meaning": en.get("reversed_meaning", ""),
455
+ "description": en.get("description", ""),
456
+ "symbolism": en.get("symbolism", ""),
457
+ "historical": en.get("historical", ""),
458
+ "psychological": en.get("psychological", ""),
459
+ "correspondences": en.get("correspondences", ""),
460
+ "faq": en.get("faq", ""),
461
+ "love": en.get("love", ""),
462
+ "career": en.get("career", ""),
463
+ "money": en.get("money", ""),
464
+ "health": en.get("health", ""),
465
+ "spirituality": en.get("spirituality", ""),
466
+ "full_interpretation": en.get("full_interpretation", ""),
467
+ }
468
+
469
+ for section, content in section_map.items():
470
+ content = clean_text(content)
471
+ if not content or len(content) < 60:
472
+ continue
473
+
474
+ for idx, chunk in enumerate(chunk_text(content)):
475
+ rows.append({
476
+ "id": f"{card['slug']}_{section}_{idx}",
477
+ "hash": sha1_id(card["slug"] + section + chunk),
478
+ "card": card["name"],
479
+ "slug": card["slug"],
480
+ "arcana": card["arcana"],
481
+ "suit": card["suit"],
482
+ "type": card["type"],
483
+ "value": card["value"],
484
+ "section": section,
485
+ "text": chunk,
486
+ "tags": base_tags + [section],
487
+ "source_url": card["source_url"],
488
+ "lang": "en"
489
+ })
490
+
491
+ return rows
492
+
493
+
494
+ # ----------------------------
495
+ # SFT dataset generator
496
+ # ----------------------------
497
+
498
+ def make_sft_dataset(cards: list):
499
+ system_prompt = (
500
+ "You are a professional tarot reader. "
501
+ "Answer clearly, mystically, but without unnecessary filler. "
502
+ "Do not invent meanings. Use tarot interpretations."
503
+ "Keep the tone confident and structured."
504
+ )
505
+
506
+ rows = []
507
+
508
+ for card in cards:
509
+ en = card["translations"]["en"]
510
+ name = card["name"]
511
+
512
+ def add_sample(user, assistant):
513
+ assistant = clean_text(assistant)
514
+ if not assistant or len(assistant) < 40:
515
+ return
516
+
517
+ rows.append({
518
+ "messages": [
519
+ {"role": "system", "content": system_prompt},
520
+ {"role": "user", "content": user},
521
+ {"role": "assistant", "content": assistant}
522
+ ]
523
+ })
524
+
525
+ upright = en.get("upright_meaning", "")
526
+ reversed_ = en.get("reversed_meaning", "")
527
+
528
+ love = en.get("love", "")
529
+ career = en.get("career", "")
530
+ money = en.get("money", "")
531
+ health = en.get("health", "")
532
+ spirituality = en.get("spirituality", "")
533
+
534
+ symbolism = en.get("symbolism", "")
535
+ psychological = en.get("psychological", "")
536
+ historical = en.get("historical", "")
537
+ correspondences = en.get("correspondences", "")
538
+ faq = en.get("faq", "")
539
+
540
+ full = en.get("full_interpretation", "")
541
+
542
+ add_sample(f"What does the tarot card {name} mean upright?", upright)
543
+ add_sample(f"What does the tarot card {name} mean reversed?", reversed_)
544
+
545
+ add_sample(f"Interpret the tarot card {name} in love and relationships.", love)
546
+ add_sample(f"Interpret the tarot card {name} in career and work.", career)
547
+ add_sample(f"Interpret the tarot card {name} for money and finances.", money)
548
+ add_sample(f"Interpret the tarot card {name} for health.", health)
549
+ add_sample(f"Interpret the tarot card {name} for spirituality.", spirituality)
550
+
551
+ add_sample(f"Explain the symbolism of the tarot card {name}.", symbolism)
552
+ add_sample(f"Explain the psychological meaning of the tarot card {name}.", psychological)
553
+ add_sample(f"Explain the historical context of the tarot card {name}.", historical)
554
+ add_sample(f"What correspondences does the tarot card {name} have (astrology, elements)?", correspondences)
555
+
556
+ add_sample(f"FAQ: common questions about the tarot card {name}.", faq)
557
+ add_sample(f"Give a full detailed interpretation of the tarot card {name}.", full)
558
+
559
+ # Advice-of-the-day sample
560
+ advice_source = upright if upright else full
561
+ add_sample(f"What advice does the tarot card {name} give as a card of the day?", advice_source)
562
+
563
+ # Spread position samples
564
+ if upright:
565
+ add_sample(
566
+ f"In a 3-card spread (past-present-future), what does {name} mean in the Past position?",
567
+ upright
568
+ )
569
+ add_sample(
570
+ f"In a 3-card spread (past-present-future), what does {name} mean in the Present position?",
571
+ upright
572
+ )
573
+ add_sample(
574
+ f"In a 3-card spread (past-present-future), what does {name} mean in the Future position?",
575
+ upright
576
+ )
577
+
578
+ return rows
579
+
580
+
581
+ # ----------------------------
582
+ # NLP datasets
583
+ # ----------------------------
584
+
585
+ def normalize_keywords(keywords: str) -> list:
586
+ if not keywords:
587
+ return []
588
+
589
+ # split by comma or semicolon
590
+ parts = re.split(r"[,;\n]", keywords)
591
+ out = []
592
+
593
+ for p in parts:
594
+ p = p.strip().lower()
595
+ p = re.sub(r"[^a-z0-9\-\s]", "", p)
596
+ p = re.sub(r"\s+", " ", p).strip()
597
+ if p and len(p) > 1:
598
+ out.append(p)
599
+
600
+ # deduplicate preserving order
601
+ seen = set()
602
+ uniq = []
603
+ for k in out:
604
+ if k not in seen:
605
+ uniq.append(k)
606
+ seen.add(k)
607
+
608
+ return uniq
609
+
610
+
611
+ def make_nlp_keywords_dataset(cards: list):
612
+ """
613
+ Generates a dataset mapping each card -> normalized keywords list.
614
+ Useful for NLP classification, tagger, query expansion.
615
+
616
+ Output rows:
617
+ { card, slug, arcana, suit, type, value, keywords: [..] }
618
+ """
619
+
620
+ rows = []
621
+
622
+ for card in cards:
623
+ en = card["translations"]["en"]
624
+ kw = normalize_keywords(en.get("keywords", ""))
625
+
626
+ if not kw:
627
+ continue
628
+
629
+ rows.append({
630
+ "card": card["name"],
631
+ "slug": card["slug"],
632
+ "arcana": card["arcana"],
633
+ "suit": card["suit"],
634
+ "type": card["type"],
635
+ "value": card["value"],
636
+ "keywords": kw,
637
+ "source_url": card["source_url"],
638
+ "lang": "en"
639
+ })
640
+
641
+ return rows
642
+
643
+
644
+ def make_nlp_intents_dataset(cards: list):
645
+ """
646
+ Generates an intent classification dataset.
647
+
648
+ Example:
649
+ input: "What does The Tower mean in love?"
650
+ label: "love"
651
+
652
+ This can train:
653
+ - intent classifier
654
+ - routing model (RAG retrieval filter)
655
+
656
+ Output format:
657
+ { "text": ..., "intent": ..., "card": ..., "slug": ... }
658
+ """
659
+
660
+ templates = {
661
+ "upright": [
662
+ "What does {card} mean upright?",
663
+ "Explain {card} upright meaning.",
664
+ "Tarot meaning of {card} upright.",
665
+ ],
666
+ "reversed": [
667
+ "What does {card} mean reversed?",
668
+ "Explain {card} reversed meaning.",
669
+ "Tarot meaning of {card} reversed.",
670
+ ],
671
+ "love": [
672
+ "What does {card} mean in love?",
673
+ "Love reading: interpret {card}.",
674
+ "Relationship meaning of {card} tarot.",
675
+ ],
676
+ "career": [
677
+ "What does {card} mean for career?",
678
+ "Work reading: interpret {card}.",
679
+ "Job meaning of {card} tarot.",
680
+ ],
681
+ "money": [
682
+ "What does {card} mean for money?",
683
+ "Financial meaning of {card} tarot.",
684
+ "Interpret {card} for finances.",
685
+ ],
686
+ "health": [
687
+ "What does {card} mean for health?",
688
+ "Health reading: interpret {card}.",
689
+ "Physical wellbeing meaning of {card} tarot.",
690
+ ],
691
+ "spirituality": [
692
+ "What does {card} mean spiritually?",
693
+ "Spiritual meaning of {card} tarot.",
694
+ "Interpret {card} for spiritual growth.",
695
+ ],
696
+ "symbolism": [
697
+ "Explain the symbolism of {card}.",
698
+ "What symbols are on {card} and what do they mean?",
699
+ ],
700
+ "psychological": [
701
+ "Explain the psychological meaning of {card}.",
702
+ "What does {card} represent psychologically?",
703
+ ],
704
+ "historical": [
705
+ "Tell me the history of {card} tarot card.",
706
+ "Historical background of {card}.",
707
+ ],
708
+ "correspondences": [
709
+ "What correspondences does {card} have?",
710
+ "Astrology and elements correspondences of {card} tarot.",
711
+ ],
712
+ "general": [
713
+ "Give a full interpretation of {card}.",
714
+ "Explain the tarot card {card}.",
715
+ ]
716
+ }
717
+
718
+ rows = []
719
+
720
+ for card in cards:
721
+ for intent, tpls in templates.items():
722
+ for tpl in tpls:
723
+ text = tpl.format(card=card["name"])
724
+ rows.append({
725
+ "text": text,
726
+ "intent": intent,
727
+ "card": card["name"],
728
+ "slug": card["slug"],
729
+ "arcana": card["arcana"],
730
+ "suit": card["suit"],
731
+ "type": card["type"],
732
+ "value": card["value"],
733
+ "lang": "en"
734
+ })
735
+
736
+ random.shuffle(rows)
737
+ return rows
738
+
739
+
740
+ # ----------------------------
741
+ # Main
742
+ # ----------------------------
743
+
744
+ def main():
745
+ os.makedirs(OUT_DIR, exist_ok=True)
746
+
747
+ print("[+] Fetching card links...")
748
+ links = get_card_links()
749
+ print(f"[+] Found {len(links)} links")
750
+
751
+ cards = []
752
+
753
+ for url in tqdm(links, desc="Scraping cards"):
754
+ try:
755
+ card = parse_card_page(url)
756
+ if card:
757
+ cards.append(card)
758
+ except Exception as e:
759
+ print(f"[!] Failed: {url} -> {e}")
760
+
761
+ safe_sleep()
762
+
763
+ # Sort: major first, then minor by value
764
+ cards.sort(key=lambda x: (0 if x["type"] == "major" else 1, x["value"], x["name"]))
765
+
766
+ # Assign IDs
767
+ for i, c in enumerate(cards, start=1):
768
+ c["id"] = i
769
+
770
+ # Save full master dump
771
+ with open(FULL_JSON, "w", encoding="utf-8") as f:
772
+ json.dump(cards, f, ensure_ascii=False, indent=2)
773
+
774
+ print(f"[+] Saved FULL JSON: {FULL_JSON}")
775
+
776
+ # Build RAG chunks
777
+ rag_rows = make_rag_chunks(cards)
778
+ write_jsonl(RAG_JSONL, rag_rows)
779
+ print(f"[+] Saved RAG JSONL: {RAG_JSONL} (rows={len(rag_rows)})")
780
+
781
+ # Build SFT dataset
782
+ sft_rows = make_sft_dataset(cards)
783
+ write_jsonl(SFT_JSONL, sft_rows)
784
+ print(f"[+] Saved SFT JSONL: {SFT_JSONL} (rows={len(sft_rows)})")
785
+
786
+ # NLP datasets
787
+ nlp_intents = make_nlp_intents_dataset(cards)
788
+ write_jsonl(NLP_INTENTS_JSONL, nlp_intents)
789
+ print(f"[+] Saved NLP intents JSONL: {NLP_INTENTS_JSONL} (rows={len(nlp_intents)})")
790
+
791
+ nlp_keywords = make_nlp_keywords_dataset(cards)
792
+ write_jsonl(NLP_KEYWORDS_JSONL, nlp_keywords)
793
+ print(f"[+] Saved NLP keywords JSONL: {NLP_KEYWORDS_JSONL} (rows={len(nlp_keywords)})")
794
+
795
+ print("[✓] DONE")
796
+
797
+
798
+ if __name__ == "__main__":
799
+ main()