NaimaAqeel commited on
Commit
c4f4dc5
1 Parent(s): aa7a7e2

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +104 -63
  2. faiss_index.pkl +3 -0
  3. requirements.txt +12 -1
  4. temp.docx +0 -0
app.py CHANGED
@@ -1,63 +1,104 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- huggingface_hub==0.22.2
 
 
 
 
 
 
 
 
 
 
 
 
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