Spaces:
Sleeping
Sleeping
Update rag_agent.py
Browse files- rag_agent.py +93 -71
rag_agent.py
CHANGED
|
@@ -1,71 +1,93 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from
|
| 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 |
-
print(
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 3 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
+
import numpy as np
|
| 5 |
+
import PyPDF2
|
| 6 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
def load_document(file_path: str) -> str:
|
| 10 |
+
"""Load document content from PDF or TXT file."""
|
| 11 |
+
try:
|
| 12 |
+
if file_path.endswith(".pdf"):
|
| 13 |
+
with open(file_path, 'rb') as file:
|
| 14 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
| 15 |
+
text = ""
|
| 16 |
+
for page in pdf_reader.pages:
|
| 17 |
+
text += page.extract_text() + "\n"
|
| 18 |
+
return text
|
| 19 |
+
elif file_path.endswith(".txt"):
|
| 20 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 21 |
+
return file.read()
|
| 22 |
+
else:
|
| 23 |
+
return "Error: Unsupported file format."
|
| 24 |
+
except Exception as e:
|
| 25 |
+
return f"Error reading file: {str(e)}"
|
| 26 |
+
|
| 27 |
+
def simple_text_search(query: str, document_text: str, max_chunks: int = 3) -> str:
|
| 28 |
+
"""Simple TF-IDF based text retrieval - much faster than FAISS."""
|
| 29 |
+
|
| 30 |
+
# Split document into chunks
|
| 31 |
+
chunks = []
|
| 32 |
+
words = document_text.split()
|
| 33 |
+
chunk_size = 200 # words per chunk
|
| 34 |
+
|
| 35 |
+
for i in range(0, len(words), chunk_size):
|
| 36 |
+
chunk = " ".join(words[i:i + chunk_size])
|
| 37 |
+
if chunk.strip():
|
| 38 |
+
chunks.append(chunk)
|
| 39 |
+
|
| 40 |
+
if not chunks:
|
| 41 |
+
return "No content found in document."
|
| 42 |
+
|
| 43 |
+
# Create TF-IDF vectors
|
| 44 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
# Vectorize chunks and query
|
| 48 |
+
chunk_vectors = vectorizer.fit_transform(chunks)
|
| 49 |
+
query_vector = vectorizer.transform([query])
|
| 50 |
+
|
| 51 |
+
# Calculate similarity
|
| 52 |
+
similarities = cosine_similarity(query_vector, chunk_vectors).flatten()
|
| 53 |
+
|
| 54 |
+
# Get top matching chunks
|
| 55 |
+
top_indices = similarities.argsort()[-max_chunks:][::-1]
|
| 56 |
+
|
| 57 |
+
relevant_chunks = [chunks[i] for i in top_indices if similarities[i] > 0.1]
|
| 58 |
+
|
| 59 |
+
return "\n\n".join(relevant_chunks[:max_chunks])
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return f"Search error: {str(e)}"
|
| 63 |
+
|
| 64 |
+
def run_rag_agent(user_prompt: str, file_path: str) -> str:
|
| 65 |
+
"""Simple but effective RAG implementation."""
|
| 66 |
+
print("--- RAG Agent Activated (Lightweight Version) ---")
|
| 67 |
+
|
| 68 |
+
# Load document
|
| 69 |
+
document_text = load_document(file_path)
|
| 70 |
+
if document_text.startswith("Error"):
|
| 71 |
+
return document_text
|
| 72 |
+
|
| 73 |
+
# Generate search query using LLM
|
| 74 |
+
api_key = st.secrets.get("GEMINI_API_KEY", os.getenv("GEMINI_API_KEY"))
|
| 75 |
+
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", google_api_key=api_key)
|
| 76 |
+
|
| 77 |
+
search_prompt = f"""Based on this story idea: "{user_prompt}"
|
| 78 |
+
|
| 79 |
+
What are the 2-3 most important keywords to search for in a document to find relevant context?
|
| 80 |
+
Respond with just the keywords separated by spaces."""
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
response = llm.invoke(search_prompt)
|
| 84 |
+
search_query = response.content.strip()
|
| 85 |
+
print(f"Generated Search Query: {search_query}")
|
| 86 |
+
except:
|
| 87 |
+
search_query = user_prompt # Fallback
|
| 88 |
+
|
| 89 |
+
# Retrieve relevant content
|
| 90 |
+
context = simple_text_search(search_query, document_text)
|
| 91 |
+
|
| 92 |
+
print("--- RAG Agent Finished ---")
|
| 93 |
+
return context
|