Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import faiss
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
from transformers import pipeline
|
| 6 |
+
import PyPDF2
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Load embedding model
|
| 10 |
+
retriever = SentenceTransformer("all-MiniLM-L6-v2")
|
| 11 |
+
|
| 12 |
+
# Ensure /mnt/data/ directory exists
|
| 13 |
+
pdf_dir = "/mnt/data/"
|
| 14 |
+
os.makedirs(pdf_dir, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
# Auto-detect the most recent PDF in /mnt/data/
|
| 17 |
+
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)
|
| 18 |
+
|
| 19 |
+
if pdf_files:
|
| 20 |
+
pdf_path = os.path.join(pdf_dir, pdf_files[0]) # Use the first detected PDF
|
| 21 |
+
print(f"β
Using detected PDF: {pdf_path}")
|
| 22 |
+
else:
|
| 23 |
+
pdf_path = None
|
| 24 |
+
print("π¨ No PDF file found in /mnt/data/")
|
| 25 |
+
|
| 26 |
+
def extract_text_from_pdf(pdf_path):
|
| 27 |
+
if not pdf_path or not os.path.exists(pdf_path):
|
| 28 |
+
print("β PDF file not found!")
|
| 29 |
+
return "Error: Output cannot be generated at this time. Please try again later."
|
| 30 |
+
|
| 31 |
+
text = []
|
| 32 |
+
try:
|
| 33 |
+
with open(pdf_path, "rb") as file:
|
| 34 |
+
reader = PyPDF2.PdfReader(file)
|
| 35 |
+
for page in reader.pages:
|
| 36 |
+
page_text = page.extract_text()
|
| 37 |
+
if page_text:
|
| 38 |
+
text.append(page_text.strip())
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"β οΈ PDF Extraction Failed: {str(e)}")
|
| 41 |
+
return "Error: Unable to read the PDF file. Please try again later."
|
| 42 |
+
|
| 43 |
+
return "\n".join(text) if text else "Error: No extractable text found in PDF."
|
| 44 |
+
|
| 45 |
+
# Process and chunk the text
|
| 46 |
+
text = extract_text_from_pdf(pdf_path) if pdf_path else ""
|
| 47 |
+
if "Error" in text or not text:
|
| 48 |
+
print("β No text extracted from PDF.")
|
| 49 |
+
chunks = []
|
| 50 |
+
else:
|
| 51 |
+
words = text.split()
|
| 52 |
+
chunk_size = 500
|
| 53 |
+
chunks = [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)]
|
| 54 |
+
print(f"β
Extracted {len(chunks)} text chunks from PDF.")
|
| 55 |
+
|
| 56 |
+
# Embed and store chunks in FAISS if available
|
| 57 |
+
if chunks:
|
| 58 |
+
chunk_vectors = retriever.encode(chunks)
|
| 59 |
+
index = faiss.IndexFlatL2(chunk_vectors.shape[1])
|
| 60 |
+
index.add(np.array(chunk_vectors))
|
| 61 |
+
print("β
FAISS index built successfully.")
|
| 62 |
+
else:
|
| 63 |
+
index = None
|
| 64 |
+
print("β FAISS index not created. No valid text chunks.")
|
| 65 |
+
|
| 66 |
+
# Load a lightweight Hugging Face model
|
| 67 |
+
model_name = "microsoft/phi-2" # Using a smaller, more efficient model
|
| 68 |
+
qa_pipeline = pipeline("text-generation", model=model_name, device="cpu") # Explicitly set CPU
|
| 69 |
+
|
| 70 |
+
# Search function
|
| 71 |
+
def search_plastics(query):
|
| 72 |
+
if not index or not chunks:
|
| 73 |
+
return "Error: Output cannot be generated at this time. Please try again later."
|
| 74 |
+
query_vector = retriever.encode([query])
|
| 75 |
+
_, indices = index.search(np.array(query_vector), k=1)
|
| 76 |
+
retrieved_doc = chunks[indices[0][0]]
|
| 77 |
+
ai_response = qa_pipeline(retrieved_doc, max_length=50, do_sample=True, temperature=0.7)[0]['generated_text']
|
| 78 |
+
return ai_response
|
| 79 |
+
|
| 80 |
+
# Gradio Interface
|
| 81 |
+
iface = gr.Interface(
|
| 82 |
+
fn=search_plastics,
|
| 83 |
+
inputs="text",
|
| 84 |
+
outputs="text",
|
| 85 |
+
title="Plastics Knowledge AI",
|
| 86 |
+
description="Ask any question about plastics, recycling, and sustainability!",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Ensure Public Access
|
| 90 |
+
iface.launch(share=True, server_name="0.0.0.0")
|