o
    z­jÉ7  ã                   @   sò  d Z ddlmZmZmZmZmZmZ ddlm	Z	m
Z
 ddlZddlZddlZddlmZmZ ddlmZmZmZmZ ddlZddlZddlZddlmZmZmZmZ eƒ ZG dd	„ d	eƒZG d
d„ deƒZ G dd„ deƒZ!e "d¡edƒfdefdd„ƒZ#e "d¡eddd�eddd�fde$de$fdd„ƒZ%e "d¡edƒeddd�fdede$fdd„ƒZ&e "d¡edƒeddd�fdede$fd d!„ƒZ'ej"d"e d#d$�edƒfd%efd&d'„ƒZ(ej"d(d#d)�edƒfd%e!fd*d+„ƒZ)ej*d,d#d)�d-e$fd.d/„ƒZ+dS )0z‡
Chat assistant API endpoints for CropPilot
This module provides endpoints for interacting with the general-purpose AI chat assistant.
é    )Ú	APIRouterÚHTTPExceptionÚDependsÚBodyÚFileÚ
UploadFile)ÚStreamingResponseÚFileResponseN)Ú	BaseModelÚField)ÚOptionalÚDictÚAnyÚList)Ú	AgentTypeÚMessageÚcoordinatorÚcontext_protocolc                   @   s¨   e Zd ZU dZedddd�Zeed< eddd	�Ze	e ed
< eddd	�Z
e	e ed< eddd	�Ze	e ed< eddd	�Ze	eeef  ed< eddd	�Ze	e ed< dS )Ú	ChatInputzModel for chat input data.é   z$User's message to the chat assistant)Ú
min_lengthÚdescriptionÚmessageNz'Session ID for continuing conversations)r   Ú
session_idÚgeminiz'Model to use (only gemini is supported)ÚmodelÚenzLanguage code (en, hi, mr)ÚlanguagezAdditional context for the chatÚcontext_dataÚgeneral_assistantz"Expert agent to handle the messageÚagent)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚstrÚ__annotations__r   r   r   r   r   r   r   r    © r'   r'   ú9/var/www/html/CropPilot/backend/app/api/endpoints/chat.pyr      s   
  r   c                   @   s.   e Zd ZU dZeed< eed< dZeed< dS )ÚChatResponsezModel for chat response dataÚresponser   zgemini-2.5-flashÚ
model_usedN)r!   r"   r#   r$   r%   r&   r+   r'   r'   r'   r(   r)      s
   
 r)   c                   @   s   e Zd ZdZdS )ÚStreamChatInputz3Model for streaming chat input, extending ChatInputN)r!   r"   r#   r$   r'   r'   r'   r(   r,   $   s    r,   z/speech-to-text.Úfilec                 Ã   s.  �zddl }W n ty } ztddd�|‚d}~ww | ¡ }tjddd��g}| |  ¡ I dH ¡ | ¡  | 	|j
¡�B}| |¡}z| |¡}d	|iW W  d  ƒ W  d  ƒ S  |jyg   td
dd�‚ |jy| } z	tdd|› �d�‚d}~ww 1 s€w   Y  W d  ƒ dS 1 s�w   Y  dS )zf
    Convert uploaded speech audio to text using SpeechRecognition.
    Accepts WAV or MP3 files.
    r   Né÷  zFSpeechRecognition is not installed. Run: pip install SpeechRecognition©Ústatus_codeÚdetailFz.wav)ÚdeleteÚsuffixÚtexté�  zCould not understand audio.éô  zSTT service error: )Úspeech_recognitionÚImportErrorr   Ú
RecognizerÚtempfileÚNamedTemporaryFileÚwriteÚreadÚflushÚ	AudioFileÚnameÚrecordÚrecognize_googleÚUnknownValueErrorÚRequestError)r-   ÚsrÚeÚ
recognizerÚ
temp_audioÚsourceÚaudior4   r'   r'   r(   Úspeech_to_text(   s>   €þý€ÿ

üý€ÿù"ýrK   z/text-to-speechT)Úembedr   r4   r   c              
   Ã   sœ   �zddl m} W n ty } ztddd�|‚d}~ww z|| |d�}t ¡ }| |¡ | d¡ t|dd	�W S  t	yM } z	td
d|› �d�‚d}~ww )zN
    Convert text to speech audio using gTTS and return as an MP3 stream.
    r   )ÚgTTSr.   z,gTTS is not installed. Run: pip install gTTSr/   N)r4   Úlangz
