northstaranlyticsma24 commited on
Commit
79eb986
1 Parent(s): c56e207

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +11 -0
  2. app.py +153 -0
  3. requirements.txt +132 -0
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+ RUN useradd -m -u 1000 user
3
+ USER user
4
+ ENV HOME=/home/user \
5
+ PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR $HOME/app
7
+ COPY --chown=user . $HOME/app
8
+ COPY ./requirements.txt ~/app/requirements.txt
9
+ RUN pip install -r requirements.txt
10
+ COPY . .
11
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Import Section ###
2
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
3
+ from langchain_community.document_loaders import PyMuPDFLoader
4
+ from qdrant_client import QdrantClient
5
+ from qdrant_client.http.models import Distance, VectorParams
6
+ from langchain_openai.embeddings import OpenAIEmbeddings
7
+ from langchain.storage import LocalFileStore
8
+ from langchain_qdrant import QdrantVectorStore
9
+ from langchain.embeddings import CacheBackedEmbeddings
10
+ from langchain_core.prompts import ChatPromptTemplate
11
+ from langchain_core.globals import set_llm_cache
12
+ from langchain_openai import ChatOpenAI
13
+ from langchain_core.caches import InMemoryCache
14
+ from operator import itemgetter
15
+ from langchain_core.runnables.passthrough import RunnablePassthrough
16
+ import uuid
17
+ import chainlit as cl
18
+
19
+ ### Global Section ###
20
+
21
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
22
+
23
+ Loader = PyMuPDFLoader
24
+
25
+ set_llm_cache(InMemoryCache())
26
+
27
+ # Typical QDrant Client Set-up
28
+ collection_name = f"pdf_to_parse_{uuid.uuid4()}"
29
+ client = QdrantClient(":memory:")
30
+ client.create_collection(
31
+ collection_name=collection_name,
32
+ vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
33
+ )
34
+
35
+ # Typical Embedding Model
36
+ core_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
37
+
38
+ rag_system_prompt_template = """\
39
+ You are a helpful assistant that uses the provided context to answer questions. Never reference this prompt, or the existance of context.
40
+ """
41
+
42
+ rag_message_list = [
43
+ {"role" : "system", "content" : rag_system_prompt_template},
44
+ ]
45
+
46
+ rag_user_prompt_template = """\
47
+ Question:
48
+ {question}
49
+ Context:
50
+ {context}
51
+ """
52
+
53
+ chat_prompt = ChatPromptTemplate.from_messages([
54
+ ("system", rag_system_prompt_template),
55
+ ("human", rag_user_prompt_template)
56
+ ])
57
+
58
+ chat_model = ChatOpenAI(model="gpt-4o-mini")
59
+
60
+ def process_file(file: cl.AskFileResponse):
61
+ import tempfile
62
+
63
+ with tempfile.NamedTemporaryFile(mode="w", delete=False) as temp_file:
64
+ with open(temp_file.name, "wb") as f:
65
+ f.write(file.content)
66
+
67
+ Loader = PyMuPDFLoader
68
+
69
+ loader = Loader(temp_file.name)
70
+ documents = loader.load()
71
+ docs = text_splitter.split_documents(documents)
72
+ for i, doc in enumerate(docs):
73
+ doc.metadata["source"] = f"source_{i}"
74
+ return docs
75
+
76
+
77
+ ### On Chat Start (Session Start) Section ###
78
+ @cl.on_chat_start
79
+ async def on_chat_start():
80
+
81
+ # Adding cache!
82
+ store = LocalFileStore("./cache/")
83
+ cached_embedder = CacheBackedEmbeddings.from_bytes_store(
84
+ core_embeddings, store, namespace=core_embeddings.model
85
+ )
86
+
87
+ # Typical QDrant Vector Store Set-up
88
+ vectorstore = QdrantVectorStore(
89
+ client=client,
90
+ collection_name=collection_name,
91
+ embedding=cached_embedder)
92
+ vectorstore.add_documents(docs)
93
+ retriever = vectorstore.as_retriever(search_type="mmr", search_kwargs={"k": 3})
94
+
95
+ retrieval_augmented_qa_chain = (
96
+ {"context": itemgetter("question") | retriever, "question": itemgetter("question")} ##
97
+ | RunnablePassthrough.assign(context=itemgetter("context"))
98
+ | chat_prompt | chat_model
99
+ )
100
+
101
+ cl.user_session.set("midterm_chain", retrieval_augmented_qa_chain)
102
+
103
+ files = None
104
+
105
+ # Wait for the user to upload a file
106
+ while files == None:
107
+ # Async method: This allows the function to pause execution while waiting for the user to upload a file,
108
+ # without blocking the entire application. It improves responsiveness and scalability.
109
+ files = await cl.AskFileMessage(
110
+ content="Please upload a PDF file to begin!",
111
+ accept=["application/pdf"],
112
+ max_size_mb=20,
113
+ timeout=180,
114
+ ).send()
115
+
116
+ file = files[0]
117
+
118
+ msg = cl.Message(
119
+ content=f"Processing `{file.name}`...",
120
+ )
121
+ await msg.send()
122
+
123
+ # load the file
124
+ docs = process_file(file)
125
+
126
+ ### Rename Chains ###
127
+ @cl.author_rename
128
+ def rename(orig_author: str):
129
+ """ RENAME CODE HERE """
130
+
131
+ ### On Message Section ###
132
+ @cl.on_message
133
+ async def main(message: cl.Message):
134
+ try:
135
+ # Retrieve the chain stored in the session
136
+ midterm_chain = cl.user_session.get("midterm_chain")
137
+
138
+ # Pass the user's message (query) to the chain for processing
139
+ response = await midterm_chain.run(message.content)
140
+
141
+ # Send the response back to the user
142
+ await message.send(response)
143
+ # Process the incoming question using the RAG chain
144
+ #result = retrieval_augmented_qa_chain.invoke({"question": message.content})
145
+
146
+ # Create a new message for the response
147
+ #response_message = cl.Message(content=result["response"].content)
148
+
149
+ except Exception as e:
150
+ # Handle any exception and log it or send a response back to the user
151
+ error_message = cl.Message(content=f"An error occurred: {str(e)}")
152
+ await error_message.send()
153
+ print(f"Error occurred: {e}")
requirements.txt ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ aiohappyeyeballs==2.4.3
3
+ aiohttp==3.10.8
4
+ aiosignal==1.3.1
5
+ annotated-types==0.7.0
6
+ anyio==3.7.1
7
+ async-timeout==4.0.3
8
+ asyncer==0.0.2
9
+ attrs==24.2.0
10
+ bidict==0.23.1
11
+ certifi==2024.8.30
12
+ chainlit==0.7.700
13
+ charset-normalizer==3.3.2
14
+ click==8.1.7
15
+ dataclasses-json==0.5.14
16
+ Deprecated==1.2.14
17
+ distro==1.9.0
18
+ exceptiongroup==1.2.2
19
+ faiss-cpu==1.8.0.post1
20
+ fastapi==0.100.1
21
+ fastapi-socketio==0.0.10
22
+ filelock==3.16.1
23
+ filetype==1.2.0
24
+ frozenlist==1.4.1
25
+ fsspec==2024.9.0
26
+ googleapis-common-protos==1.65.0
27
+ greenlet==3.1.1
28
+ grpcio==1.66.2
29
+ grpcio-tools==1.62.3
30
+ h11==0.14.0
31
+ h2==4.1.0
32
+ hpack==4.0.0
33
+ httpcore==0.17.3
34
+ httpx==0.24.1
35
+ huggingface-hub==0.25.1
36
+ hyperframe==6.0.1
37
+ idna==3.10
38
+ importlib_metadata==8.4.0
39
+ Jinja2==3.1.4
40
+ jiter==0.5.0
41
+ joblib==1.4.2
42
+ jsonpatch==1.33
43
+ jsonpointer==3.0.0
44
+ langchain==0.3.0
45
+ langchain-community==0.3.0
46
+ langchain-core==0.3.1
47
+ langchain-huggingface==0.1.0
48
+ langchain-openai==0.2.0
49
+ langchain-qdrant==0.1.4
50
+ langchain-text-splitters==0.3.0
51
+ langsmith==0.1.121
52
+ Lazify==0.4.0
53
+ MarkupSafe==2.1.5
54
+ marshmallow==3.22.0
55
+ mpmath==1.3.0
56
+ multidict==6.1.0
57
+ mypy-extensions==1.0.0
58
+ nest-asyncio==1.6.0
59
+ networkx==3.2.1
60
+ numpy==1.26.4
61
+ nvidia-cublas-cu12==12.1.3.1
62
+ nvidia-cuda-cupti-cu12==12.1.105
63
+ nvidia-cuda-nvrtc-cu12==12.1.105
64
+ nvidia-cuda-runtime-cu12==12.1.105
65
+ nvidia-cudnn-cu12==9.1.0.70
66
+ nvidia-cufft-cu12==11.0.2.54
67
+ nvidia-curand-cu12==10.3.2.106
68
+ nvidia-cusolver-cu12==11.4.5.107
69
+ nvidia-cusparse-cu12==12.1.0.106
70
+ nvidia-nccl-cu12==2.20.5
71
+ nvidia-nvjitlink-cu12==12.6.77
72
+ nvidia-nvtx-cu12==12.1.105
73
+ openai==1.51.0
74
+ opentelemetry-api==1.27.0
75
+ opentelemetry-exporter-otlp==1.27.0
76
+ opentelemetry-exporter-otlp-proto-common==1.27.0
77
+ opentelemetry-exporter-otlp-proto-grpc==1.27.0
78
+ opentelemetry-exporter-otlp-proto-http==1.27.0
79
+ opentelemetry-instrumentation==0.48b0
80
+ opentelemetry-proto==1.27.0
81
+ opentelemetry-sdk==1.27.0
82
+ opentelemetry-semantic-conventions==0.48b0
83
+ orjson==3.10.7
84
+ packaging==23.2
85
+ pillow==10.4.0
86
+ portalocker==2.10.1
87
+ protobuf==4.25.5
88
+ pydantic==2.9.2
89
+ pydantic-settings==2.5.2
90
+ pydantic_core==2.23.4
91
+ PyJWT==2.9.0
92
+ PyMuPDF==1.24.10
93
+ PyMuPDFb==1.24.10
94
+ python-dotenv==1.0.1
95
+ python-engineio==4.9.1
96
+ python-graphql-client==0.4.3
97
+ python-multipart==0.0.6
98
+ python-socketio==5.11.4
99
+ PyYAML==6.0.2
100
+ qdrant-client==1.11.2
101
+ regex==2024.9.11
102
+ requests==2.32.3
103
+ safetensors==0.4.5
104
+ scikit-learn==1.5.2
105
+ scipy==1.13.1
106
+ sentence-transformers==3.1.1
107
+ simple-websocket==1.0.0
108
+ sniffio==1.3.1
109
+ SQLAlchemy==2.0.35
110
+ starlette==0.27.0
111
+ sympy==1.13.3
112
+ syncer==2.0.3
113
+ tenacity==8.5.0
114
+ threadpoolctl==3.5.0
115
+ tiktoken==0.7.0
116
+ tokenizers==0.20.0
117
+ tomli==2.0.1
118
+ torch==2.4.1
119
+ tqdm==4.66.5
120
+ transformers==4.45.1
121
+ triton==3.0.0
122
+ typing-inspect==0.9.0
123
+ typing_extensions==4.12.2
124
+ uptrace==1.26.0
125
+ urllib3==2.2.3
126
+ uvicorn==0.23.2
127
+ watchfiles==0.20.0
128
+ websockets==13.1
129
+ wrapt==1.16.0
130
+ wsproto==1.2.0
131
+ yarl==1.13.1
132
+ zipp==3.20.2