Commit ·
642e149
1
Parent(s): c6521f5
....
Browse files- app.py +7 -7
- app_v1.py +0 -66
- generate_knowledge_graph.py +2 -2
- generate_knowledge_graph_v1.py +0 -127
- requirements_v1.txt +0 -16
app.py
CHANGED
|
@@ -44,24 +44,24 @@ if st.sidebar.button("1. Generate Knowledge Graph"):
|
|
| 44 |
# QA Section
|
| 45 |
if 'graph_docs' in st.session_state:
|
| 46 |
st.markdown("---")
|
| 47 |
-
st.subheader("
|
| 48 |
|
| 49 |
col1, col2 = st.columns([3, 1])
|
| 50 |
with col1:
|
| 51 |
-
question = st.text_input("
|
| 52 |
with col2:
|
| 53 |
-
k_value = st.slider("
|
| 54 |
|
| 55 |
-
if st.button("2.
|
| 56 |
-
with st.spinner("
|
| 57 |
answer, filtered_net = answer_question_with_graph(
|
| 58 |
question,
|
| 59 |
st.session_state['graph_docs'],
|
| 60 |
k_relations=k_value
|
| 61 |
)
|
| 62 |
|
| 63 |
-
st.info(f"**
|
| 64 |
|
| 65 |
-
st.markdown("**
|
| 66 |
HtmlFile = open("filtered_graph.html", 'r', encoding='utf-8')
|
| 67 |
components.html(HtmlFile.read(), height=450)
|
|
|
|
| 44 |
# QA Section
|
| 45 |
if 'graph_docs' in st.session_state:
|
| 46 |
st.markdown("---")
|
| 47 |
+
st.subheader("Ask a question about the document")
|
| 48 |
|
| 49 |
col1, col2 = st.columns([3, 1])
|
| 50 |
with col1:
|
| 51 |
+
question = st.text_input("Your question :")
|
| 52 |
with col2:
|
| 53 |
+
k_value = st.slider("Relationships to be analyzed (Top K)", min_value=1, max_value=20, value=7)
|
| 54 |
|
| 55 |
+
if st.button("2. Analyze") and question:
|
| 56 |
+
with st.spinner("Semantic search in the current graph..."):
|
| 57 |
answer, filtered_net = answer_question_with_graph(
|
| 58 |
question,
|
| 59 |
st.session_state['graph_docs'],
|
| 60 |
k_relations=k_value
|
| 61 |
)
|
| 62 |
|
| 63 |
+
st.info(f"**Answer :** {answer}")
|
| 64 |
|
| 65 |
+
st.markdown("**Subgraph of the relationships used to answer the question :**")
|
| 66 |
HtmlFile = open("filtered_graph.html", 'r', encoding='utf-8')
|
| 67 |
components.html(HtmlFile.read(), height=450)
|
app_v1.py
DELETED
|
@@ -1,66 +0,0 @@
|
|
| 1 |
-
# Import necessary modules
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import streamlit.components.v1 as components # For embedding custom HTML
|
| 4 |
-
from generate_knowledge_graph import generate_knowledge_graph
|
| 5 |
-
|
| 6 |
-
# Set up Streamlit page configuration
|
| 7 |
-
st.set_page_config(
|
| 8 |
-
page_icon=None,
|
| 9 |
-
layout="wide", # Use wide layout for better graph display
|
| 10 |
-
initial_sidebar_state="auto",
|
| 11 |
-
menu_items=None
|
| 12 |
-
)
|
| 13 |
-
|
| 14 |
-
# Set the title of the app
|
| 15 |
-
st.title("Knowledge Graph From Text")
|
| 16 |
-
|
| 17 |
-
# Sidebar section for user input method
|
| 18 |
-
st.sidebar.title("Input document")
|
| 19 |
-
input_method = st.sidebar.radio(
|
| 20 |
-
"Choose an input method:",
|
| 21 |
-
["Upload txt", "Input text"], # Options for uploading a file or manually inputting text
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
# Case 1: User chooses to upload a .txt file
|
| 25 |
-
if input_method == "Upload txt":
|
| 26 |
-
# File uploader widget in the sidebar
|
| 27 |
-
uploaded_file = st.sidebar.file_uploader(label="Upload file", type=["txt"])
|
| 28 |
-
|
| 29 |
-
if uploaded_file is not None:
|
| 30 |
-
# Read the uploaded file content and decode it as UTF-8 text
|
| 31 |
-
text = uploaded_file.read().decode("utf-8")
|
| 32 |
-
|
| 33 |
-
# Button to generate the knowledge graph
|
| 34 |
-
if st.sidebar.button("Generate Knowledge Graph"):
|
| 35 |
-
with st.spinner("Generating knowledge graph..."):
|
| 36 |
-
# Call the function to generate the graph from the text
|
| 37 |
-
net = generate_knowledge_graph(text)
|
| 38 |
-
st.success("Knowledge graph generated successfully!")
|
| 39 |
-
|
| 40 |
-
# Save the graph to an HTML file
|
| 41 |
-
output_file = "knowledge_graph.html"
|
| 42 |
-
net.save_graph(output_file)
|
| 43 |
-
|
| 44 |
-
# Open the HTML file and display it within the Streamlit app
|
| 45 |
-
HtmlFile = open(output_file, 'r', encoding='utf-8')
|
| 46 |
-
components.html(HtmlFile.read(), height=1000)
|
| 47 |
-
|
| 48 |
-
# Case 2: User chooses to directly input text
|
| 49 |
-
else:
|
| 50 |
-
# Text area for manual input
|
| 51 |
-
text = st.sidebar.text_area("Input text", height=300)
|
| 52 |
-
|
| 53 |
-
if text: # Check if the text area is not empty
|
| 54 |
-
if st.sidebar.button("Generate Knowledge Graph"):
|
| 55 |
-
with st.spinner("Generating knowledge graph..."):
|
| 56 |
-
# Call the function to generate the graph from the input text
|
| 57 |
-
net = generate_knowledge_graph(text)
|
| 58 |
-
st.success("Knowledge graph generated successfully!")
|
| 59 |
-
|
| 60 |
-
# Save the graph to an HTML file
|
| 61 |
-
output_file = "knowledge_graph.html"
|
| 62 |
-
net.save_graph(output_file)
|
| 63 |
-
|
| 64 |
-
# Open the HTML file and display it within the Streamlit app
|
| 65 |
-
HtmlFile = open(output_file, 'r', encoding='utf-8')
|
| 66 |
-
components.html(HtmlFile.read(), height=1000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
generate_knowledge_graph.py
CHANGED
|
@@ -55,7 +55,7 @@ def generate_knowledge_graph(text):
|
|
| 55 |
net = visualize_graph(graph_documents)
|
| 56 |
return net, graph_documents
|
| 57 |
|
| 58 |
-
def answer_question_with_graph(question, graph_documents, k_relations=
|
| 59 |
all_relationships = []
|
| 60 |
for doc in graph_documents:
|
| 61 |
all_relationships.extend(doc.relationships)
|
|
@@ -76,7 +76,7 @@ def answer_question_with_graph(question, graph_documents, k_relations=5):
|
|
| 76 |
context = "\n".join([doc.page_content for doc in retrieved_docs])
|
| 77 |
|
| 78 |
prompt = PromptTemplate(
|
| 79 |
-
template='''Tu es un assistant expert qui répond aux questions en se basant UNIQUEMENT sur ce sous-ensemble de relations extraites d'un graphe de connaissances.\n\nContexte (Relations pertinentes trouvées) :\n{context}\n\nQuestion : {question}\n\nRéponds de manière claire et concise en
|
| 80 |
input_variables=["context", "question"]
|
| 81 |
)
|
| 82 |
|
|
|
|
| 55 |
net = visualize_graph(graph_documents)
|
| 56 |
return net, graph_documents
|
| 57 |
|
| 58 |
+
def answer_question_with_graph(question, graph_documents, k_relations=7):
|
| 59 |
all_relationships = []
|
| 60 |
for doc in graph_documents:
|
| 61 |
all_relationships.extend(doc.relationships)
|
|
|
|
| 76 |
context = "\n".join([doc.page_content for doc in retrieved_docs])
|
| 77 |
|
| 78 |
prompt = PromptTemplate(
|
| 79 |
+
template='''Tu es un assistant expert qui répond aux questions en se basant UNIQUEMENT sur ce sous-ensemble de relations extraites d'un graphe de connaissances.\n\nContexte (Relations pertinentes trouvées) :\n{context}\n\nQuestion : {question}\n\nRéponds de manière claire et concise en anglais. Si la réponse n'est pas dans le contexte fourni, dis-le explicitement.''',
|
| 80 |
input_variables=["context", "question"]
|
| 81 |
)
|
| 82 |
|
generate_knowledge_graph_v1.py
DELETED
|
@@ -1,127 +0,0 @@
|
|
| 1 |
-
from langchain_experimental.graph_transformers import LLMGraphTransformer
|
| 2 |
-
from langchain_core.documents import Document
|
| 3 |
-
from langchain_openai import ChatOpenAI
|
| 4 |
-
from pyvis.network import Network
|
| 5 |
-
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
import os
|
| 8 |
-
import asyncio
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
# Load the .env file
|
| 12 |
-
load_dotenv()
|
| 13 |
-
# Get API key from environment variable
|
| 14 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 15 |
-
|
| 16 |
-
llm = ChatOpenAI(temperature=0, model_name="gpt-4o")
|
| 17 |
-
|
| 18 |
-
graph_transformer = LLMGraphTransformer(llm=llm)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# Extract graph data from input text
|
| 22 |
-
async def extract_graph_data(text):
|
| 23 |
-
"""
|
| 24 |
-
Asynchronously extracts graph data from input text using a graph transformer.
|
| 25 |
-
|
| 26 |
-
Args:
|
| 27 |
-
text (str): Input text to be processed into graph format.
|
| 28 |
-
|
| 29 |
-
Returns:
|
| 30 |
-
list: A list of GraphDocument objects containing nodes and relationships.
|
| 31 |
-
"""
|
| 32 |
-
documents = [Document(page_content=text)]
|
| 33 |
-
graph_documents = await graph_transformer.aconvert_to_graph_documents(documents)
|
| 34 |
-
return graph_documents
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def visualize_graph(graph_documents):
|
| 38 |
-
"""
|
| 39 |
-
Visualizes a knowledge graph using PyVis based on the extracted graph documents.
|
| 40 |
-
|
| 41 |
-
Args:
|
| 42 |
-
graph_documents (list): A list of GraphDocument objects with nodes and relationships.
|
| 43 |
-
|
| 44 |
-
Returns:
|
| 45 |
-
pyvis.network.Network: The visualized network graph object.
|
| 46 |
-
"""
|
| 47 |
-
# Create network
|
| 48 |
-
net = Network(height="1200px", width="100%", directed=True,
|
| 49 |
-
notebook=False, bgcolor="#222222", font_color="white", filter_menu=True, cdn_resources='remote')
|
| 50 |
-
|
| 51 |
-
nodes = graph_documents[0].nodes
|
| 52 |
-
relationships = graph_documents[0].relationships
|
| 53 |
-
|
| 54 |
-
# Build lookup for valid nodes
|
| 55 |
-
node_dict = {node.id: node for node in nodes}
|
| 56 |
-
|
| 57 |
-
# Filter out invalid edges and collect valid node IDs
|
| 58 |
-
valid_edges = []
|
| 59 |
-
valid_node_ids = set()
|
| 60 |
-
for rel in relationships:
|
| 61 |
-
if rel.source.id in node_dict and rel.target.id in node_dict:
|
| 62 |
-
valid_edges.append(rel)
|
| 63 |
-
valid_node_ids.update([rel.source.id, rel.target.id])
|
| 64 |
-
|
| 65 |
-
# Track which nodes are part of any relationship
|
| 66 |
-
connected_node_ids = set()
|
| 67 |
-
for rel in relationships:
|
| 68 |
-
connected_node_ids.add(rel.source.id)
|
| 69 |
-
connected_node_ids.add(rel.target.id)
|
| 70 |
-
|
| 71 |
-
# Add valid nodes to the graph
|
| 72 |
-
for node_id in valid_node_ids:
|
| 73 |
-
node = node_dict[node_id]
|
| 74 |
-
try:
|
| 75 |
-
net.add_node(node.id, label=node.id, title=node.type, group=node.type)
|
| 76 |
-
except:
|
| 77 |
-
continue # Skip node if error occurs
|
| 78 |
-
|
| 79 |
-
# Add valid edges to the graph
|
| 80 |
-
for rel in valid_edges:
|
| 81 |
-
try:
|
| 82 |
-
net.add_edge(rel.source.id, rel.target.id, label=rel.type.lower())
|
| 83 |
-
except:
|
| 84 |
-
continue # Skip edge if error occurs
|
| 85 |
-
|
| 86 |
-
# Configure graph layout and physics
|
| 87 |
-
net.set_options("""
|
| 88 |
-
{
|
| 89 |
-
"physics": {
|
| 90 |
-
"forceAtlas2Based": {
|
| 91 |
-
"gravitationalConstant": -100,
|
| 92 |
-
"centralGravity": 0.01,
|
| 93 |
-
"springLength": 200,
|
| 94 |
-
"springConstant": 0.08
|
| 95 |
-
},
|
| 96 |
-
"minVelocity": 0.75,
|
| 97 |
-
"solver": "forceAtlas2Based"
|
| 98 |
-
}
|
| 99 |
-
}
|
| 100 |
-
""")
|
| 101 |
-
|
| 102 |
-
output_file = "knowledge_graph.html"
|
| 103 |
-
try:
|
| 104 |
-
net.save_graph(output_file)
|
| 105 |
-
print(f"Graph saved to {os.path.abspath(output_file)}")
|
| 106 |
-
return net
|
| 107 |
-
except Exception as e:
|
| 108 |
-
print(f"Error saving graph: {e}")
|
| 109 |
-
return None
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def generate_knowledge_graph(text):
|
| 113 |
-
"""
|
| 114 |
-
Generates and visualizes a knowledge graph from input text.
|
| 115 |
-
|
| 116 |
-
This function runs the graph extraction asynchronously and then visualizes
|
| 117 |
-
the resulting graph using PyVis.
|
| 118 |
-
|
| 119 |
-
Args:
|
| 120 |
-
text (str): Input text to convert into a knowledge graph.
|
| 121 |
-
|
| 122 |
-
Returns:
|
| 123 |
-
pyvis.network.Network: The visualized network graph object.
|
| 124 |
-
"""
|
| 125 |
-
graph_documents = asyncio.run(extract_graph_data(text))
|
| 126 |
-
net = visualize_graph(graph_documents)
|
| 127 |
-
return net
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements_v1.txt
DELETED
|
@@ -1,16 +0,0 @@
|
|
| 1 |
-
# Core LLM and LangChain packages
|
| 2 |
-
langchain>=0.1.0
|
| 3 |
-
langchain-experimental>=0.0.45
|
| 4 |
-
langchain-openai>=0.1.0
|
| 5 |
-
|
| 6 |
-
# Environment variable support
|
| 7 |
-
python-dotenv>=1.0.0
|
| 8 |
-
|
| 9 |
-
# Graph visualization
|
| 10 |
-
pyvis>=0.3.2
|
| 11 |
-
|
| 12 |
-
# Web UI
|
| 13 |
-
streamlit>=1.32.0
|
| 14 |
-
|
| 15 |
-
faiss-cpu
|
| 16 |
-
tiktoken
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|