import os
os.system("python -m spacy download en_core_web_sm")
import io
import base64
import streamlit as st
import numpy as np
import fitz # PyMuPDF
import tempfile
from ultralytics import YOLO
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import cosine_similarity
from langchain_core.output_parsers import StrOutputParser
from langchain_community.document_loaders import PyMuPDFLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_text_splitters import SpacyTextSplitter
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
import re
from PIL import Image
from streamlit_chat import message
# Load the trained model
model = YOLO("best.pt")
openai_api_key = os.environ.get("openai_api_key")
# Define the class indices for figures, tables, and text
figure_class_index = 4
table_class_index = 3
# Utility functions
def clean_text(text):
return re.sub(r'\s+', ' ', text).strip()
def remove_references(text):
reference_patterns = [
r'\bReferences\b', r'\breferences\b', r'\bBibliography\b', r'\bCitations\b',
r'\bWorks Cited\b', r'\bReference\b', r'\breference\b'
]
lines = text.split('\n')
for i, line in enumerate(lines):
if any(re.search(pattern, line, re.IGNORECASE) for pattern in reference_patterns):
return '\n'.join(lines[:i])
return text
def save_uploaded_file(uploaded_file):
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.write(uploaded_file.getbuffer())
temp_file.close()
return temp_file.name
def summarize_pdf(pdf_file_path, num_clusters=10):
embeddings_model = OpenAIEmbeddings(model="text-embedding-3-small", api_key=openai_api_key)
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_api_key, temperature=0.3)
prompt = ChatPromptTemplate.from_template(
"""Could you please provide a concise and comprehensive summary of the given Contexts?
The summary should capture the main points and key details of the text while conveying the author's intended meaning accurately.
Please ensure that the summary is well-organized and easy to read, with clear headings and subheadings to guide the reader through each section.
The length of the summary should be appropriate to capture the main points and key details of the text, without including unnecessary information or becoming overly long.
example of summary:
## Summary:
## Key points:
Contexts: {topic}"""
)
output_parser = StrOutputParser()
chain = prompt | llm | output_parser
loader = PyMuPDFLoader(pdf_file_path)
docs = loader.load()
full_text = "\n".join(doc.page_content for doc in docs)
cleaned_full_text = clean_text(remove_references(full_text))
text_splitter = SpacyTextSplitter(chunk_size=500)
#text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0, separators=["\n\n", "\n", ".", " "])
split_contents = text_splitter.split_text(cleaned_full_text)
embeddings = embeddings_model.embed_documents(split_contents)
kmeans = KMeans(n_clusters=num_clusters, init='k-means++', random_state=0).fit(embeddings)
closest_point_indices = [np.argmin(np.linalg.norm(embeddings - center, axis=1)) for center in kmeans.cluster_centers_]
extracted_contents = [split_contents[idx] for idx in closest_point_indices]
results = chain.invoke({"topic": ' '.join(extracted_contents)})
return generate_citations(results, extracted_contents)
def qa_pdf(pdf_file_path, query, num_clusters=5, similarity_threshold=0.6):
embeddings_model = OpenAIEmbeddings(model="text-embedding-3-small", api_key=openai_api_key)
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_api_key, temperature=0.3)
prompt = ChatPromptTemplate.from_template(
"""Please provide a detailed and accurate answer to the given question based on the provided contexts.
Ensure that the answer is comprehensive and directly addresses the query.
If necessary, include relevant examples or details from the text.
Question: {question}
Contexts: {contexts}"""
)
output_parser = StrOutputParser()
chain = prompt | llm | output_parser
loader = PyMuPDFLoader(pdf_file_path)
docs = loader.load()
full_text = "\n".join(doc.page_content for doc in docs)
cleaned_full_text = clean_text(remove_references(full_text))
text_splitter = SpacyTextSplitter(chunk_size=500)
#text_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=0, separators=["\n\n", "\n", ".", " "])
split_contents = text_splitter.split_text(cleaned_full_text)
embeddings = embeddings_model.embed_documents(split_contents)
query_embedding = embeddings_model.embed_query(query)
similarity_scores = cosine_similarity([query_embedding], embeddings)[0]
top_indices = np.argsort(similarity_scores)[-num_clusters:]
relevant_contents = [split_contents[i] for i in top_indices]
results = chain.invoke({"question": query, "contexts": ' '.join(relevant_contents)})
return generate_citations(results, relevant_contents, similarity_threshold)
def generate_citations(text, contents, similarity_threshold=0.6):
embeddings_model = OpenAIEmbeddings(model="text-embedding-3-small", api_key=openai_api_key)
text_sentences = re.split(r'(?= similarity_threshold:
most_similar_idx = np.argmax(similarity_matrix[i])
if most_similar_idx not in source_mapping:
source_mapping[most_similar_idx] = len(relevant_sources) + 1
relevant_sources.append((most_similar_idx, contents[most_similar_idx]))
citation_idx = source_mapping[most_similar_idx]
citation = f"([Source {citation_idx}](#source-{citation_idx}))"
cited_sentence = re.sub(r'([.!?])$', f" {citation}\\1", sentence)
sentence_to_source[sentence] = citation_idx
cited_text = cited_text.replace(sentence, cited_sentence)
sources_list = "\n\n## Sources:\n"
for idx, (original_idx, content) in enumerate(relevant_sources):
sources_list += f"""
Source {idx + 1}
{content}