import gradio as gr import faiss import numpy as np from sentence_transformers import SentenceTransformer from transformers import pipeline import PyPDF2 import os # Load embedding model retriever = SentenceTransformer("all-MiniLM-L6-v2") # Ensure /mnt/data/ directory exists pdf_dir = "/mnt/data/" os.makedirs(pdf_dir, exist_ok=True) # Detect the most recent PDF in /mnt/data/ pdf_files = sorted( [f for f in os.listdir(pdf_dir) if f.endswith(".pdf")], key=lambda x: os.path.getctime(os.path.join(pdf_dir, x)), reverse=True ) if pdf_files: pdf_path = os.path.join(pdf_dir, pdf_files[0]) # Use the latest uploaded PDF print(f"✅ Using detected PDF: {pdf_path}") else: pdf_path = None print("🚨 No PDF file found in /mnt/data/") def extract_text_from_pdf(pdf_path): """Extract text from a PDF file.""" if not pdf_path or not os.path.exists(pdf_path): print("❌ PDF file not found!") return "Error: Output cannot be generated at this time. Please try again later." text = [] try: with open(pdf_path, "rb") as file: reader = PyPDF2.PdfReader(file) for page in reader.pages: page_text = page.extract_text() if page_text: text.append(page_text.strip()) except Exception as e: print(f"⚠️ PDF Extraction Failed: {str(e)}") return "Error: Unable to read the PDF file. Please try again later." if text: print(f"✅ Successfully extracted {len(text)} paragraphs from PDF.") else: print("⚠️ No extractable text found in PDF.") return "\n".join(text) if text else "Error: No extractable text found in PDF." # Process and chunk the text text = extract_text_from_pdf(pdf_path) if pdf_path else "" if "Error" in text or not text: print("❌ No text extracted from PDF.") chunks = [] else: words = text.split() chunk_size = 500 chunks = [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)] print(f"✅ Extracted {len(chunks)} text chunks from PDF.") # Embed and store chunks in FAISS if available if chunks: try: chunk_vectors = retriever.encode(chunks) index = faiss.IndexFlatL2(chunk_vectors.shape[1]) index.add(np.array(chunk_vectors)) print("✅ FAISS index built successfully.") except Exception as e: print(f"⚠️ FAISS indexing failed: {str(e)}") index = None else: index = None print("❌ FAISS index not created. No valid text chunks.") # Load a lightweight Hugging Face model model_name = "microsoft/phi-2" # Using a smaller, more efficient model try: qa_pipeline = pipeline("text-generation", model=model_name, device="cpu") # Explicitly set CPU print("✅ AI model loaded successfully.") except Exception as e: print(f"⚠️ AI model failed to load: {str(e)}") qa_pipeline = None # Search function def search_plastics(query): """Retrieve the most relevant chunk and generate AI response.""" if not index or not chunks: print("❌ No valid FAISS index or chunks available.") return "Error: Output cannot be generated at this time. Please try again later." query_vector = retriever.encode([query]) _, indices = index.search(np.array(query_vector), k=1) retrieved_doc = chunks[indices[0][0]] print(f"🔍 Retrieved document chunk: {retrieved_doc[:100]}...") if not qa_pipeline: print("❌ AI model is not available.") return "Error: AI response could not be generated. Please try again later." try: ai_response = qa_pipeline(retrieved_doc, max_length=100, do_sample=True, temperature=0.7)[0]['generated_text'] return ai_response except Exception as e: print(f"⚠️ AI response generation failed: {str(e)}") return "Error: AI response could not be generated. Please try again later." # Gradio Interface iface = gr.Interface( fn=search_plastics, inputs="text", outputs="text", title="Plastics Knowledge AI", description="Ask any question about plastics, recycling, and sustainability!", ) # Ensure Public Access iface.launch(share=True, server_name="0.0.0.0")