
    o~Ij_/                        S r SSKJr  SSKrSSKJr  SSKJr  Sr	Sr
Sr1 S	krS
S1r1 SkrSrSS jrSS jrSS jrSS jrSS jrSS jrS S jrS S jrS S jrS S jrS!S jrS"S jrS S jr S#     S$S jjrg)%zSExtrae texto de los archivos de contexto del agente (carpeta Files, no plantillas).    )annotationsN)Path)agent_v2_storage   i]  i >   .md.csv.htm.log.txt.xml.yml.html.json.yaml	.markdown.docx.pdf>   .xls.xlsm.xlsx)reporte_interactivozreporte interactivozreporte-interactivoc                |    [         R                  " SSU =(       d    SR                  5       5      R                  5       $ )Nz[^0-9kK] )resubstripupper)values    YC:\Users\jesus\Desktop\proyecto_pie360\backend\app\backend\utils\agent_v2_file_context.py_normalize_rutr    &   s+    66+rEKR#6#6#89??AA    c                    U R                  5       (       d  gU R                  U5      R                  5       nUR                  S5      (       a  gU R                  R                  5       nU[        ;   =(       d    U[        ;   =(       d	    U[        ;   $ )NFzdocumentos/)	is_filerelative_toas_posix
startswithsuffixlower_TEXT_EXTENSIONS_BINARY_EXTENSIONS_SPREADSHEET_EXTENSIONS)path
agent_rootrelexts       r   _is_context_filer0   *   so    <<>>


:
&
/
/
1C
~~m$$
++


