ó
     :h,  ã                   ó¨  • S SK Jr  S SKJrJrJr  S SKJr  S SK	r	S SK
Jr  SSKJr  \(       a  S SKJr  \" 5       r \R"                  (       aO  \R"                  S:w  a?  \R$                  " \R"                  S	9  \R&                  " S
5      r\R&                  " S
5      rO\" S5        SrSr  \R2                  (       a#  \R2                  S:w  a  \" \R2                  S	9rSrO\" S5        Sr S\S\4S jrSSS\4S jrSS\S\S\4S jjr S\!S\4S jr"g! \ a  r\" S\ 35        SrSr SrCNƒSrCff = f! \ a  r\" S\ 35        Sr SrCNcSrCff = f)é    N)ÚGroqÚRateLimitErrorÚAPIError)ÚImage)ÚTYPE_CHECKINGé   )Úget_settings)Ú
YieldInputÚYOUR_GEMINI_API_KEY_NOT_SET)Úapi_keyzgemini-1.5-flashzJAI_SERVICES: Gemini API key not configured. Gemini features will not work.z'AI_SERVICES: Error configuring Gemini: ÚYOUR_GROQ_API_KEY_NOT_SETzllama3-8b-8192zFAI_SERVICES: Groq API key not configured. Groq features will not work.z%AI_SERVICES: Error configuring Groq: Úimage_bytesÚreturnc              ƒ   ó&  #   • [         (       d  g [        R                  " [        R                  " U 5      5      nSn[         R                  X!/5      nUR                  $ ! [         a&  n[        SU 35        S[        U5       3s SnA$ SnAff = f7f)zF
Analyzes an image using Gemini Vision model to detect crop diseases.
z-Error: Gemini Vision model is not configured.aÞ  Analyze the attached image of a plant leaf from the Baramati, Maharashtra region.
        Identify potential diseases or pests. Describe the visible symptoms clearly.
        Suggest 1-2 brief, practical, and sustainable management/treatment options suitable for a local farmer.
        If the image is unclear or not a plant, state that clearly.
        Format the response clearly, perhaps using bullet points for symptoms and suggestions.
        Respond in English.
        z$Error in Gemini disease prediction: z#Error analyzing image with Gemini: N)
Úgemini_vision_modelr   ÚopenÚioÚBytesIOÚgenerate_contentÚtextÚ	ExceptionÚprintÚstr)r   ÚimgÚpromptÚresponseÚes        ÚB/home/sneha/Desktop/shweta/404/404/backend/app/core/ai_services.pyÚget_disease_predictionr   1   sƒ   é € ÷ ÒØ>ð>Ü�jŠjœŸš KÓ0Ó1ˆð	ˆô '×7Ñ7¸¸ÓFˆð �}‰}Ðøäó >ÜÐ4°Q°CÐ8Ô9à4´S¸³V°HÐ=Õ=ûð>üs5   ‚B�AA ÁBÁ
BÁ(B	ÂBÂBÂ	BÂBÚyield_inputr
   c              ƒ   ó   #   • [         (       d  g SnSU SU R                   SU R                   SU R                   SU SU R                  =(       d    S	 S
U R
                  =(       d    S	 S3n[         R                  R                  R                  SSS.SUS./[        SSS9nUR                  S   R                  R                  nUR                  5       $ ! [         a    [        S5         g[          a&  n[        SU 35        S[#        U5       3s SnA$ SnAf[$         a&  n[        SU 35        S[#        U5       3s SnA$ SnAff = f7f)z@
Generates a yield estimate using Groq based on farmer's input.
ú%Error: Groq client is not configured.zBaramati, Maharashtra, Indiaz1Act as an agricultural assistant for a farmer in z9.
        Based on the following inputs:
        - Crop: z
        - Area: z
        - Region Details: z	 (within z)
        - Soil Type: zNot specifiedz$
        - Recent/Expected Weather: as  

        Provide a realistic estimated yield range (e.g., in quintals per acre or tonnes per hectare, specify the unit clearly).
        Briefly explain the key factors (like weather, soil, crop type in this region) influencing this estimate in 2-3 short bullet points.
        Keep the explanation simple and practical for a farmer.
        Respond in English.
        Úsystemz|You are a helpful agricultural assistant providing yield estimates for farmers in the Baramati region of Maharashtra, India.©ÚroleÚcontentÚuserg333333ã?é–   ©ÚmessagesÚmodelÚtemperatureÚ
max_tokensr   z4Error in Groq yield prediction: Rate limit exceeded.zHError: The prediction service is currently busy. Please try again later.z Error in Groq yield prediction: z-Error communicating with prediction service: Nz+Unexpected error in Groq yield prediction: zBAn unexpected error occurred while generating the yield estimate: )Úgroq_clientÚ	crop_typeÚareaÚregionÚsoilÚweatherÚchatÚcompletionsÚcreateÚgroq_chat_model_idÚchoicesÚmessager&   Ústripr   r   r   r   r   )r    Úlocation_contextr   Úchat_completionÚresultr   s         r   Úget_yield_estimater>   V   sŠ  é € ÷ Š;Ø6ð+]à9ÐØFÐGWÐFXð Yà×&Ñ&Ð'ð (Ø×!Ñ!Ð"ð #Ø&×-Ñ-Ð.¨iÐ8HÐ7Ið JØ!×&Ñ&×9¨/Ð:ð ;$Ø$/×$7Ñ$7×$J¸?Ð#Kð L	ðˆô &×*Ñ*×6Ñ6×=Ñ=ð %ð  ^ñð
 #Ø%ñð	ô %ØØð >ð 
ˆð !×(Ñ(¨Ñ+×3Ñ3×;Ñ;ˆØ�|‰|‹~Ðøäó ZÜÐDÔEÙYÜó HÜÐ0°°Ð4Ô5Ø>¼sÀ1»v¸hÐGÕGûÜó ]ÜÐ;¸A¸3Ð?Ô@ØSÔTWÐXYÓTZÐS[Ð\Õ\ûð]üsY   ‚E�CC ÃEÃEÃ,EÃ.	EÃ7DÄEÄEÄEÄ%EÅ EÅEÅEÅEÚ
transcriptÚlanguagec           	   ƒ   ó  #   • [         (       d  gSSSS.nUR                  US5      nSn SU SU  S	U S
U S3	n[         R                  R                  R	                  SSU S3S.SUS./[
        SSS9nUR                  S   R                  R                  nUR                  5       $ ! [         a"    [        S5        US:X  a  SO	US:X  a  SOSnUs $ [         aP  n	[        SU	 35        US:X  a  S[        U	5       3O!US:X  a  S[        U	5       3OS[        U	5       3nUs Sn	A	$ Sn	A	f[         aP  n	[        S U	 35        US:X  a  S![        U	5       3O!US:X  a  S"[        U	5       3OS#[        U	5       3nUs Sn	A	$ Sn	A	ff = f7f)$zW
Processes a voice transcript using Groq to understand intent and generate a response.
r"   ÚEnglishÚHindiÚMarathi)ÚenÚhiÚmra]  
    The FarmGenius app can:
    1. Analyze an uploaded image of a plant to detect diseases (triggered by asking about the 'last image' or 'this picture').
    2. Predict crop yield based on inputs like crop type, area, region, soil, weather.
    3. Provide mock information about local market prices for crops like Wheat and Onion in Baramati.
    z‰You are the voice interface for the FarmGenius agricultural app, assisting a farmer in Baramati, Maharashtra.
        The user, speaking z	, said: "z%"

        App Capabilities:
        a¨  

        Your tasks:
        1. Understand the user's intent based on their statement. Does the user want to:
            - Get analysis of the last uploaded image?
            - Ask for a yield prediction (they might mention crop, area etc.)?
            - Ask about market prices (they might mention crop names)?
            - Something else (greet, ask for help)?
        2. Generate a concise and helpful response **in a÷  **.
        3. If the intent is clear and relates to an app capability:
            - For image analysis: Respond like "Okay, analyzing the last uploaded image..." or ask for the image if needed. (The actual analysis happens separately).
            - For yield prediction: If they provided details, acknowledge them. If not, ask for necessary details like crop type, area, etc.
            - For market prices: Provide the mock data if they ask for Wheat/Onion prices in Baramati, otherwise state which prices are available.
        4. If the intent is unclear or unrelated to app capabilities, politely state what the app can do or ask for clarification.
        5. Keep the response relatively short and easy to understand for a voice interaction.
        r#   zUYou are the FarmGenius voice assistant for farmers in Baramati. Respond concisely in Ú.r$   r'   gffffffæ?éd   r)   r   z4Error in Groq voice processing: Rate limit exceeded.rF   z3Seva abhi vyast hai, kripya baad mein prayas karen.rG   u[   Seva sadhya vyasta à¤†à¤¹à¥‡, à¤•à¥ƒà¤ªà¤¯à¤¾ à¤¨à¤‚à¤¤à¤° à¤ªà¥�à¤°à¤¯à¤¤à¥�à¤¨ à¤•à¤°à¤¾.z6The service is currently busy. Please try again later.z Error in Groq voice processing: z"Seva se sampark karne mein truti: zSeveshi sampark karnyat truti: z&Error communicating with the service: Nz+Unexpected error in Groq voice processing: zEk anapekshit truti aayi: zEk anapekshit truti aali: zAn unexpected error occurred: )r.   Úgetr4   r5   r6   r7   r8   r9   r&   r:   r   r   r   r   r   )
r?   r@   Úlang_mapÚlanguage_nameÚapp_capabilitiesr   r<   r=   Ú	error_msgr   s
             r   Úprocess_voice_command_airO   Œ   s  é € ÷ Š;Ø6ð   w°iÑ@€HØ—L‘L ¨9Ó5€MðÐð:ðØ)˜?¨)°J°<ð @	ð 
Ðð 9ð :G¸ð H	ðˆô* &×*Ñ*×6Ñ6×=Ñ=ð %Ø!vð  xEð  wFð  FGð   Hñð
 #Ø%ñð	ô %ØØð >ð 
ˆð !×(Ñ(¨Ñ+×3Ñ3×;Ñ;ˆØ�|‰|‹~Ðøäó ÜÐDÔEàMUÐY]ÓM]ÑIØu}ð  BFó  vFÑqØLð 	ð ÒÜó ÜÐ0°°Ð4Ô5ØEMÐQUÓEUÐ8¼¸Q»¸ÑAØBJÈdÓBRÐ5´c¸!³f°XÑ>Ø<¼SÀ»V¸HÐEð 	ð ÕûÜó ÜÐ;¸A¸3Ð?Ô@Ø=EÈÓ=MÐ0´°Q³°Ñ9Ø=EÈÓ=MÐ0´°Q³°Ñ9Ø4´S¸³V°HÐ=ð 	ð Õûðüs[   ‚'FªA;B& Â%FÂ&)FÃFÃ	FÃAD%ÄFÄ FÄ%FÄ2AE=Å7FÅ8FÅ=FÆFÚmarket_datac              ƒ   óÆ  #   • [         (       d  gU (       d  g SR                  U  Vs/ s H  nSUS    SUS    SUS	    3PM     sn5      nS
U S3n[         R                  R                  R	                  SUS./[
        SSS9nUR                  S   R                  R                  nUR                  5       $ s  snf ! [         a  n[        SU 35         SnAgSnAff = f7f)z6
Generates a brief summary of market data using Groq.
r"   z&No market data available to summarize.Ú
z- Úcropz: Úprice_per_quintalz INR/quintal at Úlocationz=Here is some recent market data from Baramati Mandi:
        z£

        Provide a very brief (1-2 sentence) summary highlighting any notable price points or trends based ONLY on this data.
        Respond in English.
        r'   r$   g      à?é<   r)   r   z!Error generating market summary: Nz"Could not generate market summary.)r.   Újoinr4   r5   r6   r7   r8   r9   r&   r:   r   r   )rP   ÚitemÚdata_stringr   r<   r=   r   s          r   Úget_market_summary_airZ   Ü   s  é € ÷ Š;Ø7ÞØ7ð4Ø—i‘iñ  ALó  !Mò  ALÐx| 2 d¨6¡l ^°2°dÐ;NÑ6OÐ5PÐP`ÐaeÐfpÑaqÐ`rÓ!sñ  ALñ  !Mó  Nˆð	Ø	ˆð 	ðˆô &×*Ñ*×6Ñ6×=Ñ=à¨FÑ3ðô %ØØð >ð 
ˆð !×(Ñ(¨Ñ+×3Ñ3×;Ñ;ˆØ�|‰|‹~Ðùò# !Møô& ó 4ÜÐ1°!°Ð5Ô6Ü3ûð4üs@   ‚C!˜B< §B7ÁA1B< Â6C!Â7B< Â<
CÃCÃC!ÃCÃC!)rE   )#Úgoogle.generativeaiÚgenerativeaiÚgenaiÚgroqr   r   r   ÚPILr   r   Útypingr   Úconfigr	   Úapp.models.yield_modelr
   ÚsettingsÚGEMINI_API_KEYÚ	configureÚGenerativeModelr   Úgemini_text_modelr   r   r   ÚGROQ_API_KEYr.   r7   Úbytesr   r   r>   rO   ÚlistrZ   © ó    r   Ú<module>rm      s†  ðÝ #ß /Ñ /Ý Û 	Ý  õ !ö Ý1ñ ‹>€ðØ×× 8×#:Ñ#:Ð>[Ó#[Ø�Š × 7Ñ 7Ò8à#×3Ò3Ð4FÓGÐà!×1Ò1Ð2DÓEÑáÐZÔ[Ø"ÐØ Ñð
Ø×× ×!6Ñ!6Ð:UÓ!UÙ 8×#8Ñ#8Ñ9ˆà-ÑáÐVÔWØ‰ð!>¨eð !>¸ô !>ðJ2]¨,ð 2]¸3ô 2]ñlM¨sð M¸cð MÈSõ Mð`4¨Tð 4°cõ 4øð ó Ù	Ð3°A°3Ð
7Ô8ØÐØÕûðûð ó Ù	Ð1°!°Ð
5Ô6Ø…Kûðús<   ¼AD ÂD Â*3D4 Ã
D4 ÄD1ÄD,Ä,D1Ä4EÄ:EÅE