Spaces:
Build error
Build error
index.py
Browse files
index.py
DELETED
|
@@ -1,94 +0,0 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
| 4 |
-
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
| 5 |
-
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 6 |
-
from llama_index.core import Settings
|
| 7 |
-
import os
|
| 8 |
-
from dotenv import load_dotenv
|
| 9 |
-
import shutil
|
| 10 |
-
|
| 11 |
-
# Load environment variables
|
| 12 |
-
load_dotenv()
|
| 13 |
-
|
| 14 |
-
app = FastAPI()
|
| 15 |
-
|
| 16 |
-
# Configure the Llama index settings
|
| 17 |
-
Settings.llm = HuggingFaceInferenceAPI(
|
| 18 |
-
model_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 19 |
-
tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 20 |
-
context_window=3900,
|
| 21 |
-
token=os.getenv("HF_TOKEN"),
|
| 22 |
-
max_new_tokens=1000,
|
| 23 |
-
generate_kwargs={"temperature": 0.5},
|
| 24 |
-
)
|
| 25 |
-
Settings.embed_model = HuggingFaceEmbedding(
|
| 26 |
-
model_name="BAAI/bge-small-en-v1.5"
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
# Define the directory for persistent storage and data
|
| 30 |
-
PERSIST_DIR = "./db"
|
| 31 |
-
DATA_DIR = "data"
|
| 32 |
-
|
| 33 |
-
# Ensure data directory exists
|
| 34 |
-
os.makedirs(DATA_DIR, exist_ok=True)
|
| 35 |
-
os.makedirs(PERSIST_DIR, exist_ok=True)
|
| 36 |
-
|
| 37 |
-
class Query(BaseModel):
|
| 38 |
-
question: str
|
| 39 |
-
|
| 40 |
-
def data_ingestion():
|
| 41 |
-
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
| 42 |
-
storage_context = StorageContext.from_defaults()
|
| 43 |
-
index = VectorStoreIndex.from_documents(documents)
|
| 44 |
-
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
| 45 |
-
|
| 46 |
-
def handle_query(query):
|
| 47 |
-
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 48 |
-
index = load_index_from_storage(storage_context)
|
| 49 |
-
chat_text_qa_msgs = [
|
| 50 |
-
(
|
| 51 |
-
"user",
|
| 52 |
-
"""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.
|
| 53 |
-
Context:
|
| 54 |
-
{context_str}
|
| 55 |
-
Question:
|
| 56 |
-
{query_str}
|
| 57 |
-
"""
|
| 58 |
-
)
|
| 59 |
-
]
|
| 60 |
-
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 61 |
-
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
| 62 |
-
answer = query_engine.query(query)
|
| 63 |
-
|
| 64 |
-
if hasattr(answer, 'response'):
|
| 65 |
-
return answer.response
|
| 66 |
-
elif isinstance(answer, dict) and 'response' in answer:
|
| 67 |
-
return answer['response']
|
| 68 |
-
else:
|
| 69 |
-
return "Sorry, I couldn't find an answer."
|
| 70 |
-
|
| 71 |
-
@app.post("/upload")
|
| 72 |
-
async def upload_file(file: UploadFile = File(...)):
|
| 73 |
-
file_extension = os.path.splitext(file.filename)[1].lower()
|
| 74 |
-
if file_extension not in [".pdf", ".docx", ".txt"]:
|
| 75 |
-
raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
|
| 76 |
-
|
| 77 |
-
file_path = os.path.join(DATA_DIR, file.filename)
|
| 78 |
-
with open(file_path, "wb") as buffer:
|
| 79 |
-
shutil.copyfileobj(file.file, buffer)
|
| 80 |
-
|
| 81 |
-
data_ingestion()
|
| 82 |
-
return {"message": "File uploaded and processed successfully"}
|
| 83 |
-
|
| 84 |
-
@app.post("/query")
|
| 85 |
-
async def query_document(query: Query):
|
| 86 |
-
if not os.listdir(DATA_DIR):
|
| 87 |
-
raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
|
| 88 |
-
|
| 89 |
-
response = handle_query(query.question)
|
| 90 |
-
return {"response": response}
|
| 91 |
-
|
| 92 |
-
if __name__ == "__main__":
|
| 93 |
-
import uvicorn
|
| 94 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|