Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from langchain.document_loaders import PyPDFLoader
|
| 3 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 4 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
| 5 |
+
from langchain.vectorstores import FAISS
|
| 6 |
+
from langchain.memory import ConversationBufferMemory
|
| 7 |
+
from groq import Groq
|
| 8 |
+
import requests
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
|
| 11 |
+
client = Groq(api_key="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")
|
| 12 |
+
embedding_model = SentenceTransformerEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
| 13 |
+
|
| 14 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 15 |
+
|
| 16 |
+
def process_pdf_with_langchain(pdf_path):
|
| 17 |
+
"""Process the PDF file using LangChain for RAG."""
|
| 18 |
+
loader = PyPDFLoader(pdf_path)
|
| 19 |
+
documents = loader.load()
|
| 20 |
+
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 21 |
+
split_documents = text_splitter.split_documents(documents)
|
| 22 |
+
|
| 23 |
+
vectorstore = FAISS.from_documents(split_documents, embedding_model)
|
| 24 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 25 |
+
return retriever
|
| 26 |
+
|
| 27 |
+
def scrape_google_search(query, num_results=3):
|
| 28 |
+
"""Search Google and return the top results."""
|
| 29 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 30 |
+
search_url = f"https://www.google.com/search?q={query}"
|
| 31 |
+
response = requests.get(search_url, headers=headers)
|
| 32 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 33 |
+
|
| 34 |
+
results = []
|
| 35 |
+
for g in soup.find_all('div', class_='tF2Cxc')[:num_results]:
|
| 36 |
+
title = g.find('h3').text
|
| 37 |
+
link = g.find('a')['href']
|
| 38 |
+
results.append(f"{title}: {link}")
|
| 39 |
+
return "\n".join(results)
|
| 40 |
+
|
| 41 |
+
def generate_response(query, retriever=None, use_web_search=False):
|
| 42 |
+
"""Generate a response using LangChain with optional retriever and web search."""
|
| 43 |
+
knowledge = ""
|
| 44 |
+
|
| 45 |
+
if retriever:
|
| 46 |
+
relevant_docs = retriever.get_relevant_documents(query)
|
| 47 |
+
knowledge += "\n".join([doc.page_content for doc in relevant_docs])
|
| 48 |
+
|
| 49 |
+
if use_web_search:
|
| 50 |
+
web_results = scrape_google_search(query)
|
| 51 |
+
knowledge += f"\n\nWeb Search Results:\n{web_results}"
|
| 52 |
+
|
| 53 |
+
chat_history = memory.load_memory_variables({}).get("chat_history", "")
|
| 54 |
+
context = (
|
| 55 |
+
f"This is a conversation with ParvizGPT, an AI model designed by Amir Mahdi Parviz, "
|
| 56 |
+
f"to help with tasks like answering questions in Persian, providing recommendations, and decision-making."
|
| 57 |
+
)
|
| 58 |
+
if knowledge:
|
| 59 |
+
context += f"\n\nRelevant Knowledge:\n{knowledge}"
|
| 60 |
+
if chat_history:
|
| 61 |
+
context += f"\n\nChat History:\n{chat_history}"
|
| 62 |
+
|
| 63 |
+
context += f"\n\nYou: {query}\nParvizGPT:"
|
| 64 |
+
|
| 65 |
+
chat_completion = client.chat.completions.create(
|
| 66 |
+
messages=[{"role": "user", "content": context}],
|
| 67 |
+
model="llama-3.3-70b-versatile",
|
| 68 |
+
)
|
| 69 |
+
response = chat_completion.choices[0].message.content.strip()
|
| 70 |
+
|
| 71 |
+
memory.save_context({"input": query}, {"output": response})
|
| 72 |
+
return response
|
| 73 |
+
|
| 74 |
+
def gradio_interface(user_message, pdf_file=None, enable_web_search=False):
|
| 75 |
+
global retriever
|
| 76 |
+
if pdf_file is not None:
|
| 77 |
+
try:
|
| 78 |
+
retriever = process_pdf_with_langchain(pdf_file.name)
|
| 79 |
+
except Exception as e:
|
| 80 |
+
return f"Error processing PDF: {e}"
|
| 81 |
+
|
| 82 |
+
response = generate_response(user_message, retriever=retriever, use_web_search=enable_web_search)
|
| 83 |
+
return response
|
| 84 |
+
|
| 85 |
+
def clear_memory():
|
| 86 |
+
memory.clear()
|
| 87 |
+
return "Memory cleared!"
|
| 88 |
+
|
| 89 |
+
retriever = None
|
| 90 |
+
|
| 91 |
+
with gr.Blocks() as interface:
|
| 92 |
+
gr.Markdown("## ParvizGPT with Memory and Web Search Toggle")
|
| 93 |
+
with gr.Row():
|
| 94 |
+
user_message = gr.Textbox(label="Your Question", placeholder="Type your question here...", lines=1)
|
| 95 |
+
submit_btn = gr.Button("Submit")
|
| 96 |
+
with gr.Row():
|
| 97 |
+
pdf_file = gr.File(label="Upload PDF for Context (Optional)", type="filepath")
|
| 98 |
+
enable_web_search = gr.Checkbox(label="Enable Web Search", value=False)
|
| 99 |
+
with gr.Row():
|
| 100 |
+
clear_memory_btn = gr.Button("Clear Memory")
|
| 101 |
+
response_output = gr.Textbox(label="Response", placeholder="ParvizGPT's response will appear here.")
|
| 102 |
+
|
| 103 |
+
submit_btn.click(gradio_interface, inputs=[user_message, pdf_file, enable_web_search], outputs=response_output)
|
| 104 |
+
clear_memory_btn.click(clear_memory, inputs=[], outputs=response_output)
|
| 105 |
+
|
| 106 |
+
gr.HTML(
|
| 107 |
+
"""
|
| 108 |
+
<script>
|
| 109 |
+
document.addEventListener("keydown", function(event) {
|
| 110 |
+
if (event.key === "Enter" && !event.shiftKey) {
|
| 111 |
+
event.preventDefault();
|
| 112 |
+
document.querySelector('button[title="Submit"]').click();
|
| 113 |
+
}
|
| 114 |
+
});
|
| 115 |
+
</script>
|
| 116 |
+
"""
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
interface.launch()
|