Spaces:
Running
Running
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
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 |
+
SERPAPI_KEY = "8a20e83850a3be0a0b4e3aed98bd3addbad56e82d52e639e1a692a02d021bca1"
|
28 |
+
|
29 |
+
def scrape_google_search(query, num_results=3):
|
30 |
+
params = {
|
31 |
+
"q": query,
|
32 |
+
"hl": "fa",
|
33 |
+
"gl": "ir",
|
34 |
+
"num": num_results,
|
35 |
+
"api_key": SERPAPI_KEY,
|
36 |
+
}
|
37 |
+
search = GoogleSearch(params)
|
38 |
+
results = search.get_dict()
|
39 |
+
|
40 |
+
if "error" in results:
|
41 |
+
return f"Error: {results['error']}"
|
42 |
+
|
43 |
+
search_results = []
|
44 |
+
for result in results.get("organic_results", []):
|
45 |
+
title = result.get("title", "No Title")
|
46 |
+
link = result.get("link", "No Link")
|
47 |
+
search_results.append(f"{title}: {link}")
|
48 |
+
return "\n".join(search_results) if search_results else "No results found"
|
49 |
+
|
50 |
+
def generate_response(query, retriever=None, use_web_search=False):
|
51 |
+
|
52 |
+
knowledge = ""
|
53 |
+
|
54 |
+
if retriever:
|
55 |
+
relevant_docs = retriever.get_relevant_documents(query)
|
56 |
+
knowledge += "\n".join([doc.page_content for doc in relevant_docs])
|
57 |
+
|
58 |
+
if use_web_search:
|
59 |
+
web_results = scrape_google_search(query)
|
60 |
+
knowledge += f"\n\nWeb Search Results:\n{web_results}"
|
61 |
+
|
62 |
+
chat_history = memory.load_memory_variables({}).get("chat_history", "")
|
63 |
+
context = (
|
64 |
+
f"This is a conversation with ParvizGPT, an AI model designed by Amir Mahdi Parviz from Kermanshah University of Technology (KUT), "
|
65 |
+
f"to help with tasks like answering questions in Persian, providing recommendations, and decision-making."
|
66 |
+
)
|
67 |
+
if knowledge:
|
68 |
+
context += f"\n\nRelevant Knowledge:\n{knowledge}"
|
69 |
+
if chat_history:
|
70 |
+
context += f"\n\nChat History:\n{chat_history}"
|
71 |
+
|
72 |
+
context += f"\n\nYou: {query}\nParvizGPT:"
|
73 |
+
|
74 |
+
chat_completion = client.chat.completions.create(
|
75 |
+
messages=[{"role": "user", "content": context}],
|
76 |
+
model="llama-3.3-70b-versatile",
|
77 |
+
)
|
78 |
+
response = chat_completion.choices[0].message.content.strip()
|
79 |
+
|
80 |
+
memory.save_context({"input": query}, {"output": response})
|
81 |
+
return response
|
82 |
+
|
83 |
+
def gradio_interface(user_message, chat_box, pdf_file=None, enable_web_search=False):
|
84 |
+
global retriever
|
85 |
+
if pdf_file is not None:
|
86 |
+
try:
|
87 |
+
retriever = process_pdf_with_langchain(pdf_file.name)
|
88 |
+
except Exception as e:
|
89 |
+
return chat_box + [("Error", f"Error processing PDF: {e}")]
|
90 |
+
|
91 |
+
response = generate_response(user_message, retriever=retriever, use_web_search=enable_web_search)
|
92 |
+
chat_box.append(("You", user_message))
|
93 |
+
chat_box.append(("ParvizGPT", response))
|
94 |
+
return chat_box
|
95 |
+
|
96 |
+
def clear_memory():
|
97 |
+
memory.clear()
|
98 |
+
return []
|
99 |
+
|
100 |
+
retriever = None
|
101 |
+
with gr.Blocks() as interface:
|
102 |
+
gr.Markdown("## ParvizGPT")
|
103 |
+
# with gr.Row():
|
104 |
+
chat_box = gr.Chatbot(label="Chat History", value=[])
|
105 |
+
|
106 |
+
# with gr.Row():
|
107 |
+
user_message = gr.Textbox(
|
108 |
+
label="Your Message",
|
109 |
+
placeholder="Type your message here and press Enter...",
|
110 |
+
lines=1,
|
111 |
+
interactive=True,
|
112 |
+
)
|
113 |
+
enable_web_search = gr.Checkbox(label="🌐Enable Web Search", value=False)
|
114 |
+
|
115 |
+
# with gr.Row():
|
116 |
+
clear_memory_btn = gr.Button("Clear Memory", interactive=True)
|
117 |
+
# enable_web_search = gr.Checkbox(label="🌐Enable Web Search", value=False, interactive=True)
|
118 |
+
pdf_file = gr.File(label="Upload PDF for Context (Optional)", type="filepath", interactive=True , scale=1)
|
119 |
+
|
120 |
+
submit_btn = gr.Button("Submit")
|
121 |
+
submit_btn.click(gradio_interface, inputs=[user_message, chat_box, pdf_file, enable_web_search], outputs=chat_box)
|
122 |
+
user_message.submit(gradio_interface, inputs=[user_message, chat_box, pdf_file, enable_web_search], outputs=chat_box)
|
123 |
+
clear_memory_btn.click(clear_memory, inputs=[], outputs=chat_box)
|
124 |
+
|
125 |
+
interface.launch()
|