Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,178 +1,186 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException, Depends, File, UploadFile
|
| 2 |
-
from typing import List
|
| 3 |
-
from fastapi.responses import FileResponse
|
| 4 |
-
import urllib
|
| 5 |
-
from embeddings import EmbeddingManager
|
| 6 |
-
from model import (
|
| 7 |
-
AddFilesRequest,
|
| 8 |
-
CreateVectorStoreRequest,
|
| 9 |
-
DeleteVectorStoreRequest,
|
| 10 |
-
DownloadVectorStoreRequest,
|
| 11 |
-
ListSourcesRequest,
|
| 12 |
-
SaveTempRequest,
|
| 13 |
-
SearchSimilarityRequest,
|
| 14 |
-
)
|
| 15 |
-
from vector_db import VectorStoreManager
|
| 16 |
-
import os
|
| 17 |
-
import shutil
|
| 18 |
-
from starlette.responses import RedirectResponse
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
)
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Depends, File, UploadFile
|
| 2 |
+
from typing import List
|
| 3 |
+
from fastapi.responses import FileResponse
|
| 4 |
+
import urllib
|
| 5 |
+
from embeddings import EmbeddingManager
|
| 6 |
+
from model import (
|
| 7 |
+
AddFilesRequest,
|
| 8 |
+
CreateVectorStoreRequest,
|
| 9 |
+
DeleteVectorStoreRequest,
|
| 10 |
+
DownloadVectorStoreRequest,
|
| 11 |
+
ListSourcesRequest,
|
| 12 |
+
SaveTempRequest,
|
| 13 |
+
SearchSimilarityRequest,
|
| 14 |
+
)
|
| 15 |
+
from vector_db import VectorStoreManager
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
from starlette.responses import RedirectResponse
|
| 19 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
+
|
| 21 |
+
app = FastAPI()
|
| 22 |
+
app.add_middleware(
|
| 23 |
+
CORSMiddleware,
|
| 24 |
+
allow_origins=["*"], # Puedes poner una lista espec铆fica de dominios si lo prefieres
|
| 25 |
+
allow_credentials=True,
|
| 26 |
+
allow_methods=["*"], # Permite todos los m茅todos (GET, POST, PUT, DELETE, etc.)
|
| 27 |
+
allow_headers=["*"], # Permite todos los encabezados
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@app.get("/", include_in_schema=False)
|
| 32 |
+
async def redirect_to_docs():
|
| 33 |
+
return RedirectResponse(url="/docs")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Crear una sola instancia de EmbeddingManager
|
| 37 |
+
embedding_manager = EmbeddingManager()
|
| 38 |
+
embeddings = embedding_manager.get_embeddings
|
| 39 |
+
path_docs = "docs" # Directorio temporal para almacenar los archivos subidos
|
| 40 |
+
path_db = "database" # Directorio para almacenar el vectorstore
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@app.post("/vectorstore/create", tags=["VectorStore"])
|
| 44 |
+
async def create_vectorstore(
|
| 45 |
+
create_request: CreateVectorStoreRequest = Depends(), # Usar el modelo como dependencia
|
| 46 |
+
files: List[UploadFile] = File(...),
|
| 47 |
+
):
|
| 48 |
+
"""Create a vectorstore from the uploaded documents."""
|
| 49 |
+
try:
|
| 50 |
+
if os.path.exists(path_docs):
|
| 51 |
+
shutil.rmtree(path_docs)
|
| 52 |
+
os.makedirs(path_docs)
|
| 53 |
+
for file in files:
|
| 54 |
+
file_path = os.path.join(path_docs, file.filename)
|
| 55 |
+
with open(file_path, "wb") as f:
|
| 56 |
+
f.write(await file.read())
|
| 57 |
+
manager = VectorStoreManager(
|
| 58 |
+
path=path_docs, name=create_request.name, embeddings=embeddings
|
| 59 |
+
)
|
| 60 |
+
if manager.create_vectorstore():
|
| 61 |
+
shutil.rmtree(path_docs)
|
| 62 |
+
return {"message": "Vectorstore created successfully."}
|
| 63 |
+
shutil.rmtree(path_docs)
|
| 64 |
+
return {"message": "Failed to create vectorstore."}
|
| 65 |
+
except Exception as e:
|
| 66 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@app.get("/vectorstore/search", tags=["Similarity Search"])
|
| 70 |
+
async def search_similarity(search_request: SearchSimilarityRequest = Depends()):
|
| 71 |
+
"""Search for similar documents in the vectorstore."""
|
| 72 |
+
try:
|
| 73 |
+
manager = VectorStoreManager(
|
| 74 |
+
path=path_db,
|
| 75 |
+
name=search_request.name_database,
|
| 76 |
+
embeddings=embeddings,
|
| 77 |
+
)
|
| 78 |
+
search_request.query = str(urllib.parse.unquote(search_request.query))
|
| 79 |
+
result = manager.search_similarity(
|
| 80 |
+
query=search_request.query, fuente=search_request.fuente
|
| 81 |
+
)
|
| 82 |
+
return {"results": result}
|
| 83 |
+
except Exception as e:
|
| 84 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@app.get("/vectorstore/sources", tags=["Sources"])
|
| 88 |
+
async def list_sources(list_request: ListSourcesRequest = Depends()):
|
| 89 |
+
try:
|
| 90 |
+
manager = VectorStoreManager(
|
| 91 |
+
path=path_db, name=list_request.nombre_db_vectorial, embeddings=embeddings
|
| 92 |
+
)
|
| 93 |
+
sources = manager.list_sources()
|
| 94 |
+
return {"sources": sources}
|
| 95 |
+
except Exception as e:
|
| 96 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@app.post("/vectorstore/save_temp", tags=["Save Temp"])
|
| 100 |
+
async def save_text_to_file_temp(save_temp: SaveTempRequest = Depends()):
|
| 101 |
+
"""Descripci贸n: Guarda en un archivo temporal el texto de una fuente espec铆fica."""
|
| 102 |
+
try:
|
| 103 |
+
manager = VectorStoreManager(
|
| 104 |
+
path=path_db, name=save_temp.nombre_db_vectorial, embeddings=embeddings
|
| 105 |
+
)
|
| 106 |
+
saved = manager.save_text_to_file_temp(source=save_temp.fuente)
|
| 107 |
+
if saved:
|
| 108 |
+
return {"message": "Text saved to file successfully."}
|
| 109 |
+
else:
|
| 110 |
+
return {"message": "No text found to save."}
|
| 111 |
+
except Exception as e:
|
| 112 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@app.post("/vectorstore/add_files", tags=["Add Files"])
|
| 116 |
+
async def add_files_vectorstore(
|
| 117 |
+
add_files_request: AddFilesRequest = Depends(), files: List[UploadFile] = File(...)
|
| 118 |
+
):
|
| 119 |
+
try:
|
| 120 |
+
if os.path.exists(path_docs):
|
| 121 |
+
shutil.rmtree(path_docs)
|
| 122 |
+
os.makedirs(path_docs)
|
| 123 |
+
|
| 124 |
+
for file in files:
|
| 125 |
+
file_path = os.path.join(path_docs, file.filename)
|
| 126 |
+
with open(file_path, "wb") as f:
|
| 127 |
+
f.write(await file.read())
|
| 128 |
+
manager = VectorStoreManager(
|
| 129 |
+
path=path_docs,
|
| 130 |
+
name=add_files_request.nombre_db_vectorial,
|
| 131 |
+
embeddings=embeddings,
|
| 132 |
+
)
|
| 133 |
+
if manager.add_files_vectorstore():
|
| 134 |
+
shutil.rmtree(path_docs)
|
| 135 |
+
return {"message": "Files added to vectorstore successfully."}
|
| 136 |
+
shutil.rmtree(path_docs)
|
| 137 |
+
return {"message": "Failed to add files to vectorstore."}
|
| 138 |
+
except Exception as e:
|
| 139 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@app.delete("/vectorstore/delete", tags=["Delete VectorStore"])
|
| 143 |
+
async def delete_vectorstore(delete_request: DeleteVectorStoreRequest = Depends()):
|
| 144 |
+
"""Delete the vectorstore and its data."""
|
| 145 |
+
try:
|
| 146 |
+
manager = VectorStoreManager(
|
| 147 |
+
path=path_db, name=delete_request.nombre_db_vectorial, embeddings=embeddings
|
| 148 |
+
)
|
| 149 |
+
if manager.delete_vectorstore():
|
| 150 |
+
return {"message": "Vectorstore deleted successfully."}
|
| 151 |
+
return {"message": "Failed to delete vectorstore."}
|
| 152 |
+
except Exception as e:
|
| 153 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@app.post("/vectorstore/download", tags=["Download VectorStore"])
|
| 157 |
+
async def download_vectorstore(
|
| 158 |
+
download_request: DownloadVectorStoreRequest = Depends(),
|
| 159 |
+
):
|
| 160 |
+
try:
|
| 161 |
+
manager = VectorStoreManager(
|
| 162 |
+
path=path_db,
|
| 163 |
+
name=download_request.nombre_db_vectorial,
|
| 164 |
+
embeddings=embeddings,
|
| 165 |
+
)
|
| 166 |
+
zip_path = manager.download_vectorstore()
|
| 167 |
+
return FileResponse(zip_path, filename="vectorstore.zip")
|
| 168 |
+
except Exception as e:
|
| 169 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if __name__ == "__main__":
|
| 173 |
+
import os
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
# crear todas las carpetas necesarias si no existen
|
| 177 |
+
carpetas = [path_docs, path_db, "temp"]
|
| 178 |
+
for carpeta in carpetas:
|
| 179 |
+
if not os.path.exists(carpeta):
|
| 180 |
+
os.makedirs(carpeta)
|
| 181 |
+
os.system("uvicorn app:app --port 7860 --host 0.0.0.0")
|
| 182 |
+
except KeyboardInterrupt:
|
| 183 |
+
print("Server stopped.")
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(e)
|
| 186 |
+
print("Failed to start server.")
|