File size: 10,604 Bytes
fd16b28
 
 
 
f1c425f
fd16b28
1fd185c
fd16b28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c425f
 
 
 
 
 
 
 
 
 
ba54f7a
f1c425f
fd16b28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184a5ac
fd16b28
 
 
 
 
 
 
 
 
 
 
1fd185c
 
fd16b28
 
 
 
 
 
 
 
 
 
f1c425f
 
fd16b28
 
 
 
f1c425f
 
fd16b28
 
 
 
 
 
 
 
184a5ac
fd16b28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76049c
 
 
fd16b28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba9c12
fd16b28
 
 
 
 
 
 
 
 
 
 
1fd185c
fd16b28
 
 
 
 
 
1fd185c
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import sys
import json
from datetime import datetime
import gradio as gr
from dateutil import parser


def _get_scene_titles(storydata):
    scene_titles = {}
    choice_names = {}
    for chapter in storydata.get("chapters", []):
        for scene_id, scene in chapter.get("contents", {}).get("scenes", {}).items():
            scene_titles[scene_id] = scene["title"]
            for comp in scene.get("components", []):
                if comp["type"] == "choiceComponent":
                    choice_names[comp["id"]] = comp["name"]

    return scene_titles, choice_names


def _print_text_component(comp, output_lines):
    print(comp["text"])
    output_lines.append(comp['text'])
    print()


def _print_dialog_component(comp, config, output_lines):
    character_key = comp.get("characterAssetId")
    character_name = config.get("characterMap", {}).get(character_key, {}).get("characterName")
    dialog = comp["dialog"].replace("\n", " ")

    if character_name:
        dialog_line = f"{character_name}: {dialog}"
        print(dialog_line)
        output_lines.append(dialog_line)
    else:
        print(dialog)
        output_lines.append(dialog)
    
    print()
    output_lines.append("")


def _print_jump_component(comp, scene_titles, output_lines):
    dest = comp["jumpTransition"]["destination"]
    if dest == "end-of-chapter":
        print("JUMP TO END OF CHAPTER")
        print()
        output_lines.append("JUMP TO END OF CHAPTER")
        output_lines.append("")
    elif dest == "specific-scene":
        scene_id = comp["jumpTransition"]["targetScene"]
        scene_title = scene_titles.get(scene_id, "")
        print(f"JUMP TO SCENE: {scene_title}")
        print()
        output_lines.append(f"JUMP TO SCENE: {scene_title}")
        output_lines.append("")
        


def _print_switch_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping):
    var_id = comp["variableId"]
    var_name = [v["name"] for v in variables if v["id"] == var_id][0]
    print(f"VARIABLE CHECK. DEPENDING ON `{var_name}`, TAKE ONE BRANCH:")
    print()
    output_lines.append(f"VARIABLE CHECK. DEPENDING ON `{var_name}`, TAKE ONE BRANCH:")
    output_lines.append("")
    for ibranch, branch in enumerate(comp["branches"], start=1):
        print(f"BRANCH {ibranch}")
        print()
        for branch_comp in branch["components"]:
            _print_component(branch_comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    print("END VARIABLE CHECK")
    print()


def _print_if_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping):
    choice_id = comp.get("choiceId")
    choice_name = choice_names.get(choice_id, "")
    if choice_name:
        choice_name = f' "{choice_name}"'
    print(f'CHOICE CHECK. DEPENDING ON CHOICE{choice_name}, TAKE ONE BRANCH:')
    print()
    output_lines.append(f'CHOICE CHECK. DEPENDING ON CHOICE{choice_name}, TAKE ONE BRANCH:')
    output_lines.append("")
    for ibranch, branch in enumerate(comp["conditions"], start=1):
        print(f"BRANCH {ibranch}")
        print()
        output_lines.append(f"BRANCH {ibranch}")
        output_lines.append("")
        for branch_comp in branch["components"]:
            _print_component(branch_comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    print(f'END CHOICE CHECK{choice_name}')
    print()
    output_lines.append(f'END CHOICE CHECK{choice_name}')
    output_lines.append("")


def _print_choice_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping):
    choice_name = comp.get("name", "")
    if choice_name:
        choice_name = f' "{choice_name}"'
    print(f"BEGIN CHOICE BLOCK{choice_name}")
    print()
    output_lines.append(f"BEGIN CHOICE BLOCK{choice_name}")
    output_lines.append("")
    prompt = comp.get("promptComponent")
    if prompt is not None:
        _print_component(prompt, variables, scene_titles, choice_names, config, output_lines, mapping)
    for iopt, option in enumerate(comp.get("options", []), start=1):
        choice_text = option.get("displayText")
        if choice_text is not None:
            print(f"OPTION {iopt}: {choice_text}")
            print()
            output_lines.append(f"OPTION {iopt}: {choice_text}")
            output_lines.append("")
        for opt_comp in option.get("components", []):
            _print_component(opt_comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    print(f"END CHOICE BLOCK{choice_name}")
    print()
    output_lines.append(f"END CHOICE BLOCK{choice_name}")
    output_lines.append("")


def _print_note_component(comp, output_lines):
    print("---")
    print()
    print(f'NOTE: {comp["note"]}')
    print()
    print("---")
    print()
    output_lines.append("---")
    output_lines.append("")
    output_lines.append(f'NOTE: {comp["note"]}')
    output_lines.append("")
    output_lines.append("---")
    output_lines.append("")

def _print_background(comp, mapping, output_lines):
    asset_id = comp.get('backgroundAssetId')
    output_lines.append(f"Transition: {comp.get('transition')}")
    output_lines.append("")
    output_lines.append(f'Background: {mapping.get(asset_id)}')
    output_lines.append("")
    print(f'Background: {mapping.get(asset_id)}')
    print()

def _print_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping):
    component_type = comp.get("type")  
    if component_type == 'backgroundComponent':
        _print_background(comp, mapping, output_lines)
    if component_type == "textComponent":
        _print_text_component(comp, output_lines)
    elif component_type == "dialogComponent":
        _print_dialog_component(comp, config, output_lines)
    elif component_type == "jumpComponent":
        _print_jump_component(comp, scene_titles, output_lines)
    elif component_type in ("choiceV2Component", "choiceComponent"):
        _print_choice_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    elif component_type == "switchComponent":
        _print_switch_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    elif component_type == "ifComponent":
        _print_if_component(comp, variables, scene_titles, choice_names, config, output_lines, mapping)
    elif component_type == "noteComponent":
        _print_note_component(comp, output_lines)
        
