pratham0011 commited on
Commit
0d00453
β€’
1 Parent(s): cc4e340

Upload main_.py

Browse files
Files changed (1) hide show
  1. main_.py +152 -0
main_.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: main.py
2
+ from fastapi import FastAPI, UploadFile, File, HTTPException
3
+ from pydantic import BaseModel
4
+ from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
5
+ from llama_index.llms.huggingface import HuggingFaceInferenceAPI
6
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
7
+ from llama_index.core import Settings
8
+ import os
9
+ from dotenv import load_dotenv
10
+ import shutil
11
+ import uvicorn
12
+ import streamlit as st
13
+ import requests
14
+ import base64
15
+ import docx2txt
16
+ import threading
17
+
18
+ # Load environment variables
19
+ load_dotenv()
20
+
21
+ app = FastAPI()
22
+
23
+ # Configure the Llama index settings
24
+ Settings.llm = HuggingFaceInferenceAPI(
25
+ model_name="meta-llama/Meta-Llama-3-8B-Instruct",
26
+ tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
27
+ context_window=3900,
28
+ token=os.getenv("HF_TOKEN"),
29
+ max_new_tokens=1000,
30
+ generate_kwargs={"temperature": 0.5},
31
+ )
32
+ Settings.embed_model = HuggingFaceEmbedding(
33
+ model_name="BAAI/bge-small-en-v1.5"
34
+ )
35
+
36
+ # Define the directory for persistent storage and data
37
+ PERSIST_DIR = "./db"
38
+ DATA_DIR = "data"
39
+
40
+ # Ensure data directory exists
41
+ os.makedirs(DATA_DIR, exist_ok=True)
42
+ os.makedirs(PERSIST_DIR, exist_ok=True)
43
+
44
+ class Query(BaseModel):
45
+ question: str
46
+
47
+ def data_ingestion():
48
+ documents = SimpleDirectoryReader(DATA_DIR).load_data()
49
+ storage_context = StorageContext.from_defaults()
50
+ index = VectorStoreIndex.from_documents(documents)
51
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
52
+
53
+ def handle_query(query):
54
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
55
+ index = load_index_from_storage(storage_context)
56
+ chat_text_qa_msgs = [
57
+ (
58
+ "user",
59
+ """You are Q&A assistant named CHAT-DOC. Your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.
60
+ Context:
61
+ {context_str}
62
+ Question:
63
+ {query_str}
64
+ """
65
+ )
66
+ ]
67
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
68
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template)
69
+ answer = query_engine.query(query)
70
+
71
+ if hasattr(answer, 'response'):
72
+ return answer.response
73
+ elif isinstance(answer, dict) and 'response' in answer:
74
+ return answer['response']
75
+ else:
76
+ return "Sorry, I couldn't find an answer."
77
+
78
+ @app.post("/upload")
79
+ async def upload_file(file: UploadFile = File(...)):
80
+ file_extension = os.path.splitext(file.filename)[1].lower()
81
+ if file_extension not in [".pdf", ".docx", ".txt"]:
82
+ raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
83
+
84
+ file_path = os.path.join(DATA_DIR, file.filename)
85
+ with open(file_path, "wb") as buffer:
86
+ shutil.copyfileobj(file.file, buffer)
87
+
88
+ data_ingestion()
89
+ return {"message": "File uploaded and processed successfully"}
90
+
91
+ @app.post("/query")
92
+ async def query_document(query: Query):
93
+ if not os.listdir(DATA_DIR):
94
+ raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
95
+
96
+ response = handle_query(query.question)
97
+ return {"response": response}
98
+
99
+ # Streamlit UI
100
+ def streamlit_ui():
101
+ st.title("Chat with your Document πŸ“„")
102
+ st.markdown("Chat hereπŸ‘‡")
103
+
104
+ icons = {"assistant": "πŸ€–", "user": "πŸ‘€"}
105
+
106
+ if 'messages' not in st.session_state:
107
+ st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF, DOCX, or TXT file and ask me anything about its content.'}]
108
+
109
+ for message in st.session_state.messages:
110
+ with st.chat_message(message['role'], avatar=icons[message['role']]):
111
+ st.write(message['content'])
112
+
113
+ with st.sidebar:
114
+ st.title("Menu:")
115
+ uploaded_file = st.file_uploader("Upload your document (PDF, DOCX, TXT)", type=["pdf", "docx", "txt"])
116
+ if st.button("Submit & Process") and uploaded_file:
117
+ with st.spinner("Processing..."):
118
+ files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
119
+ response = requests.post("http://localhost:8000/upload", files=files)
120
+ if response.status_code == 200:
121
+ st.success("File uploaded and processed successfully")
122
+ else:
123
+ st.error("Error uploading file")
124
+
125
+ user_prompt = st.chat_input("Ask me anything about the content of the document:")
126
+
127
+ if user_prompt:
128
+ st.session_state.messages.append({'role': 'user', "content": user_prompt})
129
+ with st.chat_message("user", avatar=icons["user"]):
130
+ st.write(user_prompt)
131
+
132
+ # Trigger assistant's response retrieval and update UI
133
+ with st.spinner("Thinking..."):
134
+ response = requests.post("http://localhost:8000/query", json={"question": user_prompt})
135
+ if response.status_code == 200:
136
+ assistant_response = response.json()["response"]
137
+ with st.chat_message("assistant", avatar=icons["assistant"]):
138
+ st.write(assistant_response)
139
+ st.session_state.messages.append({'role': 'assistant', "content": assistant_response})
140
+ else:
141
+ st.error("Error querying document")
142
+
143
+ def run_fastapi():
144
+ uvicorn.run(app, host="0.0.0.0", port=8000)
145
+
146
+ if __name__ == "__main__":
147
+ # Start FastAPI in a separate thread
148
+ fastapi_thread = threading.Thread(target=run_fastapi)
149
+ fastapi_thread.start()
150
+
151
+ # Run Streamlit (this will run in the main thread)
152
+ streamlit_ui()