
    j                         S r SSKrSSKrSSKrSSKrSSKJr  SSKJr  SSK	J
r
  SSKJrJrJrJrJr  S\S\4S jrS	\S\4S
 jrS\4S jrS rS r\S:X  a  \" 5         gg)a  
training_doc.py
===============
Training module for DOC/DOCX document formats.

Handles text extraction from Word documents (.doc, .docx),
semantic chunking, and FAISS embedding creation.

- .docx: Extracted directly using python-docx
- .doc:  Converted to .docx via LibreOffice, then extracted

Shared utilities (semantic chunking, embedding creation, FAISS merging)
are imported from training.py to maintain DRY principles.
    N)Document)OllamaEmbeddings) split_text_with_semantic_chunkercount_tokens_in_documentssave_documents_to_txtcreate_and_save_embeddingsmerge_all_faiss	file_pathreturnc                    [        U 5      n/ nUR                   H7  nUR                  R                  5       nU(       d  M&  UR	                  U5        M9     UR
                   H]  nUR                   HJ  nUR                   H7  nUR                  R                  5       nU(       d  M&  UR	                  U5        M9     ML     M_     SR                  U5      $ )z
Extract all text content from a .docx file using python-docx.

Iterates through all paragraphs and table cells to capture
the complete document content.

)	DocxDocument
paragraphstextstripappendtablesrowscellsjoin)	r
   doc
text_parts	paragraphstrippedtablerowcell	cell_texts	            G/var/www/eduai.edurigo.com/question_generate/production/training_doc.py_extract_text_from_docxr    '   s     y
!CJ ^^	>>'')8h' $ ::C		 IIOO-	9%%i0 "   99Z      doc_file_pathc           	      X   [         R                  R                  U 5      =(       d    Sn [        R                  " SSSSSUU /SSSS	9nUR
                  S
:w  a%  [        SUR
                   SUR                   35      e [         R                  R                  [         R                  R                  U 5      5      S
   n[         R                  R                  X S35      n[         R                  R                  U5      (       d  [        SU 35      eU$ ! [         a    [        S5      ef = f)z
Convert a legacy .doc file to .docx using LibreOffice headless mode.

Returns the path to the newly created .docx file.
Raises RuntimeError if LibreOffice conversion fails.
.libreofficez
--headlessz--convert-todocxz--outdirTx   )capture_outputr   timeoutr   z)LibreOffice conversion failed (exit code z): zYLibreOffice is not installed or not in PATH. It is required to convert legacy .doc files..docxz:LibreOffice conversion produced no output file. Expected: )ospathdirname
subprocessrun
returncodeRuntimeErrorstderrFileNotFoundErrorsplitextbasenamer   exists)r"   
output_dirresult	base_name	docx_paths        r   _convert_doc_to_docxr;   B   s.    /63J
J  
 !;F<M<M;Nc==/#  "   !1!1-!@A!DIZ;e)<=I77>>)$$"%
 	

 !  
;
 	

s   AD D)c                 r   [         R                  R                  U 5      S   R                  5       nSn US:X  a  [	        U 5      nO,US:X  a  [        U 5      n[	        U5      nO[        SU S35      eUR                  5       (       da  [        SU  35        / U(       aJ  [         R                  R                  U5      (       a%  [         R                  " U5        [        SU 35        $ $ $ [        UXS	.S
9/n[        SU S[        U5       S35        UU(       aJ  [         R                  R                  U5      (       a%  [         R                  " U5        [        SU 35        $ $ $ ! U(       aJ  [         R                  R                  U5      (       a%  [         R                  " U5        [        SU 35        f f f = f)a,  
Load a DOC or DOCX file and return a list of LangChain Document objects.

For .docx files, text is extracted directly using python-docx.
For .doc files, the document is first converted to .docx via LibreOffice.

Returns:
    list[Document]: List of LangChain Document objects with page_content set.
   Nr*   z.doczUnsupported file type: z$. Only .doc and .docx are supported.z(Warning: No text content extracted from z%Cleaned up temporary converted file: )sourceformat)page_contentmetadatazSuccessfully loaded z document: z characters extracted.)r+   r,   r4   lowerr    r;   
ValueErrorr   printr6   remover   len)r
   file_extensionconverted_docx_pathr   	documentss        r   load_docrJ   v   s    WW%%i0399;N QW$*95Dv%"6y"A*+>?D).)9 :5 6 
 zz||<YKHI 277>>2E#F#FII)*9:M9NOP $G !$-H
	 	$^$4KD	{J`ab 277>>2E#F#FII)*9:M9NOP $G277>>2E#F#FII)*9:M9NOP $Gs   A"E# ()E# #AF6c                 l    SnU  H+  nUR                   R                  5       nU[        U5      -  nM-     U$ )zx
Count total tokens across all Document objects.
Uses whitespace tokenization for consistency with the existing system.
r   )r@   splitrF   )rI   total_tokensr   tokenss       r   count_tokens_in_doc_documentsrO      s=    
 L!!'')F#  r!   c                     Sn SnSnSU SU 3n[         R                   " 5       n[        SU 35        [        U 5      nU(       d  [        S5        g[        U5      n[        S	U 35        [	        S
S9n[        XW5      n[        X5        [        XU5        [        X5        [         R                   " 5       n	[        SX-
  S S35        [        SU 35        g)z/Test the DOC/DOCX training pipeline standalone.ztest_document.docxtest_clienttest_refztemp/_zStart Time: zNo documents loaded. Exiting.NzTotal tokens: znomic-embed-text)modelzTraining process took z.2fz secondszTotal tokens processed: )	timerD   rJ   rO   r   r   r   r   r	   )
r
   	client_idreference_idr7   
start_timedocstoken_count
embeddingssplit_documentsend_times
             r   mainr^      s    $IIL1\N3JJ	L
%& ID-./5K	N;-
() "(:;J6tHO /6 <H I,yy{H	"8#8"=X
FG	$[M
23r!   __main__)__doc__r+   r.   tempfilerU   r&   r   r   langchain_core.documentslangchain_ollamar   trainingr   r   r   r   r	   strr    r;   rJ   rO   r^   __name__ r!   r   <module>rh      s    
    ) - - !s !s !6- - -h-Q -Qh	 "4J zF r!   