pratham0011 commited on
Commit
6bdb281
β€’
1 Parent(s): d72b836

Upload 10 files

Browse files
Files changed (6) hide show
  1. Dockerfile +37 -37
  2. __init__.py +0 -0
  3. app/app.py +5 -3
  4. huggingface_space.py +159 -0
  5. main.py +47 -46
  6. requirements.txt +1 -1
Dockerfile CHANGED
@@ -1,38 +1,38 @@
1
- # ... existing Dockerfile content ...
2
-
3
- # Use an official Python runtime as a parent image
4
- FROM python:3.12
5
-
6
- # Set the working directory in the container
7
- WORKDIR /app
8
-
9
- # Copy the current directory contents into the container at /app
10
- COPY . /app
11
-
12
- # Install system dependencies
13
- RUN apt-get update && apt-get install -y \
14
- build-essential \
15
- curl \
16
- software-properties-common \
17
- && rm -rf /var/lib/apt/lists/*
18
-
19
- # Install Python dependencies
20
- RUN pip install --no-cache-dir -r requirements.txt
21
-
22
- # Create the data and db directories with appropriate permissions
23
- RUN mkdir -p data db && chmod 777 data db
24
-
25
- # Make port 8000 available for FastAPI and port 7860 for Streamlit
26
- EXPOSE 7860
27
- EXPOSE 8000
28
-
29
- # Create a script to run both FastAPI and Streamlit
30
- RUN echo '#!/bin/bash\n\
31
- uvicorn main:app --host 0.0.0.0 --port 8000 &\n\
32
- streamlit run streamlit_app.py --server.port 7860 --server.address 0.0.0.0 --server.enableCORS false\n\
33
- ' > /app/run.sh
34
-
35
- RUN chmod +x /app/run.sh
36
-
37
- # Run the script when the container launches
38
  CMD ["/app/run.sh"]
 
1
+ # ... existing Dockerfile content ...
2
+
3
+ # Use an official Python runtime as a parent image
4
+ FROM python:3.12
5
+
6
+ # Set the working directory in the container
7
+ WORKDIR /app
8
+
9
+ # Copy the current directory contents into the container at /app
10
+ COPY . /app
11
+
12
+ # Install system dependencies
13
+ RUN apt-get update && apt-get install -y \
14
+ build-essential \
15
+ curl \
16
+ software-properties-common \
17
+ && rm -rf /var/lib/apt/lists/*
18
+
19
+ # Install Python dependencies
20
+ RUN pip install --no-cache-dir -r requirements.txt
21
+
22
+ # Create the data and db directories with appropriate permissions
23
+ RUN mkdir -p data db && chmod 777 data db
24
+
25
+ # Make port 8000 available for FastAPI and port 7860 for Streamlit
26
+ EXPOSE 8000
27
+ EXPOSE 7860
28
+
29
+ # Create a script to run both FastAPI and Streamlit
30
+ RUN echo '#!/bin/bash\n\
31
+ uvicorn main:app --host 0.0.0.0 --port 8000 &\n\
32
+ streamlit run streamlit_app.py --server.port 7860 --server.address 0.0.0.0 --server.enableCORS false\n\
33
+ ' > /app/run.sh
34
+
35
+ RUN chmod +x /app/run.sh
36
+
37
+ # Run the script when the container launches
38
  CMD ["/app/run.sh"]
__init__.py ADDED
File without changes
app/app.py CHANGED
@@ -1,9 +1,11 @@
 
 
 
1
  from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
2
- from llama_index.llms.huggingface import HuggingFaceInferenceAPI
3
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
4
  from llama_index.core import Settings
5
- import os
6
- from dotenv import load_dotenv
7
 
8
  # Load environment variables
9
  load_dotenv()
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
  from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
5
+ from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
6
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
7
  from llama_index.core import Settings
8
+
 
9
 
10
  # Load environment variables
11
  load_dotenv()
huggingface_space.py ADDED
@@ -0,0 +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
+ 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()
main.py CHANGED
@@ -1,47 +1,48 @@
1
- import os
2
- import shutil
3
- import uvicorn
4
-
5
- from pydantic import BaseModel
6
- from fastapi import FastAPI, File, UploadFile, HTTPException
7
- from fastapi.middleware.cors import CORSMiddleware
8
-
9
- from app.app import data_ingestion, handle_query, DATA_DIR
10
-
11
- class Query(BaseModel):
12
- question: str
13
-
14
- app = FastAPI()
15
-
16
- app.add_middleware(
17
- CORSMiddleware,
18
- allow_origins=["*"], # Adjust this to your needs
19
- allow_credentials=True,
20
- allow_methods=["*"],
21
- allow_headers=["*"],
22
- )
23
-
24
- @app.post("/upload")
25
- async def upload_file(file: UploadFile = File(...)):
26
- print(f"Received file: {file.filename}")
27
- file_extension = os.path.splitext(file.filename)[1].lower()
28
- if file_extension not in [".pdf", ".docx", ".txt"]:
29
- raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
30
-
31
- file_path = os.path.join(DATA_DIR, file.filename)
32
- with open(file_path, "wb") as buffer:
33
- shutil.copyfileobj(file.file, buffer)
34
-
35
- data_ingestion()
36
- return {"message": "File uploaded and processed successfully"}
37
-
38
- @app.post("/query")
39
- async def query_document(query: Query):
40
- if not os.listdir(DATA_DIR):
41
- raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
42
-
43
- response = handle_query(query.question)
44
- return {"response": response}
45
-
46
- if __name__ == "__main__":
 
47
  uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ import os
2
+ import shutil
3
+ import uvicorn
4
+
5
+ from pydantic import BaseModel
6
+ from fastapi import FastAPI, File, UploadFile, HTTPException
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+
9
+ from app.app import data_ingestion, handle_query, DATA_DIR
10
+
11
+
12
+ class Query(BaseModel):
13
+ question: str
14
+
15
+ app = FastAPI()
16
+
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=["*"], # Change this to your frontend's URL in production
20
+ allow_credentials=True,
21
+ allow_methods=["*"],
22
+ allow_headers=["*"],
23
+ )
24
+
25
+ @app.post("/upload")
26
+ async def upload_file(file: UploadFile = File(...)):
27
+ print(f"Received file: {file.filename}") # Log the filename
28
+ file_extension = os.path.splitext(file.filename)[1].lower()
29
+ if file_extension not in [".pdf", ".docx", ".txt"]:
30
+ raise HTTPException(status_code=400, detail="Invalid file type. Only PDF, DOCX, and TXT are allowed.")
31
+
32
+ file_path = os.path.join(DATA_DIR, file.filename)
33
+ with open(file_path, "wb") as buffer:
34
+ shutil.copyfileobj(file.file, buffer)
35
+
36
+ data_ingestion()
37
+ return {"message": "File uploaded and processed successfully"}
38
+
39
+ @app.post("/query")
40
+ async def query_document(query: Query):
41
+ if not os.listdir(DATA_DIR):
42
+ raise HTTPException(status_code=400, detail="No document has been uploaded yet.")
43
+
44
+ response = handle_query(query.question)
45
+ return {"response": response}
46
+
47
+ if __name__ == "__main__":
48
  uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt CHANGED
@@ -2,10 +2,10 @@ streamlit
2
  python-dotenv
3
  llama-index
4
  llama-index-embeddings-huggingface
5
- llama-index-llms-huggingface
6
  gradio==3.50
7
  docx2txt
8
  tf-keras
9
  fastapi
10
  pydantic
11
  uvicorn
 
 
2
  python-dotenv
3
  llama-index
4
  llama-index-embeddings-huggingface
 
5
  gradio==3.50
6
  docx2txt
7
  tf-keras
8
  fastapi
9
  pydantic
10
  uvicorn
11
+ llama_index.llms.huggingface_api