
    (<i
                        U d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
mZ ej                  j                  d      Zeej                  vrej                  j                  de       ddlmZ ddlmZmZmZmZ ddlmZ  ej2                  ej4                  d	
        ej6                  d      ZdZdaedz  ed<    ej@                         Z!defdZ"edefd       Z# eddde#      Z$e$jK                  d      dee&e
f   fd       Z'de&dee&e
f   fdZ(e$jS                  d       ed      fdedefd       Z*y)z
hybrid_server.py - FastAPI-based PDF conversion server using docling.

Endpoints:
    POST /v1/convert/file  - Upload a PDF and receive DoclingDocument as JSON
    GET  /health           - Health check
    N)asynccontextmanager)AnyDictz%~/.local/lib/python3.12/site-packages)DocumentConverter)FastAPIFileHTTPException
UploadFile)JSONResponsez1%(asctime)s [%(levelname)s] %(name)s: %(message)s)levelformathybrid_serveri  @
_converterreturnc                      t         Ot        5  t         4t        j                  d       t	               a t        j                  d       ddd       t         S t         S # 1 sw Y   t         S xY w)zBReturn the singleton DocumentConverter, creating it on first call.Nu2   Initialising DocumentConverter (model loading) …zDocumentConverter ready.)r   _converter_lockloggerinfor        F/home/jay/workspace/.worktrees/task-2057-dev2/scripts/hybrid_server.pyget_converterr   0   sZ      	8!PQ.0
67		8
 :	8
 s   ;AA*appc                   K   t         j                  d       t        j                  t               d {    t         j                  d       d  t         j                  d       y 7 4w)Nu7   Server starting up – warming up DocumentConverter …zStartup complete.zServer shutting down.)r   r   asyncio	to_threadr   )r   s    r   lifespanr   ?   sI     
KKIJ


M
***
KK#$	
KK'( +s   2A+A)5A+zdocling-fast hybrid serverz4Converts PDF files to structured JSON using docling.z1.0.0)titledescriptionversionr   z/healthc                     K   dddS w)zReturn service health status.okr   )statusservicer   r   r   r   healthr%   V   s      77s   tmp_pathc                     t               }t        5  |j                  |       }ddd       j                  }|j	                         S # 1 sw Y   %xY w)z2Run docling conversion (blocking) inside a thread.N)r   r   convertdocumentexport_to_dict)r&   	converterresultdocs       r   _convert_pdfr.   \   sI    I	 -""8,-
//C- -s   AAz/v1/convert/file.filec                   K   | j                          d{   }t        |      t        kD  rt        ddt        dz   d      t        j                  d| j                  t        |             t        j                  j                  | j                  xs d      d	   xs d
}t        j                  d|d      }	 |j                  |       |j                          |j                  }	 t        j                   t"        |       d{   }	 	 t        j(                  |j                         t-        |      S 7 #7 4# t$        $ r6}t        j'                  d| j                         t        dd|       |d}~ww xY w# t*        $ r Y ^w xY w# 	 t        j(                  |j                         w # t*        $ r Y w w xY wxY ww)z
    Accept a PDF upload and return the DoclingDocument as JSON.

    - Maximum file size: 100 MB
    - Processing is delegated to a thread pool to avoid blocking the event loop
    Ni  z(File too large. Maximum allowed size is i   z MB.)status_codedetailzReceived file: %s (%d bytes)upload   z.pdfFhybrid_upload_)deletesuffixprefixzConversion failed for %si  zConversion error: )content)readlenMAX_UPLOAD_BYTESr	   r   r   filenameospathsplitexttempfileNamedTemporaryFilewriteclosenamer   r   r.   	Exception	exceptionunlinkOSErrorr   )r/   r9   r7   tmp_filer&   doc_dictexcs          r   convert_filerM   e   s     IIKG
7|&&=>NS^>_=``de
 	

 KK.s7|L WWdmm7x8;EvF**V,<Hw==	$..|XFFH	IIhmm$ ))G  * G 	7G+C51 	  			IIhmm$ 		s   GD9B$G<-F *D> D<D> F  -G<D> >	E=1E88E==F  	F	GFGG F10G 1	F=:G <F==G  G)+__doc__r   loggingr>   sysrA   	threading
contextlibr   typingr   r   r?   
expanduser_LOCAL_SITEinsertdocling.document_converterr   fastapir   r   r	   r
   fastapi.responsesr   basicConfigINFO	getLoggerr   r<   r   __annotations__Lockr   r   r   r   getstrr%   r.   postrM   r   r   r   <module>rb      sw     	 
   *  gg  !HIchhHHOOA{# 8 < < *
   
,,> 
		?	+
 % 
 (,
$ + ).."	( 	 ) ) ) 
&F	 8d38n 8 8
 3  4S>   
*.s) +*Z +* +* +*r   