Spaces:
Build error
Build error
File size: 6,358 Bytes
65148ca | 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 | import gradio as gr
import os
import PyPDF2
from unstructured.partition.auto import partition
import nltk
from docx import Document
from sentence_transformers import SentenceTransformer, util
import logging
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
from threading import Thread
# Set up logging
logging.basicConfig(level=logging.INFO)
# Ensure NLTK data path is set correctly
nltk.data.path.append("/home/user/nltk_data")
# Download required NLTK resources
nltk.download("punkt")
# Load pre-trained embedding model for semantic search
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# Load DeepSeek model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Llama-8B")
try:
from accelerate import init_empty_weights
model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Llama-8B", device_map="auto")
except ImportError:
logging.warning("Accelerate library not found. Falling back to CPU-only mode.")
model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Llama-8B", device_map="cpu")
# Define terminators for the model
terminators = [
tokenizer.eos_token_id,
tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
# Function to extract text from files
def load_and_extract_text(file_path):
try:
if file_path.endswith(".pdf"):
with open(file_path, "rb") as file:
reader = PyPDF2.PdfReader(file)
return "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
elif file_path.endswith(".docx"):
doc = Document(file_path)
return "\n".join(para.text for para in doc.paragraphs)
elif file_path.endswith(".txt"):
with open(file_path, "r", encoding="utf-8") as file:
return file.read()
else:
elements = partition(file_path)
return "\n".join(str(el) for el in elements)
except Exception as e:
logging.error(f"Error processing {file_path}: {e}")
return ""
# Function to dynamically load resources from a folder
def load_resources(folder_path="."):
resources = {}
for filename in os.listdir(folder_path):
if filename.startswith(".") or filename.endswith((".py", ".md", ".gitattributes")):
continue
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
logging.info(f"Processing: {filename}")
resources[filename] = load_and_extract_text(file_path)
return resources
# Load resources initially
resources = load_resources()
# Function to find the most relevant section using semantic search
def find_most_relevant_section(query, text):
sections = text.split("\n\n")
section_embeddings = embedding_model.encode(sections)
query_embedding = embedding_model.encode([query])
similarities = util.cos_sim(query_embedding, section_embeddings)
max_similarity = similarities.max()
if max_similarity < 0.5: # Adjust threshold if needed
return "No relevant section found."
return sections[similarities.argmax()]
# Function to generate a chatbot response using DeepSeek model
def generate_bot_response(user_input, history, temperature=0.7, max_new_tokens=1024):
global resources
relevant_text = ""
# Loop through resources to find relevant sections
for filename, text in resources.items():
relevant_section = find_most_relevant_section(user_input, text)
if relevant_section and relevant_section != "No relevant section found.":
relevant_text += f"\n\nFrom {filename}:\n{relevant_section}\n"
# Ensure relevant_text is a string and not a list or dictionary
relevant_text = str(relevant_text).strip()
if not relevant_text:
relevant_text = "I couldn't find relevant information."
# Prepare conversation history
conversation = []
for user_msg, bot_msg in history:
conversation.extend([{"role": "user", "content": user_msg}, {"role": "assistant", "content": bot_msg}])
conversation.append({"role": "user", "content": user_input})
# Tokenize the conversation
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
# Stream the response
streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
input_ids=input_ids,
streamer=streamer,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=temperature,
eos_token_id=terminators,
)
# Start generation in a separate thread
t = Thread(target=model.generate, kwargs=generate_kwargs)
t.start()
# Stream the response token by token
outputs = []
for text in streamer:
outputs.append(text)
yield "".join(outputs)
# Function to handle chat interaction
def chatbot_response(message, history, temperature, max_new_tokens):
bot_response = generate_bot_response(message, history, temperature, max_new_tokens)
for response in bot_response:
yield history + [(message, response)]
# Function to manually refresh resources
def refresh_resources():
global resources
resources = load_resources()
return "Resources reloaded!"
# Define Gradio interface
with gr.Blocks(title="DeepSeek Chatbot") as app:
chatbot = gr.Chatbot(height=450, label="Chat with DeepSeek")
msg = gr.Textbox(placeholder="Ask something...", show_label=False)
submit_button = gr.Button("Submit")
refresh_button = gr.Button("Refresh Resources")
state = gr.State([])
# Additional parameters
with gr.Accordion("⚙️ Parameters", open=False):
temperature = gr.Slider(minimum=0, maximum=1, step=0.1, value=0.7, label="Temperature")
max_new_tokens = gr.Slider(minimum=128, maximum=4096, step=1, value=1024, label="Max New Tokens")
# Submit button action
msg.submit(chatbot_response, inputs=[msg, state, temperature, max_new_tokens], outputs=[chatbot])
submit_button.click(chatbot_response, inputs=[msg, state, temperature, max_new_tokens], outputs=[chatbot])
refresh_button.click(refresh_resources, outputs=None)
# Launch the Gradio app
if __name__ == "__main__":
app.launch(debug=True) |