Spaces:
Sleeping
Sleeping
File size: 5,401 Bytes
1b795b8 | 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 | import os
from dotenv import load_dotenv
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_groq import ChatGroq
from langchain_community.document_loaders import PyPDFLoader, TextLoader, Docx2txtLoader, CSVLoader, UnstructuredMarkdownLoader, UnstructuredExcelLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
class DocumentManager:
def __init__(self):
load_dotenv()
# Embeddings model (still HuggingFace, runs locally)
self.embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
self.vector_store = None
groq_api_key = os.getenv("GROQ_API_KEY")
if not groq_api_key:
raise ValueError(
"GROQ_API_KEY is missing. Add it to a .env file or set it as an environment variable."
)
# Default model can change over time; override via GROQ_MODEL in .env if needed.
model = os.getenv("GROQ_MODEL", "llama-3.1-8b-instant")
self.llm = ChatGroq(
groq_api_key=groq_api_key,
model=model,
temperature=0,
)
@staticmethod
def _llm_text(response) -> str:
"""Normalizes chat/non-chat LLM responses to plain text."""
return getattr(response, "content", str(response))
def load_documents(self, file_path):
"""Loads and processes the documents"""
# Load specific type of documents
if file_path.endswith(".pdf"):
loader = PyPDFLoader(file_path)
elif file_path.endswith(".txt"):
loader = TextLoader(file_path, encoding="utf-8")
elif file_path.endswith(".docx"):
loader = Docx2txtLoader(file_path)
elif file_path.endswith(".csv"):
loader = CSVLoader(file_path)
elif file_path.endswith(".md"):
loader = UnstructuredMarkdownLoader(file_path)
elif file_path.endswith(".xlsx") or file_path.endswith(".xls"):
loader = UnstructuredExcelLoader(file_path)
else:
return f"❌ Unsupported file type: {file_path}"
# Load and split
documents = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
texts = splitter.split_documents(documents)
# Create or update vector store
if self.vector_store is None:
self.vector_store = FAISS.from_documents(texts, self.embeddings)
else:
self.vector_store.add_documents(texts)
return f"Document {file_path} loaded successfully!"
def ask_question(self, question):
"""Ask a question about loaded documents"""
if self.vector_store is None:
return "No documents loaded yet!"
qa_chain = RetrievalQA.from_chain_type(
llm=self.llm,
retriever=self.vector_store.as_retriever()
)
return qa_chain.run(question)
def summarise_document(self, file_path):
"""Generates summary for the document"""
self.load_documents(file_path)
summary_prompt = """
Please provide a concise summary of the document, including:
1. Main topics covered
2. Key points
3. Important conclusions
"""
return self.ask_question(summary_prompt)
def compare_documents(self, file1_path, file2_path):
"""Compares two documents"""
self.load_documents(file1_path)
doc1_summary = self.summarise_document(file1_path)
self.load_documents(file2_path)
doc2_summary = self.summarise_document(file2_path)
compare_prompt = f"""
Compare these documents:
Document 1: {doc1_summary}
Document 2: {doc2_summary}
Please highlight:
1. Common themes
2. Key differences
3. Unique points in each document
"""
return self.ask_question(compare_prompt)
def extract_keywords(self): #extract key words from the document
if self.vector_store is None:
return "No documents loaded yet!"
docs = self.vector_store.similarity_search("",k=2)
full_text = " ".join([doc.page_content for doc in docs])
prompt = f"Extract the top 10 most important keywords from the following text:\n\n{full_text}"
return self._llm_text(self.llm.invoke(prompt))
def sentiment_analysis(self): #performs sentiment analysis of the document
if self.vector_store is None:
return "No documents loaded yet!"
docs = self.vector_store.similarity_search("",k=2)
full_text = " ".join([doc.page_content for doc in docs])
prompt = f"Analyze the overall sentiment of the following text and explain why:\n\n{full_text}"
return self._llm_text(self.llm.invoke(prompt))
def translate_text(self,target_language): #translates text in the document
if self.vector_store is None:
return "No documents loaded yet!"
docs = self.vector_store.similarity_search("",k=2)
full_text = " ".join([doc.page_content for doc in docs])
prompt = f"Translate the following text to {target_language}:\n\n{full_text}"
return self._llm_text(self.llm.invoke(prompt)) |