o
    z­j7  ã                   @   sØ   d dl Z d dlmZmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ e je jdd� e  e¡Zeƒ Zeeƒfd	ed
efdd„Zejdeddddgd�eeƒeddd�dœd	eded
efdd„ƒZdS )é    N)Ú	APIRouterÚDependsÚ
UploadFileÚFileÚHTTPException)ÚUnidentifiedImageError)Úget_disease_prediction)Úget_settingsÚSettings)ÚDiseaseResponsez4%(asctime)s - %(name)s - %(levelname)s - %(message)s)ÚlevelÚformatÚsettingsÚreturnc                 Ã   s,   �| j r	| j dkrt d¡ tddd�‚| S )z;Dependency to get settings and validate necessary API keys.ÚYOUR_GEMINI_API_KEY_NOT_SETz-Gemini API Key is not configured in settings.é÷  zÅGemini is not configured. Set GEMINI_API_KEY or GOOGLE_API_KEY in backend/.env (or the project root .env), restart the API server, then try again. Create a key at https://aistudio.google.com/apikey©Ústatus_codeÚdetail)ÚGEMINI_API_KEYÚloggerÚerrorr   )r   © r   ú</var/www/html/CropPilot/backend/app/api/endpoints/disease.pyÚget_validated_settings   s   €
ýr   z/detectéÈ   zDetect Crop Disease from ImagezUpload a plant image to get an AI-based analysis of potential diseases or pests. Supported formats include JPEG, PNG, WEBP etc.zDisease Detection)Úresponse_modelr   ÚsummaryÚdescriptionÚtags.zImage file of the plant.)r   )r   Úfiler    c                 Ã   sº  �t  d|j› �¡ |jr|j d¡s,t  d|j› d|j› d�¡ tdd|j› d�d	�‚| jd
 d
 }d}z�zW| ¡ I dH }|sOt  d|j› �¡ tddd	�‚t	|ƒ}||krzt  d|› d|j› d|› d�¡ tddt
|d dƒ› d| j› d�d	�‚t  d|j› dt
|d dƒ› d�¡ W n% ty² } zt jd|j› d|› �dd� tddt|ƒ› �d	�‚d}~ww W | ¡ I dH  t  d|j› d �¡ n| ¡ I dH  t  d|j› d �¡ w z>t  d!|j› d"�¡ t|ƒI dH }t  d#|j› d�¡ | d$¡�rt  d%|j› d|› �¡ td&|d	�‚t||j�pd'd(�W S  t�y.   t  d)|j› d*�¡ tdd+d	�‚ t�y< } z|‚d}~w t�y\ } zt jd,|j› d|› �dd� td-d.d	�‚d}~ww )/aÏ  
    Handles plant image uploads, validates them, sends for AI analysis,
    and returns the disease prediction results.

    Args:
        settings: Injected application settings.
        file: The uploaded image file.

    Returns:
        A DiseaseResponse object containing the analysis and filename.

    Raises:
        HTTPException: For various errors like invalid file type, size,
                       AI service errors, or internal server errors.
    z-Received request to detect disease for file: zimage/zInvalid file type 'z' for file 'z'.i�  zInvalid file type: 'zA'. Please upload a standard image format (JPEG, PNG, WEBP, etc.).r   i   NzEmpty file uploaded: z:Received an empty image file. Please upload a valid image.zFile too large: z bytes for file 'z'. Limit is z bytes.i�  zFile is too large (i   é   z MB). Maximum size allowed is zMB.zFile 'z' size validated (z MB).zError reading uploaded file 'z': T)Úexc_infozCould not read uploaded file: z	' closed.zSending image 'z' to AI service...z'Received AI analysis successfully for 'zError:z*AI Service returned an error message for 'r   Úunknown_filename)ÚanalysisÚfilenamez'Cannot identify image format for file 'z&'. It might be corrupt or unsupported.zTCould not identify image format. Please ensure it's a standard, non-corrupted image.z)Unexpected error during AI analysis for 'iô  zTAn internal server error occurred while analyzing the image. Please try again later.)r   Úinfor%   Úcontent_typeÚ
startswithÚwarningr   ÚMAX_FILE_SIZE_MBÚreadÚlenÚroundÚ	Exceptionr   ÚstrÚcloseÚdebugr   r   r   )r   r    Úmax_size_bytesÚimage_bytesÚ	file_sizeÚeÚprediction_resultÚhttp_excr   r   r   Údetect_crop_disease'   st   €þ þ(€ýþÿ
þ€þ€ûr8   )ÚloggingÚfastapir   r   r   r   r   ÚPILr   Úapp.core.ai_servicesr   Úapp.core.configr	   r
   Úapp.models.disease_modelr   ÚbasicConfigÚINFOÚ	getLoggerÚ__name__r   Úrouterr   Úpostr8   r   r   r   r   Ú<module>   s6   
ù
ýþýü