import os import glob import json import datasets class JourneyBeyond(datasets.GeneratorBasedBuilder): """Dataset for '432: A Journey Beyond' with structured sections.""" VERSION = datasets.Version("1.0.0") def _info(self): features = datasets.Features( { "section": datasets.Value("string"), "title": datasets.Value("string"), "text": datasets.Value("string"), } ) return datasets.DatasetInfo( description="A structured dataset from the book '432: A Journey Beyond', organized by sections with text content from individual files.", features=features, homepage="https://huggingface.co/datasets/paulolden1/432-a-journey-beyond", ) def _split_generators(self, dl_manager): # When loaded from HF, the script's directory is the root of the cloned repo. data_dir = os.path.dirname(__file__) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"data_dir": data_dir}, ), ] def _generate_examples(self, data_dir): idx = 0 sections = ["frontmatter", "chapters", "backmatter", "supplementary"] for section in sections: section_path = os.path.join(data_dir, section) if not os.path.exists(section_path): continue # Sort files alphabetically to maintain chapter/interlude order file_paths = sorted(glob.glob(os.path.join(section_path, "*.*"))) for file_path in file_paths: ext = os.path.splitext(file_path)[1].lower() if ext not in (".txt", ".md", ".json"): continue # Skip unsupported files try: with open(file_path, "r", encoding="utf-8") as f: if ext == ".json": data = json.load(f) text = json.dumps(data, indent=2) # Stringify JSON for text feature else: text = f.read().strip() # Derive title from filename (e.g., 'chapter_01.txt' -> 'Chapter 01') filename = os.path.basename(file_path) title = os.path.splitext(filename)[0].replace("_", " ").title() yield idx, { "section": section, "title": title, "text": text, } idx += 1 except Exception as e: # Skip problematic files silently pass