Spaces:
Sleeping
Sleeping
File size: 7,080 Bytes
8ea927a 410031a 41813c2 48b792e b2968ad 8ea927a 0ea720c 48b792e 0ea720c e6f14fa b31a1e4 ae1288e 9ec289c b31a1e4 ae1288e 8ea927a 0ea720c ae1288e 0ea720c 7af8c4a b2968ad 7af8c4a a4b8ea3 b2968ad a4b8ea3 a5dd2fe a4b8ea3 0ea720c 77f6b05 9ec289c 0ea720c a4b8ea3 0ea720c 77f6b05 9ec289c 0ea720c a4b8ea3 41813c2 8ea927a 0ea720c 48b792e 4f2de6f ea82e47 4f2de6f 0ea720c a5dd2fe ea82e47 4f2de6f ea82e47 b44dadb 8ea927a b44dadb |
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 |
import gradio as gr
import openai
import json
from graphviz import Digraph
from PIL import Image
import io
import requests
from bs4 import BeautifulSoup
from ast import literal_eval
# Function to scrape text from a website
def scrape_text_from_url(url):
response = requests.get(url)
if response.status_code != 200:
return "Error: Could not retrieve content from URL."
soup = BeautifulSoup(response.text, "html.parser")
paragraphs = soup.find_all("p")
text = " ".join([p.get_text() for p in paragraphs])
return text
def generate_knowledge_graph(api_key, user_input):
openai.api_key = api_key
# Check if input is URL or text
if user_input.startswith("http://") or user_input.startswith("https://"):
user_input = scrape_text_from_url(user_input)
# Chamar a API da OpenAI
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo-16k",
messages=[
{
"role": "user",
"content": f"Help me understand following by describing as a detailed knowledge graph: {user_input}",
}
],
functions=[
{
"name": "knowledge_graph",
"description": "Generate a knowledge graph with entities and relationships. Use the colors to help differentiate between different node or edge types/categories. Always provide light pastel colors that work well with black font.",
"parameters": {
"type": "object",
"properties": {
"metadata": {
"type": "object",
"properties": {
"createdDate": {"type": "string"},
"lastUpdated": {"type": "string"},
"description": {"type": "string"},
},
},
"nodes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string"},
"label": {"type": "string"},
"type": {"type": "string"},
"color": {"type": "string"}, # Added color property
"properties": {
"type": "object",
"description": "Additional attributes for the node",
},
},
"required": [
"id",
"label",
"type",
"color",
], # Added color to required
},
},
"edges": {
"type": "array",
"items": {
"type": "object",
"properties": {
"from": {"type": "string"},
"to": {"type": "string"},
"relationship": {"type": "string"},
"direction": {"type": "string"},
"color": {"type": "string"}, # Added color property
"properties": {
"type": "object",
"description": "Additional attributes for the edge",
},
},
"required": [
"from",
"to",
"relationship",
"color",
], # Added color to required
},
},
},
"required": ["nodes", "edges"],
},
}
],
function_call={"name": "knowledge_graph"},
)
response_data = completion.choices[0]["message"]["function_call"]["arguments"]
try:
if isinstance(response_data, str):
response_data = literal_eval(response_data)
except (ValueError, SyntaxError) as e:
print(f"Error in decoding JSON or literal_eval: {e}")
return "Error in decoding JSON"
if not isinstance(response_data, dict):
print("Unexpected data type for response_data")
return "Error: Unexpected data type"
dot = Digraph(comment="Knowledge Graph", format='png')
dot.attr(dpi='300')
dot.attr(bgcolor='white')
dot.attr('node', shape='box', style='filled', fillcolor='lightblue', fontcolor='black')
for node in response_data.get("nodes", []):
dot.node(node["id"], f"{node['label']} ({node['type']})", color=node.get("color", "lightblue"))
dot.attr('edge', color='black', fontcolor='black')
for edge in response_data.get("edges", []):
dot.edge(edge["from"], edge["to"], label=edge["relationship"], color=edge.get("color", "black"))
image_data = dot.pipe()
image = Image.open(io.BytesIO(image_data))
return image
title_and_description = """
# Instagraph - Knowledge Graph Generator
Created by [@artificialguybr](https://twitter.com/artificialguybr)
Code by [Instagraph on GitHub](https://github.com/yoheinakajima/instagraph)
Enter your OpenAI API Key and a question, and let the AI create a detailed knowledge graph for you.
## Features
- **URL**: You can now input a URL to scrape text for generating the knowledge graph.
- **Security**: Rest assured, the code is open for your inspection in the files. There's no risk in using your OpenAI API key here.
- **Best View**: For the best visualization, consider downloading the generated image.
- **Flexible Input**: You can either type what you want the API to generate as a graph or use a URL for this purpose.
Feel free to explore and generate your own knowledge graphs!
"""
with gr.Blocks() as app:
gr.Markdown(title_and_description)
with gr.Row():
with gr.Column():
result_image = gr.Image(type="pil", label="Generated Knowledge Graph")
with gr.Row():
with gr.Column():
api_key = gr.Textbox(label="OpenAI API Key", type="password")
user_input = gr.Textbox(label="User Input for Graph or URL", type="text")
run_btn = gr.Button("Generate")
run_btn.click(
generate_knowledge_graph,
inputs=[api_key, user_input],
outputs=[result_image]
)
app.queue(concurrency_count=10)
print("Iniciando a interface Gradio...")
app.launch() |