File size: 2,278 Bytes
2948e04
22381af
2948e04
22381af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2948e04
88f516c
22381af
 
 
 
 
 
2948e04
 
22381af
 
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
import gradio as gr
import json

def generate_carbone_tags_and_values(json_input):
    try:
        # Parse the JSON input
        data = json.loads(json_input)

        # Function to recursively extract keys, values, and format them in Carbone style
        def extract_keys_and_values(obj, parent_key=''):
            carbone_tags = []
            carbone_tags_values = []
            if isinstance(obj, dict):
                for k, v in obj.items():
                    full_key = f"{parent_key}.{k}" if parent_key else k
                    tags, tags_values = extract_keys_and_values(v, full_key)
                    carbone_tags.extend(tags)
                    carbone_tags_values.extend(tags_values)
            elif isinstance(obj, list):
                for i, item in enumerate(obj):
                    tags, tags_values = extract_keys_and_values(item, f"{parent_key}[{i}]")
                    carbone_tags.extend(tags)
                    carbone_tags_values.extend(tags_values)
            else:
                carbone_tag = f"{{d.{parent_key}}}"
                carbone_tags.append(carbone_tag)
                carbone_tags_values.append((carbone_tag, obj))
            return carbone_tags, carbone_tags_values

        # Extract keys, values and format them
        carbone_keys, carbone_keys_values = extract_keys_and_values(data)

        # Sort the keys alphabetically
        carbone_keys.sort()
        carbone_keys_values.sort(key=lambda x: x[0])

        # Format the outputs
        tags_output = "\n".join(carbone_keys)
        tags_values_output = "\n".join([f"{tag}: {value}" for tag, value in carbone_keys_values])
        return tags_output, tags_values_output
    except json.JSONDecodeError:
        return "Invalid JSON. Please check your input.", ""

# Create the Gradio interface
interface = gr.Interface(
    fn=generate_carbone_tags_and_values,
    inputs=gr.Textbox(lines=20, placeholder="Paste JSON here..."),
    outputs=[gr.Textbox(lines=20), gr.Textbox(lines=20)],
    title="JSON to Carbone Tags and Values Converter",
    description="Paste JSON to generate Carbone tags and their values. The first output box shows only tags, and the second shows tags with their corresponding values."
)

# Launch the interface
interface.launch()