File size: 11,359 Bytes
4b05aaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import tiktoken
import os
from bs4 import BeautifulSoup
import gradio as gr
from langchain import OpenAI, ConversationChain, LLMChain, PromptTemplate
from langchain.memory import ConversationBufferWindowMemory
import openai
import requests
from langchain.chat_models import ChatOpenAI
import ast
import re
import json
import tempfile
import collectionstions

OPENAI_API_KEY = os.environ['OPENAI_API_KEY']


def save_webpage_as_html(url):
    headers = {
    'authority': 'ms-mt--api-web.spain.advgo.net',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
    'accept': 'application/json, text/plain, */*',
    'x-adevinta-channel': 'web-desktop',
    'x-schibsted-tenant': 'coches',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
    'content-type': 'application/json;charset=UTF-8',
    'origin': 'https://www.coches.net',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.coches.net/',
    'accept-language': 'en-US,en;q=0.9,es;q=0.8',
    }
    
    response = requests.get(url, headers=headers)

    # Check if the request was successful
    if response.status_code != 200:
        print(f"Failed to get the webpage: {url}")
        return
    
    # Create a BeautifulSoup object and specify the parser
    soup = BeautifulSoup(response.text, 'html.parser')

    # Create a dictionary to hold the result
    result = collections.defaultdict(list)

    # Find all tags that contain text (you may need to add more tags to this list)
    for tag in soup.find_all(['li', 'ol']):
        result[tag.name].append(tag.get_text(strip=True))
        
    return result

output_json_format = '''
{
    "category": "root_category",
    "subcategories": [
        {
            "category": "node_category",
            "subcategories": [
                {
                    "category": "node_category",
                    "subcategories": [category1, category2, ...]
                },
                {
                    "category": "node_category",
                    "subcategories": [category1, category2, ...]
                }
            ]
        },
        {
            "category": "node_category",
            "subcategories": [category1, category2, ...]
        }
    ]
}

'''

empty_json = {
    "category": "root_category",
    "subcategories": [
    ]
}

def get_taxanomy_from_url(url):
    
    url_dict = save_webpage_as_html(url)
    
    json_input = str(url_dict)
    
    template = '''
    {history}
    {human_input}
    '''
    prompt = PromptTemplate(
        input_variables=["history", "human_input"], 
        template=template
    )

    chatgpt_chain = LLMChain(
        llm=ChatOpenAI(model="gpt-4", temperature=0,openai_api_key=OPENAI_API_KEY), 
        prompt=prompt, 
        verbose=True, 
        memory=ConversationBufferWindowMemory(k=10),
    )

    prompt_input2 = f'''
    You are an expert ecommerce product taxanomy analyst.
    You are equiped with vast knowledge of taxanomy, ontology and everything related to it.
    You fit have deep expertise in the domain of: "An ontology identifies and distinguishes concepts and their relationships; 
    it describes content and relationships. 
    A taxonomy formalizes the hierarchical relationships among concepts and specifies the term to be used to refer to each; 
    it prescribes structure and terminology."

    You have a task to extract taxanomy from a python dictionary of an extracted html page of an ecommerce website.

    Here is the input python dictionary:
    {json_input}

    Here is the output json format:
    {output_json_format}
    
    From the input python dictionary, extract all available products under the li and ol key and create the output json taxanomy. 
    Think step by step.  
    Place the products in categories and subcategories accordingly.
    Organize all the products to fit the output json format.

    The output should follow a python dictionary..
    Do not declare a new variable, output the python dictionary json object only.
    Do not output "The taxonomy extracted from the given python list can be represented as follows:"
    Do not provide extra information.  Directly output the python dictionary only. 
    Do not insert any string before or after the python dictionary.
    Output python dictionary only.
    '''
    encoding = tiktoken.encoding_for_model("gpt-4")
    encoded_prompt2 = encoding.encode(prompt_input2)[:8000]
    prompt_input2 = encoding.decode(encoded_prompt2)
    
    json_dict = ""
    while type(json_dict) != dict:
        json_taxanomy_output=chatgpt_chain.predict(human_input=prompt_input2)
        json_dict = ast.literal_eval(json_taxanomy_output)
        
    file_name = "url_temp.json"
    
    # Save the modified data back to the file
    with open(file_name, 'w') as json_file:
        json.dump(json_dict, json_file, indent=4)  # 'indent' parameter makes the output more readable
    
    return(file_name)


