o
    Ng	2                     @   s>  d dl mZmZmZmZmZmZmZ d dlm	Z	m
Z
mZ d dlmZ d dlm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 d dlmZ d d	lT d d
lmZ d dlmZ d dl m!Z" d dl#m$Z$m%Z%m&Z&m'Z' d dl(m)Z) d dl*m+Z+ e Z,e
 Z-e  e.d Z/e0e.dd Z1e0e.dd Z2e Z3e,4dedededededee-fdede5de0de0de0defddZ6e,7dee-fde5de)j8defddZ9e,:d ee-fde5defd!d"Z;e,j<d#e)j=d$ee-fde5defd%d&Z>e,<d'd(e0fd)d*Z?d1d,e0d-e0d.e5fd/d0Z@dS )2    )
UploadFileFileForm	APIRouterDependsHTTPExceptionstatus)OAuth2PasswordRequestForm
HTTPBearerHTTPAuthorizationCredentials)JSONResponse)load_dotenvN)OpenAI)HybridSearch)	S3Service)*)process_document_celery)AsyncResult)UserFolder	DocumentsChatHistoryCOLLECTION_NAMEDB_PATH/STORAGE_PATHz/add.
doc_select	folder_iddoc_namedoc_urlmetadatacredentialsc                    s0  t  }|j}t||}|r&zt|}W n tjy%   td Y S w | d kr0|s0tdS | r;| j	s;|s;tdS |
ttj|jktj|k }	|	sUtdS ttt|j d t|	j }
tj|
dd z| j	rtj|
| j	}tj| j	d }t|d	}||  I d H  W d    n1 sw   Y  | jd
 tj| j	d
 }nCtj|dd }tj|d }t |}tj|
| | }t!||}|j"dks|j"dkrt|j#}|$d}t||j"W S t |}t% }|&|
|| r| nd  |
 d| | }|'|}|r8t(||||)d|d|r&|nd d}|*| |+  |,| t-.|||||
||jt/|	j|j0
}|ra|j0rd|j0|||j1|j2d}t3d|W S W d S W d S  t4y } z$|
t(t(j0|j0k }d|_2|+  |5  t6ddt| dd }~ww )NzInvalid JSON format in metadataz7Please provide either a document file or a document URLz8Please provide either a document file or a document URL.zFolder ID does not exist.r   Texist_ok   wbr   .    message
Processing)r   r   sanitized_namedocument_typer   
doc_statusdoc_metadata)doc_idr   r   task_idr.   z1Document uploaded and is in queue for processing.FailedzFailed to save file: status_codedetail)7dbaseSessionLocalr!   authget_current_userjsonloadsJSONDecodeErrorerrorResponsefilenamequeryr   filteruser_idr   firststrUPLOAD_FOLDER	user_coder,   osmakedirspathjoinsplitextopenwritereadfileseekbasenamesplitreplace_special_charactersdownload_filer4   bodygetr   upload_objectget_object_urlr   lstripaddcommitrefreshr   delaycollection_namer0   idr.   successReponse	Exceptionrollbackr   )r   r   r   r   r    r!   dbtokenuserfolder
upload_dirdocument_pathfile_extensionfdocument_namer,   download_responseparsed_bodyr*   
s3_servicefile_keydocument_urlnew_documenttaskdocument_dataeupdate_status ru   0/var/www/html/answerous_api/routers/chromadoc.py
upload_pdf    s   
( 



	
"	rw   z/rename/{doc_id}r0   datac              
      s  t  }|j}t||}zh	 |jr|j nd}|s!tdW S |t	
t	j|k
tj|jk }|r<tdW S |t	
t	j| k }|sQtddW S |j|_|  |t	
t	j| k }	||	 tdtj|	 W S  ty }
 ztddt|
 d	d }
