Update huggingface_space.py
Browse files- huggingface_space.py +158 -158
huggingface_space.py
CHANGED
|
@@ -1,159 +1,159 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
import shutil
|
| 4 |
-
import uvicorn
|
| 5 |
-
import streamlit as st
|
| 6 |
-
import requests
|
| 7 |
-
import threading
|
| 8 |
-
|
| 9 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 10 |
-
from pydantic import BaseModel, ConfigDict
|
| 11 |
-
|
| 12 |
-
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
| 13 |
-
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
|
| 14 |
-
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 15 |
-
from llama_index.core import Settings
|
| 16 |
-
|
| 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 |
-
class DeployedModel(BaseModel):
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def data_ingestion():
|
| 55 |
-
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
| 56 |
-
storage_context = StorageContext.from_defaults()
|
| 57 |
-
index = VectorStoreIndex.from_documents(documents)
|
| 58 |
-
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
| 59 |
-
|
| 60 |
-
def handle_query(query):
|
| 61 |
-
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 62 |
-
index = load_index_from_storage(storage_context)
|
| 63 |
-
chat_text_qa_msgs = [
|
| 64 |
-
(
|
| 65 |
-
"user",
|
| 66 |
-
"""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.
|
| 67 |
-
Context:
|
| 68 |
-
{context_str}
|
| 69 |
-
Question:
|
| 70 |
-
{query_str}
|
| 71 |
-
"""
|
| 72 |
-
)
|
| 73 |
-
]
|
| 74 |
-
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 75 |
-
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
| 76 |
-
answer = query_engine.query(query)
|
| 77 |
-
|
| 78 |
-
if hasattr(answer, 'response'):
|
| 79 |
-
return answer.response
|
| 80 |
-
elif isinstance(answer, dict) and 'response' in answer:
|
| 81 |
-
return answer['response']
|
| 82 |
-
else:
|
| 83 |
-
return "Sorry, I couldn't find an answer."
|
| 84 |
-
|
| 85 |
-
@app.post("/upload")
|
| 86 |
-
async def upload_file(file: UploadFile = File(...)):
|
| 87 |
-
file_extension = os.path.splitext(file.filename)[1].lower()
|
| 88 |
-
if file_extension not in [".pdf", ".docx", ".txt"]:
|
| 89 |
-
raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
|
| 90 |
-
|
| 91 |
-
file_path = os.path.join(DATA_DIR, file.filename)
|
| 92 |
-
with open(file_path, "wb") as buffer:
|
| 93 |
-
shutil.copyfileobj(file.file, buffer)
|
| 94 |
-
|
| 95 |
-
data_ingestion()
|
| 96 |
-
return {"message": "File uploaded and processed successfully"}
|
| 97 |
-
|
| 98 |
-
@app.post("/query")
|
| 99 |
-
async def query_document(query: Query):
|
| 100 |
-
if not os.listdir(DATA_DIR):
|
| 101 |
-
raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
|
| 102 |
-
|
| 103 |
-
response = handle_query(query.question)
|
| 104 |
-
return {"response": response}
|
| 105 |
-
|
| 106 |
-
# Streamlit UI
|
| 107 |
-
def streamlit_ui():
|
| 108 |
-
st.title("Chat with your Document 📄")
|
| 109 |
-
st.markdown("Chat here👇")
|
| 110 |
-
|
| 111 |
-
icons = {"assistant": "🤖", "user": "👤"}
|
| 112 |
-
|
| 113 |
-
if 'messages' not in st.session_state:
|
| 114 |
-
st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF, DOCX, or TXT file and ask me anything about its content.'}]
|
| 115 |
-
|
| 116 |
-
for message in st.session_state.messages:
|
| 117 |
-
with st.chat_message(message['role'], avatar=icons[message['role']]):
|
| 118 |
-
st.write(message['content'])
|
| 119 |
-
|
| 120 |
-
with st.sidebar:
|
| 121 |
-
st.title("Menu:")
|
| 122 |
-
uploaded_file = st.file_uploader("Upload your document (PDF, DOCX, TXT)", type=["pdf", "docx", "txt"])
|
| 123 |
-
if st.button("Submit & Process") and uploaded_file:
|
| 124 |
-
with st.spinner("Processing..."):
|
| 125 |
-
files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
|
| 126 |
-
response = requests.post("http://localhost:8000/upload", files=files)
|
| 127 |
-
if response.status_code == 200:
|
| 128 |
-
st.success("File uploaded and processed successfully")
|
| 129 |
-
else:
|
| 130 |
-
st.error("Error uploading file")
|
| 131 |
-
|
| 132 |
-
user_prompt = st.chat_input("Ask me anything about the content of the document:")
|
| 133 |
-
|
| 134 |
-
if user_prompt:
|
| 135 |
-
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
| 136 |
-
with st.chat_message("user", avatar=icons["user"]):
|
| 137 |
-
st.write(user_prompt)
|
| 138 |
-
|
| 139 |
-
# Trigger assistant's response retrieval and update UI
|
| 140 |
-
with st.spinner("Thinking..."):
|
| 141 |
-
response = requests.post("http://localhost:8000/query", json={"question": user_prompt})
|
| 142 |
-
if response.status_code == 200:
|
| 143 |
-
assistant_response = response.json()["response"]
|
| 144 |
-
with st.chat_message("assistant", avatar=icons["assistant"]):
|
| 145 |
-
st.write(assistant_response)
|
| 146 |
-
st.session_state.messages.append({'role': 'assistant', "content": assistant_response})
|
| 147 |
-
else:
|
| 148 |
-
st.error("Error querying document")
|
| 149 |
-
|
| 150 |
-
def run_fastapi():
|
| 151 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 152 |
-
|
| 153 |
-
if __name__ == "__main__":
|
| 154 |
-
# Start FastAPI in a separate thread
|
| 155 |
-
fastapi_thread = threading.Thread(target=run_fastapi)
|
| 156 |
-
fastapi_thread.start()
|
| 157 |
-
|
| 158 |
-
# Run Streamlit (this will run in the main thread)
|
| 159 |
streamlit_ui()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
import shutil
|
| 4 |
+
import uvicorn
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import requests
|
| 7 |
+
import threading
|
| 8 |
+
|
| 9 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 10 |
+
from pydantic import BaseModel, ConfigDict
|
| 11 |
+
|
| 12 |
+
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
| 13 |
+
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
|
| 14 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 15 |
+
from llama_index.core import Settings
|
| 16 |
+
|
| 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 |
+
# class DeployedModel(BaseModel):
|
| 48 |
+
# model_id: str
|
| 49 |
+
# model_name: str
|
| 50 |
+
|
| 51 |
+
# class Config:
|
| 52 |
+
# model_config = ConfigDict(protected_namespaces=())
|
| 53 |
+
|
| 54 |
+
def data_ingestion():
|
| 55 |
+
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
| 56 |
+
storage_context = StorageContext.from_defaults()
|
| 57 |
+
index = VectorStoreIndex.from_documents(documents)
|
| 58 |
+
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
| 59 |
+
|
| 60 |
+
def handle_query(query):
|
| 61 |
+
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 62 |
+
index = load_index_from_storage(storage_context)
|
| 63 |
+
chat_text_qa_msgs = [
|
| 64 |
+
(
|
| 65 |
+
"user",
|
| 66 |
+
"""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.
|
| 67 |
+
Context:
|
| 68 |
+
{context_str}
|
| 69 |
+
Question:
|
| 70 |
+
{query_str}
|
| 71 |
+
"""
|
| 72 |
+
)
|
| 73 |
+
]
|
| 74 |
+
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 75 |
+
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
| 76 |
+
answer = query_engine.query(query)
|
| 77 |
+
|
| 78 |
+
if hasattr(answer, 'response'):
|
| 79 |
+
return answer.response
|
| 80 |
+
elif isinstance(answer, dict) and 'response' in answer:
|
| 81 |
+
return answer['response']
|
| 82 |
+
else:
|
| 83 |
+
return "Sorry, I couldn't find an answer."
|
| 84 |
+
|
| 85 |
+
@app.post("/upload")
|
| 86 |
+
async def upload_file(file: UploadFile = File(...)):
|
| 87 |
+
file_extension = os.path.splitext(file.filename)[1].lower()
|
| 88 |
+
if file_extension not in [".pdf", ".docx", ".txt"]:
|
| 89 |
+
raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
|
| 90 |
+
|
| 91 |
+
file_path = os.path.join(DATA_DIR, file.filename)
|
| 92 |
+
with open(file_path, "wb") as buffer:
|
| 93 |
+
shutil.copyfileobj(file.file, buffer)
|
| 94 |
+
|
| 95 |
+
data_ingestion()
|
| 96 |
+
return {"message": "File uploaded and processed successfully"}
|
| 97 |
+
|
| 98 |
+
@app.post("/query")
|
| 99 |
+
async def query_document(query: Query):
|
| 100 |
+
if not os.listdir(DATA_DIR):
|
| 101 |
+
raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
|
| 102 |
+
|
| 103 |
+
response = handle_query(query.question)
|
| 104 |
+
return {"response": response}
|
| 105 |
+
|
| 106 |
+
# Streamlit UI
|
| 107 |
+
def streamlit_ui():
|
| 108 |
+
st.title("Chat with your Document 📄")
|
| 109 |
+
st.markdown("Chat here👇")
|
| 110 |
+
|
| 111 |
+
icons = {"assistant": "🤖", "user": "👤"}
|
| 112 |
+
|
| 113 |
+
if 'messages' not in st.session_state:
|
| 114 |
+
st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF, DOCX, or TXT file and ask me anything about its content.'}]
|
| 115 |
+
|
| 116 |
+
for message in st.session_state.messages:
|
| 117 |
+
with st.chat_message(message['role'], avatar=icons[message['role']]):
|
| 118 |
+
st.write(message['content'])
|
| 119 |
+
|
| 120 |
+
with st.sidebar:
|
| 121 |
+
st.title("Menu:")
|
| 122 |
+
uploaded_file = st.file_uploader("Upload your document (PDF, DOCX, TXT)", type=["pdf", "docx", "txt"])
|
| 123 |
+
if st.button("Submit & Process") and uploaded_file:
|
| 124 |
+
with st.spinner("Processing..."):
|
| 125 |
+
files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
|
| 126 |
+
response = requests.post("http://localhost:8000/upload", files=files)
|
| 127 |
+
if response.status_code == 200:
|
| 128 |
+
st.success("File uploaded and processed successfully")
|
| 129 |
+
else:
|
| 130 |
+
st.error("Error uploading file")
|
| 131 |
+
|
| 132 |
+
user_prompt = st.chat_input("Ask me anything about the content of the document:")
|
| 133 |
+
|
| 134 |
+
if user_prompt:
|
| 135 |
+
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
| 136 |
+
with st.chat_message("user", avatar=icons["user"]):
|
| 137 |
+
st.write(user_prompt)
|
| 138 |
+
|
| 139 |
+
# Trigger assistant's response retrieval and update UI
|
| 140 |
+
with st.spinner("Thinking..."):
|
| 141 |
+
response = requests.post("http://localhost:8000/query", json={"question": user_prompt})
|
| 142 |
+
if response.status_code == 200:
|
| 143 |
+
assistant_response = response.json()["response"]
|
| 144 |
+
with st.chat_message("assistant", avatar=icons["assistant"]):
|
| 145 |
+
st.write(assistant_response)
|
| 146 |
+
st.session_state.messages.append({'role': 'assistant', "content": assistant_response})
|
| 147 |
+
else:
|
| 148 |
+
st.error("Error querying document")
|
| 149 |
+
|
| 150 |
+
def run_fastapi():
|
| 151 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
# Start FastAPI in a separate thread
|
| 155 |
+
fastapi_thread = threading.Thread(target=run_fastapi)
|
| 156 |
+
fastapi_thread.start()
|
| 157 |
+
|
| 158 |
+
# Run Streamlit (this will run in the main thread)
|
| 159 |
streamlit_ui()
|