def format_story(storydata):
    output_lines=[]
    background_map = storydata["configuration"]["backgroundMap"]

    # Creating a new dictionary with the id's as keys and the names as values
    background_dic={bg_id: details['name'] for bg_id, details in background_map.items()}

    # Get the story configuration data, etc.
    variables = storydata.get("variables", {})
    scene_titles, choice_names = _get_scene_titles(storydata)
    config = storydata.get("configuration", {})

    # Story title
    
    
    #with open(output_file, "w", encoding="utf-8") as file:
    title = storydata.get("name", "Untitled")
    #_write_to_file(file, f"# {title} #")
    #_write_to_file(file, "")
    print(f"# {title} #")
    print()
    output_lines.append(title)

    # Dates of creation and last modification
    created = storydata.get("createdOn")
    if created is not None:
        created = parser.isoparse(created).strftime("%Y/%m/%d")
        output_lines.append(created)
        #_write_to_file(file, f"{created}")
        #_write_to_file(file, "")
    lastmod = storydata.get("lastModified")
    if lastmod is not None:
        lastmod = parser.isoparse(lastmod).strftime("%Y/%m/%d")
        output_lines.append(lastmod)
        #_write_to_file(file, f"{lastmod}")
        #_write_to_file(file, "")
    print(f"Created {created}")
    print()
    print(f"Last modified {lastmod}")
    print()

    # Story description
    description = storydata.get("description")
    print("### Description ###")
    print()
    print(description)
    print()
    output_lines.append(description)
    #_write_to_file(file, f"{description}")
    #_write_to_file(file, "")

    # Chapter and scene information
    chapters = sorted(storydata.get("chapters", []),
                      key=lambda c: c.get("order", 0))
    for ichapter, chapter in enumerate(chapters, start=1):
        # Chapter title
        chapter_title = chapter.get("title")
        print(f"## Chapter {ichapter}", end="")
        print(" ##" if chapter_title is None else f": {chapter_title} ##")
        print()
        output_lines.append(f"## Chapter {ichapter}")
        output_lines.append(" ##" if chapter_title is None else f": {chapter_title} ##")
        output_lines.append("")
        if chapter_title is not None:
            output_lines.append(chapter_title)
            #_write_to_file(file, f"{description}")
            #_write_to_file(file, "")
        else:
            output_lines.append('##')
            #_write_to_file(file, "##")
            #_write_to_file(file, "")

        # Chapter description
        chapter_description = chapter.get("description")
        if chapter_description is not None:
            print("---")
            print()
            print(chapter_description)
            print()
            print("---")
            print()
            output_lines.append(chapter_description)
            #_write_to_file(file, f"{chapter_description}")
            #_write_to_file(file, "")

        scenes = sorted(chapter.get("contents", {}).get("scenes", {}).values(),
                        key=lambda s: s.get("order", 0))
        for scene in scenes:
            # Scene title
            scene_title = scene.get("title", "Untitled")
            print(f"### Scene: {scene_title} ###")
            print()
            output_lines.append(scene_title)

            #_write_to_file(file, f"{scene_title}")
            #_write_to_file(file, "")


            # Print the scene components
            for comp in scene.get("components", []):
                _print_component(comp, variables, scene_titles, choice_names, config, output_lines, background_dic)
        
    return "\n".join(output_lines)

def process_story(file):

    with open(file.name, "r", encoding="utf-8") as f:
        storydata = json.load(f)

    output=format_story(storydata)
    return output

iface = gr.Interface(
    fn=process_story,
    inputs=gr.File(type='filepath'),
    outputs="text",
    title="Story Formatter",
    description="Upload your JSON file and get the formatted story"
)

if __name__ == "__main__":
    iface.launch(share=True)