audio/mpeg©Ú
media_typer6   zTTS error: )
ÚgttsrM   r8   r   ÚioÚBytesIOÚwrite_to_fpÚseekr   Ú	Exception)r4   r   rM   rF   ÚttsÚmp3_fpr'   r'   r(   Útext_to_speechC   s,   €þý€ÿ

€ÿrY   z/sttzen-USc           
   
   Ã   s°   �zddl m} W n ty } ztddd�|‚d}~ww | ¡ }|  ¡ I dH }|j|d�}|j|jjj	|dd	d
�}|j
||d�}d dd„ |jD ƒ¡}	|	sTtddd�‚d|	iS )z]
    Accepts an audio file and returns the transcript using Google Cloud Speech-to-Text.
    r   ©Úspeechr.   zYGoogle Cloud Speech-to-Text client is not available. Run: pip install google-cloud-speechr/   N©Úcontentr   T©ÚencodingÚlanguage_codeÚaudio_channel_countÚenable_automatic_punctuation©ÚconfigrJ   Ú c                 S   ó   g | ]}|j d  j‘qS ©r   ©ÚalternativesÚ
transcript©Ú.0Úresultr'   r'   r(   Ú
<listcomp>n   ó    zstt.<locals>.<listcomp>r5   úCould not transcribe audio.rj   )Úgoogle.cloudr[   r8   r   ÚSpeechClientr=   ÚRecognitionAudioÚRecognitionConfigÚAudioEncodingÚLINEAR16Ú	recognizeÚjoinÚresults)
r-   r   r[   rF   ÚclientÚaudio_contentrJ   rd   r*   rj   r'   r'   r(   ÚsttX   s4   €þý€ÿür|   z/speech-chatc              
   Ã   s8  �zddl m} ddl m} W n ty" } ztddd�|‚d}~ww | ¡ }|  ¡ I dH }|j|d�}|j|jj	j
