from langchain.embeddings import HuggingFaceEmbeddings
2024-10-06 14:14:34,809 [INFO] Imported existing <module 'comtypes.gen' from 'D:\AI\EXP2\.venv\Lib\site-packages\comtypes\gen\init.py'>
2024-10-06 14:14:34,809 [INFO] Using writeable comtypes cache directory: 'D:\AI\EXP2.venv\Lib\site-packages\comtypes\gen'
d:\AI\EXP2\onlyocrwebsearch.py:76: LangChainDeprecationWarning: The class HuggingFaceEmbeddings was deprecated in LangChain 0.2.2 and will be removed in 1.0. An updated version of the class exists in the :class:~langchain-huggingface package and should be used instead. To use it run pip install -U :class:~langchain-huggingface and import as from :class:~langchain_huggingface import HuggingFaceEmbeddings``.
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
2024-10-06 14:14:35,067 [INFO] Use pytorch device_name: cpu
2024-10-06 14:14:35,067 [INFO] Load pretrained SentenceTransformer: all-mpnet-base-v2
D:\AI\EXP2.venv\Lib\site-packages\transformers\tokenization_utils_base.py:1617: FutureWarning: clean_up_tokenization_spaces was not set. It will be set to True by default. This behavior will be deprecated in transformers v4.45, and will be then set to False by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884
warnings.warn(
Traceback (most recent call last):
File "d:\AI\EXP2\onlyocrwebsearch.py", line 77, in
vector_store = FAISS.load_local(r"D:\AI\EXP2\faiss_index", embeddings)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\AI\EXP2.venv\Lib\site-packages\langchain_community\vectorstores\faiss.py", line 1188, in load_local
raise ValueError(
ValueError: The de-serialization relies loading a pickle file. Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.You will need to set allow_dangerous_deserialization to True to enable deserialization. If you do this, make sure that you trust the source of the data. For example, if you are loading a file that you created, and know that no one else has modified the file, then this is safe to do. Do not set this to True if you are loading a file from an untrusted source (e.g., some random site on the internet.).
Assistant
It seems you're encountering several issues while trying to use the HuggingFaceEmbeddings class from LangChain and loading a FAISS index. Let's address them step-by-step:
Deprecation Warning: The HuggingFaceEmbeddings class has been deprecated as of LangChain 0.2.2. To resolve this:
Install the updated package with the following command:
bash
User
2024-10-06 14:39:34,630 [INFO] Image preprocessing complete. Performing OCR...
2024-10-06 14:39:34,924 [INFO] OCR Text: 261, As per IRC 37:2018, for Initial (two-way) traffic
voiume in terms of commercial vehicle per day is 0-
150, the Vehicle damage factor for Plain/Rolling
terrain is (GES, Class 1/2, 2019)
(A) 3.9 (B) 1.7
(C) 5.0 (D) 0.6
2024-10-06 14:39:34,924 [INFO] OCR process completed successfully.
2024-10-06 14:39:34,924 [INFO] Generating final response...
2024-10-06 14:39:37,585 [INFO] HTTP Request: POST http://127.0.0.1:11434/api/generate "HTTP/1.1 200 OK"
2024-10-06 14:39:37,588 [INFO] Generated formatted response.
2024-10-06 14:39:37,588 [INFO] Speaking out the response: I'm sorry, but I am unable to answer this question as it is not clear what is being asked or what the calculations are for. The text seems to be a collection of diagrams and tables related to pavement design and construction, but there is no specific question or problem stated.
If you could provide more context or clarify what you would like me to do, I will do my best to assist you. the rag seems to be messing with llm
Assistant
It looks like you are working on a project involving optical character recognition (OCR) and language model processing to interpret and respond to text extracted from images. Let's break down the log messages and address the issues you might be encountering:
User
Assistant
pip install -U langchain-huggingface
Update your import statement in the code to reflect this change:
python
from langchain_huggingface import HuggingFaceEmbeddings
FAISS Index Loading Error: You're trying to load a FAISS index and encountering a security warning related to pickle file deserialization.
Ensure the FAISS index file you're trying to load is from a trusted source.
If the file is trusted:
Set allow_dangerous_deserialization to True to allow loading. However, do this only if you're sure of the source of the file as it poses a security risk.
The code for loading the FAISS index might look like this:
Transformers Future Warning: This warning indicates that the default behavior for clean_up_tokenization_spaces will change in the future.
To suppress this warning and potentially avoid future issues, you can set it explicitly, if the method you're using supports it:
python
tokenizer.clean_up_tokenization_spaces = False
General Best Practices:
Before making any changes, ensure your virtual environment and packages are up to date.
Regularly check the documentation or CHANGELOGs of the libraries you're using to stay informed about updates or deprecated features.
By following these steps, you should be able to resolve the issues and warnings you're facing in your current setup.
OCR Processing: The OCR process seems to have successfully extracted text from an image. The extracted text appears to be related to pavement design guidelines or standards (as per IRC 37:2018).
Language Model Response: After OCR, it seems like you're using a language model or system to analyze or respond to the extracted text. However, the response generated indicates difficulty in understanding or formulating a response due to the lack of a clear question or problem statement.
Improving System Understanding:
Contextual Input: Ensure that the input to your language model includes context or specific questions to guide the model in generating useful responses. For example, if the text is related to a calculation or a problem that needs solving, explicitly state that.
Pre-Processing: Prior to sending the OCR text to the language model, you could pre-process the text to remove any noise (like metadata or irrelevant text) and focus on key information or questions.
Clarification Requests: Encourage users to provide additional context or clarify their questions, as the system has prompted.
Language Model Tuning:
Model Parameters: Sometimes, modifying parameters such as temperature or providing examples in the prompt can help improve the model's output.
Custom Prompting: Tailor the prompt carefully to ensure that the language model can better understand the input text structure and the expected output.
Logging and Error Handling:
Monitor logs for unusual patterns or repetitive errors to identify potential areas of improvement.
Consider implementing more robust error handling to manage unclear or incomplete inputs gracefully.
With these adjustments, you may improve the system's ability to comprehend and respond to the OCR text effectively. If the issue persists, specifically with the model not understanding a technical context, you might explore training or fine-tuning a model on a relevant dataset for better domain-specific performance.
import re
import mss
from PIL import Image, ImageEnhance
import pytesseract
import speech_recognition as sr
import pyttsx3
import keyboard
import threading
import os
import logging
import tkinter as tk
import ctypes
import sys
import asyncio
from datetime import datetime
from word2number import w2n
from langchain.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings # Updated import per deprecation
import warnings
import ollama
embedding_model_name = "all-mpnet-base-v2" # Choose based on your VRAM constraints
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
vector_store = FAISS.load_local(r"D:\AI\EXP2\faiss_index", embeddings, allow_dangerous_deserialization=True)
def set_dpi_awareness():
try:
if sys.platform.startswith('win'):
ctypes.windll.shcore.SetProcessDpiAwareness(1)
logging.info("Process DPI awareness set to SYSTEM_AWARE.")
except Exception as e:
logging.warning(f"Could not set DPI awareness: {e}. Continuing without setting DPI awareness.")
def convert_number_words(text):
"""
Converts number words in the speech text to digits.
Example: "five hundred ninety-seven" -> "597"
"""
try:
# Attempt to convert the entire text
number = w2n.word_to_num(text)
return str(number)
except:
# Attempt to extract digits directly if conversion fails
digits = re.findall(r'\d+', text)
return ''.join(digits) if digits else text # Return the number if found, else original text
def strip_markdown(text):
"""Function to remove Markdown syntax from text."""
# Remove asterisks, underscores, and backticks
text = re.sub(r'[*_`]', '', text)
# Remove links text
text = re.sub(r'[([^]]+)]([^)]+)', r'\1', text)
# Remove headings ## Heading
text = re.sub(r'#+\s?', '', text)
# Remove Markdown inline code blocks
text = re.sub(r'[\s\S]*?', '', text)
# Remove any remaining backslashes
text = text.replace("\", "")
# Add more patterns as necessary
return text
def speak_text(text):
global tts_engine
logging.info(f"Speaking out the response: {text}")
with tts_lock:
try:
tts_engine.say(text)
code
# Add hotkeys for pausing (F4) and stopping (F5)
keyboard.add_hotkey('f4', pause_speaking)
keyboard.add_hotkey('f5', stop_speaking)
tts_engine.runAndWait()
logging.info("Text-to-Speech completed.")
except RuntimeError as e:
logging.error(f"TTS Error: {e}")
finally:
keyboard.remove_hotkey('f4')
keyboard.remove_hotkey('f5')
def pause_speaking():
global tts_engine
logging.info("Paused speaking...")
# Note: pyttsx3 does not natively support pausing. Placeholder for future implementation.
def stop_speaking():
global tts_engine
logging.info("Stopped speaking.")
tts_engine.stop()
def save_captured_image(image, output_dir, prefix="captured_region"):
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(output_dir, f"{prefix}_{timestamp}.png")
image.save(filename)
logging.info(f"Captured image saved as {filename}")
except Exception as e:
logging.error(f"Failed to save captured image: {e}")
def save_preprocessed_image(image, output_dir, prefix="preprocessed_image"):
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(output_dir, f"{prefix}_{timestamp}.png")
image.save(filename)
logging.info(f"Preprocessed image saved as {filename}")
except Exception as e:
logging.error(f"Failed to save preprocessed image: {e}")
def perform_ocr(image):
global ocr_text
try:
logging.info("Starting OCR process with image preprocessing...")
code
save_captured_image(image, OUTPUT_DIR)
gray = image.convert('L')
# Removed DEBUG logs related to image processing
enhancer = ImageEnhance.Contrast(gray)
gray_enhanced = enhancer.enhance(1.0)
# Removed DEBUG logs related to image processing
threshold = 190
gray_threshold = gray_enhanced.point(lambda x: 0 if x < threshold else 255, '1')
# Removed DEBUG logs related to image processing
final_image = gray_threshold
save_preprocessed_image(final_image, OUTPUT_DIR)
logging.info("Image preprocessing complete. Performing OCR...")
custom_config = r'--oem 3 --psm 6'
raw_text = pytesseract.image_to_string(final_image, lang='eng', config=custom_config)
if not raw_text.strip():
logging.warning("OCR returned empty text.")
speak_text("I couldn't detect any text in the selected area. Please try again with a different region.")
else:
ocr_text = raw_text.strip()
logging.info(f"OCR Text: {ocr_text}") # Log the extracted OCR text
logging.info("OCR process completed successfully.")
except pytesseract.TesseractNotFoundError:
logging.error("Tesseract executable not found. Please ensure Tesseract is installed and PATH is set correctly.")
speak_text("Tesseract is not installed or not found. Please install Tesseract and try again.")
ocr_text = ""
except Exception as e:
logging.error(f"OCR Error: {e}")
speak_text("An error occurred during OCR processing. Please try again.")
ocr_text = ""
def get_selected_region(scaling_factor):
root = tk.Tk()
root.title("Select Region (Press Esc to Cancel)")
root.attributes('-alpha', 0.3)
root.attributes("-topmost", True)
root.overrideredirect(True)
code
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.geometry(f"{screen_width}x{screen_height}")
canvas = tk.Canvas(root, cursor="cross", bg="grey")
canvas.pack(fill=tk.BOTH, expand=True)
rect = None
start_x = start_y = end_x = end_y = 0
def on_button_press(event):
nonlocal start_x, start_y, rect
start_x = int(event.x * scaling_factor)
start_y = int(event.y * scaling_factor)
rect = canvas.create_rectangle(event.x, event.y, event.x, event.y, outline='red', width=2)
logging.info("Please select the region by clicking and dragging the mouse.")
def on_move_press(event):
nonlocal end_x, end_y
end_x = int(event.x * scaling_factor)
end_y = int(event.y * scaling_factor)
canvas.coords(rect, start_x / scaling_factor, start_y / scaling_factor, event.x, event.y)
def on_button_release(event):
root.quit()
root.destroy()
def on_escape(event):
logging.info("Capture cancelled by user.")
root.quit()
root.destroy()
# Optionally, you can set a flag or perform other actions here
# but to keep the script running, do not exit the program
canvas.bind("<ButtonPress-1>", on_button_press)
canvas.bind("<B1-Motion>", on_move_press)
canvas.bind("<ButtonRelease-1>", on_button_release)
root.bind("<Escape>", on_escape)
root.mainloop()
left = min(start_x, end_x)
top = min(start_y, end_y)
right = max(start_x, end_x)
bottom = max(start_y, end_y)
logging.info(f"Selected region coordinates (scaled): Left={left}, Top={top}, Right={right}, Bottom={bottom}")
return (left, top, right, bottom)
def generate_final_response(ocr_text):
logging.info("Generating final response...")
code
# Retrieve relevant documents from the knowledge base (RAG)
query = ocr_text
retrieved_docs = vector_store.similarity_search(query, k=10) # Adjust 'k' as needed
retrieved_text = "\n".join([doc.page_content for doc in retrieved_docs])
# Combine OCR text with retrieved context
context = f"""Assume the role of a strategist who excels at logical problem-solving and planning based on the following information.
Retrieved Information:
{retrieved_text}
OCR Text:
{ocr_text}
Instructions:
Understand the OCR text and treat it as a comprehensive multiple-choice question.
1.1. Use Retrived information as your knoledge base.
Identify the correct answer from options (if provided within text).
Respond in plain text without any Markdown formatting.
Eliminate all Markdown syntax such as asterisks (*), underscores (_), backticks (`), and brackets ([]).
Keep your answer strictly to 100 words.
If there is calculation involved, follow this structure:
We have been given (calculation_data),
The formula to be used is (formula),
We need to find (answer_variable).
Perform calculations attentively.
Provide the answer below:
"""
code
try:
# Generate response from the LLM with the enriched context
response = ollama.generate(model='llama3.1', prompt=context)
raw_response = response.get('response', '').strip()
# Strip Markdown formatting
plain_text_response = strip_markdown(raw_response)
# Provide the response
if "because" or "and" in plain_text_response:
formatted_answer = plain_text_response
logging.info("Generated formatted response.")
else:
formatted_answer = "The response could not be structured correctly."
logging.warning(formatted_answer)
if formatted_answer:
speak_text(formatted_answer)
else:
logging.warning("No valid response could be generated.")
return formatted_answer
except Exception as e:
logging.error(f"LLM Error during final response generation: {e}")
return ""
def transcribe_speech(short_timeout=5, phrase_time_limit=5):
"""
Transcribes speech from the microphone with a short timeout.
If no speech is detected within the timeout, proceeds without user input.
code
Args:
short_timeout (int): Maximum number of seconds to wait for a phrase to start.
phrase_time_limit (int): Maximum number of seconds a phrase can last.
"""
global is_listening, speech_text
recognizer = sr.Recognizer()
with sr.Microphone() as source:
logging.info("Listening for voice input... Please say your query or question.")
recognizer.adjust_for_ambient_noise(source, duration=1) # Adjust for noise for 1 second
try:
# Listen for speech with shorter timeout and phrase time limit
audio = recognizer.listen(source, timeout=short_timeout, phrase_time_limit=phrase_time_limit)
logging.info("Processing the audio with Google Speech Recognition...")
text = recognizer.recognize_google(audio)
# Convert number words to digits if necessary
speech_text = convert_number_words(text)
logging.info(f"Speech Transcribed: {speech_text}")
# Provide confirmation
speak_text(f"I heard: {speech_text}.")
except sr.WaitTimeoutError:
logging.warning("Listening timed out, no speech detected. Proceeding without voice input.")
speech_text = "" # Ensure speech_text is empty
except sr.UnknownValueError:
logging.warning("Speech recognition could not understand audio. Proceeding without voice input.")
speech_text = "" # Ensure speech_text is empty
except sr.RequestError as e:
logging.error(f"Could not request results from speech recognition service; {e}")
speech_text = "" # Ensure speech_text is empty
finally:
with lock:
is_listening = False # Ensure listening flag is reset
def configure_tts_voice():
"""
Configures the TTS engine's voice, rate, and volume.
"""
global tts_engine
voices = tts_engine.getProperty('voices')
code
# List available voices (optional)
# Commented out DEBUG logs as they are now suppressed
# for index, voice in enumerate(voices):
# logging.debug(f"Voice {index}: {voice.name}, {voice.gender}, {voice.languages}")
# Change voice (select male/female, adjust the index as per your preference)
if len(voices) > 1:
tts_engine.setProperty('voice', voices[1].id) # Change index to select a different voice
logging.info(f"TTS voice set to: {voices[1].name}")
else:
logging.info("Only one voice available. Using default voice.")
# Adjust speaking rate (lower is slower and more human-like)
tts_engine.setProperty('rate', 150) # Default is 200, lowering makes it more human-like
# Adjust volume (0.0 to 1.0)
tts_engine.setProperty('volume', 1.0)
def capture_and_save_image():
global ocr_text, is_listening # Added is_listening to globals
code
region = get_selected_region(scaling_factor)
left, top, right, bottom = region
width = right - left
height = bottom - top
# Removed detailed dimension logging
logging.info("Starting OCR process with image preprocessing...")
if width <= 0 or height <= 0:
logging.error("Invalid region selected. Please try again.")
speak_text("Invalid region selected. Please try again by pressing F2.")
reset_state()
with lock:
is_listening = False # Reset the listening flag
return
with mss.mss() as sct:
monitor = {
"top": int(top / scaling_factor),
"left": int(left / scaling_factor),
"width": int(width / scaling_factor),
"height": int(height / scaling_factor)
}
try:
screenshot = sct.grab(monitor)
img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
except Exception as e:
logging.error(f"Screen capture failed: {e}")
speak_text("Screen capture failed. Please ensure the selected area is correct and try again.")
reset_state()
with lock:
is_listening = False # Reset the listening flag
return
perform_ocr(img)
if not ocr_text.strip():
logging.error("OCR returned empty text. Please ensure the selected region contains readable text.")
speak_text("OCR did not detect any text. Please ensure the selected area contains readable text and try again.")
reset_state()
with lock:
is_listening = False # Reset the listening flag
return
generate_final_response(ocr_text)
reset_state()
with lock:
is_listening = False # Reset the listening flag after processing
def start_listening(scaling):
global is_listening
with lock:
if not is_listening:
is_listening = True
logging.info("Started listening...")
threading.Thread(target=capture_and_save_image, args=(), daemon=True).start()
def stop_listening():
global is_listening
with lock:
if is_listening:
is_listening = False
logging.info("Stopped listening.")
speak_text("Stopped listening.")
async def main():
global scaling_factor
code
configure_tts_voice()
set_dpi_awareness()
scaling_factor = get_scaling_factor()
# Bind hotkeys
keyboard.add_hotkey('f2', start_listening, args=(scaling_factor,))
keyboard.add_hotkey('f3', stop_listening)
logging.info("QA Assistant is running.")
logging.info("Press 'F2' to select a region and answer a question, 'F3' to stop listening, 'Esc' to exit.")
while True:
await asyncio.sleep(0.1)
if keyboard.is_pressed('esc'):
logging.info("Exiting...")
speak_text("Exiting the QA Assistant. Goodbye!")
break
keyboard.unhook_all()
if name == "main":
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.info("Program terminated by user.")
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
finally:
keyboard.unhook_all(): generate me a script which uses this knolwdge base to chat with llm model itself. remove all other things
To create a simplified script that uses the knowledge base to chat with a language model, we will focus solely on embedding and querying the language model using LangChain and the HuggingFace embeddings you've set up. I'll structure the new script to handle user input, query the vector store (FAISS), and communicate with the language model to get responses. We'll exclude unrelated functionalities such as OCR, TTS, and hotkey management.
Below is a streamlined script to chat using the knowledge base:
python
import logging
from langchain.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
import ollama
# -------------------- Configuration --------------------
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
# Initialize embedding and vector store
embedding_model_name = "all-mpnet-base-v2" # Adjust model as needed
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
vector_store = FAISS.load_local(r"D:\AI\EXP2\faiss_index", embeddings, allow_dangerous_deserialization=True)
def strip_markdown(text):
"""Function to remove Markdown syntax from text."""
text = re.sub(r'[*_`]', '', text) # Remove asterisks, underscores, and backticks
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text) # Remove links [text](url)
text = re.sub(r'#+\s?', '', text) # Remove headings ## Heading
text = re.sub(r'```[\s\S]*?```', '', text) # Remove inline code blocks
text = text.replace("\\", "") # Remove remaining backslashes
return text
def generate_response(user_input):
# Retrieve relevant information from the knowledge base
retrieved_docs = vector_store.similarity_search(user_input, k=10) # Adjust 'k' as needed
retrieved_text = "\n".join([doc.page_content for doc in retrieved_docs])
# Prepare the context for the language model
context = f"""Use the retrieved information to assist in answering the user's query.
Retrieved Information:
{retrieved_text}
User Query:
{user_input}
Instructions:
1. Use the retrieved information to provide a relevant response to the user's query.
2. Respond in plain text without any Markdown formatting.
3. Limit your response to 100 words where possible.
Provide the response below:
"""
try:
# Generate response
response = ollama.generate(model='llama3.1', prompt=context)
raw_response = response.get('response', '').strip()
# Strip Markdown formatting
plain_text_response = strip_markdown(raw_response)
logging.info("Generated response from LLM.")
return plain_text_response
except Exception as e:
logging.error(f"Error during response generation: {e}")
return "An error occurred while generating the response."
def main():
logging.info("Simple Chat Interface with Knowledge Base.")
logging.info("Type 'exit' to quit the chat.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
logging.info("Exiting chat.")
break
response = generate_response(user_input)
print(f"Model: {response}")
if __name__ == "__main__":
main()
Key Components:
Embedding Model and FAISS Vector Store: The script initializes a vector store using HuggingFace embeddings, enabling fast retrieval of relevant documents from your knowledge base.
Language Model Invocation: It uses ollama.generate to process user queries and create responses based on retrieved context, assuming you have a compatible setup for this function.
User Interaction: This basic command-line interface lets users type queries and receive responses until they type "exit."
This script is a starting point for integrating a simple chat function with your language model, focusing purely on querying and generating responses using the set up VectorStore.