~
ww )
N zDocument name is required.z,Cannot update document with duplicate names.Document does not exist.  zDocument successfully updated.r)   Something went wrong: r3   )r6   r7   r!   r8   r9   r   stripr=   r?   r   r@   r   rA   rB   r0   rZ   r[   r_   schemasDocumentResponsefrom_ormdictr`   r   rC   )r0   rx   r!   rb   rc   rd   rj   existing_docdocupdated_datars   ru   ru   rv   updateDocName   sD   (
r   z/delete/{doc_id}c              
      s  t  }|j}t||}z|ttj| k	 }|s$t
ddW S |ttj|jk	 }|jrtt||j}||j tdd t|j d t|j }| d|j d|j }	zt|	 td|	 d W n9 ty   td|	 d Y n) ty   td	|	 d
 Y n ty }
 ztd|
  W Y d }
~
nd }
~
ww t }||	 || |  t dd W S  ty }
 zt!ddt|
 dd }
~
ww )Nrz   r{   r   r   r&   zFile 'z' has been deleted.z' not found.z%Permission denied: Unable to delete 'z'.zAn error occurred: zDocument deleted successfullyr)   r|   r3   )"r6   r7   r!   r8   r9   r?   r   r@   r0   rB   r=   r   r   document_uuidr   r]   r,   delete_collection_by_uuidrF   getenvrC   rE   r-   removeprintFileNotFoundErrorPermissionErrorr`   r   delete_filedeleterZ   r_   r   )r0   r!   rb   rc   rd   documentre   hsUPLOAD_PATH	file_pathrs   rm   ru   ru   rv   deleteDocument   sP   &


r   z/list/{folder_id})response_modelc              
      s   t  }|j}t||}z7|ttj	t
j|jk	tj| k }|s4t|dkr4tdW S dd |D }tddd |D W S  ty\ } ztddt| d	d }~ww )
Nr   zNo any document found.c                 S   s   g | ]}t j|qS ru   )r~   r   r   .0r   ru   ru   rv   
<listcomp>   s    z!get_documents.<locals>.<listcomp>z Documents retrieved successfullyc                 S   s   g | ]}|  qS ru   )r   r   ru   ru   rv   r      s    r)   r|   r3   )r6   r7   r!   r8   r9   r?   r   rI   re   r@   r   rA   r   alllenr=   r_   r`   r   rC   )r   r!   rb   rc   rd   	documentsrr   rs   ru   ru   rv   get_documents   s&   0r   z/task/{task_id}r1   c                    s    t | }|jt|j|jdS )N)r   result	traceback)r   r   rC   r   r   )r1   task_resultru   ru   rv   get_task_status  s   r      url	save_path
chunk_sizec              
   C   s  zU|  dstdW S tj| ddd}|  t|jdd}tjtj	
|dd t|d	}|j|d
D ]	}|r@|| q7W d   n1 sKw   Y  td|W S  tjjys } ztdt| dW  Y d}~S d}~w ty } ztd| dW  Y d}~S d}~ww )a  
    Downloads a file from the specified URL and saves it to the given path.
    
    Args:
        url (str): The URL of the file to download.
        save_path (str): The local path where the file should be saved.
        chunk_size (int, optional): The chunk size for streaming data. Defaults to 1024.
    
    Returns:
        str: The path of the saved file.
    
    Raises:
        ValueError: If the URL is invalid or the response status is not successful.
        Exception: For other errors during download or file saving.
    )zhttp://zhttps://z9Invalid URL. URL must start with 'http://' or 'https://'.T
   )streamtimeoutzcontent-lengthr   r"   r%   )r   Nry   z"Failed to download file from URL: r(   z)An error occurred while saving the file: r)   )
startswithr=   requestsrU   raise_for_statusintheadersrF   rG   rH   dirnamerK   iter_contentrL   r_   
exceptionsRequestExceptionrC   r`   )r   r   r   response
total_sizerN   chunkrs   ru   ru   rv   rS     s,   


 rS   )r   )Afastapir   r   r   r   r   r   r   fastapi.securityr	   r
   r   fastapi.responsesr   dotenvr   r   rF   r:   uuiddocx2pdfopenair   dependencies.HybridSearchr   dependencies.awsutilsr   dependencies.helpercelery_workerr   celery.resultr   db_config.databasedatabaser6   db_config.modelsr   r   r   r   db_config.schemasr~   db_config.authr8   routersecurityr   r]   rC   	DB_FOLDERrD   openai_clientpostr   rw   putDocumentr   r   r   rU   DocumentListResponser   r   rS   ru   ru   ru   rv   <module>   sn   $ v"&.	