|d	d
d�}|j||d�}	d dd„ |	jD ƒ¡}
|
sZtddd�‚t|
|d�}t|ƒI dH }|j}| ¡ }|j|d�}|j||jjd�}|j|j	jd�}|j|||d�}t |j¡ d¡}|
||dœS )z›
    Accepts an audio file, transcribes it with Google Cloud STT, sends to chat AI, and returns the response as audio and text using Google Cloud TTS.
    r   rZ   )Útexttospeechr.   zhGoogle Cloud Speech/TTS is not available. Run: pip install google-cloud-speech google-cloud-texttospeechr/   Nr\   r   Tr^   rc   re   c                 S   rf   rg   rh   rk   r'   r'   r(   rn   Š   ro   zspeech_chat.<locals>.<listcomp>r5   rp   )r   r   )r4   )r`   Ússml_gender)Úaudio_encoding)ÚinputÚvoiceÚaudio_configzutf-8)Úuser_transcriptÚai_textÚai_audio_base64)rq   r[   r}   r8   r   rr   r=   rs   rt   ru   rv   rw   rx   ry   r   Úchat_messager*   ÚTextToSpeechClientÚSynthesisInputÚVoiceSelectionParamsÚSsmlVoiceGenderÚNEUTRALÚAudioConfigÚMP3Úsynthesize_speechÚbase64Ú	b64encoder{   Údecode)r-   r   r[   r}   rF   Ú
client_sttr{   rJ   rd   r*   r4   Ú
chat_inputÚchat_responser„   Ú
tts_clientÚsynthesis_inputr�   r‚   Útts_responseÚaudio_base64r'   r'   r(   Úspeech_chats   sX   €þý€ÿüþÿýr™   z/messageéÈ   )Úresponse_modelr0   r“   c           
   
   Ã   sJ  �zx| j p
tt ¡ ƒ}t || j| jdœ| jpi ¥¡ t	j
t	jt	jt	jdœ}| | jp,dt	j
¡}t	j
dt	jdt	jdt	jdi}| ||t	j
 ¡}t tt	j|| j| j|dœd	|| jd
œd�¡I dH }t|jtƒrj|jn|j dd¡}t||| jd�W S  ty‡ } z|‚d}~w ty¤ }	 ztd|	› �ƒ tddt|	ƒ› �d�‚d}	~	ww )zŠ
    Send a message to the AI chat assistant and get a response.
    This endpoint handles regular (non-streaming) chat interactions.
    ©r   Úlast_message)r   Úmarket_expertÚweather_advisorÚcrop_doctorr   zFYou are CropPilot, your general agriculture AI assistant across India.zrYou are MarketExpert: Provide expert analysis and advice on agricultural markets, prices, and trends across India.zuYou are WeatherAdvisor: Provide expert advice on weather patterns, forecasts, and climate impact on farming in India.zmYou are CropDoctor: Provide expert advice on crop diseases, soil, and crop management for Indian agriculture.)r   r   Úsystem_promptÚchat)r   r   ©ÚsenderÚreceiverr]   Úmessage_typeÚcontextNr*   z(No response))r*   r   r+   z,Unexpected error in /chat/message endpoint: r6   ú#An internal server error occurred: r/   )r   r%   ÚuuidÚuuid4r   Úset_contextr   r   r   r   ÚCHAT_ASSISTANTÚMARKET_EXPERTÚWEATHER_ADVISORÚCROP_DOCTORÚgetr    r   Úroute_messager   ÚCOORDINATORr   Ú
isinstancer]   r)   r   rV   Úprint)
r“   r   Ú	agent_mapÚselected_agentÚsystem_promptsr¡   r   Úresponse_textÚhttp_excrF   r'   r'   r(   r†   ª   sZ   €þýüüýþ÷
ÿ €€ýr†   z/stream)r0   c              
   ƒ   s  �z^| j p
tt ¡ ƒ}t || j| jdœ| jpi ¥¡ t	 
ttjtj| j| jdœdd|id�¡I dH }|r:d|jv rK|rC|j dd¡nd	}td
|d�‚|j dd¡‰ ‡ fdd„}t|ƒ dd�W S  tym } z|‚d}~w tyŠ } ztd|› �ƒ tddt|ƒ› �d�‚d}~ww )a!  
    Stream a chat response from the AI assistant.
    This endpoint provides a streaming response for a more interactive experience.
    
    Note: This is a simplified implementation. In a production environment,
    you would implement actual streaming with the Gemini or Groq API.
    rœ   )r   r   r¢   r   r£   NÚerrorz%Unknown error processing chat messagezNo response from chat agentr.   r/   r*   z&Sorry, I couldn't generate a response.c                    s^   �t ˆ ƒ} td| d ƒ}td| |ƒD ]}t|| | ƒ}ˆ ||… }|V  t d¡I d H  qd S )Né   é   r   gš™™™™™©?)ÚlenÚmaxÚrangeÚminÚasyncioÚsleep)Útotal_lengthÚ
chunk_sizeÚiÚendÚchunk©r¸   r'   r(   Úfake_stream_generator  s   €øz*stream_chat.<locals>.fake_stream_generatorzapplication/x-ndjsonrO   z+Unexpected error in /chat/stream endpoint: r6   r¨   )r   r%   r©   rª   r   r«   r   r   r   r   r±   r   r   r²   r¬   r   r]   r°   r   r   rV   r´   )r“   r   r   rº   rÉ   r¹   rF   r'   rÈ   r(   Ústream_chatê   sJ   €	þýþø
ÿþ€€ýrÊ   z/history/{session_id}r   c           	   
   Ã   sö   �z[d| › �}t  |¡}|s| g dœW S g }|D ]>}| d¡}t|tƒr6ddlm}m} |j||jd� 	¡ }| 
|d › dt|tƒrHtt|ƒƒn|› �|d |d	 |d
œ¡ q| |dœW S  tyz } ztd|› �ƒ tddt|ƒ› �d�‚d}~ww )z‚
    Get the chat history for a specific session.
    This is useful for continuing conversations or displaying chat history.
    Úchat_history_)r   ÚmessagesÚ	timestampr   )ÚdatetimeÚtimezone)ÚtzÚroleÚ-r]   )ÚidrÑ   r]   rÍ   zError retrieving chat history: r6   r/   N)r   Úget_contextr°   r³   ÚfloatrÎ   rÏ   ÚfromtimestampÚutcÚ	isoformatÚappendÚintrV   r´   r   r%   )	r   Úchat_history_keyÚchat_historyrÌ   ÚitemrÍ   rÎ   rÏ   rF   r'   r'   r(   Úget_chat_history1  s0   €



&
ü€þrÞ   ),r$   Úfastapir   r   r   r   r   r   Úfastapi.responsesr   r	   rR   r�   r:   Úpydanticr
   r   Útypingr   r   r   r   r©   rÁ   ÚjsonÚapp.core.multi_agentr   r   r   r   Úrouterr   r)   r,   ÚpostrK   r%   rY   r|   r™   r†   rÊ   r°   rÞ   r'   r'   r'   r(   Ú<module>   s<     	*&&6?F