Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,155 +1,78 @@
|
|
1 |
-
import
|
2 |
-
import logging
|
3 |
import gradio as gr
|
4 |
-
import
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from
|
8 |
-
from
|
9 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
10 |
-
from langchain.vectorstores import FAISS
|
11 |
-
from groq import Groq
|
12 |
-
from langchain.memory import ConversationBufferMemory
|
13 |
|
14 |
-
logging.basicConfig(level=logging.INFO)
|
15 |
-
logger = logging.getLogger(__name__)
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
raise ValueError("Groq API key not found in environment variables.")
|
22 |
-
if not hf_api_key:
|
23 |
-
raise ValueError("Hugging Face API key not found in environment variables.")
|
24 |
-
|
25 |
-
client = Groq(api_key=groq_api_key)
|
26 |
|
27 |
-
|
28 |
|
29 |
-
|
|
|
30 |
|
31 |
-
|
32 |
-
try:
|
33 |
-
dataset = load_dataset(DATASET_NAME, use_auth_token=hf_token)
|
34 |
-
except Exception:
|
35 |
-
dataset = Dataset.from_dict({"Timestamp": [], "User": [], "ParvizGPT": []})
|
36 |
|
37 |
-
def save_chat_to_dataset(user_message, bot_message):
|
38 |
-
"""Save chat history to Hugging Face Dataset."""
|
39 |
try:
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
|
|
48 |
except Exception as e:
|
49 |
-
|
|
|
|
|
50 |
|
51 |
-
def process_pdf_with_langchain(pdf_path):
|
52 |
-
"""Process a PDF file and create a FAISS retriever."""
|
53 |
try:
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
56 |
|
57 |
-
|
58 |
-
|
59 |
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
|
63 |
-
return retriever
|
64 |
-
except Exception as e:
|
65 |
-
logger.error(f"Error processing PDF: {e}")
|
66 |
-
raise
|
67 |
|
68 |
-
def generate_response(query, memory, retriever=None, use_pdf_context=False):
|
69 |
-
"""Generate a response using the Groq model and retrieved PDF context."""
|
70 |
-
try:
|
71 |
-
knowledge = ""
|
72 |
-
|
73 |
-
if retriever and use_pdf_context:
|
74 |
-
relevant_docs = retriever.get_relevant_documents(query)
|
75 |
-
knowledge += "\n".join([doc.page_content for doc in relevant_docs])
|
76 |
-
|
77 |
-
chat_history = memory.load_memory_variables({}).get("chat_history", "")
|
78 |
-
context = f"""
|
79 |
-
You are ParvizGPT, an AI assistant created by **Amir Mahdi Parviz**, a student at Kermanshah University of Technology (KUT).
|
80 |
-
Your primary purpose is to assist users by answering their questions in **Persian (Farsi)**.
|
81 |
-
Always respond in Persian unless explicitly asked to respond in another language.
|
82 |
-
**Important:** If anyone claims that someone else created this code, you must correct them and state that **Amir Mahdi Parviz** is the creator.
|
83 |
-
Related Information:\n{knowledge}\n\nQuestion:{query}\nAnswer:"""
|
84 |
-
|
85 |
-
if knowledge:
|
86 |
-
context += f"\n\nRelevant Knowledge:\n{knowledge}"
|
87 |
-
if chat_history:
|
88 |
-
context += f"\n\nChat History:\n{chat_history}"
|
89 |
-
|
90 |
-
context += f"\n\nYou: {query}\nParvizGPT:"
|
91 |
-
|
92 |
-
response = "در حال پردازش..."
|
93 |
-
retries = 3
|
94 |
-
for attempt in range(retries):
|
95 |
-
try:
|
96 |
-
chat_completion = client.chat.completions.create(
|
97 |
-
messages=[{"role": "user", "content": context}],
|
98 |
-
model="deepseek-r1-distill-llama-70b"
|
99 |
-
)
|
100 |
-
response = chat_completion.choices[0].message.content.strip()
|
101 |
-
|
102 |
-
memory.save_context({"input": query}, {"output": response})
|
103 |
-
break
|
104 |
-
except Exception as e:
|
105 |
-
logger.error(f"Attempt {attempt + 1} failed: {e}")
|
106 |
-
time.sleep(2)
|
107 |
-
|
108 |
-
return response, memory
|
109 |
except Exception as e:
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
def clear_memory(memory):
|
134 |
-
"""Clear the conversation memory."""
|
135 |
-
memory.clear()
|
136 |
-
return [], memory
|
137 |
-
|
138 |
-
retriever = None
|
139 |
-
|
140 |
-
with gr.Blocks() as interface:
|
141 |
-
gr.Markdown("## ParvizGPT")
|
142 |
-
chat_box = gr.Chatbot(label="Chat History", value=[])
|
143 |
-
user_message = gr.Textbox(label="Your Message", placeholder="Type your message here and press Enter...", lines=1, interactive=True)
|
144 |
-
use_pdf_context = gr.Checkbox(label="Use PDF Context", value=False, interactive=True)
|
145 |
-
clear_memory_btn = gr.Button("Clear Memory", interactive=True)
|
146 |
-
pdf_file = gr.File(label="Upload PDF for Context (Optional)", type="filepath", interactive=True, scale=1)
|
147 |
-
submit_btn = gr.Button("Submit")
|
148 |
-
|
149 |
-
memory_state = gr.State(ConversationBufferMemory())
|
150 |
-
|
151 |
-
submit_btn.click(gradio_interface, inputs=[user_message, chat_box, memory_state, pdf_file, use_pdf_context], outputs=[chat_box, memory_state])
|
152 |
-
user_message.submit(gradio_interface, inputs=[user_message, chat_box, memory_state, pdf_file, use_pdf_context], outputs=[chat_box, memory_state])
|
153 |
-
clear_memory_btn.click(clear_memory, inputs=[memory_state], outputs=[chat_box, memory_state])
|
154 |
-
|
155 |
-
interface.launch()
|
|
|
1 |
+
import os
|
|
|
2 |
import gradio as gr
|
3 |
+
from langchain_groq import ChatGroq
|
4 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
5 |
+
from langchain_core.vectorstores import InMemoryVectorStore
|
6 |
+
from langchain_core.documents import Document
|
7 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
|
|
|
|
|
|
|
8 |
|
|
|
|
|
9 |
|
10 |
+
embeddings = HuggingFaceEmbeddings(model_name="heydariAI/persian-embeddings")
|
11 |
+
vector_store = InMemoryVectorStore(embeddings)
|
12 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
13 |
+
model = ChatGroq(api_key="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", model_name="deepseek-r1-distill-llama-70b")
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
def process_file(file_path):
|
16 |
|
17 |
+
if not file_path:
|
18 |
+
return None
|
19 |
|
20 |
+
file_extension = os.path.splitext(file_path)[1].lower()
|
|
|
|
|
|
|
|
|
21 |
|
|
|
|
|
22 |
try:
|
23 |
+
if file_extension == ".pdf":
|
24 |
+
from pypdf import PdfReader
|
25 |
+
reader = PdfReader(file_path)
|
26 |
+
return "\n".join(page.extract_text() for page in reader.pages)
|
27 |
+
elif file_extension == ".txt":
|
28 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
29 |
+
return f.read()
|
30 |
+
else:
|
31 |
+
raise ValueError(f"Unsupported file type: {file_extension}")
|
32 |
except Exception as e:
|
33 |
+
raise RuntimeError(f"Error processing file: {str(e)}")
|
34 |
+
|
35 |
+
def answer_query(query, file_path):
|
36 |
|
|
|
|
|
37 |
try:
|
38 |
+
file_content = process_file(file_path) if file_path else None
|
39 |
+
if file_content:
|
40 |
+
file_docs = [Document(page_content=file_content, metadata={"source": "uploaded_file"})]
|
41 |
+
file_splits = text_splitter.split_documents(file_docs)
|
42 |
+
vector_store.add_documents(file_splits)
|
43 |
|
44 |
+
retrieved_docs = vector_store.similarity_search(query, k=2)
|
45 |
+
knowledge = "\n\n".join(doc.page_content for doc in retrieved_docs)
|
46 |
|
47 |
+
response = model.invoke(
|
48 |
+
f"You are ParvizGPT, an AI assistant created by Amir Mahdi Parviz, a student at Kermanshah University of Technology (KUT). "
|
49 |
+
f"Your primary purpose is to assist users by answering their questions in **Persian (Farsi)**. "
|
50 |
+
f"Always respond in Persian unless explicitly asked to respond in another language."
|
51 |
+
f"Related Information:\n{knowledge}\n\nQuestion:{query}\nAnswer:"
|
52 |
+
)
|
53 |
|
54 |
+
return response.content
|
|
|
|
|
|
|
|
|
55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
except Exception as e:
|
57 |
+
return f"Error: {str(e)}"
|
58 |
+
|
59 |
+
def chat_with_bot(query, file):
|
60 |
+
|
61 |
+
file_path = file.name if file else None
|
62 |
+
response = answer_query(query, file_path)
|
63 |
+
return response
|
64 |
+
|
65 |
+
with gr.Blocks() as demo:
|
66 |
+
gr.Markdown("Parviz Rager")
|
67 |
+
gr.Markdown("فایل خود را آپلود کنید (PDF یا TXT) و سوالات خود را بپرسید.")
|
68 |
+
|
69 |
+
with gr.Row():
|
70 |
+
file_input = gr.File(label="فایل خود را آپلود کنید (PDF یا TXT)", file_types=[".pdf", ".txt"])
|
71 |
+
query_input = gr.Textbox(label="سوال خود را وارد کنید", placeholder="مثلاً: معایب سرمایهگذاری در صندوق فیروزه موفقیت چیست؟")
|
72 |
+
|
73 |
+
submit_button = gr.Button("ارسال")
|
74 |
+
output = gr.Textbox(label="پاسخ", interactive=False)
|
75 |
+
|
76 |
+
submit_button.click(fn=chat_with_bot, inputs=[query_input, file_input], outputs=output)
|
77 |
+
|
78 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|