artificialguybr commited on
Commit
48b792e
1 Parent(s): 4f2de6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -22
app.py CHANGED
@@ -4,16 +4,37 @@ import json
4
  from graphviz import Digraph
5
  from PIL import Image
6
  import io
 
 
7
 
8
- def generate_knowledge_graph(api_key, user_input):
9
- openai.api_key = api_key
10
-
11
- # Ensure both API key and user input are provided
12
  if not api_key or not user_input:
13
  raise ValueError("Please provide both the OpenAI API Key and User Input")
14
 
15
- # Chamar a API da OpenAI
16
- print("Chamando a API da OpenAI...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  completion = openai.ChatCompletion.create(
18
  model="gpt-3.5-turbo-16k",
19
  messages=[
@@ -91,19 +112,14 @@ def generate_knowledge_graph(api_key, user_input):
91
  )
92
 
93
  response_data = completion.choices[0]["message"]["function_call"]["arguments"]
94
- print(response_data)
95
- print("Type of response_data:", type(response_data))
96
- print("Value of response_data:", response_data)
97
-
98
- # Convert to dictionary if it's a string
99
- if isinstance(response_data, str):
100
- response_data = json.loads(response_data)
101
 
 
 
102
  # Visualizar o conhecimento usando Graphviz
103
- print("Gerando o conhecimento usando Graphviz...")
104
  dot = Digraph(comment="Knowledge Graph", format='png')
105
  dot.attr(dpi='300')
106
- dot.attr(bgcolor='transparent')
107
 
108
  # Estilizar os n贸s
109
  dot.attr('node', shape='box', style='filled', fillcolor='lightblue', fontcolor='black')
@@ -118,31 +134,40 @@ def generate_knowledge_graph(api_key, user_input):
118
  dot.edge(edge["from"], edge["to"], label=edge["relationship"], color=edge.get("color", "black"))
119
 
120
  # Renderizar para o formato PNG
121
- print("Renderizando o gr谩fico para o formato PNG...")
122
  image_data = dot.pipe()
123
  image = Image.open(io.BytesIO(image_data))
124
 
125
- print("Gr谩fico gerado com sucesso!")
126
-
127
  return image
128
 
 
 
 
 
 
 
 
 
 
 
129
  # Define a title and description for the Gradio interface using Markdown
130
  title_and_description = """
131
  # Instagraph - Knowledge Graph Generator
132
 
133
  **Created by [ArtificialGuyBR](https://twitter.com/ArtificialGuyBR)**
134
 
135
- This interactive knowledge graph generator is inspired by [this GitHub project](https://github.com/yoheinakajima/instagraph/).
 
 
136
 
137
- Enter your OpenAI API Key and a question, and let the AI create a detailed knowledge graph for you.
138
  """
139
 
140
  # Create the Gradio interface with queueing enabled and concurrency_count set to 10
141
  iface = gr.Interface(
142
- fn=generate_knowledge_graph,
143
  inputs=[
144
  gr.inputs.Textbox(label="OpenAI API Key", type="password"),
145
- gr.inputs.Textbox(label="User Input for Graph", type="text"),
146
  ],
147
  outputs=gr.outputs.Image(type="pil", label="Generated Knowledge Graph"),
148
  live=False,
 
4
  from graphviz import Digraph
5
  from PIL import Image
6
  import io
7
+ import requests
8
+ from bs4 import BeautifulSoup
9
 
10
+ # Function to generate a knowledge graph from text
11
+ def generate_knowledge_graph_from_text(api_key, user_input):
12
+ # Ensure the API key and user input are provided
 
13
  if not api_key or not user_input:
14
  raise ValueError("Please provide both the OpenAI API Key and User Input")
15
 
16
+ # Process user input
17
+ response_data = process_user_input(api_key, user_input)
18
+ return generate_knowledge_graph(response_data)
19
+
20
+ # Function to generate a knowledge graph from a URL
21
+ def generate_knowledge_graph_from_url(api_key, url):
22
+ # Ensure the API key and URL are provided
23
+ if not api_key or not url:
24
+ raise ValueError("Please provide both the OpenAI API Key and a URL")
25
+
26
+ # Scrape text from the provided URL
27
+ text = scrape_text_from_url(url)
28
+
29
+ # Process the scraped text
30
+ response_data = process_user_input(api_key, text)
31
+ return generate_knowledge_graph(response_data)
32
+
33
+ # Function to process user input and call OpenAI API
34
+ def process_user_input(api_key, user_input):
35
+ openai.api_key = api_key
36
+
37
+ # Call the OpenAI API
38
  completion = openai.ChatCompletion.create(
39
  model="gpt-3.5-turbo-16k",
40
  messages=[
 
112
  )
113
 
114
  response_data = completion.choices[0]["message"]["function_call"]["arguments"]
115
+ return response_data
 
 
 
 
 
 
116
 
117
+ # Function to generate a knowledge graph from response data
118
+ def generate_knowledge_graph(response_data):
119
  # Visualizar o conhecimento usando Graphviz
 
120
  dot = Digraph(comment="Knowledge Graph", format='png')
121
  dot.attr(dpi='300')
122
+ dot.attr(bgcolor='white') # Set background color to white
123
 
124
  # Estilizar os n贸s
125
  dot.attr('node', shape='box', style='filled', fillcolor='lightblue', fontcolor='black')
 
134
  dot.edge(edge["from"], edge["to"], label=edge["relationship"], color=edge.get("color", "black"))
135
 
136
  # Renderizar para o formato PNG
 
137
  image_data = dot.pipe()
138
  image = Image.open(io.BytesIO(image_data))
139
 
 
 
140
  return image
141
 
142
+ # Function to scrape text from a website
143
+ def scrape_text_from_url(url):
144
+ response = requests.get(url)
145
+ if response.status_code != 200:
146
+ return "Error: Could not retrieve content from URL."
147
+ soup = BeautifulSoup(response.text, "html.parser")
148
+ paragraphs = soup.find_all("p")
149
+ text = " ".join([p.get_text() for p in paragraphs])
150
+ return text
151
+
152
  # Define a title and description for the Gradio interface using Markdown
153
  title_and_description = """
154
  # Instagraph - Knowledge Graph Generator
155
 
156
  **Created by [ArtificialGuyBR](https://twitter.com/ArtificialGuyBR)**
157
 
158
+ This interactive knowledge graph generator allows you to input either text or a URL.
159
+ If you provide text, it will generate a knowledge graph based on the text you provide.
160
+ If you provide a URL, it will scrape the content from the webpage and generate a knowledge graph from that.
161
 
162
+ To get started, enter your OpenAI API Key and either your text or a URL.
163
  """
164
 
165
  # Create the Gradio interface with queueing enabled and concurrency_count set to 10
166
  iface = gr.Interface(
167
+ fn=generate_knowledge_graph_from_text,
168
  inputs=[
169
  gr.inputs.Textbox(label="OpenAI API Key", type="password"),
170
+ gr.inputs.Textbox(label="Text or URL", type="text"),
171
  ],
172
  outputs=gr.outputs.Image(type="pil", label="Generated Knowledge Graph"),
173
  live=False,