Spaces:
Running
Running
File size: 9,523 Bytes
967469d 53a7eb8 571cdbb f4d77f2 53a7eb8 687fccd 57faddd 967469d 82134da 53a7eb8 c3aaf4b 53a7eb8 57faddd 53a7eb8 57faddd 53a7eb8 c3aaf4b 687fccd 53a7eb8 571cdbb 53a7eb8 571cdbb 2ceeece 571cdbb 57faddd 571cdbb 57faddd 571cdbb 57faddd 571cdbb 57faddd 967469d 3e606db 967469d 3e606db 967469d f4d77f2 3e606db f4d77f2 53a7eb8 f4d77f2 967469d 53a7eb8 c3aaf4b 53a7eb8 82134da 967469d 82134da 687fccd 53a7eb8 2ceeece 967469d 3e606db f4d77f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# import os
# import sys
# import requests
# from langchain.chains import ConversationalRetrievalChain
# from langchain.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
# from langchain.text_splitter import CharacterTextSplitter
# from langchain.vectorstores import Chroma
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.llms.base import LLM
# import gradio as gr
# # workaround for sqlite in HF spaces
# __import__('pysqlite3')
# sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
# # π Load documents
# docs = []
# for f in os.listdir("multiple_docs"):
# if f.endswith(".pdf"):
# loader = PyPDFLoader(os.path.join("multiple_docs", f))
# docs.extend(loader.load())
# elif f.endswith(".docx") or f.endswith(".doc"):
# loader = Docx2txtLoader(os.path.join("multiple_docs", f))
# docs.extend(loader.load())
# elif f.endswith(".txt"):
# loader = TextLoader(os.path.join("multiple_docs", f))
# docs.extend(loader.load())
# # π Split into chunks
# splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=10)
# docs = splitter.split_documents(docs)
# texts = [doc.page_content for doc in docs]
# metadatas = [{"id": i} for i in range(len(texts))]
# # π§ Embeddings
# embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# # ποΈ Vectorstore
# vectorstore = Chroma(
# persist_directory="./db",
# embedding_function=embedding_function
# )
# vectorstore.add_texts(texts=texts, metadatas=metadatas)
# vectorstore.persist()
# # π Get DeepSeek API key from env
# DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
# if DEEPSEEK_API_KEY is None:
# raise ValueError("DEEPSEEK_API_KEY environment variable is not set.")
# # π DeepSeek API endpoint
# DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
# # π· Wrap DeepSeek API into LangChain LLM
# class DeepSeekLLM(LLM):
# """LLM that queries DeepSeek's API."""
# api_key: str = DEEPSEEK_API_KEY
# def _call(self, prompt, stop=None, run_manager=None, **kwargs):
# headers = {
# "Authorization": f"Bearer {self.api_key}",
# "Content-Type": "application/json"
# }
# payload = {
# "model": "deepseek-chat", # adjust if you have a specific model name
# "messages": [
# {"role": "system", "content": "You are a helpful assistant."},
# {"role": "user", "content": prompt}
# ],
# "temperature": 0.7,
# "max_tokens": 512
# }
# response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
# response.raise_for_status()
# data = response.json()
# return data["choices"][0]["message"]["content"].strip()
# @property
# def _llm_type(self) -> str:
# return "deepseek_api"
# llm = DeepSeekLLM()
# # π Conversational chain
# chain = ConversationalRetrievalChain.from_llm(
# llm,
# retriever=vectorstore.as_retriever(search_kwargs={'k': 6}),
# return_source_documents=True,
# verbose=False
# )
# # π¬ Gradio UI
# chat_history = []
# with gr.Blocks() as demo:
# chatbot = gr.Chatbot(
# [("", "Hello, I'm Thierry Decae's chatbot, you can ask me any recruitment related questions such as my experience, where I'm eligible to work, skills etc you can chat with me directly in multiple languages")],
# avatar_images=["./multiple_docs/Guest.jpg", "./multiple_docs/Thierry Picture.jpg"]
# )
# msg = gr.Textbox(placeholder="Type your question here...")
# clear = gr.Button("Clear")
# def user(query, chat_history):
# chat_history_tuples = [(m[0], m[1]) for m in chat_history]
# result = chain({"question": query, "chat_history": chat_history_tuples})
# chat_history.append((query, result["answer"]))
# return gr.update(value=""), chat_history
# msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False)
# clear.click(lambda: None, None, chatbot, queue=False)
# demo.launch(debug=True) # remove share=True if running in HF Spaces
import os
import sys
import requests
from langchain.chains import ConversationalRetrievalChain, LLMChain
from langchain.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.llms.base import LLM
from langchain.prompts import PromptTemplate
from langchain.chains.question_answering import load_qa_chain
import gradio as gr
# workaround for sqlite in HF spaces
__import__('pysqlite3')
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
# π Load documents
docs = []
for f in os.listdir("multiple_docs"):
if f.endswith(".pdf"):
loader = PyPDFLoader(os.path.join("multiple_docs", f))
docs.extend(loader.load())
elif f.endswith(".docx") or f.endswith(".doc"):
loader = Docx2txtLoader(os.path.join("multiple_docs", f))
docs.extend(loader.load())
elif f.endswith(".txt"):
loader = TextLoader(os.path.join("multiple_docs", f))
docs.extend(loader.load())
# π Split into chunks
splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=10)
docs = splitter.split_documents(docs)
texts = [doc.page_content for doc in docs]
metadatas = [{"id": i} for i in range(len(texts))]
# π§ Embeddings
embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# ποΈ Vectorstore
vectorstore = Chroma(
persist_directory="./db",
embedding_function=embedding_function
)
vectorstore.add_texts(texts=texts, metadatas=metadatas)
vectorstore.persist()
# π Get DeepSeek API key from env
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
if DEEPSEEK_API_KEY is None:
raise ValueError("DEEPSEEK_API_KEY environment variable is not set.")
# π DeepSeek API endpoint
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
# π· Wrap DeepSeek API into LangChain LLM
class DeepSeekLLM(LLM):
"""LLM that queries DeepSeek's API."""
api_key: str = DEEPSEEK_API_KEY
def _call(self, prompt, stop=None, run_manager=None, **kwargs):
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "deepseek-chat", # adjust if you have a specific model name
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 512
}
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
response.raise_for_status()
data = response.json()
return data["choices"][0]["message"]["content"].strip()
@property
def _llm_type(self) -> str:
return "deepseek_api"
llm = DeepSeekLLM()
# β¨ Custom prompt template
template = """
You are Thierry Decae's chatbot. Your role is to answer questions about his career, experience, availability β in other words
any recruitment-related question.
Use the following context to answer the user's question as fully and accurately as possible.
If you don't know the answer, say "I'm not sure about that."
Always answer as if you were Thierry Decae β do not refer to him as 'he', use 'I' instead.
Context:
{context}
Question: {question}
Answer:
"""
prompt = PromptTemplate(
input_variables=["context", "question"],
template=template,
)
# π QA chain with custom prompt
qa_chain = load_qa_chain(llm, chain_type="stuff", prompt=prompt)
# π· Question rephraser chain for follow-up questions β standalone
CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(
"""
Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:
"""
)
question_generator = LLMChain(
llm=llm,
prompt=CONDENSE_QUESTION_PROMPT
)
# π· Finally: build the ConversationalRetrievalChain manually
chain = ConversationalRetrievalChain(
retriever=vectorstore.as_retriever(search_kwargs={'k': 6}),
question_generator=question_generator,
combine_docs_chain=qa_chain,
return_source_documents=True,
verbose=False
)
# π¬ Gradio UI
chat_history = []
with gr.Blocks() as demo:
chatbot = gr.Chatbot(
[("", "Hello, I'm Thierry Decae's chatbot, you can ask me any recruitment related questions such as my experience, where I'm eligible to work, skills etc. You can chat with me directly in multiple languages.")],
avatar_images=["./multiple_docs/Guest.jpg", "./multiple_docs/Thierry Picture.jpg"]
)
msg = gr.Textbox(placeholder="Type your question here...")
clear = gr.Button("Clear")
def user(query, chat_history):
chat_history_tuples = [(m[0], m[1]) for m in chat_history]
result = chain({"question": query, "chat_history": chat_history_tuples})
chat_history.append((query, result["answer"]))
return gr.update(value=""), chat_history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False)
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch(debug=True) # remove share=True if running in HF Spaces
|