Spaces:
Sleeping
Sleeping
File size: 5,310 Bytes
4442658 9402eba d8c2382 9402eba 4442658 9402eba 4442658 d8c2382 9402eba 4442658 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba 2c28fae d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 4442658 d8c2382 9402eba 4442658 d8c2382 4442658 9402eba d8c2382 4442658 d8c2382 4442658 d8c2382 4442658 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 9402eba d8c2382 4442658 c64464b 9402eba 4442658 d8c2382 9402eba 4442658 d8c2382 4442658 d8c2382 4442658 d8c2382 4442658 9402eba | 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 | import os
import sys
import requests
# SQLite workaround (needed for Chroma on HF Spaces)
try:
__import__("pysqlite3")
sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
except Exception:
pass
import gradio as gr
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain_chroma import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
# ========================
# CONFIG
# ========================
DOCS_DIR = "multiple_docs"
DB_DIR = "./db"
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
WELCOME_MESSAGE = (
"Hello, I'm Thierry Decae's chatbot. You can ask me recruitment-related "
"questions about my experience, skills, availability, work eligibility, "
"projects, and background. You can chat with me in multiple languages."
)
# ========================
# DEEPSEEK CALL
# ========================
def call_deepseek(messages):
if not DEEPSEEK_API_KEY:
return "Missing DEEPSEEK_API_KEY."
headers = {
"Authorization": f"Bearer {DEEPSEEK_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": "deepseek-chat",
"messages": messages,
"temperature": 0.4,
"max_tokens": 700,
}
response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=60)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"].strip()
# ========================
# LOAD DOCS
# ========================
def load_documents():
docs = []
for f in os.listdir(DOCS_DIR):
path = os.path.join(DOCS_DIR, f)
try:
if f.endswith(".pdf"):
docs.extend(PyPDFLoader(path).load())
elif f.endswith(".docx"):
docs.extend(Docx2txtLoader(path).load())
elif f.endswith(".txt"):
docs.extend(TextLoader(path, encoding="utf-8").load())
except Exception as e:
print(f"Error loading {f}: {e}", flush=True)
if not docs:
raise ValueError("No documents found")
splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
return splitter.split_documents(docs)
# ========================
# VECTORSTORE
# ========================
def build_vectorstore():
print("Loading embeddings...", flush=True)
embedding = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
docs = load_documents()
print(f"Loaded {len(docs)} chunks", flush=True)
return Chroma.from_documents(
docs,
embedding,
persist_directory=DB_DIR,
)
vectorstore = build_vectorstore()
retriever = vectorstore.as_retriever(search_kwargs={"k": 6})
# ========================
# HISTORY FORMAT
# ========================
def format_history(history):
if not history:
return ""
lines = []
for msg in history[-8:]:
role = msg.get("role")
content = msg.get("content")
if role and content:
lines.append(f"{role}: {content}")
return "\n".join(lines)
# ========================
# MAIN QA FUNCTION
# ========================
def answer_question(query, history):
if history is None:
history = [{"role": "assistant", "content": WELCOME_MESSAGE}]
if not query.strip():
return "", history
try:
docs = retriever.invoke(query)
context = "\n\n".join(d.page_content for d in docs if d.page_content)
history_text = format_history(history)
system_prompt = """
You are Thierry Decae's recruitment chatbot.
Answer questions about Thierry's experience, skills, and career.
Use only provided context.
If unsure, say "I'm not sure about that."
Always answer as Thierry ("I", "my").
"""
user_prompt = f"""
Conversation:
{history_text}
Context:
{context}
Question:
{query}
Answer:
"""
answer = call_deepseek([
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
])
except Exception as e:
print(e, flush=True)
answer = "Error while answering."
history.append({"role": "user", "content": query})
history.append({"role": "assistant", "content": answer})
return "", history
def clear_chat():
return [{"role": "assistant", "content": WELCOME_MESSAGE}]
# ========================
# UI
# ========================
guest_img = os.path.join(DOCS_DIR, "Guest.jpg")
thierry_img = os.path.join(DOCS_DIR, "Thierry Picture.jpg")
avatars = None
if os.path.exists(guest_img) and os.path.exists(thierry_img):
avatars = [guest_img, thierry_img]
with gr.Blocks() as demo:
gr.Markdown("# Thierry Decae's Personal Assistant")
chatbot = gr.Chatbot(
value=[{"role": "assistant", "content": WELCOME_MESSAGE}],
avatar_images=avatars,
height=500,
)
msg = gr.Textbox(placeholder="Ask a question...")
clear = gr.Button("Clear")
msg.submit(answer_question, [msg, chatbot], [msg, chatbot])
clear.click(clear_chat, None, chatbot)
demo.launch(
server_name="0.0.0.0",
server_port=int(os.getenv("PORT", 7860)),
) |