local_chat / tool.py
sajeekahn's picture
Update tool.py
ad444df verified
Raw History Blame Contribute Delete
3.21 kB
import os
import requests
from langchain_chroma import Chroma
from langchain_community.document_loaders import WebBaseLoader, PyPDFLoader, TextLoader
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
_embedding_model = None
def _get_embeddings():
"""Load the embedding model once and reuse it (CPU is fine for MiniLM)."""
global _embedding_model
if _embedding_model is None:
# Force CPU: on ZeroGPU, touching CUDA outside a @spaces.GPU function raises an error.
_embedding_model = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2",
model_kwargs={"device": "cpu"},
encode_kwargs={"normalize_embeddings": True},
)
return _embedding_model
def vectorize_documents(file_path):
# Gradio may pass a file dict or an object with .name instead of a raw string path
if isinstance(file_path, dict):
file_path = file_path.get("path", "")
elif hasattr(file_path, "name"):
file_path = file_path.name
if not file_path or not os.path.exists(file_path):
raise ValueError(f"Invalid or missing file path: {file_path}")
if file_path.lower().endswith(".pdf"):
documents = PyPDFLoader(file_path).load()
elif file_path.lower().endswith((".txt", ".md")):
documents = TextLoader(file_path, encoding="utf-8").load()
else:
raise ValueError("Unsupported file format. Please upload a PDF or text file.")
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=300,
chunk_overlap=50,
separators=["\n\n", "\n", " ", ""],
)
documents = text_splitter.split_documents(documents)
embedding_model = _get_embeddings()
db_dir = "DB"
if os.path.exists(db_dir):
try:
Chroma(
persist_directory=db_dir, embedding_function=embedding_model
).delete_collection()
except Exception:
pass
vectorstore = Chroma.from_documents(
documents=documents,
embedding=embedding_model,
persist_directory=db_dir,
)
return vectorstore.as_retriever()
def get_weather(location: str) -> str:
"""Get the current weather for a given city name.
Provides a short, clean, one-line weather summary from wttr.in.
Args:
location (str): The name of the city or location (e.g., 'Lahore').
"""
try:
url = f"https://wttr.in/{location}?format=3"
response = requests.get(url, timeout=5)
if response.status_code == 200:
return response.text.strip()
return f"Could not retrieve weather for {location}."
except Exception as e:
return f"Error: {str(e)}"
def get_content_from_site(url: str) -> str:
"""Fetch the text content of a website.
Args:
url (str): The full URL of the page to read (e.g., 'https://example.com').
"""
try:
docs = WebBaseLoader([url]).load()
if not docs:
return "No content found."
return docs[0].page_content[:8000]
except Exception as e:
return f"Error fetching website content: {str(e)}"