Spaces:
Sleeping
Sleeping
januarevan
commited on
Commit
•
5481095
0
Parent(s):
init
Browse files- Dockerfile +28 -0
- app.py +118 -0
- milvus_singleton.py +22 -0
- requirements.txt +10 -0
Dockerfile
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.10.8
|
2 |
+
|
3 |
+
WORKDIR /app
|
4 |
+
|
5 |
+
COPY ./requirements.txt /code/requirements.txt
|
6 |
+
|
7 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
8 |
+
|
9 |
+
RUN mkdir -p /app/cache && chmod -R 777 /app/cache
|
10 |
+
RUN mkdir -p /app/milvus_data && chmod -R 777 /app/milvus_data
|
11 |
+
|
12 |
+
|
13 |
+
RUN useradd -m -u 1000 user
|
14 |
+
USER user
|
15 |
+
ENV HOME=/home/user \
|
16 |
+
PATH=/home/user/.local/bin:$PATH
|
17 |
+
ENV HF_HOME=/app/cache
|
18 |
+
ENV HF_MODULES_CACHE=/app/cache/hf_modules
|
19 |
+
ENV MILVUS_DATA_DIR=/app/milvus_data
|
20 |
+
ENV HF_WORKER_COUNT=1
|
21 |
+
|
22 |
+
WORKDIR $HOME/app
|
23 |
+
|
24 |
+
COPY --chown=user . $HOME/app
|
25 |
+
|
26 |
+
COPY . .
|
27 |
+
|
28 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Form, Depends, Request, File, UploadFile
|
2 |
+
from fastapi.encoders import jsonable_encoder
|
3 |
+
from fastapi.responses import JSONResponse
|
4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
5 |
+
import os
|
6 |
+
|
7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
8 |
+
from pymilvus import MilvusClient, db, utility, Collection, CollectionSchema, FieldSchema, DataType
|
9 |
+
from sentence_transformers import SentenceTransformer
|
10 |
+
import torch
|
11 |
+
from .milvus_singleton import MilvusClientSingleton
|
12 |
+
|
13 |
+
|
14 |
+
os.environ['HF_HOME'] = '/app/cache'
|
15 |
+
os.environ['HF_MODULES_CACHE'] = '/app/cache/hf_modules'
|
16 |
+
embedding_model = SentenceTransformer('Alibaba-NLP/gte-large-en-v1.5',
|
17 |
+
trust_remote_code=True,
|
18 |
+
device='cuda' if torch.cuda.is_available() else 'cpu',
|
19 |
+
cache_folder='/app/cache'
|
20 |
+
)
|
21 |
+
collection_name="rag"
|
22 |
+
|
23 |
+
def setup_milvus():
|
24 |
+
global milvus_client
|
25 |
+
milvus_client = MilvusClientSingleton.get_instance(uri="/app/milvus_data/milvus_demo.db")
|
26 |
+
|
27 |
+
def document_to_embeddings(content:str) -> list:
|
28 |
+
return embedding_model.encode(content, show_progress_bar=True)
|
29 |
+
|
30 |
+
setup_milvus()
|
31 |
+
|
32 |
+
app = FastAPI()
|
33 |
+
|
34 |
+
app.add_middleware(
|
35 |
+
CORSMiddleware,
|
36 |
+
allow_origins=["*"], # Replace with the list of allowed origins for production
|
37 |
+
allow_credentials=True,
|
38 |
+
allow_methods=["*"],
|
39 |
+
allow_headers=["*"],
|
40 |
+
)
|
41 |
+
|
42 |
+
def split_documents(document_data):
|
43 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=10)
|
44 |
+
return splitter.split_documents(document_data)
|
45 |
+
|
46 |
+
def create_a_collection(milvus_client, collection_name):
|
47 |
+
content = FieldSchema(name="content", dtype=DataType.VARCHAR, max_length=4096)
|
48 |
+
vector = FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=1024)
|
49 |
+
|
50 |
+
schema = CollectionSchema([
|
51 |
+
content, vector
|
52 |
+
])
|
53 |
+
|
54 |
+
vector_index = {
|
55 |
+
"index_type": "IVF_FLAT",
|
56 |
+
"metric_type": "COSINE",
|
57 |
+
"params": {
|
58 |
+
"nlist": 128
|
59 |
+
}
|
60 |
+
}
|
61 |
+
|
62 |
+
milvus_client.create_collection(
|
63 |
+
collection_name=collection_name,
|
64 |
+
schema=schema,
|
65 |
+
index_params=vector_index,
|
66 |
+
)
|
67 |
+
|
68 |
+
@app.get("/")
|
69 |
+
async def root():
|
70 |
+
return {"message": "Hello World"}
|
71 |
+
|
72 |
+
@app.post("/insert")
|
73 |
+
async def insert(file: UploadFile = File(...)):
|
74 |
+
contents = await file.read()
|
75 |
+
|
76 |
+
if not milvus_client.has_collection(collection_name):
|
77 |
+
create_a_collection(milvus_client, collection_name)
|
78 |
+
|
79 |
+
splitted_document_data = split_documents(contents)
|
80 |
+
|
81 |
+
data_objects = []
|
82 |
+
for doc in splitted_document_data:
|
83 |
+
data = {
|
84 |
+
"vector": document_to_embeddings(doc.page_content),
|
85 |
+
"content": doc.page_content,
|
86 |
+
}
|
87 |
+
data_objects.append(data)
|
88 |
+
|
89 |
+
try:
|
90 |
+
milvus_client.insert(collection_name=collection_name, data=data_objects)
|
91 |
+
|
92 |
+
except Exception as e:
|
93 |
+
raise JSONResponse(status_code=500, content={"error": str(e)})
|
94 |
+
else:
|
95 |
+
return JSONResponse(status_code=200, content={"result": 'good'})
|
96 |
+
|
97 |
+
@app.post("/rag")
|
98 |
+
async def insert(question):
|
99 |
+
if not question:
|
100 |
+
return JSONResponse(status_code=400, content={"message": "Please a question!"})
|
101 |
+
|
102 |
+
try:
|
103 |
+
search_res = milvus_client.search(
|
104 |
+
collection_name=collection_name,
|
105 |
+
data=[
|
106 |
+
document_to_embeddings(question)
|
107 |
+
],
|
108 |
+
limit=5, # Return top 3 results
|
109 |
+
search_params={"metric_type": "COSINE"}, # Inner product distance
|
110 |
+
output_fields=["content"], # Return the text field
|
111 |
+
)
|
112 |
+
|
113 |
+
retrieved_lines_with_distances = [
|
114 |
+
(res["entity"]["content"]) for res in search_res[0]
|
115 |
+
]
|
116 |
+
return JSONResponse(status_code=200, content={"result": retrieved_lines_with_distances[0]})
|
117 |
+
except Exception as e:
|
118 |
+
return JSONResponse(status_code=400, content={"error": str(e)})
|
milvus_singleton.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pymilvus import connections
|
2 |
+
from pymilvus.exceptions import ConnectionConfigException
|
3 |
+
|
4 |
+
class MilvusClientSingleton:
|
5 |
+
_instance = None
|
6 |
+
|
7 |
+
@staticmethod
|
8 |
+
def get_instance(uri):
|
9 |
+
if MilvusClientSingleton._instance is None:
|
10 |
+
MilvusClientSingleton()
|
11 |
+
# Initialize the client here
|
12 |
+
try:
|
13 |
+
MilvusClientSingleton._instance = connections.connect(uri=uri)
|
14 |
+
except ConnectionConfigException as e:
|
15 |
+
print(f"Error connecting to Milvus: {e}")
|
16 |
+
# Handle error appropriately
|
17 |
+
return MilvusClientSingleton._instance
|
18 |
+
|
19 |
+
def __init__(self):
|
20 |
+
if MilvusClientSingleton._instance is not None:
|
21 |
+
raise Exception("This class is a singleton!")
|
22 |
+
self._instance = None
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pymilvus==2.4.5
|
2 |
+
sentence-transformers==3.0.1
|
3 |
+
huggingface-hub==0.24.5
|
4 |
+
langchain_community==0.2.12
|
5 |
+
langchain-text-splitters==0.2.2
|
6 |
+
langchain==0.2.14
|
7 |
+
pypdf==4.3.1
|
8 |
+
tqdm==4.66.5
|
9 |
+
flask
|
10 |
+
flask_cors
|