File size: 8,571 Bytes
89f0644
 
 
 
00f84bd
89f0644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b82a6c
 
 
 
89f0644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00f84bd
 
 
 
89f0644
 
00f84bd
 
 
89f0644
00f84bd
 
 
 
 
 
89f0644
 
 
 
00f84bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b82a6c
00f84bd
 
 
 
6b82a6c
 
 
 
 
 
 
 
 
 
 
89f0644
6b82a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00f84bd
 
 
 
 
 
 
89f0644
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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()