Spaces:
Sleeping
Sleeping
NaimaAqeel
commited on
Commit
•
c4f4dc5
1
Parent(s):
aa7a7e2
Upload 4 files
Browse files- app.py +104 -63
- faiss_index.pkl +3 -0
- requirements.txt +12 -1
- temp.docx +0 -0
app.py
CHANGED
@@ -1,63 +1,104 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
):
|
18 |
-
|
19 |
-
|
20 |
-
for
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
""
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
)
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import fitz # PyMuPDF
|
3 |
+
from docx import Document
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import faiss
|
6 |
+
import numpy as np
|
7 |
+
import pickle
|
8 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
9 |
+
from langchain_community.vectorstores import FAISS
|
10 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
11 |
+
from fastapi import FastAPI, UploadFile, File
|
12 |
+
from typing import List
|
13 |
+
|
14 |
+
app = FastAPI()
|
15 |
+
|
16 |
+
# Function to extract text from a PDF file
|
17 |
+
def extract_text_from_pdf(pdf_path):
|
18 |
+
text = ""
|
19 |
+
doc = fitz.open(pdf_path)
|
20 |
+
for page_num in range(len(doc)):
|
21 |
+
page = doc.load_page(page_num)
|
22 |
+
text += page.get_text()
|
23 |
+
return text
|
24 |
+
|
25 |
+
# Function to extract text from a Word document
|
26 |
+
def extract_text_from_docx(docx_path):
|
27 |
+
doc = Document(docx_path)
|
28 |
+
text = "\n".join([para.text for para in doc.paragraphs])
|
29 |
+
return text
|
30 |
+
|
31 |
+
# Initialize the embedding model
|
32 |
+
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
33 |
+
|
34 |
+
# Hugging Face API token
|
35 |
+
api_token = os.getenv('HUGGINGFACEHUB_API_TOKEN')
|
36 |
+
if not api_token:
|
37 |
+
raise ValueError("HUGGINGFACEHUB_API_TOKEN environment variable is not set")
|
38 |
+
|
39 |
+
print(f"API Token: {api_token[:5]}...")
|
40 |
+
|
41 |
+
# Initialize the HuggingFace LLM
|
42 |
+
llm = HuggingFaceEndpoint(
|
43 |
+
endpoint_url="https://api-inference.huggingface.co/models/gpt2",
|
44 |
+
model_kwargs={"api_key": api_token}
|
45 |
+
)
|
46 |
+
|
47 |
+
# Initialize the HuggingFace embeddings
|
48 |
+
embedding = HuggingFaceEmbeddings()
|
49 |
+
|
50 |
+
# Load or create FAISS index
|
51 |
+
index_path = "faiss_index.pkl"
|
52 |
+
if os.path.exists(index_path):
|
53 |
+
with open(index_path, "rb") as f:
|
54 |
+
index = pickle.load(f)
|
55 |
+
else:
|
56 |
+
# Create a new FAISS index if it doesn't exist
|
57 |
+
index = faiss.IndexFlatL2(embedding_model.get_sentence_embedding_dimension())
|
58 |
+
with open(index_path, "wb") as f:
|
59 |
+
pickle.dump(index, f)
|
60 |
+
|
61 |
+
@app.post("/upload/")
|
62 |
+
async def upload_file(files: List[UploadFile] = File(...)):
|
63 |
+
for file in files:
|
64 |
+
content = await file.read()
|
65 |
+
if file.filename.endswith('.pdf'):
|
66 |
+
with open("temp.pdf", "wb") as f:
|
67 |
+
f.write(content)
|
68 |
+
text = extract_text_from_pdf("temp.pdf")
|
69 |
+
elif file.filename.endswith('.docx'):
|
70 |
+
with open("temp.docx", "wb") as f:
|
71 |
+
f.write(content)
|
72 |
+
text = extract_text_from_docx("temp.docx")
|
73 |
+
else:
|
74 |
+
return {"error": "Unsupported file format"}
|
75 |
+
|
76 |
+
# Process the text and update FAISS index
|
77 |
+
sentences = text.split("\n")
|
78 |
+
embeddings = embedding_model.encode(sentences)
|
79 |
+
index.add(np.array(embeddings))
|
80 |
+
|
81 |
+
# Save the updated index
|
82 |
+
with open(index_path, "wb") as f:
|
83 |
+
pickle.dump(index, f)
|
84 |
+
|
85 |
+
return {"message": "Files processed successfully"}
|
86 |
+
|
87 |
+
@app.post("/query/")
|
88 |
+
async def query(text: str):
|
89 |
+
# Encode the query text
|
90 |
+
query_embedding = embedding_model.encode([text])
|
91 |
+
|
92 |
+
# Search the FAISS index
|
93 |
+
D, I = index.search(np.array(query_embedding), k=5)
|
94 |
+
|
95 |
+
top_documents = []
|
96 |
+
for idx in I[0]:
|
97 |
+
if idx != -1: # Ensure that a valid index is found
|
98 |
+
top_documents.append(f"Document {idx}")
|
99 |
+
|
100 |
+
return {"top_documents": top_documents}
|
101 |
+
|
102 |
+
if __name__ == "__main__":
|
103 |
+
import uvicorn
|
104 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
faiss_index.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f8ad23da459429f29dfd33e3b9cbf1852c2a31bcc85a7c6ca28ebbe2b597bcb0
|
3 |
+
size 46191
|
requirements.txt
CHANGED
@@ -1 +1,12 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python=3.8
|
2 |
+
fastapi
|
3 |
+
uvicorn
|
4 |
+
pydantic
|
5 |
+
fitz
|
6 |
+
python-docx
|
7 |
+
sentence-transformers
|
8 |
+
faiss-cpu
|
9 |
+
langchain
|
10 |
+
langchain_community
|
11 |
+
huggingface-hub
|
12 |
+
transformers
|
temp.docx
ADDED
Binary file (19.3 kB). View file
|
|