GIGAParviz commited on
Commit
59bf8b2
·
verified ·
1 Parent(s): 0af6850

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -91
app.py CHANGED
@@ -1,23 +1,21 @@
 
 
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="heydariAI/persian-embeddings")
19
 
20
- memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
 
21
 
22
  def process_pdf_with_langchain(pdf_path):
23
  try:
@@ -25,7 +23,7 @@ def process_pdf_with_langchain(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
@@ -33,49 +31,7 @@ def process_pdf_with_langchain(pdf_path):
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
 
@@ -83,21 +39,9 @@ def generate_response(query, retriever=None, use_web_search=False, scrape_web=Fa
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:
@@ -105,19 +49,32 @@ def generate_response(query, retriever=None, use_web_search=False, scrape_web=Fa
105
 
106
  context += f"\n\nYou: {query}\nParvizGPT:"
107
 
108
- chat_completion = client.chat.completions.create(
109
- messages=[{"role": "user", "content": context}],
110
- model= "deepseek-r1-distill-llama-70b"
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:
@@ -125,9 +82,13 @@ def gradio_interface(user_message, chat_box, pdf_file=None, enable_web_search=Fa
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():
@@ -139,24 +100,12 @@ retriever = None
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()
161
-
162
-
 
1
+ import time
2
+ import logging
3
  import gradio as gr
4
  from langchain.document_loaders import PyPDFLoader
5
  from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain.embeddings import HuggingFaceEmbeddings
7
  from langchain.vectorstores import FAISS
8
+ from langchain_core.vectorstores import InMemoryVectorStore
9
  from groq import Groq
 
 
 
 
10
 
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
  client = Groq(api_key="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")
 
15
  embedding_model = HuggingFaceEmbeddings(model_name="heydariAI/persian-embeddings")
16
 
17
+ # Initialize in-memory vector store for chat history
18
+ memory = InMemoryVectorStore()
19
 
20
  def process_pdf_with_langchain(pdf_path):
21
  try:
 
23
  documents = loader.load()
24
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
25
  split_documents = text_splitter.split_documents(documents)
26
+
27
  vectorstore = FAISS.from_documents(split_documents, embedding_model)
28
  retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
29
  return retriever
 
31
  logger.error(f"Error processing PDF: {e}")
32
  raise
33
 
34
+ def generate_response(query, retriever=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
  knowledge = ""
37
 
 
39
  relevant_docs = retriever.get_relevant_documents(query)
40
  knowledge += "\n".join([doc.page_content for doc in relevant_docs])
41
 
 
 
 
 
 
 
 
 
 
 
42
  chat_history = memory.load_memory_variables({}).get("chat_history", "")
43
+ context = "This is a conversation with ParvizGPT, an AI model designed by Amir Mahdi Parviz from KUT."
44
+
 
 
45
  if knowledge:
46
  context += f"\n\nRelevant Knowledge:\n{knowledge}"
47
  if chat_history:
 
49
 
50
  context += f"\n\nYou: {query}\nParvizGPT:"
51
 
52
+ # ابتدا یک پیام موقت نمایش داده شود
53
+ response = "در حال پردازش..."
54
+
55
+ retries = 3
56
+ for attempt in range(retries):
57
+ try:
58
+ chat_completion = client.chat.completions.create(
59
+ messages=[{"role": "user", "content": context}],
60
+ model="deepseek-r1-distill-llama-70b"
61
+ )
62
+ response = chat_completion.choices[0].message.content.strip()
63
+ memory.save_context({"input": query}, {"output": response})
64
+ break
65
+ except Exception as e:
66
+ logger.error(f"Attempt {attempt + 1} failed: {e}")
67
+ time.sleep(2)
68
 
 
69
  return response
70
  except Exception as e:
71
  logger.error(f"Error generating response: {e}")
72
  return f"Error: {e}"
73
 
74
+
75
+
76
+
77
+ def gradio_interface(user_message, chat_box, pdf_file=None):
78
  global retriever
79
  if pdf_file is not None:
80
  try:
 
82
  except Exception as e:
83
  return chat_box + [("Error", f"Error processing PDF: {e}")]
84
 
85
+ chat_box.append(("ParvizGPT", "در حال پردازش..."))
86
+
87
+ response = generate_response(user_message, retriever=retriever)
88
+
89
+ chat_box[-1] = ("ParvizGPT", response)
90
  chat_box.append(("You", user_message))
91
+
92
  return chat_box
93
 
94
  def clear_memory():
 
100
  with gr.Blocks() as interface:
101
  gr.Markdown("## ParvizGPT")
102
  chat_box = gr.Chatbot(label="Chat History", value=[])
103
+ user_message = gr.Textbox(label="Your Message", placeholder="Type your message here and press Enter...", lines=1, interactive=True)
 
 
 
 
 
 
 
 
 
104
  clear_memory_btn = gr.Button("Clear Memory", interactive=True)
105
+ pdf_file = gr.File(label="Upload PDF for Context (Optional)", type="filepath", interactive=True, scale=1)
 
106
  submit_btn = gr.Button("Submit")
107
+ submit_btn.click(gradio_interface, inputs=[user_message, chat_box, pdf_file], outputs=chat_box)
108
+ user_message.submit(gradio_interface, inputs=[user_message, chat_box, pdf_file], outputs=chat_box)
109
  clear_memory_btn.click(clear_memory, inputs=[], outputs=chat_box)
110
 
111
  interface.launch()