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