
    hi                         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mZmZm	Z	 d dl
m
Z
mZ d dlmZ d dl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j2                  e      Z G d
 d      Zy)    N)DictAnyOptionalList)datetimetimezone)AzureOpenAI)Session)Image)BytesIO)
ChatThreadChatMessage)StorePersonac                      e Zd ZdZd Zddededee   defdZ		 dded	ed
ede
eeef      fdZddedee   defdZ	 ddedede
eeef      dee   deeef   f
dZ	 	 ddededededee   d	ee   deeef   fdZ	 ddedede
e   fdZdedede
eeef      defdZddededeeef   fdZ	 	 	 d dededededee   d	ee   dedeeef   fdZy)!ChatbotLLMServicezVLLM service for the hwGpt chatbot with store persona integration and image generation.c                    t        t        j                  d      t        j                  dd      t        j                  d            | _        t        j                  dd      | _        t        j                  d      | _        t        j                  d	      | _        t        j                  d
d      | _        t        j                  j                  t        j                  j                  t        j                  j                  t              ddd            }t        j                  j                  |dddd      | _        t        j                  | j                  d       y )NAZURE_OPENAI_API_KEYAZURE_OPENAI_API_VERSIONz2024-02-15-previewAZURE_OPENAI_ENDPOINT)api_keyapi_versionazure_endpointAZURE_OPENAI_DEPLOYMENTzgpt-4IDEOGRAM_URLIDEOGRAM_API_KEYBASE_URLz(https://hubwallet-dev.dreamztesting.com/z..menu_designdesignerstaticgenerated_imagesT)exist_ok)r	   osgetenvclientdeployment_namer   r   r   pathabspathjoindirname__file__STATIC_PATHmakedirs)selfBASE_DIRs     C/var/www/html/hubwallet-dev/src/marketing/apps/hwGpt/llm_service.py__init__zChatbotLLMService.__init__   s    !II45		"<>RS99%<=

  "yy)BGL IIn5 "		*< =		*.XY 77??277<<0I4QUW[#\] 77<<-XWij 	D$$t4    Ndbstore_id	branch_idreturnc                 N   	 t        |t              r|dk  r%t        j                  d| dt	        |              y|;t        |t              r|dk  r&t        j                  d| dt	        |              d}|j                  t              j                  t        j                  |k(  t        j                  dk(        }|r"|j                  t        j                  |k(        }|j                         }|syd|j                  xs d	 d
|j                  xs d	 d|j                  xs d	 d|j                  xs d	 d|j                   xs d	 d|j"                  xs d	 d}|j%                         S # t&        $ r+}t        j                  dt)        |              Y d}~yd}~ww xY w)z*Get store persona context for LLM prompts.r   zInvalid store_id: z, type: zGNo specific store persona available. Please provide general assistance.NzInvalid branch_id: TzB
                Store Brand Persona:
                - Industry: zNot specifiedz$
                - Target Audience: z 
                - Brand Voice: z"
                - Content Style: z%
                - Analysis Summary: z%
                - Confidence Score: ao  

                Based on this persona, you should:
                1. Match the brand voice and tone
                2. Use industry-specific terminology when appropriate
                3. Tailor responses to the target audience
                4. Maintain the established content style
                5. Provide contextually relevant information
                zError getting store persona: zDUnable to retrieve store persona. Please provide general assistance.)
isinstanceintloggererrortypequeryr   filterr3   	is_activer4   firstindustryaudience_typebrand_voicecontent_styleanalysis_summaryconfidence_scorestrip	Exceptionstr)r-   r2   r3   r4   r<   personapersona_contextes           r/   get_store_persona_contextz+ChatbotLLMService.get_store_persona_context,   s   /	Zh,A1(8DNCSTU` $jC.HIYZN29+Xd9oEVWX 	 HH\*11%%1&&$.E
 \%;%;y%HIkkmG`#$--@A B$$+$9$9$L_#M N  ' 3 3 FG H"")"7"7"J?!K L%%,%=%=%P$Q R%%,%=%=%P$Q RO" #((** 	ZLL8QABY	Zs$   9E0 B:E0 7A8E0 0	F$9!FF$	thread_idmax_messagesc                 z   	 t        |t              r|dk  rt        j                  d| d       g S |j	                  t
              j                  t
        j                  |k(  t
        j                  dk(        j                  t
        j                  j                               j                  |      j                         }|j                          g }|D ]*  }|j                  |j                   |j"                  d       , |S # t$        $ r-}t        j'                  dt)        |              g cY d}~S d}~ww xY w)z/Build conversation context from thread history.r   zInvalid thread_id: z, returning empty contextFrolecontentz%Error building conversation context: N)r7   r8   r9   warningr<   r   r=   rM   
