Lucas ARRIESSE commited on
Commit ·
2c86f91
1
Parent(s): 2ba1434
Use kreuzberg for document extraction + rate limit downloads
Browse filesFiles changed (4)
- Dockerfile+1-1
- api/docs.py+50-37
- app.py+1-1
- requirements.txt+2-1
1234567FROM python:3.11.3RUN apt-get update && \apt-get install -y libreoffice libreoffice-writer libreoffice-calc libreoffice-impress && \apt-get clean && rm -rf /var/lib/apt/lists/*RUN useradd -m -u 1000 user1234567FROM python:3.11.3RUN apt-get update && \apt-get install -y libreoffice libreoffice-writer libreoffice-calc libreoffice-impress pandoc && \apt-get clean && rm -rf /var/lib/apt/lists/*RUN useradd -m -u 1000 user
123414 unmodified lines1920212223248 unmodified lines33343536373839409 unmodified lines5051525354555634 unmodified lines919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913058 unmodified lines1891901911921931942 unmodified lines197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227import asynciofrom pathlib import Pathimport tracebackfrom typing import Literal, Tuple14 unmodified linesfrom dependencies import get_http_client, get_llm_routerfrom fastapi.responses import StreamingResponsefrom litellm.router import Routerfrom schemas import DataRequest, DataResponse, DocRequirements, DocDownloadRequest, MeetingsRequest, MeetingsResponse, ExtractRequirementsRequest, ExtractRequirementsResponse8 unmodified lines# ================================== Converting of files to .txt ====================================# Unfortunately needs to be kept to 1, as libreoffice isn't built to support parallel instancesCONVERSION_MUTEX = asyncio.Semaphore(1)async def convert_file(contents: io.BytesIO, filename: str, input_ext: str, output_ext: str, filter: str = None) -> io.BytesIO:9 unmodified linesfilter: The conversion filter to use."""await CONVERSION_MUTEX.acquire()with tempfile.TemporaryDirectory() as tmpdir:dir_path = Path(tmpdir)34 unmodified linesstderr=stderr)CONVERSION_MUTEX.release()with open(output_file_path, mode="rb") as out:out_bytes.write(out.read())2 unmodified linesreturn out_bytesasync def get_doc_archive(url: str, client: AsyncClient) -> tuple[str, str, io.BytesIO]:"""Récupère le docx depuis l'URL et le retourne un tuple (nom, extension, contenu)"""if not url.endswith("zip"):raise ValueError("URL doit pointer vers un fichier ZIP")doc_id = os.path.splitext(os.path.basename(url))[0]resp = await client.get(url, headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'})resp.raise_for_status()with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:# there should be a single file per filefor entry in zf.infolist():if entry.is_dir():continuefile_name = entry.filenameroot, ext = os.path.splitext(file_name)doc_bytes = zf.read(file_name)return (root, ext.lower(), io.BytesIO(doc_bytes))raise ValueError("Aucun fichier trouvé dans l'archive")def apply_docx_revisions(docx_zip: zipfile.ZipFile) -> io.BytesIO:58 unmodified linesreturn outputasync def doc_to_txt(doc_id: str, url: str, client: AsyncClient) -> str:"""Télécharge le TDoc spécifié et le convertit en texte.2 unmodified lines# Grab the document archivefilename, ext, bytes = await get_doc_archive(url, client)final_bytes: io.BytesIO = Noneif ext == ".doc":logging.debug(f"Converting {filename} .doc --> .docx")docx_bytes = await convert_file(bytes, doc_id, "doc", "docx")logging.debug(f"Converting {filename} .docx --> .txt")final_bytes = await convert_file(docx_bytes, f"{doc_id}", "docx", "txt")elif ext == ".docx":logging.debug(f"Updating .docx revisions")applied_revision = apply_docx_revisions(zipfile.ZipFile(bytes))logging.debug(f"Converting {filename} .docx --> .txt")final_bytes = await convert_file(applied_revision, f"{doc_id}", "docx", "txt")elif ext == ".pdf":logging.debug(f"Converting {filename} .pdf --> .txt")final_bytes = await convert_file(bytes, doc_id, "pdf", "txt")elif ext == ".pptx":logging.debug(f"Converting {filename} .pptx --> .pdf")pdf_bytes = await convert_file(bytes, doc_id, "pptx", "pdf")logging.debug(f"Converting {filename} .pdf --> .txt")final_bytes = await convert_file(pdf_bytes, doc_id, "pdf", "txt")else:raise Exception(f"Unsupported file type: {ext}, filename: {filename}")text_from_bytes = str(final_bytes.read(), encoding="utf-8")txt_data = [line.strip()for line in text_from_bytes.splitlines() if line.strip()]return txt_data1234514 unmodified lines202122232425268 unmodified lines35363738394041424344459 unmodified lines5556575859606134 unmodified lines969798991001011022 unmodified lines10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813958 unmodified lines1981992002012022032042052062072082092102 unmodified lines213214215216217218219220221222223224225226227228229230231232233234235236237238239240import asynciofrom aiolimiter import AsyncLimiterfrom pathlib import Pathimport tracebackfrom typing import Literal, Tuple14 unmodified linesfrom dependencies import get_http_client, get_llm_routerfrom fastapi.responses import StreamingResponsefrom litellm.router import Routerfrom kreuzberg import ExtractionConfig, extract_bytesfrom schemas import DataRequest, DataResponse, DocRequirements, DocDownloadRequest, MeetingsRequest, MeetingsResponse, ExtractRequirementsRequest, ExtractRequirementsResponse8 unmodified lines# ================================== Converting of files to .txt ====================================KREUZBERG_CONFIG: ExtractionConfig = ExtractionConfig(force_ocr=False, ocr_backend=None)# Unfortunately needs to be kept to 1, as libreoffice isn't built to support parallel instancesLO_CONVERSION_MUTEX = asyncio.Semaphore(1)async def convert_file(contents: io.BytesIO, filename: str, input_ext: str, output_ext: str, filter: str = None) -> io.BytesIO:9 unmodified linesfilter: The conversion filter to use."""await LO_CONVERSION_MUTEX.acquire()with tempfile.TemporaryDirectory() as tmpdir:dir_path = Path(tmpdir)34 unmodified linesstderr=stderr)LO_CONVERSION_MUTEX.release()with open(output_file_path, mode="rb") as out:out_bytes.write(out.read())2 unmodified linesreturn out_bytes# Rate limit of FTP downloads per minuteFTP_DOWNLOAD_RATE_LIMITER = AsyncLimiter(max_rate=120, time_period=60)async def get_doc_archive(url: str, client: AsyncClient) -> tuple[str, str, io.BytesIO]:"""Récupère le docx depuis l'URL et le retourne un tuple (nom, extension, contenu)"""async with FTP_DOWNLOAD_RATE_LIMITER:if not url.endswith("zip"):raise ValueError("URL doit pointer vers un fichier ZIP")doc_id = os.path.splitext(os.path.basename(url))[0]resp = await client.get(url, headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'})resp.raise_for_status()with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:# there should be a single file per filefor entry in zf.infolist():if entry.is_dir():continuefile_name = entry.filenameroot, ext = os.path.splitext(file_name)doc_bytes = zf.read(file_name)return (root, ext.lower(), io.BytesIO(doc_bytes))raise ValueError("Aucun fichier trouvé dans l'archive")def apply_docx_revisions(docx_zip: zipfile.ZipFile) -> io.BytesIO:58 unmodified linesreturn outputFORMAT_MIME_TYPES = {".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",".pdf": "application/pdf",".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"}async def doc_to_txt(doc_id: str, url: str, client: AsyncClient) -> str:"""Télécharge le TDoc spécifié et le convertit en texte.2 unmodified lines# Grab the document archivefilename, ext, bytes = await get_doc_archive(url, client)final_text: str = Noneif ext == ".doc":logging.debug(f"Converting {filename} .doc --> .docx")docx_bytes = await convert_file(bytes, doc_id, "doc", "docx")extracted_data = await extract_bytes(docx_bytes.read(), FORMAT_MIME_TYPES[".docx"], config=KREUZBERG_CONFIG)final_text = extracted_data.contentelif ext == ".docx":# Applying doc revisions to docx files (especially for pCR / draftCR files)logging.debug(f"Updating .docx revisions for {doc_id}.")applied_revision = apply_docx_revisions(zipfile.ZipFile(bytes))extracted_data = await extract_bytes(applied_revision.read(), FORMAT_MIME_TYPES[".docx"], config=KREUZBERG_CONFIG)final_text = extracted_data.contentelse:if ext in FORMAT_MIME_TYPES: # file extension is supportedextracted_data = await extract_bytes(bytes.read(), FORMAT_MIME_TYPES[ext], config=KREUZBERG_CONFIG)final_text = extracted_data.contentelse:raise Exception(f"Unsupported file type: {ext}, filename: {filename}")txt_data = [line.strip()for line in final_text.splitlines() if line.strip()]return txt_data
20 unmodified lines2122232425262720 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')logging.info("DEBUG logging is disabled. Set `DEBUG_LOG` env var to 1 to enable debug logging.")# Initialize global dependenciesinit_dependencies()20 unmodified lines2122232425262720 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')logging.info(f"Set `DEBUG_LOG` env var to 1 to enable debug logging.")# Initialize global dependenciesinit_dependencies()
9 unmodified lines101112139 unmodified linesbeautifulsoup4aiolimiterhttpxJinja29 unmodified lines10111213149 unmodified linesbeautifulsoup4aiolimiterhttpxJinja2kreuzberg
Dockerfile+1-1
api/docs.py+50-37
app.py+1-1
requirements.txt+2-1