import sqlite3 import random import json import hashlib from pybloom_live import ScalableBloomFilter from tqdm import tqdm 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 main(): """Main function to generate and output conversation paths.""" conn = sqlite3.connect(DATABASE_FILE) cursor = conn.cursor() conversations = [] num_paths_to_generate = 1000 paths_generated = 0 # Track seen conversation patterns seen_windows = set() min_window_size = 5 # Minimum consecutive dialogues to consider for duplication # Either pick a random starting point: starting_dialogues = get_starting_dialogues(cursor) if not starting_dialogues: print("Error: No starting dialogues found in the database.") conn.close() return with tqdm(total=num_paths_to_generate, desc="Generating paths") as pbar: while paths_generated < num_paths_to_generate: start_convo_id, start_dialogue_id = random.choice(starting_dialogues) path = generate_conversation_path(cursor, start_convo_id, start_dialogue_id) # Skip paths that are too short if len(path) < 5: continue # Create semantic key for conversation path_text = " ".join(entry["dialogue"].strip().lower() for entry in path 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 # Check for duplicates try: if (not is_duplicate(path_text) and not is_added(path) and any(entry["dialogue"][0] != "[" for entry in path)): conversations.append(path) paths_generated += 1 pbar.update(1) except Exception as e: print(f"Error: {e}") continue output = {"conversations": conversations} with open("output.json", "w") as f: json.dump(output, f, indent=4) conn.close() if __name__ == "__main__": main()