is_deletedorder_by
created_atdesclimitallreverseappendrQ   rR   rG   r:   rH   )r-   r2   rM   rN   messagesconversation_contextmessagerK   s           r/   build_conversation_contextz,ChatbotLLMService.build_conversation_context_   s   	i-a!4YK?XYZ	 xx,33%%2&&%/ h{--2245eeL6I##%  #% # $++#LL&-  (' 	LL@QIJI	s#   /D CD 	D:"D5/D:5D:store_personathread_contextc                 <    d| d|r|nd d}|j                         S )z<Create system prompt with store persona and marketing focus.zMYou are a marketing-focused AI assistant for a business store. 

            a  

            Your role is to:
            1. **Help with marketing strategies and campaigns**
            2. **Provide content creation assistance for social media, emails, and ads**
            3. **Analyze customer engagement and suggest improvements**
            4. **Help with brand messaging and positioning**
            5. **Assist with marketing analytics interpretation**
            6. **Provide creative ideas for promotional activities**
            7. **Help optimize marketing performance and ROI**

            Marketing Guidelines:
            - Focus on **customer acquisition and retention**
            - Suggest **promotional strategies and campaigns**
            - Help with **content marketing and social media**
            - Provide **marketing analytics insights**
            - Assist with **brand development and messaging**
            - Suggest **lead generation and conversion tactics**
            - Help with **marketing automation and workflows**

            Remember: You are a **marketing assistant** - focus on helping with marketing activities, campaigns, content creation, and strategy. Keep responses marketing-focused and business-oriented.

             z

            Stay within marketing scope: social media, advertising, content creation, customer engagement, brand development, and marketing analytics.)rF   )r-   r`   ra   system_prompts       r/   create_system_promptz&ChatbotLLMService.create_system_prompt   s<    O ,  .^26 7W1Z8 ""$$r1   user_messageconversation_historyc           	         	 | j                  ||      }d|dg}|dd D ]  }|j                  |d   |d   d        |j                  d|d       t        j                  dt	        |       d	       | j
                  j                  j                  j                  | j                  |d
dddd      }|j                  d   j                  j                  }	|j                  }
t        j                  dt	        |	       d       t        j                  d|
j                          d|	|
j                  | j                  dS # t        $ r:}t        j!                  dt#        |              dt#        |      ddcY d}~S d}~ww xY w)z(Generate AI response using Azure OpenAI.systemrP   iNrQ   rR   userzGenerating response with z context messagesi  ffffff?g?g?)modelr\   
max_tokenstemperaturetop_pfrequency_penaltypresence_penaltyr   zGenerated response: z characterszTokens used: T)successresponsetokens_used
model_usedzError generating AI response: FzWI apologize, but I'm experiencing technical difficulties. Please try again in a moment.rr   r:   rs   )re   r[   r9   infolenr$   chatcompletionscreater%   choicesr^   rR   usagetotal_tokensrG   r:   rH   )r-   rf   r`   rg   ra   rd   r\   msgrs   ai_responser}   rK   s               r/   generate_responsez#ChatbotLLMService.generate_response   s   /	 55m^TM "*mDEH ,CD1 RVY PQR OOVEFKK3CM?BSTU {{''33::**!"%!$ ; H #**1-55==KNNEKK.s;/?.@LMKK-(:(:';<=  '$11"22	   	LL9#a&BC Qu 	s   D?E 	F/F :F Fuser_idc                 6  K   	 | j                  |||      }t        d|       g }d}	t        |t              rp|dkD  rk	 | j	                  ||      }|j                  t              j                  t        j                  |k(        j                         }
|
rd|
j                  xs d }	t        d	|       t        d
|	       | j                  ||||	      }|d   s|S t!        ||d|d      }|j#                  |       |j%                          t!        ||d|d   d|j'                  d      |j'                  d            }|j#                  |       t)        j*                  t,        j.                        
_        |j3                          |j5                  |       |j5                  |       t        j7                  d|j                   d|j                          d|j                  |j8                  |j:                  |j<                  j?                         d|j                  |j8                  |j:                  |j<                  j?                         |j@                  |jB                  d|tE        |      dkD  r
|dd dz   dS |dS # t        $ r3}t        j                  d| dt        |              g }d}	Y d}~d}~ww xY w# t        $ rJ}t        jG                  dt        |              |jI                          dt        |      ddcY d}~S d}~ww xY ww) z0Process a chat message and generate AI response.r`   zGeneral marketing assistancer   zCurrent conversation topic: zGeneral chatz,Could not load thread context for thread_id : Nrg   ra   rr   rj   textrM   r   rQ   rR   message_type	assistantrs   rt   ru   )rM   r   rQ   rR   r   rt   ru   z(Processed chat message: User message ID , AI response ID T)idrR   rQ   rV   )r   rR   rQ   rV   rt   ru      ...)rr   rf   r   rM   store_persona_summaryzError processing chat message: FzRI apologize, but I encountered an error processing your message. Please try again.rv   )%rL   printr7   r8   r_   r<   r   r=   r   r?   titlerG   r9   rS   rH   r   r   addflushgetr   nowr   utc
updated_atcommitrefreshrw   rR   rQ   rV   	isoformatrt   ru   rx   r:   rollback)r-   r2   r   rf   r3   r4   rM   r`   rg   ra   threadrK   r   user_msgai_msgs                  r/   process_chat_messagez&ChatbotLLMService.process_chat_message   s    b	 ::2xSM/=1 $& ;N)S)i!m	D+/+J+J2y+Y(XXj188)9STZZ\F+GHfXfGg)h (*>?"N3 00$	K y)"" ##$#H FF8HHJ !# #J/#'OOM:&??<8F FF6N !)X\\ :F IIK JJx JJvKKB8;;-O`agajaj`klm  "++'//$MM"*"5"5"?"?"A	! !))%~~"KK"("3"3"="="?#)#5#5"("3"3  'HKMHZ]`H`t)<u)D# " gt# m ! DNN%QR[Q\\^_bcd_e^f#gh+-(%CNDT  	LL:3q6(CDKKM Qp 	sw   L8K A*J '2K LF%K ?L K L	K (J;5K ;K  K 	L?LLLLLcontextc                 "   	 d| d| d}| j                   j                  j                  j                  | j                  d|dgdd      }|j
                  d	   j                  j                  j                         j                  d
      }|D cg c]5  }|j                         s|j                  d      r&|j                         7 }}|dd S c c}w # t        $ r/}t        j                  dt        |              g dcY d}~S d}~ww xY w)z,Generate marketing-focused chat suggestions.zBased on this store persona:

zx

Generate 5 marketing-focused conversation starters that marketing teams or business owners might ask about. 
Context: a  

Focus on:
- Marketing strategy questions
- Content creation help
- Campaign planning
- Social media management
- Customer engagement tactics
- Brand development
- Marketing analytics

Return only the suggestions, one per line, without numbering or extra text.rj   rP   r   rk   rl   r\   rm   rn   r   
)z1.z2.z3.z4.z5.N   z#Error generating chat suggestions: )z0How can I help you with your marketing strategy?z>What type of content should I create for your target audience?z-How can I improve my social media engagement?z8What marketing campaigns should I plan for this quarter?z$How can I optimize my marketing ROI?)r$   ry   rz   r{   r%   r|   r^   rR   rF   split
startswithrG   r9   r:   rH   )r-   r`   r   suggestions_promptrs   suggestionssrK   s           r/   get_chat_suggestionsz&ChatbotLLMService.get_chat_suggestionsI  s   (	& 
  L"O$ {{''33::**#)6HIJ	 ; H #**1-55==CCEKKDQK.9|QWWYq||\zO{1779|K|r?" }  	LL>s1vhGH 	s<   BC C&C8C