C""ac-?&?a3JaCaar!   c                  ^^ U R                   R                  5       mU R                  5       R                  5       m[        UU4S j[         5       5      (       a  ST4$ U R
                  R                  5       [        ;   a  ST4$ ST4$ )uC   Prioriza reportes interactivos y Excel antes del orden alfabético.c              3  D   >#    U  H  oT;   =(       d    UT;   v   M     g 7fN ).0markernamer.   s     r   	<genexpr>)_context_file_sort_key.<locals>.<genexpr>8   s!     
U9TvT>*Vs]*9Ts    r         )r7   r(   r%   any_INTERACTIVE_REPORT_MARKERSr'   r+   )r,   r7   r.   s    @@r   _context_file_sort_keyr>   4   sj    99??D
--/


!C

U9T
UUU3x{{553xs8Or!   c                    [         R                  " U 5      nUR                  5       (       d  / $ UR                  S5       Vs/ s H  n[	        X!5      (       d  M  UPM     nn[        U[        S9$ s  snf )N*)key)storageagent_folderexistsrglobr0   sortedr>   )
agent_namerootpfiless       r   list_all_context_file_pathsrK   ?   sZ    
+D;;==	

3E1+;A+DQEE%344 Fs   A/A/c                &    [        U 5      S [         $ r3   )rK   	MAX_FILES)rG   s    r   list_context_file_pathsrN   G   s    &z2:I>>r!   c                    [        U 5       Vs/ s H)  nUR                  R                  5       [        ;   d  M'  UPM+     sn$ s  snf r3   )rK   r'   r(   r+   )rG   rI   s     r   list_spreadsheet_pathsrP   K   sB     -Z88A88>>66 	
8  s
   &AAc                "    U R                  SSS9$ )Nzutf-8replace)encodingerrors)	read_text)r,   s    r   _read_text_filerV   S   s    >>79>==r!   c                (   SSK Jn  U" [        U 5      5      n/ nUR                   H@  nUR                  =(       d    SR                  5       nU(       d  M/  UR                  U5        MB     UR                   H  nUR                   Hq  nUR                   Vs/ s H%  oR                  =(       d    SR                  5       PM'     n	nSR                  S U	 5       5      n
U
(       d  M`  UR                  U
5        Ms     M     SR                  U5      $ s  snf )Nr   )Documentr   z | c              3  6   #    U  H  o(       d  M  Uv   M     g 7fr3   r4   )r5   cs     r   r8   _read_docx.<locals>.<genexpr>c   s     4A!aa   
	
)docxrX   str
paragraphstextr   appendtablesrowscellsjoin)r,   rX   docpartsparara   tablerowcellre   lines              r   
_read_docxrn   W   s    
3t9
CE		R&&(4LL  ::C=@YYGYTyyB--/YEG::444DtT"	   99U	 Hs   ,Dc                D   SS K nUR                  [        U 5      5      n / nU HD  nUR                  5       =(       d    SR	                  5       nU(       d  M3  UR                  U5        MF     SR                  U5      UR                  5         $ ! UR                  5         f = f)Nr   r   

)fitzopenr_   get_textr   rb   rf   close)r,   rq   rg   rh   pagera   s         r   	_read_pdfrv   i   sv    
))CI
CDMMO)r002DtT"  {{5!				s   3B %B Bc           	        SSK nU R                  R                  5       nSnUS:X  a  SnOUS;   a  SnSS[        S.nU(       a  X4S'    UR                  " U 40 UD6n[        U[        5      (       d  S
U0n/ nSn	UR                  5        H  u  pUR                  S5      n[        U
5      nUR                  SU 35        [        U5      U	:  a)  UR                  U	5      nUR                  SU	 SU S35        UR                  UR                  SSSS95        M     SR                  U5      $ ! [
         aD  n UR	                  U SS[        S9n SnAN! [
         a  n[        U S	U 35      UeSnAff = fSnAff = f)zQConvierte hojas Excel (.xls / .xlsx) a texto tabular para el contexto del modelo.r   Nr   xlrd   r   r   openpyxl
sheet_nameheaderdtypeenginez; reintento: Hoja1iX  r   	## Hoja: z[Mostrando primeras z
 filas de ]F	r]   )indexseplineterminator)pandasr'   r(   r_   
read_excel	ExceptionRuntimeError
isinstancedictitemsfillnarb   lenheadto_csvrf   )r,   pdr/   r   read_kwargssheets	first_exc
second_excrh   max_rowsr|   dflabels                r   _read_excelr   x   s   
++


CF
f}	"	"'+tcJK &HWt3{3 fd##6"EH ,,.
YYr]Jy()r7X"BLL/zE7!LMRYYUTYJK ) 99U)  W	W]]4DS]QF 	W)M*FGYV	WWs0   D* *
E85E
E0E++E00E33E8c                    U (       a  U(       d  g[        U 5      nU(       d  gX!:X  a  g[        U5      S:  a  UR                  US S 5      (       a  g[        U5      S:  a  UR                  US S 5      (       a  gg)NFT   )r    r   r&   )
cell_value
target_rut	cell_norms      r   _cell_matches_rutr      sp    Zz*I
:!	 4 4Z_ E E
9~z44Ys^DDr!   c           	     R  ^^ [        U5      m[        T5      S:  a  S/ 4$ [        R                  " U 5      m[	        U 5      nU(       d  S/ 4$ SSKn/ n/ nU GH  nUR                  T5      R                  5       n UR                  R                  5       nUS:X  a  SO	US;   a  SOSn	SS[        S	.n
U	(       a  XS
'   UR                  " U40 U
D6n[        U[        5      (       d  SU0n/ nUR!                  5        GH  u  pUR#                  S5      nUR%                  5        GH  u  nnUR'                  5        Vs/ s H  n[        U5      R)                  5       PM     nn[+        U4S jU 5       5      (       d  MZ  / n[-        U5      S:  a_  UR.                  [-        U5      S-
     R#                  S5      R'                  5        Vs/ s H  n[        U5      R)                  5       PM     nnSU SU 3/nU(       a  [+        U5      (       a}  / n[1        U5       HK  u  nnU(       d  M  U[        U5      :  a  UU   (       a  UU   OSUS-    3nUR                  U SU 35        MM     UR                  SR3                  U5      5        O'UR                  SR3                  S U 5       5      5        UR                  SR3                  U5      5          GM     GM     U(       d  GM  UR                  U5        UR                  SU S3SR3                  U5      -   5        GM     U(       d.  SR3                  U4S jU 5       5      nS[        U5       SU 3/ 4$ SnUSR3                  U5      -   U4$ ! [         a$  nUR                  SU SU S35         SnAGM@  SnAff = fs  snf s  snf ) u   
Busca el RUT del estudiante en TODOS los Excel de Files (sin límite de 25 archivos).
Devuelve (bloque de texto para el prompt, rutas de archivos donde hubo coincidencia).
r   r   r   Nr   rx   ry   rz   r{   r   r   z### Excel: z
[Error al leer: z9. Verifique openpyxl (xlsx) y xlrd (xls) en el servidor.]c              3  L   >#    U  H  o(       d  M  [        UT5      v   M     g 7fr3   )r   )r5   vtargets     r   r8   3extract_spreadsheet_hint_for_rut.<locals>.<genexpr>   s!     QAq7,Q77s   
$$r:   r   u    — fila con RUT col_z: r]   r   c              3  6   #    U  H  o(       d  M  Uv   M     g 7fr3   r4   )r5   r   s     r   r8   r      s     *FjA11jr\   ### Archivo: rp   , c              3  `   >#    U  H#  oR                  T5      R                  5       v   M%     g 7fr3   r$   r%   r5   rI   rH   s     r   r8   r      s$     H%Q---6688%   +.zPEXCEL EN FILES (sin fila coincidente para el RUT indicado). Archivos revisados (): u   DATOS EXTRAÍDOS DE EXCEL (búsqueda directa por RUT del estudiante). Usa esto para apoderado, contacto y datos del reporte interactivo.


---

)r    r   rB   rC   rP   r   r$   r%   r'   r(   r_   r   r   r   r   rb   r   r   iterrowstolistr   r<   intiloc	enumeraterf   )rG   student_rutpathsr   sectionsmatched_filesr,   r.   r/   r   r   r   exc	file_hitsr|   r   row_idxrk   r   
row_valuesheader_valslinespairscol_idxvalr   r   r}   rH   r   s                               @@r    extract_spreadsheet_hint_for_rutr      s   
 K(F
6{Q2v
+D":.E2vH!Mt$--/	++##%C"f}VHZAZ:`dF/3tc RK(.H%]]47;7Ffd++!6*  "	$llnNJ2B "69jjlClc!fllnl
CQQQQ)+w<!# "$W)9!:!A!A"!E!L!L!N#!NA A!N   # %ZL0B;-PQ3{#3#3E(1*(="$  '[)99k'>R (0#'!}!5 
 wb%67 )> LL5!12LL*Fj*F!FG  5!127 !. -> 9  %OOmC55I8NNOi l 		H%HH##&u:,c%:
 	
	O  M&&x00-??o  	OOcU"4SE :J J 	 D#s%   ;A-M.:#N
#N$
.
N8NNc                    U R                   R                  5       nU[        ;   a  [        U 5      $ US:X  a  [	        U 5      $ US:X  a  [        U 5      $ U[        ;   a  [        U 5      $ g)Nr   r   r   )r'   r(   r)   rV   rn   rv   r+   r   )r,   r/   s     r   extract_file_textr     sb    
++


C
t$$
g~$
f}
%%4  r!   c                  ^ [         R                  " U 5      m[        U 5      n[        U 5      nU Vs/ s H(  oDR                  R                  5       [        ;   d  M&  UPM*     nnSnU(       a"  UR                  5       (       a  [        X5      u  pgU(       d  U(       d  gU Vs/ s H!  oDR                  T5      R                  5       PM#     nn/ n	Sn
SnU(       a  U	R                  U5        U
[        U5      -  n
U GH  nUR                  T5      R                  5       nUR                  R                  5       n [        U5      R                  5       nU(       d  U[        [         -  [        -  ;   a  SnOM{  [        U5      ["        :  a  US["         S-   nS	U S
U 3nU
[        U5      -   [$        :  a(  [$        U
-
  nUS:  a  U	R                  USU S-   5          O)U	R                  U5        U
[        U5      -  n
US-  nGM     U	(       d  gSnU(       aL  SR'                  U4S jUSS  5       5      n[        U5      S-
  nUS:  a	  USU S3-  nS[        U5       SU 3nS[        U5       S[(         S3SR'                  U5      -   U-   S-   nUSR'                  U	5      -   U4$ s  snf s  snf ! [         a  nSU S3n SnAGNsSnAff = f)z
Devuelve (bloque de texto para el prompt, cantidad de archivos incluidos).
Solo archivos subidos en Files; excluye plantillas en documentos/.
r   )r   r   r   z[No se pudo leer el archivo: r   Nu'   [Archivo sin texto extraíble o vacío]u   
… [contenido truncado]r   rp      u   
… [contexto total truncado]r:   r   c              3  `   >#    U  H#  oR                  T5      R                  5       v   M%     g 7fr3   r   r   s     r   r8   ,build_agent_files_context.<locals>.<genexpr>S  s(       
4JqMM$((**4Jr   
   u    … (+u    más)z
Excel en Files (r   u   ARCHIVOS DE CONTEXTO (subidos en Files del agente). Cuando las instrucciones pidan revisar, buscar o usar archivos adjuntos, utiliza ÚNICAMENTE el contenido de estos archivos como fuente.
Índice de archivos elegibles (z; hasta z priorizados en el cuerpo): r]   r   )rB   rC   rN   rK   r'   r(   r+   r   r   r$   r%   rb   r   r   r   r)   r*   MAX_CHARS_PER_FILEMAX_TOTAL_CHARSrf   rM   )rG   r   r   	all_pathsrI   spreadsheet_paths	rut_block_matchedindex_linesr   total_charsincludedr,   r.   r/   contentr   block	remaining
excel_noteexcel_namesextrar}   rH   s                          @r   build_agent_files_contextr     s    
+D#J/E+J7I$-]Iq1AE\1\I]I{((**>zW	;DE9a==&//19KEHKH	"s9~%t$--/kk!	='-335G &);;>UUUCw<,,1125QQGuD	2U#o5'+5I3jy 14U UVs5z!A5 8 Jii  
4Ecr4J 
 
 %&+19WUG622K)#.?*@)A[MR
	* +.k*:); <7		9
 ))K
 	! 	 	  M&&x00(::K ^ F  	=5cU!<G	=s)   %J#J#!(J(7J--
K7KK)r   r_   returnr_   )r,   r   r-   r   r   bool)r,   r   r   ztuple[int, str])rG   r_   r   z
list[Path])r,   r   r   r_   )r   r_   r   r_   r   r   )rG   r_   r   r_   r   ztuple[str, list[str]]r3   )rG   r_   r   z
str | Noner   ztuple[str, int])__doc__
__future__r   r   pathlibr   app.backend.utilsr   rB   rM   r   r   r)   r*   r+   r=   r    r0   r>   rK   rN   rP   rV   rn   rv   r   r   r   r   r   r4   r!   r   <module>r      s    Y " 	  9 	   v& 4  Bb5?>$%P U@p
 #P;P;P; P;r!   