Spaces:
Running
Running
Delete app.py
Browse files
app.py
DELETED
@@ -1,132 +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 |
-
import time
|
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, progress_callback):
|
19 |
-
# progress_callback("Initializing PDF processing... 0%")
|
20 |
-
time.sleep(0.5)
|
21 |
-
loader = PyPDFLoader(pdf_path)
|
22 |
-
# progress_callback("Loading PDF... 20%")
|
23 |
-
documents = loader.load()
|
24 |
-
time.sleep(0.5)
|
25 |
-
# progress_callback("Splitting documents... 50%")
|
26 |
-
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
27 |
-
split_documents = text_splitter.split_documents(documents)
|
28 |
-
time.sleep(0.5)
|
29 |
-
# progress_callback("Creating vector store... 80%")
|
30 |
-
vectorstore = FAISS.from_documents(split_documents, embedding_model)
|
31 |
-
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
32 |
-
progress_callback("Processing complete! 100%")
|
33 |
-
return retriever
|
34 |
-
|
35 |
-
|
36 |
-
def scrape_google_search(query, num_results=3):
|
37 |
-
|
38 |
-
headers = {"User-Agent": "Mozilla/5.0"}
|
39 |
-
search_url = f"https://www.google.com/search?q={query}"
|
40 |
-
response = requests.get(search_url, headers=headers)
|
41 |
-
soup = BeautifulSoup(response.text, "html.parser")
|
42 |
-
|
43 |
-
results = []
|
44 |
-
for g in soup.find_all('div', class_='tF2Cxc')[:num_results]:
|
45 |
-
title = g.find('h3').text
|
46 |
-
link = g.find('a')['href']
|
47 |
-
results.append(f"{title}: {link}")
|
48 |
-
return "\n".join(results)
|
49 |
-
|
50 |
-
|
51 |
-
def generate_response(query, retriever=None, use_web_search=False):
|
52 |
-
|
53 |
-
knowledge = ""
|
54 |
-
|
55 |
-
if retriever:
|
56 |
-
relevant_docs = retriever.get_relevant_documents(query)
|
57 |
-
knowledge += "\n".join([doc.page_content for doc in relevant_docs])
|
58 |
-
|
59 |
-
if use_web_search:
|
60 |
-
web_results = scrape_google_search(query)
|
61 |
-
knowledge += f"\n\nWeb Search Results:\n{web_results}"
|
62 |
-
|
63 |
-
chat_history = memory.load_memory_variables({}).get("chat_history", "")
|
64 |
-
context = (
|
65 |
-
f"This is a conversation with ParvizGPT, an AI model designed by Amir Mahdi Parviz from Kermanshah University of Technology (KUT), "
|
66 |
-
f"to help with tasks like answering questions in Persian, providing recommendations, and decision-making."
|
67 |
-
)
|
68 |
-
if knowledge:
|
69 |
-
context += f"\n\nRelevant Knowledge:\n{knowledge}"
|
70 |
-
if chat_history:
|
71 |
-
context += f"\n\nChat History:\n{chat_history}"
|
72 |
-
|
73 |
-
context += f"\n\nYou: {query}\nParvizGPT:"
|
74 |
-
|
75 |
-
chat_completion = client.chat.completions.create(
|
76 |
-
messages=[{"role": "user", "content": context}],
|
77 |
-
model="llama-3.3-70b-versatile",
|
78 |
-
)
|
79 |
-
response = chat_completion.choices[0].message.content.strip()
|
80 |
-
|
81 |
-
memory.save_context({"input": query}, {"output": response})
|
82 |
-
return response
|
83 |
-
|
84 |
-
def upload_and_process(file, progress_display):
|
85 |
-
try:
|
86 |
-
global retriever
|
87 |
-
progress_updates = []
|
88 |
-
|
89 |
-
retriever = process_pdf_with_langchain(file.name, lambda msg: progress_updates.append(msg))
|
90 |
-
|
91 |
-
return "\n".join(progress_updates), "File uploaded and processed successfully."
|
92 |
-
except Exception as e:
|
93 |
-
return "", f"Error processing file: {e}"
|
94 |
-
|
95 |
-
def gradio_interface(user_message, chat_box, enable_web_search=False):
|
96 |
-
global retriever
|
97 |
-
response = generate_response(user_message, retriever=retriever, use_web_search=enable_web_search)
|
98 |
-
chat_box.append(("You", user_message))
|
99 |
-
chat_box.append(("ParvizGPT", response))
|
100 |
-
return chat_box
|
101 |
-
|
102 |
-
def clear_memory():
|
103 |
-
memory.clear()
|
104 |
-
return []
|
105 |
-
|
106 |
-
retriever = None
|
107 |
-
with gr.Blocks() as interface:
|
108 |
-
gr.Markdown("## ParvizGPT")
|
109 |
-
with gr.Row():
|
110 |
-
chat_box = gr.Chatbot(label="Chat History", value=[])
|
111 |
-
with gr.Row():
|
112 |
-
user_message = gr.Textbox(
|
113 |
-
label="Your Message",
|
114 |
-
placeholder="Type your message here and press Enter...",
|
115 |
-
lines=1,
|
116 |
-
interactive=True,
|
117 |
-
)
|
118 |
-
with gr.Row():
|
119 |
-
clear_memory_btn = gr.Button("Clear Memory", interactive=True)
|
120 |
-
enable_web_search = gr.Checkbox(label="🌐Enable Web Search", value=False, interactive=True)
|
121 |
-
with gr.Row():
|
122 |
-
pdf_upload = gr.UploadButton(label="📄 Upload Your PDF", file_types=[".pdf"])
|
123 |
-
progress_display = gr.Textbox(label="Progress", placeholder="Progress updates will appear here", interactive=True)
|
124 |
-
with gr.Row():
|
125 |
-
submit_btn = gr.Button("Submit")
|
126 |
-
pdf_upload.upload(upload_and_process, inputs=[pdf_upload, progress_display], outputs=[progress_display])
|
127 |
-
|
128 |
-
submit_btn.click(gradio_interface, inputs=[user_message, chat_box, enable_web_search], outputs=chat_box)
|
129 |
-
user_message.submit(gradio_interface, inputs=[user_message, chat_box, enable_web_search], outputs=chat_box)
|
130 |
-
clear_memory_btn.click(clear_memory, inputs=[], outputs=chat_box)
|
131 |
-
|
132 |
-
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|