nvymshr commited on
Commit
7c08f86
·
verified ·
1 Parent(s): 02f2c9b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pdf_path = os.path.join(pdf_dir, pdf_files[0]) if pdf_files else None
20
+
21
+ def extract_text_from_pdf(pdf_path):
22
+ if not pdf_path or not os.path.exists(pdf_path):
23
+ return "Error: Output cannot be generated at this time. Please try again later."
24
+
25
+ text = []
26
+ try:
27
+ with open(pdf_path, "rb") as file:
28
+ reader = PyPDF2.PdfReader(file)
29
+ for page in reader.pages:
30
+ page_text = page.extract_text()
31
+ if page_text:
32
+ text.append(page_text.strip())
33
+ except Exception as e:
34
+ return "Error: Output cannot be generated at this time. Please try again later."
35
+
36
+ return "\n".join(text) if text else "Error: Output cannot be generated at this time. Please try again later."
37
+
38
+ # Process and chunk the text
39
+ text = extract_text_from_pdf(pdf_path) if pdf_path else ""
40
+ if "Error" in text or not text:
41
+ chunks = []
42
+ else:
43
+ words = text.split()
44
+ chunk_size = 500
45
+ chunks = [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)]
46
+
47
+ # Embed and store chunks in FAISS if available
48
+ if chunks:
49
+ chunk_vectors = retriever.encode(chunks)
50
+ index = faiss.IndexFlatL2(chunk_vectors.shape[1])
51
+ index.add(np.array(chunk_vectors))
52
+ else:
53
+ index = None
54
+
55
+ # Load a lightweight Hugging Face model
56
+ model_name = "microsoft/phi-2" # Using a smaller, more efficient model
57
+ qa_pipeline = pipeline("text-generation", model=model_name, device=0) # Enable GPU if available
58
+
59
+ # Search function
60
+ def search_plastics(query):
61
+ if not index or not chunks:
62
+ return "Error: Output cannot be generated at this time. Please try again later."
63
+ query_vector = retriever.encode([query])
64
+ _, indices = index.search(np.array(query_vector), k=1)
65
+ retrieved_doc = chunks[indices[0][0]]
66
+ ai_response = qa_pipeline(retrieved_doc, max_length=100, do_sample=True, temperature=0.7)[0]['generated_text']
67
+ return ai_response
68
+
69
+ # Gradio Interface
70
+ iface = gr.Interface(
71
+ fn=search_plastics,
72
+ inputs="text",
73
+ outputs="text",
74
+ title="Plastics Knowledge AI",
75
+ description="Ask any question about plastics, recycling, and sustainability!",
76
+ )
77
+
78
+ # Ensure Public Access
79
+ iface.launch(share=True, server_name="0.0.0.0")