ASCO-based-QA / graph_rag.py
AbdulMoid's picture
Update graph_rag.py
f38d527 verified
raw
history blame
2.48 kB
import os
import zipfile
import shutil
import logging
import subprocess
from dotenv import load_dotenv
import gradio as gr
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
def unzip_folder(zip_path, extract_path):
output_dir = os.path.join(extract_path, "ragtest")
os.makedirs(output_dir, exist_ok=True)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(output_dir)
logger.info(f"Extracted contents to {output_dir}")
logger.info(f"Contents of {output_dir}:")
for file in os.listdir(output_dir):
logger.info(os.path.join(output_dir, file))
return output_dir
def run_graphrag_query(query):
# Define the command
command = [
"python", "-m", "graphrag.query",
"--root", "./ragtest",
"--method", "local",
query
]
# Run the command
result = subprocess.run(command, capture_output=True, text=True)
# Return the output or error message
if result.returncode == 0:
return result.stdout
else:
return result.stderr
def qa_tool_graph_rag(user_question):
try:
# Paths from environment variables
zip_path = os.getenv('ZIP_PATH', '/home/user/app/ragtest.zip')
extract_path = os.getenv('EXTRACT_PATH', '/home/user/app')
# Unzip the folder
output_dir = unzip_folder(zip_path, extract_path)
# Change to the directory containing the ragtest folder
os.chdir(extract_path)
# Run the GraphRAG query
answer = run_graphrag_query(user_question)
logger.info(f"GraphRAG answer generated: {answer}")
# For simplicity, we're not handling images here.
# You may need to adjust this based on how GraphRAG returns results.
images = []
return answer, images, gr.update(visible=True), gr.update(visible=True)
except Exception as e:
logger.error(f"Error in GraphRAG processing: {str(e)}")
return f"An error occurred: {str(e)}", [], gr.update(visible=False), gr.update(visible=False)
finally:
# Clean up: remove the extracted directory
if 'output_dir' in locals():
shutil.rmtree(output_dir)
# Change back to the original directory
os.chdir('/home/user/app')