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)