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|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from langchain.document_loaders import PyPDFLoader
|
| 3 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
+
from langchain.embeddings import HuggingFaceEmbeddings # Updated for Persian embeddings
|
| 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 |
+
from serpapi import GoogleSearch
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
client = Groq(api_key="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")
|
| 17 |
+
|
| 18 |
+
embedding_model = HuggingFaceEmbeddings(model_name="HooshvareLab/bert-fa-base-uncased")
|
| 19 |
+
|
| 20 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 21 |
+
|
| 22 |
+
def process_pdf_with_langchain(pdf_path):
|
| 23 |
+
try:
|
| 24 |
+
loader = PyPDFLoader(pdf_path)
|
| 25 |
+
documents = loader.load()
|
| 26 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 27 |
+
split_documents = text_splitter.split_documents(documents)
|
| 28 |
+
|
| 29 |
+
vectorstore = FAISS.from_documents(split_documents, embedding_model)
|
| 30 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 31 |
+
return retriever
|
| 32 |
+
except Exception as e:
|
| 33 |
+
logger.error(f"Error processing PDF: {e}")
|
| 34 |
+
raise
|
| 35 |
+
|
| 36 |
+
SERPAPI_KEY = "8a20e83850a3be0a0b4e3aed98bd3addbad56e82d52e639e1a692a02d021bca1"
|
| 37 |
+
|
| 38 |
+
def scrape_google_search(query, num_results=3):
|
| 39 |
+
try:
|
| 40 |
+
params = {
|
| 41 |
+
"q": query,
|
| 42 |
+
"hl": "fa",
|
| 43 |
+
"gl": "ir",
|
| 44 |
+
"num": num_results,
|
| 45 |
+
"api_key": SERPAPI_KEY,
|
| 46 |
+
}
|
| 47 |
+
search = GoogleSearch(params)
|
| 48 |
+
results = search.get_dict()
|
| 49 |
+
|
| 50 |
+
if "error" in results:
|
| 51 |
+
return f"Error: {results['error']}"
|
| 52 |
+
|
| 53 |
+
search_results = []
|
| 54 |
+
for result in results.get("organic_results", []):
|
| 55 |
+
title = result.get("title", "No Title")
|
| 56 |
+
link = result.get("link", "No Link")
|
| 57 |
+
search_results.append(f"{title}: {link}")
|
| 58 |
+
return "\n".join(search_results) if search_results else "No results found"
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.error(f"Error scraping Google search: {e}")
|
| 61 |
+
return f"Error: {e}"
|
| 62 |
+
|
| 63 |
+
def scrape_webpage(url):
|
| 64 |
+
try:
|
| 65 |
+
headers = {
|
| 66 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
| 67 |
+
}
|
| 68 |
+
response = requests.get(url, headers=headers)
|
| 69 |
+
response.raise_for_status()
|
| 70 |
+
|
| 71 |
+
soup = BeautifulSoup(response.content, "html.parser")
|
| 72 |
+
text = soup.get_text(separator="\n")
|
| 73 |
+
return text.strip()
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"Error scraping webpage {url}: {e}")
|
| 76 |
+
return f"Error: {e}"
|
| 77 |
+
|
| 78 |
+
def generate_response(query, retriever=None, use_web_search=False, scrape_web=False):
|
| 79 |
+
try:
|
| 80 |
+
knowledge = ""
|
| 81 |
+
|
| 82 |
+
if retriever:
|
| 83 |
+
relevant_docs = retriever.get_relevant_documents(query)
|
| 84 |
+
knowledge += "\n".join([doc.page_content for doc in relevant_docs])
|
| 85 |
+
|
| 86 |
+
if use_web_search:
|
| 87 |
+
web_results = scrape_google_search(query)
|
| 88 |
+
knowledge += f"\n\nWeb Search Results:\n{web_results}"
|
| 89 |
+
|
| 90 |
+
if scrape_web:
|
| 91 |
+
urls = [word for word in query.split() if word.startswith("http://") or word.startswith("https://")]
|
| 92 |
+
for url in urls:
|
| 93 |
+
webpage_content = scrape_webpage(url)
|
| 94 |
+
knowledge += f"\n\nWebpage Content from {url}:\n{webpage_content}"
|
| 95 |
+
|
| 96 |
+
chat_history = memory.load_memory_variables({}).get("chat_history", "")
|
| 97 |
+
context = (
|
| 98 |
+
f"This is a conversation with ParvizGPT, an AI model designed by Amir Mahdi Parviz from Kermanshah University of Technology (KUT), "
|
| 99 |
+
f"to help with tasks like answering questions in Persian, providing recommendations, and decision-making."
|
| 100 |
+
)
|
| 101 |
+
if knowledge:
|
| 102 |
+
context += f"\n\nRelevant Knowledge:\n{knowledge}"
|
| 103 |
+
if chat_history:
|
| 104 |
+
context += f"\n\nChat History:\n{chat_history}"
|
| 105 |
+
|
| 106 |
+
context += f"\n\nYou: {query}\nParvizGPT:"
|
| 107 |
+
|
| 108 |
+
chat_completion = client.chat.completions.create(
|
| 109 |
+
messages=[{"role": "user", "content": context}],
|
| 110 |
+
model= "gemma2-9b-it" #"llama-3.3-70b-versatile",
|
| 111 |
+
)
|
| 112 |
+
response = chat_completion.choices[0].message.content.strip()
|
| 113 |
+
|
| 114 |
+
memory.save_context({"input": query}, {"output": response})
|
| 115 |
+
return response
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"Error generating response: {e}")
|
| 118 |
+
return f"Error: {e}"
|
| 119 |
+
|
| 120 |
+
def gradio_interface(user_message, chat_box, pdf_file=None, enable_web_search=False, scrape_web=False):
|
| 121 |
+
global retriever
|
| 122 |
+
if pdf_file is not None:
|
| 123 |
+
try:
|
| 124 |
+
retriever = process_pdf_with_langchain(pdf_file.name)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
return chat_box + [("Error", f"Error processing PDF: {e}")]
|
| 127 |
+
|
| 128 |
+
response = generate_response(user_message, retriever=retriever, use_web_search=enable_web_search, scrape_web=scrape_web)
|
| 129 |
+
chat_box.append(("You", user_message))
|
| 130 |
+
chat_box.append(("ParvizGPT", response))
|
| 131 |
+
return chat_box
|
| 132 |
+
|
| 133 |
+
def clear_memory():
|
| 134 |
+
memory.clear()
|
| 135 |
+
return []
|
| 136 |
+
|
| 137 |
+
retriever = None
|
| 138 |
+
|
| 139 |
+
with gr.Blocks() as interface:
|
| 140 |
+
gr.Markdown("## ParvizGPT")
|
| 141 |
+
chat_box = gr.Chatbot(label="Chat History", value=[])
|
| 142 |
+
|
| 143 |
+
user_message = gr.Textbox(
|
| 144 |
+
label="Your Message",
|
| 145 |
+
placeholder="Type your message here and press Enter...",
|
| 146 |
+
lines=1,
|
| 147 |
+
interactive=True,
|
| 148 |
+
)
|
| 149 |
+
enable_web_search = gr.Checkbox(label="🌐Enable Web Search", value=False)
|
| 150 |
+
scrape_web = gr.Checkbox(label="🌍Scrape Webpages", value=False)
|
| 151 |
+
|
| 152 |
+
clear_memory_btn = gr.Button("Clear Memory", interactive=True)
|
| 153 |
+
pdf_file = gr.File(label="Upload PDF for Context (Optional)", type="filepath", interactive=True , scale=1)
|
| 154 |
+
|
| 155 |
+
submit_btn = gr.Button("Submit")
|
| 156 |
+
submit_btn.click(gradio_interface, inputs=[user_message, chat_box, pdf_file, enable_web_search, scrape_web], outputs=chat_box)
|
| 157 |
+
user_message.submit(gradio_interface, inputs=[user_message, chat_box, pdf_file, enable_web_search, scrape_web], outputs=chat_box)
|
| 158 |
+
clear_memory_btn.click(clear_memory, inputs=[], outputs=chat_box)
|
| 159 |
+
|
| 160 |
+
interface.launch()
|