C C 	D$D	D	Dc           	      0   	 d}|r/|dd }dj                  |D cg c]  }|d    d|d     c}      }d| d	| d
| d}| j                  j                  j                  j	                  | j
                  dddd|dgdd      }|j                  d   j                  j                  j                         }	|	dz  }	t        j                  d|	        |	S c c}w # t        $ r1}
t        j                  dt        |
              d| dcY d}
~
S d}
~
ww xY w)z]Generate a detailed image prompt for marketing content based on user input and store persona.rc   Nr   rQ   r   rR   z
            Create a detailed image prompt for marketing content based on the following information:
            
            Store Persona:
            z4
            
            User Request:
            zC
            
            Recent Conversation Context:
            a  
            
            Requirements:
            - Create a professional marketing image suitable for social media, ads, or promotional materials
            - The image should align with the store's brand persona and target audience
            - Focus on visual appeal and marketing effectiveness
            - Include relevant product/service elements if mentioned
            - Use appropriate colors, style, and composition for the brand
            - Make it suitable for digital marketing use (social media, website, ads)
            
            IMPORTANT: 
            - Do NOT include any text, logos, or written content in the image
            - Focus purely on visual elements and composition
            - Make it high-quality and professional
            - Ensure it's appropriate for marketing use
            
            Generate a detailed prompt (max 300 characters) that can be used to create this marketing image.
            ri   zYou are an expert at creating detailed image prompts for marketing content. Focus on visual elements, composition, and brand alignment.rP   rj   i,  rk   r   r   zj Professional marketing image, no text, no logos, high quality, suitable for social media and advertising.z"Generated marketing image prompt: zError generating image prompt: z!Professional marketing image for z>, no text, high quality, suitable for social media advertising)r(   r$   ry   rz   r{   r%   r|   r^   rR   rF   r9   rw   rG   r:   rH   )r-   rf   r`   rg   r]   recent_messagesr   promptrs   image_promptrK   s              r/   generate_marketing_image_promptz1ChatbotLLMService.generate_marketing_image_prompty  sy   ;	D#% #"6rs";'+yyBQ2;>s6{m2c)n%562 ($ O  N  "" #F: {{''33::**%  3|  }#7  ; H $++A.66>>DDFL   I  ILKK<\NKLc2f  	DLL:3q6(CD6|n  EC  D  D	Ds.   C CB'C C 	D$&D