def expand_taxanomy(json_dict, num_layers, num_items, category_type):
    
    num_layers = str(int(num_layers))
    num_items = str(int(num_items))
    json_input = str(json_dict)
    
    template = '''
    {history}
    {human_input}
    '''
    prompt = PromptTemplate(
        input_variables=["history", "human_input"], 
        template=template
    )

    chatgpt_chain = LLMChain(
        llm=ChatOpenAI(model="gpt-4", temperature=0,openai_api_key=OPENAI_API_KEY), 
        prompt=prompt, 
        verbose=True, 
        memory=ConversationBufferWindowMemory(k=10),
    )

    prompt_input1 = f'''
    You are an expert ecommerce product taxanomy analyst.
    You are equiped with vast knowledge of taxanomy, ontology and everything related to it.
    You fit have deep expertise in the domain of: "An ontology identifies and distinguishes concepts and their relationships; 
    it describes content and relationships. 
    A taxonomy formalizes the hierarchical relationships among concepts and specifies the term to be used to refer to each; 
    it prescribes structure and terminology."

    You have a task to expand a taxanomy that is formatted in a json file.
    The taxanomy tree should be {num_layers} layer deep with a total of {num_items} items.
    The category type is {category_type}.

    Here is the input json file:
    {json_input}

    Here is the output json format:
    {output_json_format}
    
    Expand the taxanomy of the input json file.  
    Find subcategories that fits each category.
    Expand the leafs of the taxanomy tree.
    Go deeper. Think step by step.  
    Find all subcategories and output it as a json object.

    The output should follow a python dictionary..
    Do not declare a new variable, output the python dictionary json object only.
    Do not provide extra information.  Directly output the python dictionary only. 
    '''
    
    encoding = tiktoken.encoding_for_model("gpt-4")
    encoded_prompt1 = encoding.encode(prompt_input1)[:8000]
    prompt_input1 = encoding.decode(encoded_prompt1)
    
    json_taxanomy_output=chatgpt_chain.predict(human_input=prompt_input1)
    json_dict = ast.literal_eval(json_taxanomy_output)
    
    return(json_dict)


def add_nodes_edges(graph, data, parent=None):
    new_name = data['category']
    
    # create node
    graph.node(new_name)
    
    if parent:
        # create an edge between parent and child
        graph.edge(parent, new_name)
    
    # iterate over subcategories (if they exist)
    for subcat in data.get('subcategories', []):
        # subcategories can be either strings or new dicts
        if isinstance(subcat, str):
            # create node for the string subcategory
            graph.node(subcat)
            # create edge between the parent category and this subcategory
            graph.edge(new_name, subcat)
        else:
            # if subcat is a dict, repeat the process with subcat as the parent
            add_nodes_edges(graph, subcat, new_name)

def visualize_json(data):
    
    graph = graphviz.Digraph(graph_attr={'rankdir': 'LR'})  # Added 'LR' for left to right graph

    # Add nodes and edges
    add_nodes_edges(graph, data)

    # Visualize the graph
    #graph.view()
    return graph

def get_file(json_file):
   
    try:
        print("loading json file")
        print("temp_file", json_file.name)
        file_path = json_file.name

        with open(file_path, 'r') as json_file:
            data = json.load(json_file)
    except:
        print("using temp json")
        file_path = 'temp.json'

        with open(file_path, 'r') as json_file:
            data = json.load(json_file)
    
    try:
        os.remove('graph.png')
        print("graph removed")
    except:
        print("no existing graph")
        
    graph = visualize_json(data)
    # Render the graph as a PNG file
    graph.format = 'png'
    graph = graph.render(filename='graph', cleanup=True)
    
    return graph

def modify_json(json_input, num_layers, num_items, category_type):
    
    print("json_input first", json_input)
    if json_input is not None:
    
        file_path = json_input.name
        # Open the file and load the JSON data
        with open(file_path, 'r') as json_file:
            data = json.load(json_file)
    else:
        data = empty_json
        data["category"] = category_type
        
        # Directly from dictionary
        file_path = 'temp.json'
        with open(file_path, 'w') as outfile:
            json.dump(data, outfile)
        
    json_dict = expand_taxanomy(data, num_layers, num_items,category_type)
    
    print("json_dict", json_dict)
    
    # Save the modified data back to the file
    with open(file_path, 'w') as json_file:
        json.dump(json_dict, json_file, indent=4)  # 'indent' parameter makes the output more readable
        
    return(file_path)

def print_num(a,b):
    return(int(a), int(b))



with gr.Blocks() as demo:
    
    gr.Markdown(
    """
    # Auto Taxanomy App
    Upload a JSON taxanomy file or generate from scratch.
    """)
    with gr.Row():
        with gr.Column():
            json_file = gr.File(label="Upload JSON here.")
            num_layers = gr.Number(label="Number of layers")
            num_items = gr.Number(label="Number of items")
            category_type = gr.Text(label="Category type")
            modify_btn = gr.Button(value="Generate")
            render_btn = gr.Button(value="Render")
            print_btn = gr.Button(value="Print")
        with gr.Column():
            input_url = gr.Text(label="Insert URL")
            geturl_btn = gr.Button(value="Get JSON Taxanomy")
            #url_json_file = gr.File(label="URL JSON file.")
            rendered_tree =  gr.Image(label="Taxanomy Tree.")
            output_file = gr.File(label="Ouput JSON file.")
            print_text = gr.Text(label="Printing")

    modify_btn.click(modify_json, inputs=[json_file, num_layers, num_items, category_type], outputs=output_file)
    render_btn.click(get_file, inputs=json_file, outputs=rendered_tree)
    print_btn.click(print_num, inputs=[num_layers,num_items], outputs=print_text)
    geturl_btn.click(get_taxanomy_from_url, inputs=input_url, outputs=output_file)

demo.launch()