Spaces:
Runtime error
Runtime error
Upload 4 files
Browse filesFiles changed (4)
- app (3).pyAdded+10
- app_large_books.pyAdded+185
- packages.txtAdded+1
- requirements.txtAdded+10
12345678910import subprocessimport os
if __name__ == "__main__": # Run Chainlit server on Hugging Face port 7860 subprocess.run([ "chainlit", "run", "app_large_books.py", "--host", "0.0.0.0", "--port", "7860" ])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import osimport asyncioimport base64from io import BytesIOfrom concurrent.futures import ThreadPoolExecutorfrom PIL import Imagefrom pdf2image import convert_from_path
import torchimport open_clipimport chainlit as cl
from langchain_groq import ChatGroqfrom langchain_core.messages import HumanMessagefrom langchain_chroma import Chromafrom langchain_core.embeddings import Embeddings
# Thread pool executor to handle sync heavy operations outside main asyncio loopexecutor = ThreadPoolExecutor(max_workers=2)
# Set Poppler path explicitly if running on Windows (Uncomment if needed)# POPPLER_PATH = r"C:\Program Files\poppler\Release-24.08.0-0\poppler-24.08.0\Library\bin"
class OpenCLIPEmbeddings(Embeddings): """ Multimodal OpenCLIP Embedding class to handle both image and text inputs. Generates joint vector space embeddings. """ def __init__(self, model_name="ViT-B-32", pretrained="laion2b_s34b_b79k"): self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model, _, self.preprocess = open_clip.create_model_and_transforms( model_name, pretrained=pretrained, device=self.device ) self.tokenizer = open_clip.get_tokenizer(model_name)
def embed_documents(self, texts): text_tokens = self.tokenizer(texts).to(self.device) with torch.no_grad(): text_features = self.model.encode_text(text_tokens) text_features /= text_features.norm(dim=-1, keepdim=True) return text_features.cpu().numpy().tolist()
def embed_query(self, text): return self.embed_documents([text])[0]
def embed_image(self, image_path): image = Image.open(image_path).convert("RGB") image_input = self.preprocess(image).unsqueeze(0).to(self.device) with torch.no_grad(): image_features = self.model.encode_image(image_input) image_features /= image_features.norm(dim=-1, keepdim=True) return image_features.cpu().numpy().tolist()[0]
def encode_image_to_base64(image_path): """Encodes local image file into a Base64 string for Groq Vision payload.""" with Image.open(image_path) as img: buffered = BytesIO() img.save(buffered, format="JPEG") return base64.b64encode(buffered.getvalue()).decode('utf-8')
def sync_init_and_process(pdf_path, pdf_name): """Synchronous worker function executed inside ThreadPoolExecutor.""" embedding_function = OpenCLIPEmbeddings() images_dir = f"./pdf_screenshots_{hash(pdf_name)}" os.makedirs(images_dir, exist_ok=True) # PDF page screenshot rendering images = convert_from_path(pdf_path, dpi=200) # poppler_path=POPPLER_PATH db_path = f"./chroma_chainlit_{hash(pdf_name)}" vectorstore = Chroma( persist_directory=db_path, embedding_function=embedding_function )
ids = [] embeddings_list = [] metadatas = []
for idx, image in enumerate(images): page_num = idx + 1 img_path = os.path.join(images_dir, f"page_{page_num}.jpg") image.save(img_path, "JPEG") img_emb = embedding_function.embed_image(img_path) ids.append(f"page_{page_num}") embeddings_list.append(img_emb) metadatas.append({"page": page_num, "image_path": img_path})
vectorstore._collection.add( ids=ids, embeddings=embeddings_list, metadatas=metadatas )
return vectorstore, len(images)
@cl.on_chat_startasync def on_chat_start(): api_key = os.getenv("GROQ_API_KEY") if not api_key: res = await cl.AskUserMessage( content="Please enter your **Groq API Key** to begin:", timeout=180 ).send() if res: api_key = res['output'].strip() cl.user_session.set("groq_api_key", api_key) else: cl.user_session.set("groq_api_key", api_key)
files = await cl.AskFileMessage( content="Please upload a PDF document to analyze:", accept=["application/pdf"], max_size_mb=100, timeout=180 ).send()
if not files: return
pdf_file = files[0] msg = cl.Message(content=f"Processing `{pdf_file.name}` into screenshots & embeddings...") await msg.send()
# Offload heavy tasks to ThreadPoolExecutor loop = asyncio.get_running_loop() vectorstore, total_pages = await loop.run_in_executor( executor, sync_init_and_process, pdf_file.path, pdf_file.name )
cl.user_session.set("vectorstore", vectorstore) await cl.Message(content=f"✅ **Indexing Complete!** Processed **{total_pages} pages**.").send()
@cl.on_messageasync def on_message(message: cl.Message): vectorstore = cl.user_session.get("vectorstore") groq_api_key = cl.user_session.get("groq_api_key")
if not vectorstore: await cl.Message(content="⚠️ Please upload a PDF first.").send() return
# Retrieval executed inside worker thread loop = asyncio.get_running_loop() retriever = vectorstore.as_retriever(search_kwargs={"k": 2}) relevant_docs = await loop.run_in_executor(executor, retriever.invoke, message.content)
if not relevant_docs: await cl.Message(content="Information not found in the uploaded document.").send() return
content_payload = [ { "type": "text", "text": f"Answer based strictly on the provided page screenshots.\n\nQuery: {message.content}" } ]
elements = [] for doc in relevant_docs: img_path = doc.metadata.get("image_path") page_num = doc.metadata.get("page") if img_path and os.path.exists(img_path): base64_img = encode_image_to_base64(img_path) content_payload.append({ "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_img}"} }) elements.append(cl.Image(path=img_path, name=f"Page {page_num}", display="inline"))
# Active Groq Vision Model llm_vision = ChatGroq( groq_api_key=groq_api_key, model_name="meta-llama/llama-4-scout-17b-16e-instruct", temperature=0.1 )
response = await llm_vision.ainvoke([HumanMessage(content=content_payload)]) await cl.Message(content=response.content, elements=elements).send()1poppler-utils12345678910chainlit>=2.0.0pdf2imagepillowtorchopen_clip_torchchromadblangchain-chromalangchain-groqlangchain-coregradioapp (3).pyAdded+10
app_large_books.pyAdded+185
packages.txtAdded+1
requirements.txtAdded+10