main.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. from fastapi import (
  2. FastAPI,
  3. Depends,
  4. HTTPException,
  5. status,
  6. UploadFile,
  7. File,
  8. Form,
  9. )
  10. from fastapi.middleware.cors import CORSMiddleware
  11. import os, shutil, logging, re
  12. from pathlib import Path
  13. from typing import List
  14. from chromadb.utils.batch_utils import create_batches
  15. from langchain_community.document_loaders import (
  16. WebBaseLoader,
  17. TextLoader,
  18. PyPDFLoader,
  19. CSVLoader,
  20. BSHTMLLoader,
  21. Docx2txtLoader,
  22. UnstructuredEPubLoader,
  23. UnstructuredWordDocumentLoader,
  24. UnstructuredMarkdownLoader,
  25. UnstructuredXMLLoader,
  26. UnstructuredRSTLoader,
  27. UnstructuredExcelLoader,
  28. YoutubeLoader,
  29. )
  30. from langchain.text_splitter import RecursiveCharacterTextSplitter
  31. import validators
  32. import urllib.parse
  33. import socket
  34. from pydantic import BaseModel
  35. from typing import Optional
  36. import mimetypes
  37. import uuid
  38. import json
  39. import sentence_transformers
  40. from apps.web.models.documents import (
  41. Documents,
  42. DocumentForm,
  43. DocumentResponse,
  44. )
  45. from apps.rag.utils import (
  46. get_model_path,
  47. get_embedding_function,
  48. query_doc,
  49. query_doc_with_hybrid_search,
  50. query_collection,
  51. query_collection_with_hybrid_search,
  52. )
  53. from utils.misc import (
  54. calculate_sha256,
  55. calculate_sha256_string,
  56. sanitize_filename,
  57. extract_folders_after_data_docs,
  58. )
  59. from utils.utils import get_current_user, get_admin_user
  60. from config import (
  61. SRC_LOG_LEVELS,
  62. UPLOAD_DIR,
  63. DOCS_DIR,
  64. RAG_TOP_K,
  65. RAG_RELEVANCE_THRESHOLD,
  66. RAG_EMBEDDING_ENGINE,
  67. RAG_EMBEDDING_MODEL,
  68. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  69. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  70. ENABLE_RAG_HYBRID_SEARCH,
  71. RAG_RERANKING_MODEL,
  72. PDF_EXTRACT_IMAGES,
  73. RAG_RERANKING_MODEL_AUTO_UPDATE,
  74. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  75. RAG_OPENAI_API_BASE_URL,
  76. RAG_OPENAI_API_KEY,
  77. DEVICE_TYPE,
  78. CHROMA_CLIENT,
  79. CHUNK_SIZE,
  80. CHUNK_OVERLAP,
  81. RAG_TEMPLATE,
  82. ENABLE_LOCAL_WEB_FETCH,
  83. )
  84. from constants import ERROR_MESSAGES
  85. log = logging.getLogger(__name__)
  86. log.setLevel(SRC_LOG_LEVELS["RAG"])
  87. app = FastAPI()
  88. app.state.TOP_K = RAG_TOP_K
  89. app.state.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  90. app.state.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
  91. app.state.CHUNK_SIZE = CHUNK_SIZE
  92. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  93. app.state.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  94. app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  95. app.state.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  96. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  97. app.state.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  98. app.state.OPENAI_API_KEY = RAG_OPENAI_API_KEY
  99. app.state.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
  100. def update_embedding_model(
  101. embedding_model: str,
  102. update_model: bool = False,
  103. ):
  104. if embedding_model and app.state.RAG_EMBEDDING_ENGINE == "":
  105. app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
  106. get_model_path(embedding_model, update_model),
  107. device=DEVICE_TYPE,
  108. trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  109. )
  110. else:
  111. app.state.sentence_transformer_ef = None
  112. def update_reranking_model(
  113. reranking_model: str,
  114. update_model: bool = False,
  115. ):
  116. if reranking_model:
  117. app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
  118. get_model_path(reranking_model, update_model),
  119. device=DEVICE_TYPE,
  120. trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  121. )
  122. else:
  123. app.state.sentence_transformer_rf = None
  124. update_embedding_model(
  125. app.state.RAG_EMBEDDING_MODEL,
  126. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  127. )
  128. update_reranking_model(
  129. app.state.RAG_RERANKING_MODEL,
  130. RAG_RERANKING_MODEL_AUTO_UPDATE,
  131. )
  132. app.state.EMBEDDING_FUNCTION = get_embedding_function(
  133. app.state.RAG_EMBEDDING_ENGINE,
  134. app.state.RAG_EMBEDDING_MODEL,
  135. app.state.sentence_transformer_ef,
  136. app.state.OPENAI_API_KEY,
  137. app.state.OPENAI_API_BASE_URL,
  138. )
  139. origins = ["*"]
  140. app.add_middleware(
  141. CORSMiddleware,
  142. allow_origins=origins,
  143. allow_credentials=True,
  144. allow_methods=["*"],
  145. allow_headers=["*"],
  146. )
  147. class CollectionNameForm(BaseModel):
  148. collection_name: Optional[str] = "test"
  149. class UrlForm(CollectionNameForm):
  150. url: str
  151. @app.get("/")
  152. async def get_status():
  153. return {
  154. "status": True,
  155. "chunk_size": app.state.CHUNK_SIZE,
  156. "chunk_overlap": app.state.CHUNK_OVERLAP,
  157. "template": app.state.RAG_TEMPLATE,
  158. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  159. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  160. "reranking_model": app.state.RAG_RERANKING_MODEL,
  161. }
  162. @app.get("/embedding")
  163. async def get_embedding_config(user=Depends(get_admin_user)):
  164. return {
  165. "status": True,
  166. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  167. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  168. "openai_config": {
  169. "url": app.state.OPENAI_API_BASE_URL,
  170. "key": app.state.OPENAI_API_KEY,
  171. },
  172. }
  173. @app.get("/reranking")
  174. async def get_reraanking_config(user=Depends(get_admin_user)):
  175. return {"status": True, "reranking_model": app.state.RAG_RERANKING_MODEL}
  176. class OpenAIConfigForm(BaseModel):
  177. url: str
  178. key: str
  179. class EmbeddingModelUpdateForm(BaseModel):
  180. openai_config: Optional[OpenAIConfigForm] = None
  181. embedding_engine: str
  182. embedding_model: str
  183. @app.post("/embedding/update")
  184. async def update_embedding_config(
  185. form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  186. ):
  187. log.info(
  188. f"Updating embedding model: {app.state.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
  189. )
  190. try:
  191. app.state.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
  192. app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
  193. if app.state.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
  194. if form_data.openai_config != None:
  195. app.state.OPENAI_API_BASE_URL = form_data.openai_config.url
  196. app.state.OPENAI_API_KEY = form_data.openai_config.key
  197. update_embedding_model(app.state.RAG_EMBEDDING_MODEL, True)
  198. app.state.EMBEDDING_FUNCTION = get_embedding_function(
  199. app.state.RAG_EMBEDDING_ENGINE,
  200. app.state.RAG_EMBEDDING_MODEL,
  201. app.state.sentence_transformer_ef,
  202. app.state.OPENAI_API_KEY,
  203. app.state.OPENAI_API_BASE_URL,
  204. )
  205. return {
  206. "status": True,
  207. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  208. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  209. "openai_config": {
  210. "url": app.state.OPENAI_API_BASE_URL,
  211. "key": app.state.OPENAI_API_KEY,
  212. },
  213. }
  214. except Exception as e:
  215. log.exception(f"Problem updating embedding model: {e}")
  216. raise HTTPException(
  217. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  218. detail=ERROR_MESSAGES.DEFAULT(e),
  219. )
  220. class RerankingModelUpdateForm(BaseModel):
  221. reranking_model: str
  222. @app.post("/reranking/update")
  223. async def update_reranking_config(
  224. form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
  225. ):
  226. log.info(
  227. f"Updating reranking model: {app.state.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
  228. )
  229. try:
  230. app.state.RAG_RERANKING_MODEL = form_data.reranking_model
  231. update_reranking_model(app.state.RAG_RERANKING_MODEL, True)
  232. return {
  233. "status": True,
  234. "reranking_model": app.state.RAG_RERANKING_MODEL,
  235. }
  236. except Exception as e:
  237. log.exception(f"Problem updating reranking model: {e}")
  238. raise HTTPException(
  239. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  240. detail=ERROR_MESSAGES.DEFAULT(e),
  241. )
  242. @app.get("/config")
  243. async def get_rag_config(user=Depends(get_admin_user)):
  244. return {
  245. "status": True,
  246. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  247. "chunk": {
  248. "chunk_size": app.state.CHUNK_SIZE,
  249. "chunk_overlap": app.state.CHUNK_OVERLAP,
  250. },
  251. }
  252. class ChunkParamUpdateForm(BaseModel):
  253. chunk_size: int
  254. chunk_overlap: int
  255. class ConfigUpdateForm(BaseModel):
  256. pdf_extract_images: bool
  257. chunk: ChunkParamUpdateForm
  258. @app.post("/config/update")
  259. async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
  260. app.state.PDF_EXTRACT_IMAGES = form_data.pdf_extract_images
  261. app.state.CHUNK_SIZE = form_data.chunk.chunk_size
  262. app.state.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
  263. return {
  264. "status": True,
  265. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  266. "chunk": {
  267. "chunk_size": app.state.CHUNK_SIZE,
  268. "chunk_overlap": app.state.CHUNK_OVERLAP,
  269. },
  270. }
  271. @app.get("/template")
  272. async def get_rag_template(user=Depends(get_current_user)):
  273. return {
  274. "status": True,
  275. "template": app.state.RAG_TEMPLATE,
  276. }
  277. @app.get("/query/settings")
  278. async def get_query_settings(user=Depends(get_admin_user)):
  279. return {
  280. "status": True,
  281. "template": app.state.RAG_TEMPLATE,
  282. "k": app.state.TOP_K,
  283. "r": app.state.RELEVANCE_THRESHOLD,
  284. "hybrid": app.state.ENABLE_RAG_HYBRID_SEARCH,
  285. }
  286. class QuerySettingsForm(BaseModel):
  287. k: Optional[int] = None
  288. r: Optional[float] = None
  289. template: Optional[str] = None
  290. hybrid: Optional[bool] = None
  291. @app.post("/query/settings/update")
  292. async def update_query_settings(
  293. form_data: QuerySettingsForm, user=Depends(get_admin_user)
  294. ):
  295. app.state.RAG_TEMPLATE = form_data.template if form_data.template else RAG_TEMPLATE
  296. app.state.TOP_K = form_data.k if form_data.k else 4
  297. app.state.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
  298. app.state.ENABLE_RAG_HYBRID_SEARCH = form_data.hybrid if form_data.hybrid else False
  299. return {
  300. "status": True,
  301. "template": app.state.RAG_TEMPLATE,
  302. "k": app.state.TOP_K,
  303. "r": app.state.RELEVANCE_THRESHOLD,
  304. "hybrid": app.state.ENABLE_RAG_HYBRID_SEARCH,
  305. }
  306. class QueryDocForm(BaseModel):
  307. collection_name: str
  308. query: str
  309. k: Optional[int] = None
  310. r: Optional[float] = None
  311. hybrid: Optional[bool] = None
  312. @app.post("/query/doc")
  313. def query_doc_handler(
  314. form_data: QueryDocForm,
  315. user=Depends(get_current_user),
  316. ):
  317. try:
  318. if app.state.ENABLE_RAG_HYBRID_SEARCH:
  319. return query_doc_with_hybrid_search(
  320. collection_name=form_data.collection_name,
  321. query=form_data.query,
  322. embedding_function=app.state.EMBEDDING_FUNCTION,
  323. k=form_data.k if form_data.k else app.state.TOP_K,
  324. reranking_function=app.state.sentence_transformer_rf,
  325. r=form_data.r if form_data.r else app.state.RELEVANCE_THRESHOLD,
  326. )
  327. else:
  328. return query_doc(
  329. collection_name=form_data.collection_name,
  330. query=form_data.query,
  331. embedding_function=app.state.EMBEDDING_FUNCTION,
  332. k=form_data.k if form_data.k else app.state.TOP_K,
  333. )
  334. except Exception as e:
  335. log.exception(e)
  336. raise HTTPException(
  337. status_code=status.HTTP_400_BAD_REQUEST,
  338. detail=ERROR_MESSAGES.DEFAULT(e),
  339. )
  340. class QueryCollectionsForm(BaseModel):
  341. collection_names: List[str]
  342. query: str
  343. k: Optional[int] = None
  344. r: Optional[float] = None
  345. hybrid: Optional[bool] = None
  346. @app.post("/query/collection")
  347. def query_collection_handler(
  348. form_data: QueryCollectionsForm,
  349. user=Depends(get_current_user),
  350. ):
  351. try:
  352. if app.state.ENABLE_RAG_HYBRID_SEARCH:
  353. return query_collection_with_hybrid_search(
  354. collection_names=form_data.collection_names,
  355. query=form_data.query,
  356. embedding_function=app.state.EMBEDDING_FUNCTION,
  357. k=form_data.k if form_data.k else app.state.TOP_K,
  358. reranking_function=app.state.sentence_transformer_rf,
  359. r=form_data.r if form_data.r else app.state.RELEVANCE_THRESHOLD,
  360. )
  361. else:
  362. return query_collection(
  363. collection_names=form_data.collection_names,
  364. query=form_data.query,
  365. embedding_function=app.state.EMBEDDING_FUNCTION,
  366. k=form_data.k if form_data.k else app.state.TOP_K,
  367. )
  368. except Exception as e:
  369. log.exception(e)
  370. raise HTTPException(
  371. status_code=status.HTTP_400_BAD_REQUEST,
  372. detail=ERROR_MESSAGES.DEFAULT(e),
  373. )
  374. @app.post("/youtube")
  375. def store_youtube_video(form_data: UrlForm, user=Depends(get_current_user)):
  376. try:
  377. loader = YoutubeLoader.from_youtube_url(form_data.url, add_video_info=False)
  378. data = loader.load()
  379. collection_name = form_data.collection_name
  380. if collection_name == "":
  381. collection_name = calculate_sha256_string(form_data.url)[:63]
  382. store_data_in_vector_db(data, collection_name, overwrite=True)
  383. return {
  384. "status": True,
  385. "collection_name": collection_name,
  386. "filename": form_data.url,
  387. }
  388. except Exception as e:
  389. log.exception(e)
  390. raise HTTPException(
  391. status_code=status.HTTP_400_BAD_REQUEST,
  392. detail=ERROR_MESSAGES.DEFAULT(e),
  393. )
  394. @app.post("/web")
  395. def store_web(form_data: UrlForm, user=Depends(get_current_user)):
  396. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  397. try:
  398. loader = get_web_loader(form_data.url)
  399. data = loader.load()
  400. collection_name = form_data.collection_name
  401. if collection_name == "":
  402. collection_name = calculate_sha256_string(form_data.url)[:63]
  403. store_data_in_vector_db(data, collection_name, overwrite=True)
  404. return {
  405. "status": True,
  406. "collection_name": collection_name,
  407. "filename": form_data.url,
  408. }
  409. except Exception as e:
  410. log.exception(e)
  411. raise HTTPException(
  412. status_code=status.HTTP_400_BAD_REQUEST,
  413. detail=ERROR_MESSAGES.DEFAULT(e),
  414. )
  415. def get_web_loader(url: str):
  416. # Check if the URL is valid
  417. if isinstance(validators.url(url), validators.ValidationError):
  418. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  419. if not ENABLE_LOCAL_WEB_FETCH:
  420. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  421. parsed_url = urllib.parse.urlparse(url)
  422. # Get IPv4 and IPv6 addresses
  423. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  424. # Check if any of the resolved addresses are private
  425. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  426. for ip in ipv4_addresses:
  427. if validators.ipv4(ip, private=True):
  428. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  429. for ip in ipv6_addresses:
  430. if validators.ipv6(ip, private=True):
  431. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  432. return WebBaseLoader(url)
  433. def resolve_hostname(hostname):
  434. # Get address information
  435. addr_info = socket.getaddrinfo(hostname, None)
  436. # Extract IP addresses from address information
  437. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  438. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  439. return ipv4_addresses, ipv6_addresses
  440. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  441. text_splitter = RecursiveCharacterTextSplitter(
  442. chunk_size=app.state.CHUNK_SIZE,
  443. chunk_overlap=app.state.CHUNK_OVERLAP,
  444. add_start_index=True,
  445. )
  446. docs = text_splitter.split_documents(data)
  447. if len(docs) > 0:
  448. log.info(f"store_data_in_vector_db {docs}")
  449. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  450. else:
  451. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  452. def store_text_in_vector_db(
  453. text, metadata, collection_name, overwrite: bool = False
  454. ) -> bool:
  455. text_splitter = RecursiveCharacterTextSplitter(
  456. chunk_size=app.state.CHUNK_SIZE,
  457. chunk_overlap=app.state.CHUNK_OVERLAP,
  458. add_start_index=True,
  459. )
  460. docs = text_splitter.create_documents([text], metadatas=[metadata])
  461. return store_docs_in_vector_db(docs, collection_name, overwrite)
  462. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  463. log.info(f"store_docs_in_vector_db {docs} {collection_name}")
  464. texts = [doc.page_content for doc in docs]
  465. metadatas = [doc.metadata for doc in docs]
  466. try:
  467. if overwrite:
  468. for collection in CHROMA_CLIENT.list_collections():
  469. if collection_name == collection.name:
  470. log.info(f"deleting existing collection {collection_name}")
  471. CHROMA_CLIENT.delete_collection(name=collection_name)
  472. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  473. embedding_func = get_embedding_function(
  474. app.state.RAG_EMBEDDING_ENGINE,
  475. app.state.RAG_EMBEDDING_MODEL,
  476. app.state.sentence_transformer_ef,
  477. app.state.OPENAI_API_KEY,
  478. app.state.OPENAI_API_BASE_URL,
  479. )
  480. embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
  481. embeddings = embedding_func(embedding_texts)
  482. for batch in create_batches(
  483. api=CHROMA_CLIENT,
  484. ids=[str(uuid.uuid1()) for _ in texts],
  485. metadatas=metadatas,
  486. embeddings=embeddings,
  487. documents=texts,
  488. ):
  489. collection.add(*batch)
  490. return True
  491. except Exception as e:
  492. log.exception(e)
  493. if e.__class__.__name__ == "UniqueConstraintError":
  494. return True
  495. return False
  496. def get_loader(filename: str, file_content_type: str, file_path: str):
  497. file_ext = filename.split(".")[-1].lower()
  498. known_type = True
  499. known_source_ext = [
  500. "go",
  501. "py",
  502. "java",
  503. "sh",
  504. "bat",
  505. "ps1",
  506. "cmd",
  507. "js",
  508. "ts",
  509. "css",
  510. "cpp",
  511. "hpp",
  512. "h",
  513. "c",
  514. "cs",
  515. "sql",
  516. "log",
  517. "ini",
  518. "pl",
  519. "pm",
  520. "r",
  521. "dart",
  522. "dockerfile",
  523. "env",
  524. "php",
  525. "hs",
  526. "hsc",
  527. "lua",
  528. "nginxconf",
  529. "conf",
  530. "m",
  531. "mm",
  532. "plsql",
  533. "perl",
  534. "rb",
  535. "rs",
  536. "db2",
  537. "scala",
  538. "bash",
  539. "swift",
  540. "vue",
  541. "svelte",
  542. ]
  543. if file_ext == "pdf":
  544. loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
  545. elif file_ext == "csv":
  546. loader = CSVLoader(file_path)
  547. elif file_ext == "rst":
  548. loader = UnstructuredRSTLoader(file_path, mode="elements")
  549. elif file_ext == "xml":
  550. loader = UnstructuredXMLLoader(file_path)
  551. elif file_ext in ["htm", "html"]:
  552. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  553. elif file_ext == "md":
  554. loader = UnstructuredMarkdownLoader(file_path)
  555. elif file_content_type == "application/epub+zip":
  556. loader = UnstructuredEPubLoader(file_path)
  557. elif (
  558. file_content_type
  559. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  560. or file_ext in ["doc", "docx"]
  561. ):
  562. loader = Docx2txtLoader(file_path)
  563. elif file_content_type in [
  564. "application/vnd.ms-excel",
  565. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  566. ] or file_ext in ["xls", "xlsx"]:
  567. loader = UnstructuredExcelLoader(file_path)
  568. elif file_ext in known_source_ext or (
  569. file_content_type and file_content_type.find("text/") >= 0
  570. ):
  571. loader = TextLoader(file_path, autodetect_encoding=True)
  572. else:
  573. loader = TextLoader(file_path, autodetect_encoding=True)
  574. known_type = False
  575. return loader, known_type
  576. @app.post("/doc")
  577. def store_doc(
  578. collection_name: Optional[str] = Form(None),
  579. file: UploadFile = File(...),
  580. user=Depends(get_current_user),
  581. ):
  582. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  583. log.info(f"file.content_type: {file.content_type}")
  584. try:
  585. unsanitized_filename = file.filename
  586. filename = os.path.basename(unsanitized_filename)
  587. file_path = f"{UPLOAD_DIR}/{filename}"
  588. contents = file.file.read()
  589. with open(file_path, "wb") as f:
  590. f.write(contents)
  591. f.close()
  592. f = open(file_path, "rb")
  593. if collection_name == None:
  594. collection_name = calculate_sha256(f)[:63]
  595. f.close()
  596. loader, known_type = get_loader(filename, file.content_type, file_path)
  597. data = loader.load()
  598. try:
  599. result = store_data_in_vector_db(data, collection_name)
  600. if result:
  601. return {
  602. "status": True,
  603. "collection_name": collection_name,
  604. "filename": filename,
  605. "known_type": known_type,
  606. }
  607. except Exception as e:
  608. raise HTTPException(
  609. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  610. detail=e,
  611. )
  612. except Exception as e:
  613. log.exception(e)
  614. if "No pandoc was found" in str(e):
  615. raise HTTPException(
  616. status_code=status.HTTP_400_BAD_REQUEST,
  617. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  618. )
  619. else:
  620. raise HTTPException(
  621. status_code=status.HTTP_400_BAD_REQUEST,
  622. detail=ERROR_MESSAGES.DEFAULT(e),
  623. )
  624. class TextRAGForm(BaseModel):
  625. name: str
  626. content: str
  627. collection_name: Optional[str] = None
  628. @app.post("/text")
  629. def store_text(
  630. form_data: TextRAGForm,
  631. user=Depends(get_current_user),
  632. ):
  633. collection_name = form_data.collection_name
  634. if collection_name == None:
  635. collection_name = calculate_sha256_string(form_data.content)
  636. result = store_text_in_vector_db(
  637. form_data.content,
  638. metadata={"name": form_data.name, "created_by": user.id},
  639. collection_name=collection_name,
  640. )
  641. if result:
  642. return {"status": True, "collection_name": collection_name}
  643. else:
  644. raise HTTPException(
  645. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  646. detail=ERROR_MESSAGES.DEFAULT(),
  647. )
  648. @app.get("/scan")
  649. def scan_docs_dir(user=Depends(get_admin_user)):
  650. for path in Path(DOCS_DIR).rglob("./**/*"):
  651. try:
  652. if path.is_file() and not path.name.startswith("."):
  653. tags = extract_folders_after_data_docs(path)
  654. filename = path.name
  655. file_content_type = mimetypes.guess_type(path)
  656. f = open(path, "rb")
  657. collection_name = calculate_sha256(f)[:63]
  658. f.close()
  659. loader, known_type = get_loader(
  660. filename, file_content_type[0], str(path)
  661. )
  662. data = loader.load()
  663. try:
  664. result = store_data_in_vector_db(data, collection_name)
  665. if result:
  666. sanitized_filename = sanitize_filename(filename)
  667. doc = Documents.get_doc_by_name(sanitized_filename)
  668. if doc == None:
  669. doc = Documents.insert_new_doc(
  670. user.id,
  671. DocumentForm(
  672. **{
  673. "name": sanitized_filename,
  674. "title": filename,
  675. "collection_name": collection_name,
  676. "filename": filename,
  677. "content": (
  678. json.dumps(
  679. {
  680. "tags": list(
  681. map(
  682. lambda name: {"name": name},
  683. tags,
  684. )
  685. )
  686. }
  687. )
  688. if len(tags)
  689. else "{}"
  690. ),
  691. }
  692. ),
  693. )
  694. except Exception as e:
  695. log.exception(e)
  696. pass
  697. except Exception as e:
  698. log.exception(e)
  699. return True
  700. @app.get("/reset/db")
  701. def reset_vector_db(user=Depends(get_admin_user)):
  702. CHROMA_CLIENT.reset()
  703. @app.get("/reset")
  704. def reset(user=Depends(get_admin_user)) -> bool:
  705. folder = f"{UPLOAD_DIR}"
  706. for filename in os.listdir(folder):
  707. file_path = os.path.join(folder, filename)
  708. try:
  709. if os.path.isfile(file_path) or os.path.islink(file_path):
  710. os.unlink(file_path)
  711. elif os.path.isdir(file_path):
  712. shutil.rmtree(file_path)
  713. except Exception as e:
  714. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  715. try:
  716. CHROMA_CLIENT.reset()
  717. except Exception as e:
  718. log.exception(e)
  719. return True