import os import json import sys import re from pathlib import Path import argparse import subprocess import importlib def install_tqdm_if_needed(): """Checks for tqdm and installs it if not found.""" try: importlib.import_module('tqdm') except ImportError: print("`tqdm` library not found. Installing...") try: subprocess.check_call([sys.executable, "-m", "pip", "install", "tqdm"]) except subprocess.CalledProcessError as e: print(f"Error: Failed to install tqdm. Please install it manually using 'pip install tqdm'.") sys.exit(1) def create_sft_dataset(input_folder, output_file): """ Scans a directory for .txt thread files, parses them, and creates a JSONL dataset suitable for Supervised Fine-Tuning (SFT). """ from tqdm import tqdm folder_path = Path(input_folder) output_path = Path(output_file) if not folder_path.is_dir(): print(f"Error: The input folder '{input_folder}' does not exist.") sys.exit(1) try: output_path.parent.mkdir(parents=True, exist_ok=True) except Exception as e: print(f"Error: Could not create output directory '{output_path.parent}'. Error: {e}") sys.exit(1) thread_files = list(folder_path.glob("*.txt")) if not thread_files: print(f"Error: No .txt files found in '{input_folder}'.") sys.exit(1) print(f"Found {len(thread_files)} thread files. Processing...") total_conversations = 0 system_prompt = "You are an anonymous message board user. You are opinionated and use informal language. You discuss various topics." reply_pattern = re.compile(r'>>(\d{8,9})') with open(output_path, 'w', encoding='utf-8') as f_out: for file_path in tqdm(thread_files, desc="Processing Threads"): try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() posts_map = {} ordered_post_ids = [] raw_posts = [p.strip() for p in content.split('--- ') if p.strip()] for post_text in raw_posts: lines = post_text.splitlines() if lines and lines[0].strip().isdigit(): post_id = lines[0].strip() post_content = "\n".join(lines[1:]).strip() if post_content: posts_map[post_id] = post_content ordered_post_ids.append(post_id) if not ordered_post_ids: continue op_id = ordered_post_ids[0] op_content = posts_map[op_id] # --- LOGIC REMAINS THE SAME FOR DIRECT REPLIES --- for post_id, post_content in posts_map.items(): reply_ids = reply_pattern.findall(post_content) if reply_ids: assistant_text = post_content.strip() for parent_id in reply_ids: if parent_id in posts_map: human_text = posts_map[parent_id] conversation = { "conversations": [ {"from": "system", "value": system_prompt}, {"from": "human", "value": human_text}, {"from": "assistant", "value": assistant_text} ] } f_out.write(json.dumps(conversation) + '\n') total_conversations += 1 # --- NEW LOGIC FOR STANDALONE POSTS --- for post_id, post_content in posts_map.items(): # A post is standalone if it's not the OP and has no reply links if post_id != op_id and not reply_pattern.search(post_content): assistant_text = post_content.strip() conversation = { "conversations": [ {"from": "system", "value": system_prompt}, {"from": "human", "value": op_content}, {"from": "assistant", "value": assistant_text} ] } f_out.write(json.dumps(conversation) + '\n') total_conversations += 1 except Exception as e: tqdm.write(f"Warning: Could not read or process file {file_path}. Error: {e}") print(f"\nProcessing complete.") print(f"Successfully created SFT dataset with {total_conversations} conversations.") print(f"Output file: {output_path}") if __name__ == "__main__": install_tqdm_if_needed() parser = argparse.ArgumentParser( description="Create an SFT dataset in JSONL format from a folder of message board thread files.", formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( "input_folder", help="The path to the folder containing your .txt thread files." ) parser.add_argument( "-o", "--output_file", default="sft_dataset.jsonl", help="The name of the output .jsonl file. Defaults to 'sft_dataset.jsonl'." ) args = parser.parse_args() create_sft_dataset(args.input_folder, args.output_file)