DDr   
session_idc           	         	 t        t        j                               }d| d| d}t        j                  j	                  | j
                  |      }| j                  r| j                  sddddS t        j                  | j                  d| j                  id|fd	d
dd      }t        j                  d|j                          |j                  dk7  rdd|j                   ddS |j                         }|j                  d      rt!        |d         dk(  rddddS |d   d   j                  d      }|sddddS t        j                  |d      }	|	j                  dk7  rdd|	j                   ddS t#        j$                  t'        |	j(                              }
|
j+                  |       t        j                  d|        | j,                  j/                  d      r| j,                  n| j,                  dz   }| d| }t        j                  d|        d|||ddS # t0        $ r:}t        j3                  dt5        |              dt5        |      ddcY d}~S d}~ww xY w) z9Generate an image using Ideogram API and save it locally.hwgpt_marketing__z.pngFzIdeogram API not configuredN)rr   r:   	image_urlzApi-Key)N1x1)NON)NzText, text overlay, logos, brands, written content, words, letters, typography. No text allowed in the image. Strictly no text. No text in the image. No text in the image. No text in the image. No text in the image. No text in the image.)r   aspect_ratiomagic_promptnegative_prompt)headersfilesz%Received response from Ideogram API: r   zIdeogram API error: datar   z&No image data returned by Ideogram APIurlz%No image URL returned by Ideogram APIx   )timeoutzFailed to download image: zImage saved locally at: /zstatic/generated_images/zImage URL: T)rr   r   
local_pathfilenamer:   zError generating image: )r8   timer"   r&   r(   r+   r   r   requestspostr9   rw   status_coder   jsonr   rx   r   openr   rR   saver   endswithrG   r:   rH   )r-   r   r   	timestampimage_filenameimage_filepathrs   response_datageneration_urlimage_responseimgbase_urlr   rK   s                 r/   generate_image_with_ideogramz.ChatbotLLMService.generate_image_with_ideogram  s   X	DIIK(I/
|1YKtLNWW\\$*:*:NKN $$D,A,A$:!%   }}!!t44  $\2$1$0 (_	H KK?@T@T?UVW ##s*$3HMM?C!%  %MMOM $$V,M&4I0Ja0O$E!%  +621599%@N!$D!%  &\\.#FN))S0$9.:T:T9UV!%  **W^%;%;<=CHH^$KK2>2BCD )-(>(>s(Ct}}Y\I\H#*$<^<LMIKK+i[12  &,*   	LL3CF8<= Q! 	s>   A-H' 0A8H' )7H' !H'  8H' 9B-H' '	I*0/I%I*%I*c           
        K   	 | j                  |||      }g }	t        |t              r|dkD  r| j                  ||      }	| j	                  |||	      }
