import sqlite3 import random import json from tqdm import tqdm from multiprocessing import Pool, Value, Lock DATABASE_FILE = "discobase3-29-2021-9-32-09-PM.db" # Replace with your database file def get_actor_name(cursor, actor_id): """Fetches the name of an actor from the actors table.""" cursor.execute("SELECT name FROM actors WHERE id=?", (actor_id,)) result = cursor.fetchone() return result[0] if result else f"Unknown Actor ({actor_id})" def get_dialogue_children(cursor, convo_id, dialogue_id): """Fetches the child dialogue entries of a given dialogue entry.""" cursor.execute( "SELECT destinationconversationid, destinationdialogueid FROM dlinks WHERE originconversationid=? AND origindialogueid=?", (convo_id, dialogue_id), ) return cursor.fetchall() def get_dialogue_entry(cursor, convo_id, dialogue_id): """Fetches a specific dialogue entry from the dentries table.""" cursor.execute( "SELECT dialoguetext, actor, conversant, conditionstring, userscript FROM dentries WHERE conversationid=? AND id=?", (convo_id, dialogue_id), ) return cursor.fetchone() def is_hub(entry): """Checks if a dialogue entry is a HUB (actor is 'HUB' and dialoguetext is '0').""" if entry is None: return False dialogue_text, actor_id, conversant_id, _, _ = entry # unpack all return dialogue_text == "0" and actor_id == 0 def generate_conversation_path(cursor, start_convo_id, start_dialogue_id, max_length=20): """Generates a single conversation path, treating '0' entries as placeholders.""" path = [] current_convo_id = start_convo_id current_dialogue_id = start_dialogue_id for _ in range(max_length): entry = get_dialogue_entry(cursor, current_convo_id, current_dialogue_id) if not entry: print(f"Warning: Could not find dialogue entry for convo_id={current_convo_id}, dialogue_id={current_dialogue_id}. Path may be incomplete.") break dialogue_text, actor_id, conversant_id, conditionstring, userscript = entry if is_hub(entry): # Skip HUB entries children = get_dialogue_children(cursor, current_convo_id, current_dialogue_id) if not children: break current_convo_id, current_dialogue_id = random.choice(children) continue actor_name = get_actor_name(cursor, actor_id) if dialogue_text == "0": # Treat '0' entry as a placeholder with context placeholder_text = "[Action/Check: " if conditionstring: placeholder_text += f"Condition: {conditionstring}; " if userscript: placeholder_text += f"Script: {userscript}; " placeholder_text = placeholder_text.rstrip("; ") + "]" if placeholder_text == "[Action/Check:]": pass else: path.append({"actor": actor_name, "dialogue": placeholder_text}) else: path.append({"actor": actor_name, "dialogue": dialogue_text}) children = get_dialogue_children(cursor, current_convo_id, current_dialogue_id) if not children: break current_convo_id, current_dialogue_id = random.choice(children) return path def get_starting_dialogues(cursor): """Get a list of potential starting dialogues (those with no parents).""" cursor.execute(""" SELECT dentries.conversationid, dentries.id FROM dentries LEFT JOIN dlinks ON dentries.conversationid = dlinks.destinationconversationid AND dentries.id = dlinks.destinationdialogueid WHERE dlinks.originconversationid IS NULL """) return cursor.fetchall() def format_conversation_output(conversation): """ Formats a conversation list into a string that resembles the game's output. Args: conversation: A list of dictionaries, where each dictionary represents a dialogue entry with "actor" and "dialogue" keys. """ output = "" for entry in conversation: actor = entry["actor"] dialogue = entry["dialogue"] if dialogue.startswith("["): # Placeholder for action/check output += f"{dialogue}\n" elif actor.upper() == actor: # If the actor is all uppercase, it's like a skill or internal thought output += f"\n{actor} - {dialogue}\n" else: output += f"{actor} - {dialogue}\n" return output.strip() def worker_process(args): """Worker function for parallel processing""" db_file, starting_dialogues = args conn = sqlite3.connect(db_file) cursor = conn.cursor() # Generate a single path start_convo_id, start_dialogue_id = random.choice(starting_dialogues) path = generate_conversation_path(cursor, start_convo_id, start_dialogue_id) conn.close() return path def main(): """Main function using multiprocessing""" starting_dialogues = get_starting_dialogues(sqlite3.connect(DATABASE_FILE).cursor()) if not starting_dialogues: print("Error: No starting dialogues found in the database.") return conversations = [] seen_windows = set() min_window_size = 5 num_paths_to_generate = 5000 # Create worker arguments (same for all workers) worker_args = (DATABASE_FILE, starting_dialogues) # Create process pool counter = Value('i', 0) lock = Lock() def update_progress(_): with lock: counter.value += 1 if counter.value % 10 == 0: print(f"\rGenerated {counter.value}/{num_paths_to_generate} paths", end="") with Pool(processes=8) as pool: # Adjust number of processes based on CPU cores results = [] # Submit initial batch of tasks for _ in range(num_paths_to_generate * 2): # Generate extra to account for rejected paths results.append(pool.apply_async(worker_process, (worker_args,), callback=update_progress)) # Collect valid results while len(conversations) < num_paths_to_generate and results: result = results.pop(0).get() if len(result) < 5: continue # Duplicate checking (now in main process) path_text = " ".join(entry["dialogue"].strip().lower() for entry in result if not entry["dialogue"].startswith("[")) def is_duplicate(new_text): """Check if new conversation contains or is contained within existing conversations""" for existing in conversations: existing_text = " ".join(entry["dialogue"].strip().lower() for entry in existing if not entry["dialogue"].startswith("[")) if len(new_text) < min_window_size or len(existing_text) < min_window_size: continue # Check for substring matches in either direction if new_text in existing_text or existing_text in new_text: return True return False # More efficient window-based check def is_added(current_path): """Check for matching subsequences using sliding window""" path_dialogues = [entry["dialogue"] for entry in current_path if not entry["dialogue"].startswith("[")] window = [] for dialogue in path_dialogues: window.append(dialogue) if len(window) > min_window_size: window.pop(0) if len(window) == min_window_size: window_str = " ".join(window) if window_str in seen_windows: return True # Add windows if not duplicate for i in range(len(path_dialogues) - min_window_size + 1): seen_windows.add(" ".join(path_dialogues[i:i+min_window_size])) return False if (not is_duplicate(path_text) and not is_added(result) and any(entry["dialogue"][0] != "[" for entry in result)): conversations.append(result) pool.close() pool.join() output = {"conversations": conversations} with open("output.json", "w") as f: json.dump(output, f, indent=4) if __name__ == "__main__": main()