| j                  |
|      }|d   rd| d}nd| d|d    d}t        ||d	|d
      }|j                  |       |j                          t        ||d| d|j                  d      rd|d   z   dz   nd d|j                  d      r|j                  d      nd      }|j                  |       |rm|j                  t              j                  t        j                  |k(        j                         }|r(t        j                   t"        j$                        |_        |j)                          |j+                  |       |j+                  |       t,        j/                  d|j                   d|j                          d|j                  |j0                  |j2                  |j4                  |j6                  j9                         d|j                  |j0                  |j2                  |j4                  |j6                  j9                         d||
|t;        |      dkD  r
|dd dz   dS |dS # t<        $ rJ}t,        j?                  dtA        |              |jC                          dtA        |      ddcY d}~S d}~ww xY ww) zLProcess an image generation request and return both text response and image.r   rr   z9I've generated a marketing image based on your request: 'z'. The image has been created to align with your store's brand persona and is suitable for your marketing campaigns. You can use this image for social media posts, advertisements, or other promotional materials.z'I understand you'd like an image for: 'z9'. However, I encountered an issue generating the image: r:   zE. Let me help you with other marketing strategies or try again later.rj   image_requestr   r   z

r   z![Generated Image]()rc   r   N)rM   r   rQ   rR   r   r   z4Processed image generation request: User message ID r   T)r   rR   rQ   r   rV   r   r   )rr   rf   r   image_generationr   rM   r   z+Error processing image generation request: FzcI apologize, but I encountered an error processing your image generation request. Please try again.rv   )"rL   r7   r8   r_   r   r   r   r   r   r   r<   r   r=   r   r?   r   r   r   r   r   r   r   r9   rw   rR   rQ   r   rV   r   rx   rG   r:   rH   r   )r-   r2   r   rf   r3   r4   rM   r   r`   rg   r   image_resulttext_responser   r   r   rK   s                    r/    process_image_generation_requestz2ChatbotLLMService.process_image_generation_request  s    \	 ::2xSM $& )S)i!m'+'F'Fr9'U$  ??m-AL
  <<\:VL I&"[\h[i  j}  !~"I,  XQ  R^  _f  Rg  Qh  hm  !n ##$,H FF8HHJ !# $oTR^RbRbcnRo,|K/HH3Nuwxz .;G;K;KI;V,**;7\`
F FF6N *-44Z]]i5OPVVX(0X\\(BF% IIK JJx JJvKKNx{{m[lmsmvmvlwxy  "++'//$MM$,$9$9"*"5"5"?"?"A! !))%~~"KK$*$7$7"("3"3"="="?  %1 ,&HKMHZ]`H`t)<u)D' & gt' ,  	LLFs1vhOPKKM Q B 	sA   K'JJ K'J K'	K$?KK$K'K$$K')N)
   )NN)general)default)NNr   )__name__
__module____qualname____doc__r0   r
   r8   r   rH   rL   r   r   r_   re   r   r   r   r   r   r   r    r1   r/   r   r      se   `5,1ZG 1Zs 1ZxX[} 1Zhk 1Zn 	!! ! 	!
 
d38n	!F%# %xPS} %`c %J )-77 7 #4S>2	7
 !7 
c3h7~ $(#'ll l 	l
 l C=l C=l 
c3hlb !.. . 
c	.`BDBD BD #4S>2	BD
 
BDHZ Z# Z^bcfhkck^l ZD $(#'#gg g 	g
 g C=g C=g g 
c3hgr1   r   )r"   r   loggingr   r   typingr   r   r   r   r   r   openair	   sqlalchemy.ormr
   PILr   ior   src.marketing.apps.hwGpt.modelr   r    src.marketing.apps.persona.modelr   	getLoggerr   r9   r   r   r1   r/   <module>r      sM    	     , , '  "   B 9			8	$m	 m	r1   